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
|
---|---|---|---|---|---|---|---|---|---|
f71239deabb7fc6c2368c1de2cab76b6 | UNKNOWN | You'll be given a list of two strings, and each will contain exactly one colon (`":"`) in the middle (but not at beginning or end). The length of the strings, before and after the colon, are random.
Your job is to return a list of two strings (in the same order as the original list), but with the characters after each colon swapped.
## Examples
```
["abc:123", "cde:456"] --> ["abc:456", "cde:123"]
["a:12345", "777:xyz"] --> ["a:xyz", "777:12345"]
``` | ["def tail_swap(strings):\n head0, tail0 = strings[0].split(':')\n head1, tail1 = strings[1].split(':')\n return [head0 + ':' + tail1, head1 + ':' + tail0]", "def tail_swap(arr):\n fmt = '{}:{}'.format\n (head, tail), (head_2, tail_2) = (a.split(':') for a in arr)\n return [fmt(head, tail_2), fmt(head_2, tail)]\n", "def tail_swap(strings):\n (h1, t1), (h2, t2) = (s.split(':') for s in strings)\n return [f\"{h1}:{t2}\", f\"{h2}:{t1}\"]", "def tail_swap(ss):\n a = [s.split(':') for s in ss]\n a[0][1], a[1][1] = a[1][1], a[0][1]\n return [':'.join(p) for p in a]", "def tail_swap(lst):\n (a,b),(c,d) = (s.split(':') for s in lst)\n return list(map(':'.join, ((a,d),(c,b))))", "def tail_swap(s):\n h1,t1 = s[0].split(':')\n h2,t2 = s[1].split(':')\n return ['{}:{}'.format(h1,t2), '{}:{}'.format(h2,t1)]", "def tail_swap(strings):\n s = [x.split(':') for x in strings]\n return [s[0][0] + ':' + s[1][1], s[1][0] + ':' + s[0][1]]", "def tail_swap(strings):\n return '{0}:{3} {2}:{1}'.format(*[j for i in strings for j in i.split(':')]).split()", "def tail_swap(strings):\n a, b = strings\n a, b = a.split(':'), b.split(':')\n return [f'{a[0]}:{b[1]}', f'{b[0]}:{a[1]}']", "def tail_swap(strings):\n a,b = [ele.split(':') for ele in strings]\n return [ f'{a[0]}:{b[1]}',f'{b[0]}:{a[1]}' ]"] | {"fn_name": "tail_swap", "inputs": [[["abc:123", "cde:456"]], [["a:12345", "777:xyz"]]], "outputs": [[["abc:456", "cde:123"]], [["a:xyz", "777:12345"]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,356 |
def tail_swap(strings):
|
82810a916e8d2170716efc6ef8986341 | UNKNOWN | Adding tip to a restaurant bill in a graceful way can be tricky, thats why you need make a function for it.
The function will receive the restaurant bill (always a positive number) as an argument. You need to 1) **add at least 15%** in tip, 2) round that number up to an *elegant* value and 3) return it.
What is an *elegant* number? It depends on the magnitude of the number to be rounded. Numbers below 10 should simply be rounded to whole numbers. Numbers 10 and above should be rounded like this:
10 - 99.99... ---> Round to number divisible by 5
100 - 999.99... ---> Round to number divisible by 50
1000 - 9999.99... ---> Round to number divisible by 500
And so on...
Good luck!
## Examples
```
1 --> 2
7 --> 9
12 --> 15
86 --> 100
``` | ["from math import ceil, log10\n\ndef graceful_tipping(bill):\n bill *= 1.15\n if bill < 10:\n return ceil(bill)\n e = int(log10(bill))\n unit = (10 ** e) / 2\n return ceil(bill / unit) * unit", "import math\ndef graceful_tipping(bill):\n c = bill * 115 / 100\n m = 1 if c < 10 else 5 * 10 ** int(math.log10(c) - 1)\n return math.ceil(c / m) * m\n", "def graceful_tipping(bill):\n import math\n multiple = 0\n tip = bill + (0.15 * bill)\n if tip < 10:\n multiple = 1\n elif tip < 100:\n multiple = 5\n elif tip < 1000:\n multiple = 50\n elif tip < 10000:\n multiple = 500\n elif tip < 100000:\n multiple = 5000\n elif tip < 1000000:\n multiple = 50000\n elif tip < 10000000:\n multiple = 500000\n elif tip < 100000000:\n multiple = 5000000\n \n return math.ceil(float(tip) / multiple) * multiple\n", "import math\ndef graceful_tipping(bill):\n x=math.ceil(bill+bill*15/100)\n if x<11:\n return x\n else:\n le=(len(str(x))-2)\n y=(5*(10**le))\n return x+((y*(math.ceil(x/y)))-x)", "import math\ndef graceful_tipping(bill):\n x=math.ceil(bill+bill*15/100)\n if x<11:\n return x\n else:\n le=(len(str(x))-2)\n y=(5*(10**le))\n z=math.ceil(x/y)\n b=(y*z)-x\n x=x+b\n return x", "import math\ndef graceful_tipping(rest_bill):\n res = rest_bill * 1.15\n if res < 10:\n return math.ceil(res)\n tmp = 5 * 10.0 ** (math.ceil(math.log10(res)) - 2)\n if res % tmp > 0:\n res += (tmp - res % tmp)\n return res\n", "import math\ndef graceful_tipping(bill):\n bill = bill * 1.15\n if bill < 10:\n return math.ceil(bill)\n elif 10 <= bill < 100:\n bill = math.ceil(bill)\n mul5 = [i for i in range(1,bill+5) if i % 5 ==0]\n return mul5[-1]\n elif 100 <= bill < 1000:\n bill = math.ceil(bill)\n mul50 = [i for i in range(1,bill+50) if i % 50 ==0]\n return mul50[-1] \n elif 1000 <= bill < 10000:\n bill = math.ceil(bill)\n mul500 = [i for i in range(1,bill+500) if i % 500 ==0]\n return mul500[-1] \n elif 10000 <= bill < 100000:\n bill = math.ceil(bill)\n mul5000 = [i for i in range(1,bill+5000) if i % 5000 ==0]\n return mul5000[-1] \n elif 100000 <= bill < 1000000:\n bill = math.ceil(bill)\n mul50000 = [i for i in range(1,bill+50000) if i % 50000 ==0]\n return mul50000[-1] \n elif 1000000 <= bill < 10000000:\n bill = math.ceil(bill)\n mul500000 = [i for i in range(1,bill+500000) if i % 500000 ==0]\n return mul500000[-1] \n \n \n \n", "def graceful_tipping(bill):\n total = bill * 1.15\n if total < 10:\n total = (int(total) + (total % 1 > 0))\n else :\n x = len(str(int(total))) - 2\n m = 5 * (10 ** x)\n total = (int(total/m) + (total % m > 0)) * m\n return total\n", "from math import ceil\n\ndef graceful_tipping(bill):\n total = bill * 1.15\n if total < 10:\n return ceil(total)\n total /= 5\n d = 0\n while total >= 20:\n d += 1\n total /= 10\n return ceil(total) * 5 * 10**d", "from math import ceil\nfrom itertools import count\ndef graceful_tipping(bill):\n num = ceil(bill * 0.15 + bill)\n if num < 10:\n return num\n d = int('5' + ((len(str(num))-2) * '0'))\n for n in count(num):\n if n % d == 0:\n return n\n"] | {"fn_name": "graceful_tipping", "inputs": [[1], [7], [12], [86], [99], [1149], [983212]], "outputs": [[2], [9], [15], [100], [150], [1500], [1500000]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,449 |
def graceful_tipping(bill):
|
102b6b9b666f8c662e824af6365ad1f4 | UNKNOWN | Given a triangle of consecutive odd numbers:
```
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
```
find the triangle's row knowing its index (the rows are 1-indexed), e.g.:
```
odd_row(1) == [1]
odd_row(2) == [3, 5]
odd_row(3) == [7, 9, 11]
```
**Note**: your code should be optimized to handle big inputs.
___
The idea for this kata was taken from this kata: [Sum of odd numbers](https://www.codewars.com/kata/sum-of-odd-numbers) | ["odd_row = lambda n:list(range(n*(n-1)+1,n*(n+1),2))\n", "def odd_row(n):\n m = (n - 1) * n + 1\n return [*range(m, m + n * 2, 2)]", "def odd_row(n):\n return [x for x in range(n**2-n+1, (n+1)**2-n,2)]", "def odd_row(n):\n return [x for x in range(n*n-n, n*n+n) if (x)%2!=0]", "def odd_row(n):\n return list(range(n**2 - n + 1, n**2 + n, 2))\n", "def odd_row(n):\n return list(range(n*(n-1) + 1, n*(n+1), 2))", "def odd_row(n):\n return [x for x in range((n**2)-(n-1), (2*n)+ ((n**2)-(n-1))) if (x%2)]", "def odd_row(n):\n row = [ i for i in range(n**2-n+1,n**2+n,2)]\n \n return row\n \n return", "def odd_row(n):\n arr = []\n value = (n * n) - (n -1)\n for i in range(n):\n arr.append(value)\n value += 2\n return arr", "def odd_row(n):\n stop = n * (n+1)\n return list(range(stop - n*2 + 1, stop, 2))"] | {"fn_name": "odd_row", "inputs": [[1], [2], [13], [19], [41], [93]], "outputs": [[[1]], [[3, 5]], [[157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181]], [[343, 345, 347, 349, 351, 353, 355, 357, 359, 361, 363, 365, 367, 369, 371, 373, 375, 377, 379]], [[1641, 1643, 1645, 1647, 1649, 1651, 1653, 1655, 1657, 1659, 1661, 1663, 1665, 1667, 1669, 1671, 1673, 1675, 1677, 1679, 1681, 1683, 1685, 1687, 1689, 1691, 1693, 1695, 1697, 1699, 1701, 1703, 1705, 1707, 1709, 1711, 1713, 1715, 1717, 1719, 1721]], [[8557, 8559, 8561, 8563, 8565, 8567, 8569, 8571, 8573, 8575, 8577, 8579, 8581, 8583, 8585, 8587, 8589, 8591, 8593, 8595, 8597, 8599, 8601, 8603, 8605, 8607, 8609, 8611, 8613, 8615, 8617, 8619, 8621, 8623, 8625, 8627, 8629, 8631, 8633, 8635, 8637, 8639, 8641, 8643, 8645, 8647, 8649, 8651, 8653, 8655, 8657, 8659, 8661, 8663, 8665, 8667, 8669, 8671, 8673, 8675, 8677, 8679, 8681, 8683, 8685, 8687, 8689, 8691, 8693, 8695, 8697, 8699, 8701, 8703, 8705, 8707, 8709, 8711, 8713, 8715, 8717, 8719, 8721, 8723, 8725, 8727, 8729, 8731, 8733, 8735, 8737, 8739, 8741]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 878 |
def odd_row(n):
|
f81fda052a04ba5a0fba45084dc499f4 | UNKNOWN | You might know some pretty large perfect squares. But what about the NEXT one?
Complete the `findNextSquare` method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.
If the parameter is itself not a perfect square then `-1` should be returned. You may assume the parameter is positive.
**Examples:**
```
findNextSquare(121) --> returns 144
findNextSquare(625) --> returns 676
findNextSquare(114) --> returns -1 since 114 is not a perfect
``` | ["def find_next_square(sq):\n root = sq ** 0.5\n if root.is_integer():\n return (root + 1)**2\n return -1\n", "def find_next_square(sq):\n x = sq**0.5 \n return -1 if x % 1 else (x+1)**2\n", "import math\n\n\ndef find_next_square(sq):\n return (math.sqrt(sq) + 1) ** 2 if (math.sqrt(sq)).is_integer() else -1", "from math import sqrt\ndef find_next_square(sq):\n return (sqrt(sq)+1)**2 if sqrt(sq)%1 == 0 else -1\n", "import math\ndef find_next_square(sq): \n input = float(math.sqrt(sq))\n if input % 1 == 0: # Check input whether it is an integer\n return pow(int(input)+1,2) # Return the next square if sq is a square\n return -1 # Return -1 otherwise\n", "import math\n\n\ndef find_next_square(sq):\n \"\"\"Return the next square if sq is a square, -1 otherwise\"\"\"\n square = math.sqrt(float(sq))\n return -1 if not square.is_integer() else math.pow(square + 1, 2)\n", "def find_next_square(sq):\n return (sq**0.5+1)**2 if int(sq**0.5)**2 == sq else -1", "from math import sqrt\ndef find_next_square(sq):\n\n if int(sqrt(sq)) == sqrt(sq):\n return (sqrt(sq) + 1) ** 2\n else:\n return -1\n", "def find_next_square(sq):\n import math\n f = float(sq)\n root = math.sqrt(f)\n if root.is_integer():\n next_int = int(root) + 1\n next_square = next_int * next_int\n return next_square\n else:\n return -1\n", "def find_next_square(sq):\n sqrt=sq**(0.5)\n if sqrt % 1 == 0:\n return (sqrt+1)**2\n return -1\n"] | {"fn_name": "find_next_square", "inputs": [[121], [625], [319225], [15241383936], [155], [342786627]], "outputs": [[144], [676], [320356], [15241630849], [-1], [-1]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,548 |
def find_next_square(sq):
|
bff37517e2ffdd9ab92d4479e28d0ce6 | UNKNOWN | It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters. | ["def remove_char(s):\n return s[1 : -1]", "def remove_char(s):\n return '' if len(s) <= 2 else s[1:-1]", "def remove_char(s):\n return s[1:len(s)-1]", "remove_char=lambda s: s[1:-1]", "def remove_char(s):\n if s == \"eloquent\": #confirming the s variable equals the word \"eloquent\"\n return(s[1:7]) #telling the program if s is \"eloquent\" print all except first and last letters\n elif s == \"country\": #confirming the s variable equals the word \"country\"\n return(s[1:6]) #telling the program if s is \"country\" print all except first and last \n elif s == \"person\": #same as 1,3\n return(s[1:5]) #same as 2,4\n elif s == \"place\": #same as 1,3\n return(s[1:4]) #same as 2,4\n elif s == \"ok\": #same as 1,3\n return\"\" #telling the program if s is \"ok\" don't print anything, ok is only 2 letters\n else: #if anything else is entered,\n return(s[1:-1]) #tell the program s is the input without the first and last characters", "def remove_char(s):\n s = list(s)\n s.pop()\n s.pop(0)\n return ''.join(s)", "def remove_char(s):\n #your code here\n if s is not None and len(s) > 1:\n return s[1:len(s)-1]\n \n return s", "def remove_char(s):\n #your code here\n s = s[1:-1]\n return s", "def remove_char(s):\n if len(s)>0:\n return s[1:-1]\n else:\n return ''", "remove_char = lambda s: s[1:-1] #Lambda is great -Mr. Stupido", "def remove_char(s):\n x = s[1:-1]\n return x ", "remove_char = lambda _: _[1:-1]\n", "def remove_char(s):\n list_s = list(s)\n list_s.pop()\n list_s.pop(0)\n return ''.join(list_s)", "def remove_char(s):\n #your code here\n if len(s) > 2:\n x = s[1:-1]\n return x\n else:\n return ''", "def remove_char(s):\n if len(s) > 2:\n return s[1:-1]\n else:\n return \"\"", "def remove_char(s):\n a = list(s)\n a.pop()\n a.reverse()\n a.pop()\n a.reverse()\n return ''.join(a)", "def remove_char(s):\n return s.replace(s[0:],s[1:-1]) ", "remove_char = lambda x:x[not():-(not())]", "def remove_char(s):\n long=len(s)\n s = s[:0] + s[(0+1):]\n s = s[:long-2] + s[(long-1):]\n return s", "def remove_char(s):\n return s.split()[0][1:len(s)-1]", "def remove_char(s):\n list1 = list(s)\n list1.pop(-1)\n list1.pop(0)\n return \"\".join(list1) ", "def remove_char(s):\n l = list(s)\n del (l[0],l[len(l)-1])\n return \"\".join(l)", "def remove_char(s):\n return s[1:len(s)-1] if len(s) > 1 else s", "def remove_char(s):\n return s[1:][:-1]", "def remove_char(s):\n return ''.join([list(s)[i] for i in range(1,len(s)-1)])", "def remove_char(s):\n lista = list(s)\n del lista[0]\n del lista[-1]\n s = \"\".join(lista)\n return s", "def remove_char(s):\n return \"\" + s[1:-1] + \"\"", "def remove_char(s: str) -> str:\n return s[1:len(s) - 1]\n", "def remove_char(s):\n r = s[1:]\n r = r[:len(r)-1]\n return r", "def remove_char(s):\n l = len(s)\n v = s[1:(l-1)]\n return v", "def remove_char(s):\n s_neu=s[1:]\n k=s_neu[:-1]\n return k", "def remove_char(s):\n s1=[]\n for x in s:\n s1.append(x)\n s1.pop(0)\n s1.pop(-1)\n s2=\"\"\n for x in s1:\n s2+=x \n return s2", "def remove_char(s):\n beforelastchar=len(s)-1\n news=s[1:beforelastchar]\n return news", "def remove_char(s):\n s = s[:0] + \"\" + s[1:]\n s = s[:-1] + \"\"\n \n return(s)\n", "def remove_char(s):\n l = list(s)\n nl = [j for i,j in enumerate(l) if i != 0 and i != len(s)-1]\n return ''.join(nl)", "def remove_char(s):\n a = [word for word in s]\n return \"\".join(a[1:-1])", "def remove_char(s):\n s_list = []\n for x in s:\n s_list.append(x)\n return \"\".join(s_list[1:(len(s)-1)])", "def remove_char(s):\n new = s[1:]\n new2 = new[:-1]\n return new2", "def remove_char(s):\n #your code here\n if len(s)<2:\n return s\n else:\n n=len(s)-1\n return s[1:n]", "def remove_char(s):\n #your code here\n b = s[1:-1]\n return str(b)"] | {"fn_name": "remove_char", "inputs": [["eloquent"], ["country"], ["person"], ["place"], ["ok"], ["ooopsss"]], "outputs": [["loquen"], ["ountr"], ["erso"], ["lac"], [""], ["oopss"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,323 |
def remove_char(s):
|
60fe3c2a9bcc93ba5de895e70af5e8fe | UNKNOWN | Write a function that returns the number of '2's in the factorization of a number.
For example,
```python
two_count(24)
```
should return 3, since the factorization of 24 is 2^3 x 3
```python
two_count(17280)
```
should return 7, since the factorization of 17280 is 2^7 x 5 x 3^3
The number passed to two_count (twoCount) will always be a positive integer greater than or equal to 1. | ["def two_count(n):\n res = 0\n while not n & 1:\n res += 1\n n >>= 1\n return res\n", "def two_count(n):\n return bin(n)[::-1].index('1')", "def two_count(n):\n return n.bit_length() - len(bin(n).rstrip('0')) + 2", "def two_count(n):\n i = 0\n while True:\n n, r = divmod(n, 2)\n if r:\n break\n i += 1\n return i\n", "def two_count(n):\n \n # store the brinary digits of n as an array\n binaryArr = list(bin(n))\n \n # reverse the array\n binaryArr.reverse()\n \n # return the index of the first location of element '1'\n return binaryArr.index('1')\n\n", "def two_count(n):\n return bin(n)[::-1].index('1')\n", "def two_count(n):\n if n%2 != 0:\n return 0\n else:\n return 1 + two_count(n//2)\n", "def two_count(n):\n n = bin(n)[2:]\n \n return len(n) - len(n.strip('0'))\n"] | {"fn_name": "two_count", "inputs": [[24], [17280], [222222222222], [256], [1], [2], [482848428248882482], [7], [7777777777777777], [84934656]], "outputs": [[3], [7], [1], [8], [0], [1], [1], [0], [0], [20]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 885 |
def two_count(n):
|
d3cdb5914dc3c80c3772aa89f070f707 | UNKNOWN | #Find the missing letter
Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.
You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.
The array will always contain letters in only one case.
Example:
```if-not:swift
['a','b','c','d','f'] -> 'e'
['O','Q','R','S'] -> 'P'
```
(Use the English alphabet with 26 letters!)
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have also created other katas. Take a look if you enjoyed this kata! | ["def find_missing_letter(chars):\n n = 0\n while ord(chars[n]) == ord(chars[n+1]) - 1:\n n += 1\n return chr(1+ord(chars[n]))\n\n", "def find_missing_letter(input):\n alphabet = list(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n start = alphabet.index(input[0])\n for i in range(len(input)):\n if not input[i] == alphabet[start+i]:\n return alphabet[start+i]", "def find_missing_letter(c):\n return next(chr(ord(c[i])+1) for i in range(len(c)-1) if ord(c[i])+1 != ord(c[i+1]))", "def find_missing_letter(chars):\n for x in range(1, len(chars)):\n if ord(chars[x]) - ord(chars[x - 1]) != 1:\n return chr(ord(chars[x]) - 1)\n\n", "def find_missing_letter(chars):\n return [chr(n) for n in range(ord(chars[0]),ord(chars[-1])+1) if n not in [ord(c) for c in chars]][0]\n \n\n", "def find_missing_letter(chars):\n s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n match = False\n count = 0;\n for letter in s:\n if letter == chars[count]:\n match = True\n count = count +1\n elif match == True:\n return letter", "def find_missing_letter(chars):\n for i in range(0, len(chars)-1):\n current = chars[i]\n after = chars[i+1]\n expected = chr(ord(current)+1)\n \n if after != expected:\n return expected\n \n return ''\n\n", "def find_missing_letter(chars):\n for i in range(len(chars) - 1):\n if ord(chars[i]) != ord(chars[i + 1]) - 1:\n return chr(ord(chars[i]) + 1)", "def find_missing_letter(chars):\n return set(chr(i) for i in range(ord(chars[0]), ord(chars[-1]) + 1)).difference(set(chars)).pop()\n\n", "def find_missing_letter(chars):\n next = chars[0]\n for letter in chars: \n if letter != next: return next\n next = chr(ord(letter) + 1)\n return 0\n\n"] | {"fn_name": "find_missing_letter", "inputs": [[["a", "b", "c", "d", "f"]], [["O", "Q", "R", "S"]], [["b", "d"]]], "outputs": [["e"], ["P"], ["c"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,916 |
def find_missing_letter(chars):
|
d3acf3e20d59e27d11600cde701dec8b | UNKNOWN | Cluster analysis - Unweighted pair-group average
Clustering is a task of grouping a set of objects in such a way that the objects in the same class are similar to each other and the objects in different classes are distinct. Cluster analysis is employed in many fields such as machine learning, pattern recognition, image analysis, etc.
In this kata, your task is to implement a simple clustering technique called 'Unweighted pair-group average'. This method takes a set of 2D points and the desired number of final clusters. Initially, each point forms its own cluster. The most similar (least distant) clusters are iteratively merged until the target number of clusters is reached.
The distance metric between two clusters is defined as the average distance between all pairs of points from the two clusters. For example:
```
Cluster 1: (0, 0), (0, 1)
Cluster 2: (4, 3)
Distance = (sqrt((0-4)^2 + (0-3)^2) + sqrt((0-4)^2 + (1-2)^2)) / 2
```
Input:
- ```points``` - a list of 2D points ```[(1, 1), (3, 5), (4, 4), (8, 2), (0, 1)]```
- ```n``` - the desired number of clusters
Output:
- list of clusters, each cluster is a list of points
- points in each cluster should be sorted in ascending order
- the list of clusters should also be sorted in ascending order
Example:
- ```cluster(3, [(1, 1), (3, 5), (4, 4), (8, 2), (0, 1)])```
- should return
```[ [(0, 1), (1, 1)],
[(3, 5), (4, 4)],
[(8, 2)]
]
```
Notes:
- the coordinates ```(x, y)``` are chosen from interval ```<0, 1000>```
- ```0 < len(points) <= 100```
- ```0 < n <= len(points)```
- there is always only one unique solution
- there are no duplicate points in the input | ["from sklearn.cluster import KMeans\n\n# Doesn't work for big tests, too bad\ndef cluster_kmeans(points, n):\n kmeans = KMeans(n_clusters=n)\n kmeans.fit(points)\n res = [[] for _ in range(n)]\n for i,p in zip(kmeans.labels_, points):\n res[i].append(p)\n return sorted(map(sorted, res))\n\n\nfrom itertools import combinations, product, starmap\nimport numpy as np\n\nmemo_points = {}\ndef point_dist(p1, p2):\n key = (p1, p2) if p1 < p2 else (p2, p1)\n if not key in memo_points: memo_points[key] = np.linalg.norm(np.array(key[0]) - np.array(key[1]))\n return memo_points[key]\n\nmemo_clusters = {}\ndef cluster_dist(clusters):\n key = tuple(map(tuple, clusters))\n if not key in memo_clusters: memo_clusters[key] = np.mean(list(starmap(point_dist, product(*key))))\n return memo_clusters[key]\n\ndef cluster(points, n):\n clusters = [[p] for p in points]\n while len(clusters) > n:\n c1, c2 = min(combinations(clusters, 2), key=cluster_dist)\n c1.extend(c2)\n clusters.remove(c2)\n return sorted(map(sorted, clusters))", "import math\nimport random\n\ndef cluster(points, n):\n def distance(c1, c2):\n s = 0\n for p1 in c1:\n for p2 in c2:\n s += math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)\n return float(s) / (len(c1) * len(c2))\n\n def closest(cs):\n min_dist, i1, i2 = float('inf'), -1, -1\n for i in range(len(cs)):\n for j in range(i+1, len(cs)):\n dist = distance(cs[i], cs[j])\n if dist < min_dist:\n min_dist = dist\n i1, i2 = i, j\n return i1, i2\n\n def merge(cs, i1, i2):\n cs[i1].extend(cs[i2])\n del cs[i2]\n\n clusts = [[x] for x in points]\n while len(clusts) > n:\n ind1, ind2 = closest(clusts)\n merge(clusts, ind1, ind2)\n for i in range(len(clusts)):\n clusts[i] = sorted(clusts[i])\n return list(sorted(clusts))", "from statistics import mean\nfrom itertools import product\nfrom math import sqrt, inf\n\n\ndef distance_between_points(point1, point2):\n return sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)\n\n\ndef distance_between_clusters(cluster1, cluster2):\n return mean(\n distance_between_points(point1, point2) for (point1, point2) in product(cluster1, cluster2)\n )\n\n\ndef merge_clusters(cluster1, cluster2):\n return sorted([*cluster1, *cluster2])\n\n\ndef identificator(cluster):\n return (cluster[0], len(cluster))\n\n\ndef update_distances(clusters, distances):\n for cluster1 in clusters:\n for cluster2 in clusters:\n id1 = identificator(cluster1)\n id2 = identificator(cluster2)\n if id1 != id2 and distances.get((id1, id2)) is None:\n distance = distance_between_clusters(cluster1, cluster2)\n distances[(id1, id2)] = distance\n distances[(id2, id1)] = distance\n\n\ndef clear_unactual_distances(distances, cluster1, cluster2):\n old_ids = [identificator(cluster1), identificator(cluster2)]\n new_distances = {k: v for k, v in list(distances.items()) if k[0] not in old_ids and k[1] not in old_ids}\n return new_distances\n \n\ndef pop_minimal_distance_pair(clusters, distances):\n minimal_ids = None\n minimal_distance = 10_000_000\n for ids_pair, distance in list(distances.items()):\n if distance < minimal_distance:\n minimal_distance = distance\n minimal_ids = ids_pair\n cluster1 = next(cluster for cluster in clusters if identificator(cluster) == minimal_ids[0])\n cluster2 = next(cluster for cluster in clusters if identificator(cluster) == minimal_ids[1])\n clusters.remove(cluster1)\n clusters.remove(cluster2)\n return (cluster1, cluster2)\n \ndef cluster(points, n):\n clusters = [[point] for point in points]\n distances = {}\n while n != len(clusters):\n update_distances(clusters, distances)\n cluster1, cluster2 = pop_minimal_distance_pair(clusters, distances)\n new_cluster = merge_clusters(cluster1, cluster2)\n clusters.append(new_cluster)\n distances = clear_unactual_distances(distances, cluster1, cluster2)\n return sorted(clusters)\n", "def dist_between_clusters(cluster1, cluster2):\n res = 0\n n = 0\n for point1 in cluster1:\n for point2 in cluster2:\n res += ((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2) ** 0.5\n n += 1\n return res / n\n\ndef cluster(points, n):\n clusters = [[point] for point in points]\n \n while n < len(clusters):\n min_dist, min1, min2 = None, None, None\n for i, cluster1 in enumerate(clusters[:-1]):\n for j, cluster2 in enumerate(clusters[i+1:]):\n dist = dist_between_clusters(cluster1, cluster2)\n if min_dist is None or dist < min_dist:\n min_dist, min1, min2 = dist, i, i+1+j\n clusters[min1].extend(clusters[min2])\n clusters.pop(min2)\n \n for i in range(len(clusters)):\n clusters[i].sort()\n clusters.sort()\n \n return clusters\n", "from itertools import product\n\ndef distance(p1, p2):\n return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5\n\n\ndef cluster(points, n):\n lista = [[en] for en in points]\n while len(lista) > n:\n min_pair, min_dist = (0, 0), float('inf')\n for i in range(len(lista) - 1):\n for j in range(i + 1, len(lista)):\n dist = 0\n pairs = list(product(lista[i], lista[j]))\n for pair in pairs:\n dist += distance(pair[0], pair[1])\n dist /= len(pairs)\n if dist < min_dist:\n min_dist = dist\n min_pair = (i, j)\n lista[min_pair[0]].extend(lista[min_pair[1]])\n del(lista[min_pair[1]])\n lista = [sorted(en) for en in lista]\n return sorted(lista, key=lambda x: x[0])", "def dist(p1, p2):\n return ((p1[0]-p2[0])**2+(p1[1]-p2[1])**2)**0.5\n\ndef MeanDist(clus1, clus2):\n c = 0\n for p1 in clus1:\n for p2 in clus2:\n c += dist(p1, p2)\n return c/(len(clus1)*len(clus2))\n\nfrom sklearn.cluster import KMeans\nfrom collections import defaultdict\ndef cluster(points, n):\n if len(points) < 20:\n pred = KMeans(n_clusters=n).fit_predict(points)\n ans = defaultdict(list)\n for x, y in zip(pred, points):\n ans[x].append(y)\n res = [sorted(i) for i in list(ans.values())]\n res = sorted(res, key=lambda x: x[0][0])\n return res\n \n clus = [[p] for p in points]\n leng = len(clus)\n while leng > n:\n md = float('inf')\n for i in range(leng):\n for j in range(i+1, leng):\n d = MeanDist(clus[i], clus[j])\n if d < md:\n md = d\n c = [clus[i] + clus[j]]\n curr = [i, j]\n temp = [x for i, x in enumerate(clus) if i not in curr]\n clus = temp + c\n leng = len(clus)\n res = [sorted(i) for i in clus]\n res = sorted(res, key=lambda x: x[0][0])\n return res\n", "from itertools import product, combinations\nfrom math import hypot\n\ndef euclid(p):\n (x1, y1), (x2, y2) = p\n return hypot(x1 - x2, y1 - y2)\n\ndef sim(pc):\n pc1, pc2 = pc\n return sum(map(euclid, product(pc1, pc2))) / (len(pc1) * len(pc2))\n\ndef cluster(points, n):\n res = [[p] for p in points]\n while len(res) > n:\n p0, p1 = min(combinations(res, 2), key = sim)\n res.remove(p0)\n res.remove(p1)\n res.append(p0 + p1)\n return sorted(map(sorted, res))", "from math import hypot\nfrom statistics import mean\n\ndef cluster(points, n):\n cs = [[p] for p in points]\n def key(ij):\n return mean(dist(p1, p2) for p1 in cs[ij[0]] for p2 in cs[ij[1]])\n while len(cs) > n:\n i, j = min(((i, j) for i in range(len(cs)) for j in range(i)), key=key)\n cs[i] += cs[j]\n del cs[j]\n return sorted(map(sorted, cs))\n\ndef dist(a, b):\n return hypot(a[0] - b[0], a[1] - b[1])", "import math\nimport numpy as np\nimport itertools\n\ndef cluster(points, n):\n \n def get_cluster_distance(cluster1, cluster2):\n \n # function to find distance between a single pair\n def get_point_distance(coord_1, coord_2):\n x1, y1 = coord_1\n x2, y2 = coord_2\n return math.sqrt( ((x1 - x2)**2) + ((y1 - y2)**2) )\n \n distances = []\n for point_i in cluster1:\n for point_j in cluster2:\n distances.append(get_point_distance(point_i, point_j))\n \n return np.mean(distances)\n \n # Initiate list of all clusters, initially every point is a cluster (its own list)\n all_clusters = [[point] for point in points]\n \n # Main function\n while len(all_clusters) > n:\n distances = []\n for i, j in itertools.combinations([ _ for _ in range(len(all_clusters))], 2):\n distances.append([i, j, get_cluster_distance(all_clusters[i], all_clusters[j])])\n minimum_distance_pair = min(distances, key = lambda x:x[2])\n i, j, distance = minimum_distance_pair\n all_clusters[i] = all_clusters[i] + all_clusters.pop(j)\n \n # Sort points in each cluster\n for i in range(len(all_clusters)):\n all_clusters[i] = sorted(all_clusters[i])\n # Sort each cluster\n return sorted(all_clusters)"] | {"fn_name": "cluster", "inputs": [[[[100, 100]], 1]], "outputs": [[[[[100, 100]]]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 9,693 |
def cluster(points, n):
|
05d36dfc31c21d9b2d5bccf8543dc958 | UNKNOWN | This function should test if the `factor` is a factor of `base`.
Return `true` if it is a factor or `false` if it is not.
## About factors
Factors are numbers you can multiply together to get another number.
2 and 3 are factors of 6 because: `2 * 3 = 6`
- You can find a factor by dividing numbers. If the remainder is 0 then the number is a factor.
- You can use the mod operator (`%`) in most languages to check for a remainder
For example 2 is not a factor of 7 because: `7 % 2 = 1`
Note: `base` is a non-negative number, `factor` is a positive number. | ["def check_for_factor(base, factor):\n return base % factor == 0", "def check_for_factor(b,f):\n return not b%f", "def check_for_factor(base, factor):\n return not (base % factor)", "def check_for_factor(base, factor):\n return True if base%factor == 0 else False", "check_for_factor = lambda base, factor: base % factor == 0", "check_for_factor=lambda a,b:not a%b", "check_for_factor = lambda _,__: not _%__", "def check_for_factor(base, factor):\n ans = False\n for x in range(base+1):\n if factor * x == base:\n ans = True\n return ans", "def check_for_factor(n, factor):\n return factor != 0 and n % factor == 0", "def check_for_factor(base, factor):\n integer = int(base / factor)\n return base / factor == integer", "def check_for_factor(base, factor):\n f = [i for i in range(1, base+1) if base/i == base//i]\n return True if factor in f else False\n # your code here\n", "def check_for_factor(base, factor):\n #base and factor are opposite?! No?\n return(base%factor==0)\n", "def check_for_factor(base, factor):\n \"\"\"(^-__-^)\"\"\"\n return base % factor == 0\n", "def check_for_factor(base, factor):\n return factor in [i for i in range(1, base + 1) if base % i == 0]", "check_for_factor = lambda b, f: (b/f).is_integer()", "def check_for_factor(b, f):\n return 1 if b%f is 0 else 0", "def check_for_factor(base, factor):\n # Given a base, check if factor can be divided by base w/ no remainder\n if (base % factor == 0):\n return True\n else:\n return False", "def check_for_factor(base, factor):\n if base % factor == int():\n return True\n else:\n return False", "def check_for_factor(base, factor):\n return int(base / factor) == base / factor", "import unittest\n\n\ndef check_for_factor(base, factor):\n return base % factor == 0\n \n \nclass TestCheckForFactor(unittest.TestCase):\n def test_check_for_factor_should_return_true_when_factor_is_divided_by_base(self):\n base, factor = 10, 2\n actual = check_for_factor(base, factor)\n self.assertEqual(actual, True)\n\n def test_check_for_factor_should_return_false_when_factor_is_not_divided_by_base(self):\n base, factor = 9, 2\n actual = check_for_factor(base, factor)\n self.assertEqual(actual, False)\n", "def check_for_factor(base, factor):\n print(base, factor)\n if base > factor:\n return base % factor == 0\n else:\n return factor % base == 0", "import math\n\ndef check_for_factor(base, factor):\n return base % factor == 0", "def check_for_factor(base, factor):\n ba = base / factor\n return(ba).is_integer()", "def check_for_factor(base, factor):\n return divmod(base, factor)[1] == 0", "def check_for_factor(base, factor):\n return True if (base / factor).is_integer() else False", "check_for_factor = lambda b, f: b % f == 0\n\n# def check_for_factor(base, factor):\n# return base % factor == 0\n", "def check_for_factor(base, factor):\n remainder = base % factor\n if remainder > 0:\n return False\n else:\n return True", "def check_for_factor(base, factor):\n if base % factor == 0 and base > 0:\n return True\n else:\n return False", "check_for_factor = lambda base, factor: not base % factor", "def check_for_factor(base, factor):\n m = []\n for i in range(1,base+1):\n if base%i == 0:\n m.append(i)\n return factor in m", "def check_for_factor(base,factor):\n \n check=False\n base=int(base)\n factor=int(factor)\n \n if factor > 0:\n if base%factor==0:\n check=True\n else :\n check=False\n else:\n check=False \n \n return check \n \n", "def check_for_factor(base, factor):\n if base%factor==0:\n return True\n else:\n return False\ns = check_for_factor(10,2)\nprint(s)", "def check_for_factor(base, factor):\n s=base%factor\n if s==0:\n return True\n else:\n return False\n", "def check_for_factor(base, factor):\n return base / factor % 1 ==0", "def check_for_factor(base, factor):\n return True if base % factor is 0 else False", "def check_for_factor(base, factor):\n if base < 0 or factor < 0:\n return False\n elif base % factor != 0:\n return False\n else:\n return True", "def check_for_factor(base, factor):\n return factor != 0 and base % factor == 0", "def check_for_factor(base, factor):\n return base%factor == 0\n\n# from Russia with love\n", "def check_for_factor(base, factor):\n if base > 0 and factor >=0:\n if base%factor == 0:\n return True\n else:\n return False\n", "check_for_factor = lambda a,b: a % b == 0 \n # your code here\n", "def check_for_factor(base, factor):\n\n check = base % factor\n \n if check > 0:\n return False\n else:\n return True", "def check_for_factor(base, factor):\n a = base / factor\n if a - (int(a)) == 0:\n return True\n else:\n return False", "def check_for_factor(base, factor):\n return [False, True][base%factor == 0]", "def check_for_factor(base, factor):\n # your code here\n return base % factor == 0\n \n\nprint((check_for_factor(10,2)))\n", "def check_for_factor(base, factor):\n \"\"\"Check if factor is a factor of base\"\"\"\n return base % factor == 0", "def check_for_factor(base, factor):\n return base%factor == 0 if base != 0 or factor != 0 else False", "def check_for_factor(base, factor):\n return base % factor == 0 if factor != 0 and base != 0 else False", "def check_for_factor(base, factor):\n for n in range (1,base):\n if base % (factor * n) == 0:\n return True\n else:\n return False", "def check_for_factor(base, factor):\n # your code here\n if (base % factor == 0): \n bool=True \n else: \n bool =False\n return bool ", "def check_for_factor(base, factor):\n # your code here\n if base % factor == 0 and base > 0:\n return True\n elif base is None:\n return False\n else:\n return False", "def check_for_factor(base, factor):\n if base and factor < 0:\n return None\n else:\n a = base % factor\n if a == 0:\n return True\n else:\n return False\n", "def check_for_factor(base, factor):\n if base>=0 and factor>=0:\n if base%factor==0:\n return True\n else: \n return False\n", "def check_for_factor(base, factor):\n if factor % base == 0:\n return True\n if base % factor == 0:\n return True\n else:\n return False", "def check_for_factor(base, factor):\n return bool(1) if base%factor==0 else bool(0)# your code here", "def check_for_factor(base, factor):\n # your code here\n a = base % factor \n if a==0:\n return True \n else:\n return False ", "def check_for_factor(base, factor):\n rem = base%factor\n if rem == 0:\n return True\n else:\n return False\n # your code here\n", "def check_for_factor(base, factor):\n return base - factor * (base // factor) == 0 ", "def check_for_factor(base, factor):\n if base % factor != 0:\n return False\n elif base % factor == 0:\n return True", "def check_for_factor(factor, base):\n return (factor % base) == 0", "def check_for_factor(base, factor):\n if (base % factor) == 0:\n m = True \n else: m = False\n return m", "def check_for_factor(base, factor):\n i = base % factor\n if i == 0:\n return True\n \n else:\n return False", "def check_for_factor(base, factor):\n x = base % factor \n if x == 0:\n return True \n else:\n return False ", "def check_for_factor(base, factor):\n# i take the parameters and convert in integer\n base = int(base)\n factor = int(factor)\n# here checking if the mod would evaluate to 0\n if base %factor == 0:\n return True\n else:\n return False \n", "def check_for_factor(base, factor):\n return True if int(base/factor)*factor == base else False", "def check_for_factor(base, factor):\n if base % factor == 0 and base > 0 and factor > 0:\n return True\n else: \n return False", "def check_for_factor(base, factor):\n return base % factor == 0 if True else False", "def check_for_factor(base, factor):\n i=base%factor\n if i!=0:\n return False\n return True\n # your code here\n", "def check_for_factor(base, factor):\n print(factor % base)\n return True if base % factor == 0 else False ", "def check_for_factor(base, factor):\n return base % factor == 0 and 0 not in [factor, base]", "def check_for_factor(base, factor):\n \n if base < factor:\n return False\n \n if base is factor:\n return True\n else:\n if (base%factor) == 0:\n return True\n else:\n return False", "def check_for_factor(base, factor):\n if base % factor == 0:\n print(str(factor) + ' is a factor of ' + str(base))\n return True\n \n else:\n print(str(factor) + ' is not a factor of ' + str(base))\n return False", "def check_for_factor(base, factor):\n if base >= 0 and factor > 0 :\n if base % factor == 0:\n return True\n else :\n return False\n else :\n return False", "def check_for_factor(base, factor):\n if base%factor==0 or factor%base==0:\n return True \n else:\n return False", "def check_for_factor(a, b):\n return not a % b", "def check_for_factor(base, factor):\n # your code here\n remainder = base % factor\n if remainder == 0:\n return True\n else:\n return False", "def check_for_factor(g, f):\n a = g % f\n if a != 0:\n return False\n else:\n return True", "def check_for_factor(base, factor):\n a = base % factor# your code here\n if a == 0:\n c = True\n else:\n c = False\n return c", "def check_for_factor(base, factor):\n if base % factor != 0:\n return False\n return True", "def check_for_factor(base, factor):\n # your code here\n return bool(not(base % factor))", "def check_for_factor(base, factor):\n ls=[]\n for i in range(1,base+1):\n if base%i==0:\n ls.append(i)\n if factor in ls:\n return True\n else:\n return False", "check_for_factor = lambda base, factor: True if not base%factor else False", "def check_for_factor(base, factor):\n test = True if base%factor == 0 else False;\n return test;", "check_for_factor = lambda b,f: not bool(b%f)\n", "def check_for_factor(base, factor):\n check = base % factor\n if (check == 0):\n return True\n else:\n return False", "def check_for_factor(base, factor):\n return (False,True)[base%factor==0]", "def check_for_factor(base, factor):\n return base//factor == base/factor", "def check_for_factor(base, factor):\n resultat = False\n if (base % factor) == 0:\n resultat = True\n return resultat", "def check_for_factor(base, factor):\n if factor == 0:\n return False\n else:\n return(base % factor == 0)", "def check_for_factor(base, factor):\n case = base % factor\n if case == 0:\n return True\n else:\n return False", "def check_for_factor(base, factor):\n if base % factor == 0:\n return True\n else:\n base % factor != 0\n return False", "def check_for_factor(base, factor):\n x = 0\n return 1 if base % factor == x else 0", "def check_for_factor(base, factor):\n print(base, factor)\n # your code here\n if base % factor == 0:\n return True\n else:\n return False", "check_for_factor = lambda b,f: True if b%f==0 else False", "def check_for_factor(b, f):\n if b % f == 0:\n return True\n else:\n return False", "def check_for_factor(base, factor):\n return base / factor == int( base / factor )", "def check_for_factor(base: int, factor: int) -> bool:\n return base % factor == 0", "check_for_factor = lambda x,y: not x%y", "def check_for_factor(base, factor):\n return(base//factor*factor == base)", "def check_for_factor(base, factor):\n return True if float(base) / factor == base // factor else False", "def check_for_factor(b, f):\n return True if b % f == 0 else False"] | {"fn_name": "check_for_factor", "inputs": [[10, 2], [63, 7], [2450, 5], [24612, 3], [9, 2], [653, 7], [2453, 5], [24617, 3]], "outputs": [[true], [true], [true], [true], [false], [false], [false], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 12,597 |
def check_for_factor(base, factor):
|
84a4a9dd2e8dca3ac9440be924907284 | UNKNOWN | The aim of this Kata is to write a function which will reverse the case of all consecutive duplicate letters in a string. That is, any letters that occur one after the other and are identical.
If the duplicate letters are lowercase then they must be set to uppercase, and if they are uppercase then they need to be changed to lowercase.
**Examples:**
```python
reverse_case("puzzles") Expected Result: "puZZles"
reverse_case("massive") Expected Result: "maSSive"
reverse_case("LITTLE") Expected Result: "LIttLE"
reverse_case("shhh") Expected Result: "sHHH"
```
Arguments passed will include only alphabetical letters A–Z or a–z. | ["import re\n\ndef reverse(s):\n return re.sub(r'(.)\\1+', lambda m: m.group().swapcase(), s)", "import re\n\ndef reverse(strng): return re.sub(r'(\\w)\\1+', lambda m: m.group().swapcase(), strng)", "import re\n\ndef reverse(stg):\n return re.sub(r\"(([a-zA-Z])\\2+)\", lambda m: m.group(1).swapcase(), stg)", "from functools import partial\nfrom re import compile\n\nreverse = partial(compile(r\"(.)\\1+\").sub, lambda s: s.group().swapcase())", "reverse=lambda s:__import__('re').sub(r'(.)\\1+',lambda x:x.group(0).swapcase(),s)", "def reverse(s):\n index, l = 0, [[]]\n for x in s:\n if x in l[index]:\n l[index].append(x)\n elif not l[index]:\n l[index].append(x)\n else:\n l.append([x])\n index += 1\n return \"\".join(''.join(c.swapcase()for c in x)if len(x)>1 else x.pop()for x in l)", "def reverse(s):\n s=list(s)\n indexes=[]\n for i in range(len(s)-1):\n if s[i]==s[i+1]:\n indexes.append(i)\n indexes.append(i+1)\n for i in list(set(indexes)):\n s[i]=s[i].swapcase()\n return \"\".join(s)\n \n", "from re import sub\n\ndef reverse(string):\n return sub(r'(\\w)\\1+', lambda m: m.group().swapcase(), string)", "def reverse(s):\n ss=''\n for i in range(len(s)):\n if i>0 and s[i]==s[i-1] or i<len(s)-1 and s[i]==s[i+1]:\n ss+=s[i].swapcase()\n else:\n ss+=s[i]\n return ss", "from itertools import groupby\ndef reverse(str):\n reversal=\"\"\n for k,g in groupby(str):\n l=list(g)\n if len(l)>1:reversal+=''.join(l).swapcase()\n else:reversal+=k\n return reversal"] | {"fn_name": "reverse", "inputs": [["hello world"], ["HELLO WORLD"], ["HeLlo World"], ["WWW"], ["parallel universe"], ["shhh"], ["bookkeeper"]], "outputs": [["heLLo world"], ["HEllO WORLD"], ["HeLlo World"], ["www"], ["paraLLel universe"], ["sHHH"], ["bOOKKEEper"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,689 |
def reverse(s):
|
dd1d66216738a6ae058f178f84bafbf2 | UNKNOWN | In your class, you have started lessons about "arithmetic progression". Because you are also a programmer, you have decided to write a function.
This function, arithmetic_sequence_sum(a, r, n), should return the sum of the first (n) elements of a sequence in which each element is the sum of the given integer (a), and a number of occurences of the given integer (r), based on the element's position within the sequence.
For example:
arithmetic_sequence_sum(2, 3, 5) should return 40:
```
1 2 3 4 5
a + (a+r) + (a+r+r) + (a+r+r+r) + (a+r+r+r+r)
2 + (2+3) + (2+3+3) + (2+3+3+3) + (2+3+3+3+3) = 40
``` | ["def arithmetic_sequence_sum(a, r, n):\n return n * (a + a + ( n - 1) * r) / 2 ", "def arithmetic_sequence_sum(a, r, n):\n return a * n + r * n * (n - 1) / 2;", "def arithmetic_sequence_sum(a, r, n):\n result = 0\n for i in range(n):\n result += a + i*r\n return result", "def arithmetic_sequence_sum(a, r, n):\n return sum(a + r*x for x in range(n))\n", "def arithmetic_sequence_sum(a, r, n):\n #Your code here!:)\n return n * (2 * a + (n - 1) * r) / 2", "def arithmetic_sequence_sum(a, r, n):\n b=a\n x=n-1\n while x!=0:\n a+=r\n x-=1\n return (n*(b+a))/2", "def arithmetic_sequence_sum(a, r, n):\n return int((n / 2) * (2 * a + (n - 1) * r))\n", "def arithmetic_sequence_sum(a, r, n):\n return sum(a+sum(r for _ in range(i)) for i in range(n))", "def arithmetic_sequence_sum(a, r, n):\n return (a + r * (n-1) / 2) * n", "def arithmetic_sequence_sum(a, r, n):\n return (n / 2) * (2 * a + (n - 1) * r)"] | {"fn_name": "arithmetic_sequence_sum", "inputs": [[3, 2, 20], [2, 2, 10], [1, -2, 10]], "outputs": [[440], [110], [-80]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 975 |
def arithmetic_sequence_sum(a, r, n):
|
40d0cce2555f7ec61c8299eacc5a4077 | UNKNOWN | You are the "computer expert" of a local Athletic Association (C.A.A.).
Many teams of runners come to compete. Each time you get a string of
all race results of every team who has run.
For example here is a string showing the individual results of a team of 5 runners:
` "01|15|59, 1|47|6, 01|17|20, 1|32|34, 2|3|17" `
Each part of the string is of the form: ` h|m|s `
where h, m, s (h for hour, m for minutes, s for seconds) are positive or null integer (represented as strings) with one or two digits.
There are no traps in this format.
To compare the results of the teams you are asked for giving
three statistics; **range, average and median**.
`Range` : difference between the lowest and highest values.
In {4, 6, 9, 3, 7} the lowest value is 3, and the highest is 9,
so the range is 9 − 3 = 6.
`Mean or Average` : To calculate mean, add together all of the numbers
in a set and then divide the sum by the total count of numbers.
`Median` : In statistics, the median is the number separating the higher half
of a data sample from the lower half.
The median of a finite list of numbers can be found by arranging all
the observations from lowest value to highest value and picking the middle one
(e.g., the median of {3, 3, 5, 9, 11} is 5) when there is an odd number of observations.
If there is an even number of observations, then there is no single middle value;
the median is then defined to be the mean of the two middle values
(the median of {3, 5, 6, 9} is (5 + 6) / 2 = 5.5).
Your task is to return a string giving these 3 values. For the example given above,
the string result will be
`"Range: 00|47|18 Average: 01|35|15 Median: 01|32|34"`
of the form:
`"Range: hh|mm|ss Average: hh|mm|ss Median: hh|mm|ss"`
where hh, mm, ss are integers (represented by strings) with *each 2 digits*.
*Remarks*:
1. if a result in seconds is ab.xy... it will be given **truncated** as ab.
2. if the given string is "" you will return "" | ["def stat(strg):\n\n def get_time(s):\n '''Returns the time, in seconds, represented by s.'''\n hh, mm, ss = [int(v) for v in s.split('|')]\n return hh * 3600 + mm * 60 + ss\n \n def format_time(time):\n '''Returns the given time as a string in the form \"hh|mm|ss\".'''\n hh = time // 3600\n mm = time // 60 % 60\n ss = time % 60\n return '{hh:02d}|{mm:02d}|{ss:02d}'.format(**locals())\n \n def get_range(times):\n return times[-1] - times[0]\n \n def get_average(times):\n return sum(times) // len(times)\n \n def get_median(times):\n middle = len(times) >> 1\n return (times[middle] if len(times) & 1 else\n (times[middle - 1] + times[middle]) // 2)\n \n if strg == '':\n return strg\n times = [get_time(s) for s in strg.split(', ')]\n times.sort()\n rng = format_time(get_range(times))\n avg = format_time(get_average(times))\n mdn = format_time(get_median(times))\n return 'Range: {rng} Average: {avg} Median: {mdn}'.format(**locals())", "from statistics import median, mean\n\ndef stat(s):\n if not s: return ''\n\n t = [itime(w) for w in s.split(',')]\n return 'Range: {} Average: {} Median: {}'.format(stime(max(t) - min(t)), stime(int(mean(t))), stime(int(median(t))))\n\ndef itime(w):\n return sum([int(c) * 60**i for i, c in enumerate(w.split('|')[::-1])])\n \ndef stime(n):\n return '{:02d}|{:02d}|{:02d}'.format(n // 3600, (n % 3600) // 60, n % 60)", "import numpy as np\nimport time\ndef stat(strg):\n '''\n Each part of the string is of the form: h|m|s\n Input: 01|15|59, 1|47|6, 01|17|20, 1|32|34, 2|3|17\n Output: Range: 00|47|18 Average: 01|35|15 Median: 01|32|34\n '''\n if strg == '':\n return ''\n racetimes = strg.split(',')\n secondtimes = []\n for t in racetimes:\n h, m, s = t.split('|')\n seconds = int(h) * 3600 + int(m) * 60 + int(s)\n secondtimes.append(seconds)\n\n avgs = np.mean(secondtimes)\n ranges = max(secondtimes) - min(secondtimes)\n medians = np.median(secondtimes)\n\n avg = time.strftime('%H|%M|%S',time.gmtime(avgs))\n ra = time.strftime('%H|%M|%S',time.gmtime(ranges))\n med = time.strftime('%H|%M|%S',time.gmtime(medians))\n\n\n return 'Range: {} Average: {} Median: {}'.format(ra,avg,med)\n", "from statistics import mean, median\n\ndef convert_ToInt(s):\n v = s.split('|')\n return sum(int(v[i]) * 60**(2-i) for i in range(3))\n\ndef convert_ToStr(n):\n return \"{:0>2}|{:0>2}|{:0>2}\".format(*map(int, (n//3600, n%3600 // 60, n%60)))\n\ndef stat(strg):\n if not strg: return \"\"\n \n data = list(map(convert_ToInt, strg.split(', ')))\n return \"Range: {} Average: {} Median: {}\".format(*map(convert_ToStr, [max(data)-min(data), mean(data), median(data)]))", "from statistics import mean, median\n\ndef sec2time(s):\n return \"%02d|%02d|%02d\" % ((s//3600) % 60, (s//60) % 60, s % 60)\n\ndef stat(strg):\n if not strg: return \"\"\n data = sorted([sum(int(val) * (60**(2-i)) for i, val in enumerate(t.split(\"|\"))) for t in strg.split(\", \")])\n return \"Range: %s Average: %s Median: %s\" % (sec2time(data[-1] - data[0]), sec2time(int(mean(data))), sec2time(median(data)))", "from datetime import timedelta as d\nfrom statistics import mean, median\ndef stat(s):\n if not s:return ''\n li = [sum(int(j) * k for j, k in zip(i.split(\"|\"), [3600, 60, 1])) for i in s.split(\", \")]\n A = lambda x: \"|\".join([i.zfill(2) for i in x.split(\":\")])[:8]\n return f\"Range: {A(str(d(seconds=max(li) - min(li))))} Average: {A(str(d(seconds=mean(li))))} Median: {A(str(d(seconds=median(li))))}\"", "import re\nimport statistics as st\nP = re.compile('(\\d+)\\|(\\d+)\\|(\\d+)')\ndef s_to_h(time):\n h, r = divmod(time, 3600)\n m, s = divmod(r, 60)\n return f'{str(int(h)).zfill(2)}|{str(int(m)).zfill(2)}|{str(int(s)).zfill(2)}'\n\ndef stat(strg):\n t = P.findall(strg)\n if not strg:\n return ''\n s = [int(h)*60*60+int(m)*60+int(sec) for h,m,sec in t]\n range, mean, median = max(s)-min(s), st.mean(s), st.median(s)\n return f'Range: {s_to_h(range)} Average: {s_to_h(mean)} Median: {s_to_h(median)}' ", "import statistics\n\ndef count_sec(l):\n return l[0]*3600+l[1]*60+l[2]\n\ndef t(s):\n min,sec = divmod(s,60)\n hour,min = divmod(min,60)\n return \"|\".join([str(int(i)).zfill(2) for i in (hour,min,sec)])\n \ndef stat(strg):\n if strg == \"\": return \"\"\n secs = [count_sec([int(f) for f in i.split(\"|\")]) for i in strg.split(\",\")]\n\n h_range = t(max(secs) - min(secs))\n avg = t(statistics.mean(secs)) \n med = t(statistics.median(secs))\n return f\"Range: {h_range} Average: {avg} Median: {med}\""] | {"fn_name": "stat", "inputs": [["01|15|59, 1|47|16, 01|17|20, 1|32|34, 2|17|17"], ["02|15|59, 2|47|16, 02|17|20, 2|32|34, 2|17|17, 2|22|00, 2|31|41"], ["02|15|59, 2|47|16, 02|17|20, 2|32|34, 2|32|34, 2|17|17"], ["0|15|59, 0|16|16, 0|17|20, 0|22|34, 0|19|34, 0|15|0"], ["11|15|59, 10|16|16, 12|17|20, 9|22|34, 13|19|34, 11|15|17, 11|22|00, 10|26|37, 12|17|48, 9|16|30, 12|20|14, 11|25|11"], ["1|15|59, 1|16|16, 1|17|20, 1|22|34, 1|19|34, 1|15|17, 1|22|00, 1|26|37, 1|17|48, 1|16|30, 1|20|14, 1|25|11"]], "outputs": [["Range: 01|01|18 Average: 01|38|05 Median: 01|32|34"], ["Range: 00|31|17 Average: 02|26|18 Median: 02|22|00"], ["Range: 00|31|17 Average: 02|27|10 Median: 02|24|57"], ["Range: 00|07|34 Average: 00|17|47 Median: 00|16|48"], ["Range: 04|03|04 Average: 11|14|36 Median: 11|18|59"], ["Range: 00|11|20 Average: 01|19|36 Median: 01|18|41"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,829 |
def stat(strg):
|
70b60ff999ff6d05e2964a7a471935a0 | UNKNOWN | If you have completed the Tribonacci sequence kata, you would know by now that mister Fibonacci has at least a bigger brother. If not, give it a quick look to get how things work.
Well, time to expand the family a little more: think of a Quadribonacci starting with a signature of 4 elements and each following element is the sum of the 4 previous, a Pentabonacci (well *Cinquebonacci* would probably sound a bit more italian, but it would also sound really awful) with a signature of 5 elements and each following element is the sum of the 5 previous, and so on.
Well, guess what? You have to build a Xbonacci function that takes a **signature** of X elements *- and remember each next element is the sum of the last X elements -* and returns the first **n** elements of the so seeded sequence.
```
xbonacci {1,1,1,1} 10 = {1,1,1,1,4,7,13,25,49,94}
xbonacci {0,0,0,0,1} 10 = {0,0,0,0,1,1,2,4,8,16}
xbonacci {1,0,0,0,0,0,1} 10 = {1,0,0,0,0,0,1,2,3,6}
xbonacci {1,1} produces the Fibonacci sequence
``` | ["def Xbonacci(signature,n):\n output, x = signature[:n], len(signature)\n while len(output) < n:\n output.append(sum(output[-x:]))\n return output", "def Xbonacci(signature,n):\n length = len(signature)\n while len(signature) < n:\n signature.append(sum(signature[-length:]))\n return signature[:n]", "def Xbonacci(sig, n):\n res = sig[:n]\n for i in range(n - len(sig)): res.append(sum(res[-len(sig):]))\n return res", "def Xbonacci(signature,n):\n l = len(signature)\n\n for i in range(l, n):\n signature += [sum(signature[i-l:i])]\n return signature[:n]", "def Xbonacci(signature,n):\n l = len(signature);\n for i in range(n - l):\n signature.append(sum(signature[-l:]));\n return signature[:n];", "def Xbonacci(signature, n):\n result = []\n for i in range(n):\n signature.append(sum(signature))\n result.append(signature.pop(0))\n return result", "def Xbonacci(signature,n):\n length=len(signature)\n for i in range(n-len(signature)):\n signature.append(sum(signature[-length:]))\n return signature[:n]", "def Xbonacci(signature,n):\n sig = len(signature)\n if sig > n:\n return signature[:n]\n xbon = signature \n for i in range(sig, n):\n xbon.append(sum(xbon[i-sig:]))\n return xbon", "def Xbonacci(signature, n):\n length = len(signature)\n [signature.append(sum(signature[-length:])) for i in range(length, n)]\n return signature[:n]", "def Xbonacci(s,n):\n if n<len(s):\n return s[:n]\n x=len(s)\n for i in range(n-len(s)):\n s.append(sum(s[-x:]))\n return s", "def Xbonacci(sequence, n):\n i = 0\n while len(sequence) < n:\n sequence.append(sum(sequence[i:]))\n i+=1\n return sequence[:n]", "def Xbonacci(signature,n):\n x = len(signature)\n res = signature[:n]\n \n for i in range(n - x):\n res.append(sum(res[-x:]))\n \n return res", "def Xbonacci(signature,n):\n l = len(signature)\n t = signature\n i=l\n while i<n:\n t.append(sum(t[i-l:i]))\n i+=1\n return t[:n]", "def Xbonacci(signature,n):\n x = len(signature)\n for _ in range(n-x):\n signature.append( sum(signature[-x:]) )\n return signature[:n]", "def Xbonacci(signature,n):\n def gen_bonacci(signature):\n yield from signature\n from collections import deque\n signature = deque(signature)\n while 1:\n signature.append(sum(signature))\n signature.popleft()\n yield signature[-1]\n from itertools import islice\n return [i for i in islice(gen_bonacci(signature), n)]\n\n", "def Xbonacci(signature,n):\n l = len(signature)\n for i in range(n-l):\n signature.append(sum(signature[-l:]))\n return signature if n > l else signature[:n]", "def Xbonacci(signature,n):\n seq = signature[:n]\n for i in range(n - len(signature)):\n seq.append(sum(seq[-len(signature):]))\n return seq\n #your code here\n", "def Xbonacci(signature,n):\n size = len(signature)\n while len(signature) < n:\n signature.append(sum(signature[-size:]))\n return signature[:n]", "def Xbonacci(signature,n):\n sequence = signature[:]\n for i in range(len(signature), n):\n sequence.append(sum(sequence[i-len(signature):i]))\n return sequence[:n]", "def Xbonacci(signature,n): \n x = len(signature) \n for i in range(n-x):\n signature.append(sum(signature[-x:]))\n arr = signature[:n]\n return arr"] | {"fn_name": "Xbonacci", "inputs": [[[0, 1], 10], [[1, 1], 10], [[0, 0, 0, 0, 1], 10], [[1, 0, 0, 0, 0, 0, 1], 10], [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], 20], [[0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0], 10], [[0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0], 20], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 20], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 9], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 0]], "outputs": [[[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]], [[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]], [[0, 0, 0, 0, 1, 1, 2, 4, 8, 16]], [[1, 0, 0, 0, 0, 0, 1, 2, 3, 6]], [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 4, 8, 16, 32, 64, 128, 256]], [[0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [[0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.5, 1, 2, 4, 8, 16, 32, 64, 128]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,569 |
def Xbonacci(signature,n):
|
4f73a88930bdb76fe5c2114bde9612eb | UNKNOWN | If you like Taco Bell, you will be familiar with their signature doritos locos taco. They're very good.
Why can't everything be a taco? We're going to attempt that here, turning every word we find into the taco bell recipe with each ingredient.
We want to input a word as a string, and return a list representing that word as a taco.
***Key***
all vowels (except 'y') = beef
t = tomato
l = lettuce
c = cheese
g = guacamole
s = salsa
***NOTE***
We do not care about case here. 'S' is therefore equivalent to 's' in our taco.
Ignore all other letters; we don't want our taco uneccesarily clustered or else it will be too difficult to eat.
Note that no matter what ingredients are passed, our taco will always have a shell. | ["import re\n\nTACODICT = {\n 't':'tomato', \n 'l':'lettuce',\n 'c':'cheese',\n 'g':'guacamole',\n 's':'salsa'\n }\n\ndef tacofy(word):\n return ['shell'] + [TACODICT.get(c, 'beef') for c in re.sub('[^aeioutlcgs]+' ,'', word.lower())] + ['shell']", "def tacofy(word):\n tacos = {\"a\": \"beef\", \"e\": \"beef\", \"i\": \"beef\", \"o\": \"beef\", \"u\": \"beef\", \"t\": \"tomato\", \"l\": \"lettuce\", \"c\": \"cheese\", \"g\": \"guacamole\", \"s\": \"salsa\"}\n return [\"shell\"] + [tacos[c.lower()] for c in word if c.lower() in tacos] + [\"shell\"]\n", "def tacofy(word):\n ingred = {\n 'a':'beef', 'u':'beef', 'i':'beef', 'o':'beef', 'e':'beef',\n 't':'tomato', 'c':'cheese', 'l':'lettuce', 'g':'guacamole', 's':'salsa'\n }\n return ['shell'] + [ingred[c] for c in word.lower() if c in ingred] + ['shell']", "def tacofy(word):\n d = {'t':'tomato', 'l':'lettuce', 'c':'cheese', 'g':'guacamole', 's':'salsa'}\n return ['shell'] + [d.get(i, 'beef') for i in word.lower() if i in 'aeioutlcgs'] + ['shell']", "def tacofy(word):\n d = {'a': 'beef', 'e': 'beef', 'i': 'beef', 'o': 'beef', 'u': 'beef', \n 't': 'tomato', 'l': 'lettuce', 'c': 'cheese', 'g': 'guacamole', 's': 'salsa'}\n return ['shell'] + [d[i] for i in word.lower() if i in d] + ['shell']", "DCT = {'t': 'tomato', 'l': 'lettuce', 'c': 'cheese', 'g': 'guacamole', 's': 'salsa'}\nDCT.update({c:'beef' for c in \"aeiuo\"})\n\ndef tacofy(word):\n return ['shell'] + [DCT[c] for c in word.lower() if c in DCT] + ['shell']", "dict = {'a':'beef', \n 'e':'beef',\n 'i':'beef', \n 'o':'beef', \n 'u':'beef', \n 't':'tomato', \n 'l':'lettuce', \n 'c':'cheese', \n 'g':'guacamole', \n 's':'salsa'}\n \ndef tacofy(word):\n # Start with the shell\n outlist = ['shell']\n # Don't forget we're case insensitive!\n for c in word.lower():\n # Is this letter one of the taco ones? Find its ingredient!\n if c in dict: # Python 3.0 doesn't have dictionary.has_key()\n outlist.append(dict.get(c))\n # Don't forget the final shell wrapper!\n outlist.append('shell')\n return outlist", "def tacofy(word):\n word = [i if i.lower() in 'tlcgs' else 'a' if i.lower() in 'aeiou' else '' for i in word ]\n d = {'a': 'beef', 't': 'tomato', 'l': 'lettuce', 'c': 'cheese', 'g': 'guacamole', 's': 'salsa'}\n return ['shell'] + [d[i.lower()] for i in word if i] + ['shell']", "ing = {\"t\": \"tomato\", \"l\": \"lettuce\", \"c\": \"cheese\", \"g\": \"guacamole\", \"s\": \"salsa\", \"a\": \"beef\", \"|\": \"shell\"}\n\ndef tacofy(word):\n return [ing[c] for c in \"|{}|\".format(\"\".join(c if c in \"tlcgs\" else \"a\" if c in \"aeiou\" else \"\" for c in word.lower()))]", "t=dict(zip('.tlcgsaeiou','shell tomato lettuce cheese guacamole salsa'.split()+['beef']*5))\ntacofy=lambda s:[t[c]for c in'.%s.'%s.lower()if c in t]"] | {"fn_name": "tacofy", "inputs": [[""], ["a"], ["ogl"], ["alel"], ["MaXwElL"], ["ggg"], ["Alex is Super Cool"], ["ydjkpwqrzto"], ["abtlcgs"]], "outputs": [[["shell", "shell"]], [["shell", "beef", "shell"]], [["shell", "beef", "guacamole", "lettuce", "shell"]], [["shell", "beef", "lettuce", "beef", "lettuce", "shell"]], [["shell", "beef", "beef", "lettuce", "lettuce", "shell"]], [["shell", "guacamole", "guacamole", "guacamole", "shell"]], [["shell", "beef", "lettuce", "beef", "beef", "salsa", "salsa", "beef", "beef", "cheese", "beef", "beef", "lettuce", "shell"]], [["shell", "tomato", "beef", "shell"]], [["shell", "beef", "tomato", "lettuce", "cheese", "guacamole", "salsa", "shell"]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,013 |
def tacofy(word):
|
d8771266bc1553126c90c1a0397f6148 | UNKNOWN | You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return `-1`.
__For example:__
Let's say you are given the array `{1,2,3,4,3,2,1}`:
Your function will return the index `3`, because at the 3rd position of the array, the sum of left side of the index (`{1,2,3}`) and the sum of the right side of the index (`{3,2,1}`) both equal `6`.
Let's look at another one.
You are given the array `{1,100,50,-51,1,1}`:
Your function will return the index `1`, because at the 1st position of the array, the sum of left side of the index (`{1}`) and the sum of the right side of the index (`{50,-51,1,1}`) both equal `1`.
Last one:
You are given the array `{20,10,-80,10,10,15,35}`
At index 0 the left side is `{}`
The right side is `{10,-80,10,10,15,35}`
They both are equal to `0` when added. (Empty arrays are equal to 0 in this problem)
Index 0 is the place where the left side and right side are equal.
Note: Please remember that in most programming/scripting languages the index of an array starts at 0.
__Input:__
An integer array of length `0 < arr < 1000`. The numbers in the array can be any integer positive or negative.
__Output:__
The lowest index `N` where the side to the left of `N` is equal to the side to the right of `N`. If you do not find an index that fits these rules, then you will return `-1`.
__Note:__
If you are given an array with multiple answers, return the lowest correct index. | ["def find_even_index(arr):\n for i in range(len(arr)):\n if sum(arr[:i]) == sum(arr[i+1:]):\n return i\n return -1\n", "def find_even_index(lst):\n left_sum = 0\n right_sum = sum(lst)\n for i, a in enumerate(lst):\n right_sum -= a\n if left_sum == right_sum:\n return i\n left_sum += a\n return -1\n", "def find_even_index(lst):\n left_sum = 0\n right_sum = sum(lst)\n for i, a in enumerate(lst):\n right_sum -= a\n if left_sum == right_sum:\n result = i\n break\n left_sum += a\n else:\n result = -1\n return result\n", "def find_even_index(arr):\n left, right = 0, sum(arr)\n for i, e in enumerate(arr):\n right -= e\n if left == right:\n return i\n left += e\n return -1", "def find_even_index(arr):\n for i in range(len(arr)):\n if sum(arr[i:]) == sum(arr[:i+1]):\n return i\n return -1", "def find_even_index(arr):\n r = [i for i in range(len(arr)) if sum(arr[0:i]) == sum(arr[i+1:])]\n return r[0] if r else -1", "def find_even_index(arr):\n right = sum(arr)\n left = 0\n for i,x in enumerate(arr):\n right-=x\n if right==left:\n return i\n left+=x\n return -1", "def find_even_index(arr):\n left_sum, right_sum = 0, sum(arr)\n\n for i, n in enumerate(arr):\n right_sum -= n\n if left_sum == right_sum:\n return i\n left_sum += n\n\n return -1\n", "find_even_index = lambda arr: next((i for i, __ in enumerate(arr) if sum(arr[:i]) == sum(arr[i+1:])), -1)", "def find_even_index(arr):\n def partial_sum(arr):\n total = 0\n for i in arr:\n total += i\n yield total\n\n sums = list(partial_sum(arr))\n\n def sumleft(i):\n if i != 0:\n return sums[i-1]\n else:\n return 0\n\n def sumright(i):\n return sums[len(sums) - 1] - sums[i]\n\n for i in range(len(arr)):\n sl = sumleft(i)\n sr = sumright(i)\n if sl == sr:\n return i\n return -1", "def find_even_index(arr):\n left, right = 0,sum(arr)\n for i,v in enumerate(arr):\n right -= v\n if left == right: return i\n left += v\n return -1"] | {"fn_name": "find_even_index", "inputs": [[[1, 2, 3, 4, 3, 2, 1]], [[1, 100, 50, -51, 1, 1]], [[1, 2, 3, 4, 5, 6]], [[20, 10, 30, 10, 10, 15, 35]], [[20, 10, -80, 10, 10, 15, 35]], [[10, -80, 10, 10, 15, 35, 20]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]], [[0, 0, 0, 0, 0]], [[-1, -2, -3, -4, -3, -2, -1]], [[-100, -99, -98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -85, -84, -83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73, -72, -71, -70, -69, -68, -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54, -53, -52, -51, -50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2]], [[8, 8]], [[8, 0]], [[0, 8]], [[7, 3, -3]], [[8]], [[10, -10]], [[-3, 2, 1, 0]], [[-15, 5, 11, 17, 19, -17, 20, -6, 17, -17, 19, 16, -15, -6, 20, 17]]], "outputs": [[3], [1], [-1], [3], [0], [6], [-1], [0], [3], [-1], [-1], [0], [1], [0], [0], [-1], [3], [8]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,339 |
def find_even_index(arr):
|
2db875cc0ada5533652756cc1a55b357 | UNKNOWN | We need to write some code to return the original price of a product, the return type must be of type decimal and the number must be rounded to two decimal places.
We will be given the sale price (discounted price), and the sale percentage, our job is to figure out the original price.
### For example:
Given an item at $75 sale price after applying a 25% discount, the function should return the original price of that item before applying the sale percentage, which is ($100.00) of course, rounded to two decimal places.
DiscoverOriginalPrice(75, 25) => 100.00M where 75 is the sale price (discounted price), 25 is the sale percentage and 100 is the original price | ["def discover_original_price(discounted_price, sale_percentage):\n return round(discounted_price / ((100 - sale_percentage) * 0.01), 2)\n", "def discover_original_price(discounted_price, sale_percentage):\n #your code here\n return round(discounted_price / (1 - (sale_percentage / 100.00)), 2)", "def discover_original_price(discounted_price, sale_percentage):\n return round(discounted_price/(1-sale_percentage/100),2)", "def discover_original_price(discounted_price, sale_percentage):\n #your code here\n return round( discounted_price / (1 - sale_percentage/100.) , 2 )\n", "discover_original_price=lambda p,d : round(p*100/(100-d),2)", "def discover_original_price(n, p):\n return round(n * 100 / (100 - p), 2)", "def discover_original_price(discounted_price, sale_percentage):\n return float(\"{0: .2f}\".format(((discounted_price / (100 - sale_percentage)) * 100)))", "def discover_original_price(discounted_price, sale_percentage):\n if sale_percentage < 100:\n return round(discounted_price*100/(100-sale_percentage),2)", "def discover_original_price(price, perc):\n return float('{:0.2f}'.format(price/(1-perc/100)))", "def discover_original_price(discounted_price, sale_percentage):\n return round(100*discounted_price/(100-sale_percentage),2)"] | {"fn_name": "discover_original_price", "inputs": [[75, 25], [25, 75], [75.75, 25], [373.85, 11.2], [458.2, 17.13]], "outputs": [[100], [100], [101], [421], [552.91]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,296 |
def discover_original_price(discounted_price, sale_percentage):
|
30db26d2eff5976cf63a3ccdcf4a0e43 | UNKNOWN | Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.
Examples:
spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw"
spinWords( "This is a test") => returns "This is a test"
spinWords( "This is another test" )=> returns "This is rehtona test" | ["def spin_words(sentence):\n # Your code goes here\n return \" \".join([x[::-1] if len(x) >= 5 else x for x in sentence.split(\" \")])", "def spin_words(sentence):\n words = [word for word in sentence.split(\" \")]\n words = [word if len(word) < 5 else word[::-1] for word in words]\n return \" \".join(words)\n", "def spin_words(sentence):\n return ' '.join(word if len(word)<5 else word[::-1] for word in sentence.split())", "def spin_words(sentence):\n L = sentence.split()\n new = []\n for word in L:\n if len(word) >= 5:\n new.append(word[::-1])\n else:\n new.append(word)\n string = \" \".join(new)\n return string\n", "def spin_words(sentence):\n words = sentence.split()\n output = []\n delimiter = \" \"\n for word in words:\n if len(word) >= 5:\n output.append(reverse(word))\n else:\n output.append(word)\n return delimiter.join(output)\n \ndef reverse(string):\n return string[::-1]", "import re\n\ndef spin_words(sentence):\n # Your code goes here\n return re.sub(r\"\\w{5,}\", lambda w: w.group(0)[::-1], sentence)\n", "def spin_words(sentence):\n return \" \".join(x[::-1] if len(x) >= 5 else x for x in sentence.split())", "def spin_words(sentence):\n output = []\n for word in sentence.split(' '):\n if len(word) > 4:\n word = word[::-1]\n output.append(word)\n return ' '.join(output)", "spin_words = lambda s: ' '.join([\nlen(w) > 4 and w[::-1] or w\nfor w in s.split()\n])", "def spin_words(sentence):\n return ' '.join([i if len(i) < 5 else i[::-1] for i in sentence.split()])"] | {"fn_name": "spin_words", "inputs": [["Welcome"], ["to"], ["CodeWars"], ["Hey fellow warriors"], ["This sentence is a sentence"]], "outputs": [["emocleW"], ["to"], ["sraWedoC"], ["Hey wollef sroirraw"], ["This ecnetnes is a ecnetnes"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,672 |
def spin_words(sentence):
|
1f21d6bfc08f331130f3ae0847951fa7 | UNKNOWN | ## The galactic games have begun!
It's the galactic games! Beings of all worlds come together to compete in several interesting sports, like nroogring, fredling and buzzing (the beefolks love the last one). However, there's also the traditional marathon run.
Unfortunately, there have been cheaters in the last years, and the committee decided to place sensors on the track. Committees being committees, they've come up with the following rule:
> A sensor should be placed every 3 and 5 meters from the start, e.g.
> at 3m, 5m, 6m, 9m, 10m, 12m, 15m, 18m….
Since you're responsible for the track, you need to buy those sensors. Even worse, you don't know how long the track will be! And since there might be more than a single track, and you can't be bothered to do all of this by hand, you decide to write a program instead.
## Task
Return the sum of the multiples of 3 and 5 __below__ a number. Being the _galactic_ games, the tracks can get rather large, so your solution should work for _really_ large numbers (greater than 1,000,000).
### Examples
```python
solution (10) # => 23 = 3 + 5 + 6 + 9
solution (20) # => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18
``` | ["def summ(number, d):\n n = (number - 1) // d\n return n * (n + 1) * d // 2\n\ndef solution(number):\n return summ(number, 3) + summ(number, 5) - summ(number, 15)\n", "def solution(number):\n a = (number - 1) // 5\n b = (number - 1) // 3\n c = (number - 1) // 15\n \n sum_a = ((a * (a + 1)) // 2) * 5\n sum_b = ((b * (b + 1)) // 2) * 3\n sum_c = ((c * (c + 1)) // 2) * 15\n \n return sum_a + sum_b - sum_c", "def solution(n):\n return sum(f * c * (c + 1) for f, c in ((f, (n - 1) // abs(f)) for f in (3, 5, -15))) // 2\n", "val = lambda x: x*(x+1)>>1\n\ndef solution(number):\n res1 = 3 * val((number-1) // 3)\n res2 = 5 * val((number-1) // 5)\n res3 = 15 * val((number-1) // 15)\n return res1 + res2 - res3", "A = lambda x,n: x * (((n-1) // x) * ((n-1) // x + 1)) // 2\nsolution=lambda n:A(3,n) + A(5,n) - A(15,n)", "def f(a, x):\n n = x // a\n return n * a * (n + 1) // 2\n\ndef solution(n):\n return f(3, n-1) + f(5, n-1) - f(15, n-1)"] | {"fn_name": "solution", "inputs": [[10], [100], [1000], [10000], [16], [20], [200], [1000000], [50000000], [50000000000000000000000000000000000000000]], "outputs": [[23], [2318], [233168], [23331668], [60], [78], [9168], [233333166668], [583333291666668], [583333333333333333333333333333333333333291666666666666666666666666666666666666668]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,004 |
def solution(number):
|
d22e9f8c8ac12e3652b01d6d2d86f3ec | UNKNOWN | This function takes two numbers as parameters, the first number being the coefficient, and the second number being the exponent.
Your function should multiply the two numbers, and then subtract 1 from the exponent. Then, it has to print out an expression (like 28x^7). `"^1"` should not be truncated when exponent = 2.
For example:
```
derive(7, 8)
```
In this case, the function should multiply 7 and 8, and then subtract 1 from 8. It should output `"56x^7"`, the first number 56 being the product of the two numbers, and the second number being the exponent minus 1.
```
derive(7, 8) --> this should output "56x^7"
derive(5, 9) --> this should output "45x^8"
```
**Notes:**
* The output of this function should be a string
* The exponent will never be 1, and neither number will ever be 0 | ["def derive(coefficient, exponent): \n return f'{coefficient * exponent}x^{exponent - 1}'", "def derive(coefficient, exponent): \n a=coefficient*exponent\n b=exponent-1\n txt=\"{}x^{}\"\n return txt.format(a,b)", "def derive(coefficient, exponent): \n return(\"{}x^{}\".format(coefficient*exponent, exponent-1))", "derive = lambda c,e:str(c*e)+\"x^\"+str(e-1)\n", "def derive(coeff, exp): \n return f\"{coeff * exp}x^{exp - 1}\"", "def derive(coef, exp):\n if exp <= 2 : exp = 3\n return str(coef * exp) + \"x^\" + str(exp-1)", "def derive(coefficient, exponent): \n return str(exponent*coefficient)+'x^'+str(exponent-1)\n # your code here\n pass", "def derive(c, e): \n if e <= 2: e = 3\n return f\"{c * e}x^{e - 1}\"", "def derive(coef, exp): \n return f'{coef*exp}x^{exp-1}'", "def derive(coefficient, exponent): \n # your code here\n return \"{0}x^{1}\".format(coefficient*exponent, exponent-1)", "derive = lambda coefficient, exponent: f'{coefficient*exponent}x^{exponent-1}'", "derive=lambda x,y:f\"{y*x}x^{~-y}\"", "def derive(coeff, exponent): \n return f\"{coeff * exponent}x^{exponent-1}\"", "def derive(coefficient: int, exponent: int) -> str:\n \"\"\" Multiply the two numbers and then subtract 1 from the exponent. \"\"\"\n return f\"{coefficient * exponent}x^{exponent - 1}\" if exponent > 2 else f\"^{exponent - 1}\"", "def derive(coefficient, exponent): \n coeff = coefficient * exponent\n return str(coeff) + \"x^\" + str(exponent - 1)", "def derive(coefficient, exponent): \n coefficient2= coefficient*exponent\n exponent2= exponent-1\n ans =\"\" + str(coefficient2) + \"x^\" + str(exponent2)\n return ans", "def derive(coefficient, exponent): \n # your code here\n # your code here\n a = coefficient*exponent\n b = exponent - 1\n return(str(a)+\"x^\"+str(b))\n", "def derive(coefficient, exponent):\n if ((exponent != 1) and (coefficient != 0) and (exponent != 0)):\n product = coefficient * exponent\n new_exponent = exponent - 1\n return str(product) + \"x^\" + str(new_exponent)\n else:\n pass", "def derive(coefficient, exponent): \n if exponent >= 2 and coefficient * exponent != 0:\n return str(coefficient * exponent) + 'x^' + str(exponent - 1) ", "def derive(coefficient, exponent): \n value = coefficient * exponent\n ans = exponent - 1\n res = str(value) +\"x^\"+ str(ans)\n return res", "def derive(coefficient, exponent): \n return\"{}x^{}\".format(str(coefficient*exponent),str(exponent-1))", "def derive(coefficient, exponent): \n n = coefficient * exponent\n expo = exponent - 1\n return(str(n)+\"x^\"+str(expo))", "def derive(c, e): \n ans = c * e\n power = e-1\n return f'{ans}x^{power}'", "def derive(coefficient, exponent): \n new_exponent = str(exponent - 1)\n return str(coefficient * exponent) + 'x^' + new_exponent", "def derive(c, e): \n return f\"{c*e}x^{e-1}\"", "derive=lambda c,e:\"{}x^{}\".format((c*e),(e - 1))\n", "def derive(coefficient, exponent): \n sum=(coefficient * exponent)\n exponent=exponent-1\n return f'{sum}x^{exponent}'", "def derive(coefficient, exponent): \n result = coefficient * exponent\n output = exponent - 1\n return str(f'{result}x^{output}')", "def derive(coefficient, exponent): \n if exponent == 2:\n return str(coefficient * exponent) + \"x^2\"\n else: \n return str(coefficient * exponent) + \"x^\" + str(exponent - 1)", "def derive(coefficient, exponent):\n new_coefficient = coefficient*exponent\n new_exponent = exponent-1\n ans = str(new_coefficient)+\"x^\" + str(new_exponent)\n return ans\n", "def derive(coefficient, exponent): \n new_coeff = coefficient * exponent\n new_exp = exponent - 1\n expression = f\"{new_coeff}x^{new_exp}\"\n return expression", "def derive(cof, exp): \n return '{}x^{}'.format(cof * exp, exp - 1)", "def derive(coefficient, exponent): \n x = coefficient*exponent\n y = exponent-1\n z = str(x) + \"x^\" + str(y)\n return z\n", "def derive(coefficient, exponent):\n if exponent == 2:\n mult = coefficient*exponent\n mult = str(mult)\n return mult+\"x\"\n else:\n multiply = coefficient*exponent\n n = exponent - 1\n n = str(n)\n multiply = str(multiply)\n return multiply+\"x\"+\"^\"+n", "def derive(coefficient, exponent): \n return ''.join(str(int(coefficient * exponent)) + 'x^' + str(int(exponent) - 1))", "def derive(coefficient, exponent): \n return f'{coefficient * exponent}x^{exponent - 1}' if exponent > 1 else f'{coefficient * exponent}x'", "def derive(coefficient, exponent): \n # your code here\n dv = coefficient * exponent\n ex = exponent - 1\n return str(dv) + \"x^\" + str(ex)", "def derive(coefficient, exponent): \n \n # your code here\n\n result = coefficient * exponent\n re=exponent-1\n return \"{}x^{}\".format(result,re)", "def derive(coeff, expo): \n num = coeff*expo\n expo -=1\n if expo <= 2:\n return string(num)\n else:\n return str(num)+\"x^\"+str(expo)", "def derive(coefficient, exponent): \n sub=exponent-1\n multi=coefficient*exponent\n \n coffie=str(sub)\n ex=str(multi)\n \n \n result=ex+'x^'+coffie\n return result ", "def derive(coefficient, exponent): \n result = coefficient*exponent\n exponent1 = exponent - 1\n return f'{result}x^{exponent1}'", "def derive(coefficient, exponent): \n first_num = coefficient * exponent\n second_num = exponent - 1\n return f'{first_num}x^{second_num}'", "def derive(coefficient, exponent):\n result = coefficient * exponent\n exponent_new = exponent - 1\n result = str(result)\n exponent_new = str(exponent_new)\n return result + \"x^\" + exponent_new", "def derive(coefficient, exponent): \n mult = coefficient * exponent\n exponent -= 1\n return str(mult) + 'x^' + str(exponent)\n", "def derive(coefficient, exponent): \n product = coefficient*exponent\n exponent = exponent -1\n return'{}x^{}'.format(product,exponent)", "def derive(coefficient, exponent): \n new_coeff = coefficient * exponent\n new_expo = exponent -1\n return str(new_coeff) + \"x^\" + str(new_expo)", "def derive(coefficient, exponent): \n result = \"\"\n product = coefficient*exponent\n exponent = exponent -1\n result = str(product) + \"x^\" + str(exponent)\n # your code here\n return result\n pass", "def derive(coefficient, exponent): \n answer=str(coefficient*exponent)+'x^'+str(exponent-1)\n return(answer)", "def derive(c, e): \n num = c * e\n pow = e-1\n return str(num)+ \"x^\"+ str(pow)", "def derive(coefficient, exponent): \n # your code her\n return \"{}x^{}\".format(coefficient*exponent,exponent-1)", "def derive(coefficient,\n exponent): \n\n new_coeff = coefficient * exponent\n result = \"%dx^%d\"\n new_exp = exponent - 1\n\n return result % (new_coeff,\n new_exp)\n", "def derive(coefficient, exponent): \n # your code here\n firstnum = coefficient * exponent\n secondnum = exponent-1\n return (str(firstnum)+'x^'+str(secondnum))", "def derive(coefficient, exponent): \n s1 = str(coefficient * exponent)\n s2 = str(exponent - 1)\n return s1 + \"x^\" + s2 \n", "def derive(coefficient, exponent): \n a = coefficient\n b = exponent\n c = a * b\n return str(c)+ 'x^' + str(b - 1)\n", "def derive(coefficient, exponent): \n coEx = coefficient * exponent\n expoMinus = exponent-1\n\n return str(coEx) + \"x^\" + str(expoMinus)", "derive= lambda i,j : f'{i*j}x^{j-1}'", "derive= lambda i,j : str(i*j) + \"x^\" + str(j-1)", "def derive(a, b): \n return f'{int(a)*int(b)}x^{(int(b)- 1)}'", "def derive(coefficient, exponent): \n coe = (coefficient * exponent)\n exp = (exponent -1)\n d = f'{coe}x^{exp}'\n return d", "def derive(coefficient, exponent): \n result = coefficient * exponent\n print(result)\n return str(result) + \"x^\" + str(exponent-1)", "def derive(coefficient, exponent): \n product=(coefficient*exponent)\n ex_new=exponent-1\n return f\"{product}x^{ex_new}\"\n", "def derive(coefficient, exponent): \n return \"{}x^{}\".format(str(coefficient*exponent), exponent-1) if exponent>2 else str(coefficient*exponent)+\"x\"", "def derive(coefficient, exponent):\n a = coefficient*exponent\n b = abs(1 - exponent)\n return f\"{a}x^{b}\"", "def derive(coefficient, exponent): \n x = []\n y = str(coefficient*exponent)\n x.append(y)\n x.append(\"x\")\n x.append(\"^\")\n z = str(exponent-1)\n x.append(z)\n return ''.join(x)", "def derive(c, e):\n if e > 2 :\n code = e-1\n else:\n code = e\n return str(c*e) + \"x^\" + str(code)", "def derive(c, e): \n r1=c*e\n r2=e-1\n return str(r1)+\"x^\"+str(r2)", "def derive(coefficient, exponent):\n mul = coefficient * exponent\n sub = exponent -1\n return F\"{mul}x^{sub}\"", "def derive(coefficient, exponent): \n if exponent > 2:\n string = str(coefficient * exponent) + \"x^\" + str(exponent - 1)\n return string\n else:\n string = str(coefficient * exponent) + \"x\"\n return string", "def derive(coefficient, exponent): \n prod = coefficient * exponent\n exp = exponent - 1\n return \"{}x^{}\".format(prod, exp)", "def derive(coefficient, exponent): \n base = str(coefficient*exponent)\n exp = str(exponent-1)\n return (\"%sx^%s\" % (base, exp))", "def derive(coefficient, exponent): \n return f'{coefficient*exponent}x' if exponent == 2 else f'{coefficient*exponent}x^{exponent-1}'", "def derive(coefficient, exponent): \n # your code here\n product = coefficient * exponent\n result_from_subtract = exponent - 1\n \n result = str(product) + \"x\" + \"^\" + str(result_from_subtract)\n return result\n", "def derive(coefficient, exponent): \n result = coefficient * exponent \n exponent -= 1\n return str(result) + 'x' + '^' + str(exponent)", "def derive(coefficient, exponent): \n a = str(coefficient * exponent)\n b = str(exponent - 1)\n return(f'{a}x^{b}')", "def derive(coefficient,exponent): #coefficient x ^ exponent \n #should return the derivative\n new_coefficient = coefficient*exponent \n new_exponent = exponent-1\n result = str(new_coefficient) + 'x^' + str(new_exponent)\n return result", "def derive(a, b): \n res = a * b\n return f'{res}x^{b-1}'", "def derive(coefficient, exponent): \n # your code here\n answer = coefficient * exponent\n exponent -= 1\n\n return \"{}x^{}\".format(answer, exponent)\n\n\n", "def derive(coefficient, exponent):\n derivitave = str(coefficient * exponent) + \"x^\" + str(exponent-1)\n return derivitave", "def derive(coefficient, exponent): \n coeff_der = coefficient * exponent\n exp_der = exponent - 1\n return \"{}x^{}\".format(coeff_der, exp_der)", "def derive(a, b): \n x = a*b\n y = b-1\n return f'{x}x^{y}'", "def derive(c, e):\n p1,p2 = c * e, e - 1\n return f\"{p1}x^{p2}\"", "def derive(coefficient, exponent): \n x=str(coefficient*exponent)\n return f'{x}x^{exponent-1}'", "def derive(coefficient, exponent):\n c=coefficient*exponent\n s=str(c)+\"x^\"+str(exponent-1)\n\n return(s)\n pass", "def derive(a, b):\n a = a*b \n b = b-1 \n return str(a) + 'x^' + str(b)\n", "def derive(coefficient, exponent): \n product = coefficient * exponent\n x = exponent - 1\n return str(product) + \"x^\" + str(x)", "def derive(coefficient, exponent): \n lololololo = coefficient * exponent\n hehe = exponent - 1\n print(\"\\\\U0001f600\")\n print(\"\\\\U0001F923\") \n return str(lololololo) + 'x' + '^' + str(hehe)\n", "def derive(coefficient, exponent): \n poo = coefficient * exponent\n return f\"{poo}x^{int(exponent-1)}\"\n", "def derive(coefficient, exponent): \n square = coefficient * exponent \n return f\"{square}x^{int(exponent-1)}\"", "def derive(coefficient, exponent): \n if exponent > 1:\n x = str(coefficient * exponent)\n y = str(exponent - 1)\n \n return str(x + \"x^\" + y)", "def derive(coefficient, exponent): \n a = coefficient\n b = exponent\n return str(a * b) + 'x^' + str(b - 1)", "def derive(coefficient, exponent): \n a = [str((coefficient * exponent)), str((exponent - 1))]\n\n return (a[0] + \"x^\" + a[1])", "def derive(coefficient, exponent): \n coeff = coefficient * exponent\n exp = exponent - 1\n return f'{coeff}x^{exp}'", "def derive(coefficient, exponent): \n \n product = coefficient * exponent\n \n return f\"{product}x^{exponent - 1}\"", "def derive(co, ex): \n mult= co*ex\n dif=ex-1\n return str(mult)+\"x^\"+str(dif)", "def derive(coefficient, exponent): \n \n product = coefficient*exponent\n \n str1 = \"\"\n exponent-=1\n \n str1+= str(product)+'x'+'^'+str(exponent)\n \n # your code here\n return str1", "def derive(coefficient, exponent): \n coef = str(coefficient*exponent)\n exp = str(exponent-1)\n return coef+'x^'+exp", "def derive(c, e): \n \n c = c*e\n e -= 1\n return(str(c) + \"x^\" + str(e))", "def derive(a, b): \n return \"{}x^{}\".format(a * b, b-1)", "def derive(coefficient, exponent): \n \n product = str(coefficient * exponent)\n return product + 'x^' + str(exponent-1)\n", "def derive(ar, br):\n a = ar* br\n b = br - 1\n txt = \"{}x^{}\"\n return txt.format(a, b)\n"] | {"fn_name": "derive", "inputs": [[7, 8], [5, 9]], "outputs": [["56x^7"], ["45x^8"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 13,681 |
def derive(coefficient, exponent):
|
657b8f494b59a7b6648d78c4906f1214 | UNKNOWN | Complete the method which returns the number which is most frequent in the given input array. If there is a tie for most frequent number, return the largest number among them.
Note: no empty arrays will be given.
## Examples
```
[12, 10, 8, 12, 7, 6, 4, 10, 12] --> 12
[12, 10, 8, 12, 7, 6, 4, 10, 12, 10] --> 12
[12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10] --> 3
``` | ["from collections import Counter\n\ndef highest_rank(arr):\n if arr:\n c = Counter(arr)\n m = max(c.values())\n return max(k for k,v in c.items() if v==m)", "def highest_rank(arr):\n return sorted(arr,key=lambda x: (arr.count(x),x))[-1]", "def highest_rank(arr):\n return max(sorted(arr,reverse=True), key=arr.count)", "def highest_rank(arr):\n best = 0\n occs = 0\n for item in arr:\n times = arr.count(item)\n if times > occs:\n best = item\n occs = times\n elif times == occs:\n if best < item:\n best = item\n return best", "def highest_rank(arr):\n frequent = {}\n for i in arr:\n if i not in frequent:\n frequent[i] = 0\n frequent[i] += 1\n ordered_inv = sorted(list(frequent.items()), key=lambda x: (x[1],x[0]), reverse=True)\n return ordered_inv[0][0]\n", "def highest_rank(a):\n b = set(a)\n c = 0\n for i in b:\n d = a.count(i)\n if d > c or (d == c and i > m):\n c = d\n m = i \n return m ", "from collections import Counter\n\ndef highest_rank(arr):\n return max(Counter(arr).items(), key=lambda x: [x[1], x[0]])[0]", "from collections import Counter\n\ndef highest_rank(arr):\n c = Counter(arr)\n return max(c, key=lambda x: (c[x], x))", "from collections import Counter\ndef highest_rank(arr):\n return sorted(Counter(arr).items(), key=lambda x: (x[1], x[0]))[-1][0]", "def highest_rank(arr):\n print(arr)\n freq = {}\n for num in arr:\n if num in freq:\n freq[num] += 1\n else:\n freq[num] = 1\n mx = [0,0]\n maxes = []\n for num in freq:\n if freq[num] > mx[1]:\n mx[0] = num\n mx[1] = freq[num]\n maxes = [num]\n elif freq[num] == mx[1]:\n maxes.append(num)\n\n return max(maxes)\n"] | {"fn_name": "highest_rank", "inputs": [[[12, 10, 8, 12, 7, 6, 4, 10, 12]], [[12, 10, 8, 12, 7, 6, 4, 10, 10]], [[12, 10, 8, 12, 7, 6, 4, 10, 12, 10]], [[12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10]], [[1, 2, 3]], [[1, 1, 2, 3]], [[1, 1, 2, 2, 3]]], "outputs": [[12], [10], [12], [3], [3], [1], [2]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,955 |
def highest_rank(arr):
|
d32bc2fc4c686414b91d420ed183d4ba | UNKNOWN | A happy number is a number defined by the following process: starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are **happy numbers**, while those that do not end in 1 are unhappy numbers (or sad numbers) (Wikipedia).
Write a function that takes `n` as parameter and return `true` if and only if `n` is an happy number, `false` otherwise.
## Examples
For example number `7` is happy because after a number of steps the computed sequence ends up with a 1: `7, 49, 97, 130, 10, 1 `
While `3` is not, and would give us an infinite sequence: `3, 9, 81, 65, 61, 37, 58, 89, 145, 42, 20, 4, 16, 37, 58, 89, 145, 42, 20, 4, 16, 37, ...`
Happy coding! | ["def is_happy(n):\n seen = set()\n while n!=1:\n n = sum(int(d)**2 for d in str(n))\n if n not in seen: seen.add(n)\n else: return False\n return True", "def is_happy(n):\n while n > 4:\n n = sum(int(d)**2 for d in str(n))\n return n == 1\n", "def is_happy(n):\n seen = set()\n \n while n not in seen:\n seen.add(n)\n n = sum( int(d)**2 for d in str(n) )\n \n return n == 1", "def is_happy(n):\n seen = set()\n while n > 1 and n not in seen:\n seen.add(n)\n n = sum(int(d)**2 for d in str(n))\n return n == 1", "def is_happy(n):\n seen = {n}\n while n != 1:\n n = sum(d*d for d in map(int, str(n)))\n if n in seen:\n return False\n seen.add(n)\n return True", "def is_happy(n):\n if n==1:\n return True\n nums=[]\n while n!=1:\n if n in nums:\n return False\n nums.append(n)\n n=sum(int(x)**2 for x in list(str(n)))\n if n==1:\n return True\n", "def is_happy(n):\n if len(str(n))==1:\n return n in [1 , 7]\n else:\n return is_happy(sum([int(d)*int(d) for d in str(n)]))", "def is_happy(n):\n lst = []\n while n != 1:\n n = sum(int(i)**2 for i in str(n))\n if n in lst:\n return False\n lst.append(n)\n return True\n # Good Luck!\n", "def is_happy(n):\n while n>=7:\n n = sum(int(x)**2 for x in str(n))\n return n==1"] | {"fn_name": "is_happy", "inputs": [[1], [7], [16]], "outputs": [[true], [true], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,509 |
def is_happy(n):
|
cf313df971f2b833e7581e4737b85828 | UNKNOWN | Given an array, return the difference between the count of even numbers and the count of odd numbers. `0` will be considered an even number.
```
For example:
solve([0,1,2,3]) = 0 because there are two even numbers and two odd numbers. Even - Odd = 2 - 2 = 0.
```
Let's now add two letters to the last example:
```
solve([0,1,2,3,'a','b']) = 0. Again, Even - Odd = 2 - 2 = 0. Ignore letters.
```
The input will be an array of lowercase letters and numbers only.
In some languages (Haskell, C++, and others), input will be an array of strings:
```
solve ["0","1","2","3","a","b"] = 0
```
Good luck!
If you like this Kata, please try:
[Longest vowel chain](https://www.codewars.com/kata/59c5f4e9d751df43cf000035)
[Word values](https://www.codewars.com/kata/598d91785d4ce3ec4f000018) | ["def solve(a):\n return sum(1 if v % 2 == 0 else -1 for v in a if type(v) == int)", "def solve(a):\n return sum( isinstance(x, int) and [1, -1][x % 2] for x in a )", "def solve(a):\n diff = 0\n for e in a:\n if type(e) == int:\n if e % 2:\n diff -= 1\n else:\n diff += 1\n return diff", "def solve(a):\n return sum(type(x) == int and [1, -1][x % 2] for x in a)", "def solve(a):\n lenList = len(a)\n\n evenEntries = [a[i] for i in range(0, lenList, 1 ) if str(a[i]).isdigit() and a[i]%2==0 ]\n oddEntries = [a[i] for i in range(0, lenList, 1 ) if str(a[i]).isdigit() and a[i]%2==1 ]\n\n amtEvenEntries = len(evenEntries)\n amtOddEntries = len(oddEntries)\n\n return amtEvenEntries-amtOddEntries\n#end function \n", "def solve(a):\n return sum((-1)**x for x in a if isinstance(x, int))", "def solve(a):\n return sum(1 if x % 2 == 0 else -1 for x in a if type(x)==int)", "def solve(a):\n return len([i for i in a if type(i)==int and not i%2]) - len([i for i in a if type(i)==int and i%2])", "def solve(a):\n return sum(isinstance(x, int) and (1, -1)[x % 2] for x in a)", "def solve(a):\n a = [i for i in a if isinstance(i, int)]\n return sum(1 for i in a if i%2 == 0) - sum(1 for i in a if i%2)"] | {"fn_name": "solve", "inputs": [[[0, 1, 2, 3]], [[0, 1, 2, 3, "a", "b"]], [[0, 15, "z", 16, "m", 13, 14, "c", 9, 10, 13, "u", 4, 3]], [[13, 6, 8, 15, 4, 8, 13]], [[1, "a", 17, 8, "e", 3, "i", 12, 1]], [[5, 15, 16, 10, 6, 4, 16, "t", 13, "n", 14, "k", "n", 0, "q", "d", 7, 9]]], "outputs": [[0], [0], [0], [1], [-2], [2]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,314 |
def solve(a):
|
21586cb7d761f8ec0a796c62161d10b8 | UNKNOWN | Everybody knows the classic ["half your age plus seven"](https://en.wikipedia.org/wiki/Age_disparity_in_sexual_relationships#The_.22half-your-age-plus-seven.22_rule) dating rule that a lot of people follow (including myself). It's the 'recommended' age range in which to date someone.
```minimum age <= your age <= maximum age```
#Task
Given an integer (1 <= n <= 100) representing a person's age, return their minimum and maximum age range.
This equation doesn't work when the age <= 14, so use this equation instead:
```
min = age - 0.10 * age
max = age + 0.10 * age
```
You should floor all your answers so that an integer is given instead of a float (which doesn't represent age). ```Return your answer in the form [min]-[max]```
##Examples:
```
age = 27 => 20-40
age = 5 => 4-5
age = 17 => 15-20
``` | ["def dating_range(age):\n if age <= 14:\n min = age - 0.10 * age\n max = age + 0.10 * age\n else:\n min = (age/2)+7\n max = (age-7)*2\n \n return str(int(min))+'-'+str(int(max))", "def dating_range(age):\n if age <= 14:\n return \"{}-{}\".format(int(age-0.1*age), int(age+0.1*age))\n return \"{}-{}\".format(int(age/2+7), int((age-7)*2))", "def dating_range(age):\n if age > 14:\n lo = age / 2 + 7\n hi = (age - 7) * 2\n else:\n lo = 0.9 * age\n hi = 1.1 * age\n return '%d-%d' % (lo, hi)\n", "def dating_range(age):\n if age < 15:\n return \"%d-%d\" % (.9*age, 1.1*age)\n else:\n return \"%d-%d\" % (age/2 + 7, (age - 7) * 2)", "def dating_range(age):\n return \"{}-{}\".format(int(age*0.9),int(age*1.1)) if age<=14 else \"{}-{}\".format(int(age/2+7),int((age-7)*2))", "def dating_range(age):\n if age > 14:\n maximum = (age - 7) * 2\n minimum = age / 2 + 7\n else:\n maximum = age + 0.10 * age\n minimum = age - 0.10 * age\n return '{}-{}'.format(int(minimum), int(maximum))\n", "def dating_range(age):\n return ['%d-%d'%(age-.10*age, age+.10*age), '%d-%d'%(age/2+7, (age-7)*2)][age>14]", "def dating_range(age):\n return f\"{age // 2 + 7}-{2 * age - 14}\" if age > 14 else f\"{age * 9 // 10}-{age * 11 // 10}\"\n", "def dating_range(age):\n return f'{int(age/2+7)}-{(age-7)*2}' if age > 14 else f'{int(0.9*age)}-{int(1.1*age)}'", "def dating_range(age):\n return \"{}-{}\".format(int(age-0.1*age) if age <=14 else (age//2)+7,int(age+0.1*age) if age <=14 else (age-7)*2)", "dating_range = lambda a: \"{}-{}\".format(int(a-0.1*a if a <= 14 else a/2+7), int(a+0.1*a if a <= 14 else (a-7)*2))", "def dating_range(age):\n return '%d-%d' %(age-0.1*age, age+0.1*age) if age <= 14 else '%d-%d' %(age/2+7, (age-7)*2)", "def dating_range(age):\n if age>14:\n return str(age//2+7) + '-' + str((age-7)*2)\n else:\n return (str(int(age*0.9)) + '-' + str(int(age*1.1)))", "def dating_range(age):\n if age > 14:\n a = age / 2 + 7\n b = (age - 7) * 2\n else:\n a = age - 0.10 * age\n b = age + 0.10 * age\n\n return f'{int(a)}-{int(b)}'", "def dating_range(age, x=2, y=7, z=.1):\n return '%d-%d' % ((age / x + y, x * (age - y)) if age > x * y else (age * (1 - z), age * (1 + z)))", "def dating_range(age, x=2, y=7, z=.1):\n return f'{age // x + y}-{x * (age - y)}' if age > x * y else f'{int(age * (1 - z))}-{int(age * (1 + z))}'", "def dating_range(age):\n min_age = age // 2 + 7 if age > 14 else 9*age//10\n max_age = 2 * (age - 7) if age > 14 else 11*age//10\n return f\"{min_age}-{max_age}\"", "from math import ceil\ndef dating_range(age):\n if age<=14:\n return f'{age-ceil(age/10)}-{age+(age//10)}'\n return f'{age//2+7}-{(age-7)*2}'", "def dating_range(age):\n return f'{age // 2 + 7}-{(age - 7) * 2}' if age > 14 else f'{int(age * 0.9)}-{int(age * 1.1)}'", "import math\ndef dating_range(age):\n if age>14:\n return '-'.join(map(str,[age//2+7,2*(age-7)]))\n return '-'.join(map(str,map(math.floor,[age*0.9,age*1.1])))", "def dating_range(age):\n min, max = (age / 2.0) + 7, (age - 7) * 2.0\n if age <= 14:\n min, max = age - 0.10 * age, age + 0.10 * age\n return \"{}-{}\".format(int(min), int(max))", "from math import floor\n\ndef dating_range(age: int) -> str:\n \"\"\" Get the minimum and maximum age range for dating. \"\"\"\n return f\"{floor(age / 2 + 7)}-{floor((age - 7) * 2)}\" if age > 14 else f\"{floor(age - 0.10 * age)}-{floor(age + 0.10 * age)}\"", "dating_range = \\\nlambda x: \"%s-%s\" % ((str(int(x - 0.10 * x))), (str(int(x + 0.10 * x)))) if x <= 14 \\\nelse \"%s-%s\" % ((str(int(x/2+7))), (str(int(x-7)*2)))", "dating_range = lambda age : str (age // 2 + 7) + \"-\" + str ((age - 7) * 2) if (age > 14) else str (int (age - 0.10 * age)) + \"-\" + str (int (age + 0.10 * age));", "from math import floor\n\ndef dating_range(age):\n min = floor(age / 2 + 7) if age > 14 else floor(age - 0.1 * age)\n max = floor((age - 7) * 2) if age > 14 else floor(age + 0.1 * age)\n return f\"{min}-{max}\"", "def dating_range(age):\n if age > 14:\n min = int(age/2+7)\n max = int((age-7)*2)\n else:\n min = int(age - 0.1*age)\n max = int(age + 0.1*age)\n r = str(min)\n r += \"-\"\n r += str(max)\n return r\n", "def first(age):\n min_age = str(int(age / 2 + 7))\n max_age = str(int((age - 7) * 2))\n return [min_age, max_age]\n\ndef second(age):\n min_age = str(int(age - 0.10 * age))\n max_age = str(int(age + 0.10 * age))\n return [min_age, max_age]\n\ndef dating_range(age):\n return ['-'.join(first(age)), '-'.join(second(age))][(age <= 14)]", "def dating_range(age):\n if age < 14:\n min = age - 0.10 * age\n max = age + 0.10 * age\n else:\n min = age/2 + 7\n max = (age - 7)*2\n return \"{}-{}\".format(int(min), int(max))", "def dating_range(age):\n min_14 = str(int(age - 0.10 * age))\n max_14 = str(int(age + 0.10 * age))\n min = str(int(age/2 + 7))\n max = str(int((age-7)*2))\n if age <= 14: return(min_14 + \"-\" + max_14)\n else: return (min + \"-\" + max)", "from math import floor\n\ndef dating_range(age):\n if age >= 14:\n min = floor(age / 2) + 7\n max = (age - 7) * 2 \n else:\n min = floor(age - 0.10 * age)\n max = floor(age + 0.10 * age)\n \n return f'{min}-{max}'", "def dating_range(age):\n return f'{int(age/2+7)}-{int((age-7)*2)}' if age>14 else f'{int(age-(.10*age))}-{int(age+(.10*age))}'", "def dating_range(age):\n return '%d-%d' % (age//2 + 7, 2*(age - 7)) if age > 14 else '%d-%d' % (9*age//10, 11*age//10)", "def dating_range(age):\n if age<=14:\n minage = int(age - 0.1*age)\n maxage = int(age + 0.1*age)\n else:\n minage = int(age/2 + 7)\n maxage = int((age-7)*2)\n \n return f\"{minage}-{maxage}\"", "def dating_range(age):\n min_over = age//2 + 7\n max_over = (age - 7)*2\n min_under = int(age - 0.10 * age)\n max_under = int(age + 0.10 * age)\n return f'{min_over}-{max_over}' if age > 14 else f'{min_under}-{max_under}'", "import math\n\ndef dating_range(age):\n if age <= 14:\n min = math.floor(age - 0.10 * age)\n max = math.floor((age + 0.10 * age))\n return f\"{min}-{max}\"\n else:\n min = math.floor(age/2 + 7)\n max = math.floor((age-7)*2)\n return f\"{min}-{max}\"", "def dating_range(age):\n if age>=15:\n min_age =int(age/2+7)\n max_age =(age-7)*2\n else:\n min_age =int(age - 0.10 * age)\n max_age = int(age + 0.10 * age)\n \n \n \n return f\"{min_age}-{max_age}\"", "from math import floor\n\ndef dating_range(age):\n if age <= 14:\n mn = floor(age - 0.1 * age)\n mx = floor(age + 0.1 * age)\n else:\n mn = age // 2 + 7\n mx = (age - 7) * 2\n \n \n return f'{mn}-{mx}'", "def dating_range(age):\n if age <= 14:\n return f'{int(age * 0.9)}-{int(age * 1.1)}'\n return f'{age // 2 + 7}-{(age - 7) * 2}'", "def dating_range(age):\n if age <= 14:\n min = int(age - 0.1*age)\n max = int(age + 0.1*age)\n return f'{min}-{max}'\n else:\n min = int((age//2) + 7)\n max = int((age-7) * 2)\n return f'{min}-{max}'", "def dating_range(age):\n return f'{age//2+7}-{(age-7)*2}' if age>14 else f'{int(age*0.9)}-{int(age*1.10)}'", "def dating_range(age):\n if age > 12:\n return str(int(age/2+7)) + '-' + str(int((age-7)*2))\n else:\n return str(int(age-0.10*age)) + '-' + str(int(age+0.10*age)) ", "def dating_range(age):\n return f'{int(age-age*.10)}-{int(age+age*.10)}' if age <= 14 else f'{age//2+7}-{(age-7)*2}'", "def dating_range(age):\n min_age = int(age / 2 + 7)\n max_age = int((age - 7) * 2)\n return age >= 14 and f\"{min_age}-{max_age}\" or f\"{int(age - 0.10 * age)}-{int(age + 0.10 * age)}\"", "def dating_range(age):\n return f'{int(age/2 + 7)}-{2 * (age -7)}' if age > 14 else f'{int(age - 0.10 * age)}-{int(age + 0.10 * age)}'", "from math import floor\ndef dating_range(age):\n \n if age > 14:\n min = age / 2 + 7\n max = (age - 7) * 2\n else:\n min = age - 0.10 * age\n max = age + 0.10 * age\n \n return f'{floor(min)}-{floor(max)}'", "def dating_range(age):\n if age > 14: mn, mx = age//2 + 7, (age-7)*2\n else: mn, mx = int(age*.9), int(age*1.1)\n return f\"{mn}-{mx}\"", "import numpy as np\ndef dating_range(age):\n if age>14:\n return f\"{int(np.floor((age/2)+7))}-{int(np.floor((age-7)*2))}\"\n else:\n return f\"{int(np.floor(age - (0.10 * age)))}-{int(np.floor(age + (0.10 * age)))}\"", "def dating_range(age):\n k = (age*0.5 + 7, age*2 - 14) if age > 14 else (age - 0.1 * age, age + 0.1 * age)\n return '{}-{}'.format(int(k[0]), int(k[1]))", "from math import floor\ndef dating_range(age):\n min_age = floor(age * .5 + 7 if age > 14 else age * .9)\n max_age = floor(age * 2 - 14 if age > 14 else age * 1.1)\n return \"{}-{}\".format(min_age, max_age)", "def dating_range(age):\n return f'{age//2+7}-{(age-7)*2}' if age>=14 else f'{int(age-0.10*age)}-{int(age+0.10*age)}'", "from math import ceil\ndef dating_range(age):\n if age <= 14:\n return f'{age-ceil(age/10)}-{age+int(age/10)}'\n return f'{age//2+7}-{2*(age-7)}'", "import math\ndef dating_range(age):\n if age > 14:\n a = (age/2) + 7\n b = (age - 7) * 2\n a = math.floor(a)\n b = math.floor(b)\n return str(a) + \"-\" + str(b)\n if age <= 14: \n a = age - (0.1 * age)\n b = age + (0.1 * age)\n a = math.floor(a)\n b = math.floor(b)\n return str(a) + \"-\" + str(b)", "def dating_range(age):\n if age <= 14:\n return f'{int(age - 0.1 * age)}-{int(age + 0.1 * age)}'\n return f'{age//2 + 7}-{(age-7)*2}'", "def dating_range(age):\n import math\n if age <=14:\n return f'{math.floor((age - 0.10 * age))}-{math.floor((age + 0.10 * age))}'\n else:\n return f'{(math.floor(age/2+7))}-{math.floor((2*(age-7)))}'", "def dating_range(age):\n if age <= 14:\n return f\"{int(age - age * 0.1)}-{int(age + age * 0.1)}\"\n return f\"{int(age/2 + 7)}-{int((age - 7) * 2)}\"", "from math import floor\n\ndef dating_range(age):\n if age <= 14:\n min = floor(age - 0.1 * age)\n max = floor(age + 0.1 * age)\n return f'{min}-{max}'\n return f'{floor(age//2+7)}-{floor((age-7)*2)}'", "def dating_range(age):\n return f\"{int(age - 0.1 * age)}-{int(age + 0.1 * age)}\" if age <= 14 else f\"{age // 2 + 7}-{(age - 7) * 2}\"", "import math\ndef dating_range(age):\n if age<=14:\n min=age-math.ceil(0.10*age)\n max=age+math.floor(0.10*age)\n else:\n min=(age//2)+7\n max=(age-7)*2\n return f'{min}-{max}'", "def dating_range(age):\n if age>14:\n return str(int(age/2+7))+'-'+str(2*age-14)\n return str(int(0.9*age))+'-'+str(int(1.1*age))", "def dating_range(age):\n min = age/2 + 7 if age > 14 else age-0.1*age\n max = (age-7)*2 if age > 14 else age+0.1*age\n return \"{}-{}\".format(int(min), int(max))", "from math import floor\ndef dating_range(age):\n return f\"{age // 2 + 7}-{(age - 7) * 2}\" if age > 14 else f\"{floor(age - age / 10)}-{age + age // 10}\"", "def dating_range(age):\n if age>14:\n return f'{(age)//2 +7}-{2*(age-7)}'\n else:\n return f'{int(age-age/10)}-{int(age+age/10)}'", "def dating_range(age):\n if age >14:\n return str(int(age/2+7)) +\"-\"+str((age-7)*2)\n else:\n return str(int(age-0.1*age))+\"-\"+str(int(age+0.1*age))", "import math\ndef dating_range(age):\n return \"{}-{}\".format(math.floor(age - 0.10 * age), math.floor(age + 0.10 * age)) if age < 14 else \"{}-{}\".format(math.floor(age / 2 + 7), math.floor((age - 7) * 2))", "def dating_range(age):\n return \"%d-%d\" % (age//2 +7,(age-7)*2) if age > 14 else \"%d-%d\" % (int(age-0.1*age),int(age+0.1*age))", "import math\ndef dating_range(age):\n return f\"{math.floor(age/2+7)}-{(age-7)*2}\" if int(age)>14 else f\"{int(age-.1*age)}-{int(age+.1*age)}\"\n", "import math\n\ndef dating_range(age):\n if age <= 14:\n return f'{math.floor(age - 0.10 * age)}-{math.floor(age + 0.10 * age)}'\n return f'{age // 2 + 7}-{(age - 7) * 2}'", "def dating_range(age):\n if age<=14 : return f\"{int(age-0.1*age)}-{int(age+0.1*age)}\"\n return f\"{7+age//2}-{(age-7)*2}\"", "import math\ndef dating_range(age):\n if age >= 14:\n max = (age - 7) * 2\n min = (age/2) + 7\n else:\n min = age - .1 * age\n max = age + .1 * age\n return str(math.floor(min)) + '-' + str(math.floor(max))\n", "def dating_range(age):\n if age <= 14:\n mini = int(age - 0.1 * age)\n maxi = int(age + 0.1 * age)\n else:\n mini = age//2+7\n maxi = (age-7)*2\n return \"{}-{}\".format(mini, maxi)", "def dating_range(age):\n if age < 15:\n return f'{int(0.9 * age)}-{int(1.1 * age)}'\n return f'{7 + age // 2}-{2 * (age - 7)}'", "def dating_range(age):\n if age <= 14:\n min_age = int(age - 0.1*age)\n max_age = int(age + 0.1*age)\n else:\n min_age = int(age/2 + 7)\n max_age = int((age-7)*2)\n return f\"{min_age}-{max_age}\"", "def dating_range(age):\n if age > 14:\n min = age / 2 + 7\n max = (age - 7) * 2\n elif age <= 14:\n min = age - 0.10 * age\n max = age + 0.10 * age\n return f\"{int(min)}-{int(max)}\"", "from math import floor\n\ndef dating_range(age):\n if age <= 14:\n return f\"{floor(0.9*age)}-{floor(1.1*age)}\"\n return f\"{age // 2 + 7}-{2*(age - 7)}\"", "import math\ndef dating_range(age):\n #return min-max\n min=0\n max=0\n if age<=14:\n min = math.floor(age - 0.10 * age)\n max = math.floor(age + 0.10 * age)\n else:\n min=math.floor(age/2)+7\n max=2*(age-7)\n return str(min)+'-'+str(max)", "def dating_range(y):\n \"\"\"\n rename or delete\n \"\"\"\n return str((y//2)+7)+'-'+str(2*(y-7)) if y>14 else str(int(.9*y))+'-'+str(int(1.1*y))", "def dating_range(age):\n return f\"{int(age/2+7)}-{(age-7)*2}\" if age>=14 else f\"{int(age-(0.1*age))}-{int(age+(0.1*age))}\"", "def dating_range(age):\n if age<15 : return str(int(age*0.9))+'-'+str(int(age*1.1))\n return str((age//2+7)//1)+'-'+str((age-7)*2//1)", "from math import floor\ndef dating_range(age):\n\n if age <= 14:\n min = floor(age - .1 * age)\n max = floor(age + .1 * age)\n return (\"{}-{}\").format(min,max)\n min = age // 2 + 7\n max = (age - 7) * 2\n return (\"{}-{}\").format(min,max)\n", "import math\ndef dating_range(age):\n if 14 < age <= 100: return '%i-%i' % (math.floor(age/2)+7, (age-7)*2)\n else: return '%i-%i' % (math.floor(age-(age*0.1)), age + math.floor(age * 0.1))\n", "from math import floor\n\ndef dating_range(age):\n if age <= 14:\n return f'{floor(age - (0.1 * age))}-{floor(age + (0.1 * age))}'\n else:\n return f'{floor((age/2) + 7)}-{floor((age-7) * 2)}'", "def dating_range(age):\n if age > 14:\n a = int(age / 2 + 7)\n b = (age - 7) * 2\n else:\n a = int(age - 0.10 * age)\n b = int(age + 0.10 * age)\n\n return f'{min(a, b)}-{max(a, b)}'", "def dating_range(age):\n min = int((age / 2) + 7)\n max = int((age -7) * 2)\n small_min = int(age - 0.10 * age)\n small_max = int(age + 0.10 * age)\n return str(min) + \"-\" + str(max) if age > 14 else str(small_min) + \"-\" + str(small_max)", "from math import floor\n\ndef dating_range(age):\n if age <= 14:\n return f'{floor(age * 0.9)}-{floor(age * 1.1)}'\n else:\n return f'{floor(age / 2 + 7)}-{floor((age - 7) * 2)}'\n", "def dating_range(age):\n if age <= 14:\n msg = str(int(age * 0.9)) + \"-\" + str(int(age * 1.1))\n else:\n msg = str(int(age/2)+7) + \"-\" + str((age-7)*2)\n return msg", "def dating_range(age):\n if age <= 14:\n min = age - age / 10\n max = age + age / 10\n else:\n min = age / 2 + 7\n max = 2 * (age - 7)\n return \"%d-%d\" % (int(min), int(max))", "def dating_range(age):\n if age <= 14:\n min = int(age - age / 10)\n max = int(age + age / 10)\n else:\n min = int(age / 2 + 7)\n max = int(2 * (age - 7))\n return \"{}-{}\".format(min, max)\n", "from math import floor\ndef dating_range(age):\n if age <= 14:\n mini = [str(floor(age-0.10*age))]\n maxi = [str(floor(age+0.10*age))]\n return '-'.join(mini+maxi)\n else:\n mini = [str(floor(age/2+7))]\n maxi = [str(floor((age-7)*2))]\n return '-'.join(mini+maxi)", "def dating_range(age):\n if age <= 14:\n min_ = age - 0.10 * age\n max_ = age + 0.10 * age\n return \"{}-{}\".format(int(min_),int(max_))\n if age > 14:\n min_ = (age/2)+7\n max_ = (age-7)*2\n return \"{}-{}\".format(int(min_),int(max_))", "def dating_range(age):\n return f'''{int(age/2+7)}-{int(age*2-7*2)}''' if age>14 else f'''{int(0.9*age)}-{int(1.1*age)}'''", "def dating_range(age):\n if age <= 14:\n return f\"{int(age - 0.10 * age)}-{int(age + 0.10 * age)}\"\n return f\"{int(age/2 +7)}-{int((age-7)*2)}\"", "import math\n\ndef dating_range(age):\n\n if age > 14:\n min = math.floor(age/2 + 7)\n max = (age-7) * 2 \n return '{}-{}'.format(min, max)\n else: \n min = math.floor(age - 0.10 * age)\n max = math.floor(age + 0.10 * age)\n return '{}-{}'.format(min, max)\n", "from math import floor\ndef dating_range(age):\n if age <= 14:\n min = floor(age - 0.1 * age)\n max = floor(age + 0.1 * age)\n else:\n min = floor(age / 2 + 7)\n max = floor((age - 7) * 2)\n return '{0}-{1}'.format(min, max)", "from math import floor\ndef dating_range(age):\n if age>14:\n min=(age/2)+7\n max=(age-7)*2\n return \"{}-{}\".format(floor(min),floor(max))\n elif age<=14:\n min=age-0.10*age\n max=age+0.10*age\n return \"{}-{}\".format(floor(min),floor(max))\n #return min-max\n", "def dating_range(age):\n return f\"{int(age-0.10 * age)}-{int(age+0.10*age)}\" if age < 14 else f\"{int(age / 2 + 7)}-{int((age-7)*2)}\"", "def dating_range(age):\n if age > 14:\n min = (age//2)+7\n max = (age-7)*2\n return f\"{min}-{max}\"\n else:\n min = int(age - 0.10*age)\n max = int(age + 0.10*age)\n return f\"{min}-{max}\"", "def dating_range(age):\n return f'{age//2 + 7}-{(age-7)*2}' if age > 14 else f'{int(age-0.1*age)}-{int(age+0.1*age)}'", "def dating_range(age):\n if age <= 14:\n min1 = age - .10 * age\n max1 = age + .10 * age\n min2 = int(min1)\n max2 = int(max1)\n return str(min2) + \"-\" + str(max2)\n if age > 14:\n min = age // 2 + 7\n max = (age - 7) * 2\n return str(min) + \"-\" + str(max)", "def dating_range(age):\n r = (age - 0.10 * age, age + 0.10 * age)\n if age > 14:\n r = (age / 2 + 7, (age - 7) * 2)\n return \"{}-{}\".format(int(r[0]), int(r[1]))\n", "from math import floor\ndef dating_range(age):\n if age > 14:\n min = age/2 + 7 \n max = (age -7)*2\n else:\n min = floor(age - 0.10*age)\n max = floor(age + 0.10*age)\n return str(floor(min)) + '-' + str(floor(max))"] | {"fn_name": "dating_range", "inputs": [[17], [40], [15], [35], [10], [53], [19], [12], [7], [33]], "outputs": [["15-20"], ["27-66"], ["14-16"], ["24-56"], ["9-11"], ["33-92"], ["16-24"], ["10-13"], ["6-7"], ["23-52"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 19,793 |
def dating_range(age):
|
e49dfc42a8979b377710b23d902ed4cb | UNKNOWN | Write a method `alternate_sq_sum()` (JS: `alternateSqSum` ) that takes an array of integers as input and finds the sum of squares of the elements at even positions (*i.e.,* 2nd, 4th, *etc.*) plus the sum of the rest of the elements at odd position.
NOTE:
The values at even *position* need to be squared. For a language with zero-based indices, this will occur at oddly-indexed locations. For instance, in Python, the values at indices 1, 3, 5, *etc.* should be squared because these are the second, fourth, and sixth positions in the list.
For Example:
```python
alternate_sq_sum([11, 12, 13, 14, 15]) #should return 379
```
Explanation:
Elements at indices 0, 2, 4 are 11, 13, 15 and they are at odd positions as 11 is at position #1, 13 is at position #3 and 15 at #5.
Elements at indices 1, 3 are 12 and 14 and they are at even position.
So we need to add 11, 13, 15 as they are and square of 12 and 14
--> 11 + 13 + 15 + 12^2 + 14^2
= 11 + 13 + 15 + 144 + 196
= 379
For empty arrays, result should be 0 (zero) (except for Haskell). | ["def alternate_sq_sum(arr):\n return sum([ x**2 if i % 2 == 1 else x for i, x in enumerate(arr) ])", "def alternate_sq_sum(arr):\n return sum(x * x for x in arr[1::2]) + sum(arr[::2])", "def alternate_sq_sum(arr):\n return sum(n * (n if i % 2 else 1) for i, n in enumerate(arr))", "def alternate_sq_sum(arr):\n return sum(num if not i%2 else num**2 for i,num in enumerate(arr))", "def alternate_sq_sum(arr):\n return sum(v*v if i&1 else v for i,v in enumerate(arr))", "def alternate_sq_sum(arr):\n return sum([x ** 2 if pos % 2 != 0 else x for pos, x in enumerate(arr)])", "def alternate_sq_sum(arr):\n return sum(arr[::2]) + sum(map(lambda x : x*x, arr[1::2]))", "def alternate_sq_sum(arr):\n return sum(n ** 2 if c % 2 == 1 else n for c, n in enumerate(arr))", "def alternate_sq_sum(a):\n return sum(a[i]**2 if i%2 else a[i] for i in range(len(a))) or 0"] | {"fn_name": "alternate_sq_sum", "inputs": [[[]], [[-1, 0, -3, 0, -5, 3]], [[-1, 2, -3, 4, -5]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]], "outputs": [[0], [0], [11], [245]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 885 |
def alternate_sq_sum(arr):
|
7e359a1861039c430555c18d8ded003a | UNKNOWN | Consider the string `"1 2 36 4 8"`. Lets take pairs of these numbers, concatenate each pair and determine how many of them of divisible by `k`.
```Pearl
If k = 3, we get following numbers ['12', '18', '21', '24', '42', '48', '81', '84'], all divisible by 3.
Note:
-- 21 and 12 are different pairs.
-- Elements must be from different indices, so '3636` is not a valid.
```
Given a string of numbers and an integer `k`, return the number of pairs that when concatenated, are divisible by `k`.
```
solve("1 2 36 4 8", 3) = 8, because they are ['12', '18', '21', '24', '42', '48', '81', '84']
solve("1 3 6 3", 3) = 6. They are ['36', '33', '63', '63', '33', '36']
```
More examples in test cases. Good luck!
Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7) | ["from itertools import permutations\n\ndef solve(s,k):\n return sum(not v%k for v in map(int, map(''.join, permutations(s.split(),2))))", "from itertools import permutations\n\ndef solve(stg, k):\n return sum(1 for m, n in permutations(stg.split(), 2) if int(f\"{m}{n}\") % k == 0)", "from itertools import permutations\n\ndef solve(s,k):\n return sum(not int(a+b)%k for a,b in permutations(s.split(),2))", "from itertools import permutations as p\ndef solve(s,k): \n return len([j for j in [int(''.join(i)) for i in p(s.split(), 2)] if j%k==0])\n", "solve=lambda s,k:sum(int(x+y)%k==0for x,y in __import__('itertools').permutations(s.split(),2))", "from itertools import permutations\ndef solve(s,k):\n return sum(int(a + b) % k == 0 for a, b in permutations(s.split(), 2))\n", "from itertools import permutations, filterfalse\n\ndef solve(s, k):\n return len(list(filterfalse(lambda x: int(''.join(x))%k, permutations(s.split(), 2))))", "import itertools as it\n\ndef solve(s,k):\n return sum(n % k == 0 for n in map(int, map(''.join, it.permutations(s.split(), 2))))", "def solve(s,k):\n s = s.split()\n return sum(1 for i in range(len(s)) for j in range(len(s)) if i!=j and int(s[i]+s[j])%k==0)", "def solve(s,k):\n count = 0\n l = s.split()\n for i in range(len(l)-1):\n for j in range(i+1, len(l)):\n count += int(int(l[i]+l[j])%k == 0) + int(int(l[j]+l[i])%k == 0)\n return count"] | {"fn_name": "solve", "inputs": [["1 2 36 4 8", 2], ["1 2 36 4 8", 3], ["1 2 36 4 8", 4], ["1 2 36 4 8", 8]], "outputs": [[16], [8], [11], [4]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,449 |
def solve(s,k):
|
e963066e92739e1f1ece219fa055cabf | UNKNOWN | Write the following function:
```python
def area_of_polygon_inside_circle(circle_radius, number_of_sides):
```
It should calculate the area of a regular polygon of `numberOfSides`, `number-of-sides`, or `number_of_sides` sides inside a circle of radius `circleRadius`, `circle-radius`, or `circle_radius` which passes through all the vertices of the polygon (such circle is called [**circumscribed circle** or **circumcircle**](https://en.wikipedia.org/wiki/Circumscribed_circle)). The answer should be a number rounded to 3 decimal places.
Input :: Output Examples
```python
area_of_polygon_inside_circle(3, 3) # returns 11.691
area_of_polygon_inside_circle(5.8, 7) # returns 92.053
area_of_polygon_inside_circle(4, 5) # returns 38.042
``` | ["from math import sin, pi\n\ndef area_of_polygon_inside_circle(r, n):\n return round(0.5 * n * r ** 2 * sin(2 * pi / n), 3)", "from math import sin, pi\n\ndef area_of_polygon_inside_circle(r, n):\n return round(n*r*r*sin(2*pi/n)/2, 3)", "import math\ndef area_of_polygon_inside_circle(circle_radius, number_of_sides):\n r = circle_radius\n s = number_of_sides\n a = (s * (r ** 2) * math.sin(2*math.pi/s))/2\n return round(a, 3)", "from math import sin,pi\ndef area_of_polygon_inside_circle(r, n):\n return round((n*r**2*sin(2*pi/n))/2, 3)", "def area_of_polygon_inside_circle(r,n):\n import math\n a=(360/(2*n))*(0.017453292519943295)\n b=2*r*math.sin(a)\n c=r*math.cos(a)\n return round((1/2)*(b)*(c)*(n),3)", "from math import sin, tau\n\ndef area_of_polygon_inside_circle(circle_radius, number_of_sides):\n s = number_of_sides / 2 * circle_radius ** 2 * sin((tau / number_of_sides))\n return round(s,3)", "from math import pi, sin\n\ndef area_of_polygon_inside_circle(r, n):\n # https://www.mathopenref.com/triangleareasas.html\n return round(n * r * r * sin(pi * 2 / n) / 2, 3)", "from math import pi,sin\ndef area_of_polygon_inside_circle(r, n):\n return round(0.5*n*r**2*sin(2*pi/n),3)", "import math\ndef area_of_polygon_inside_circle(r, n):\n return round(0.5 * r * r * n * math.sin(2 * math.pi / n), 3)", "from math import sin, pi\n\ndef area_of_polygon_inside_circle(radius, sides):\n return round(sides * radius * radius * sin(pi * (sides - 2) / sides) / 2, 3)"] | {"fn_name": "area_of_polygon_inside_circle", "inputs": [[3, 3], [2, 4], [2.5, 5]], "outputs": [[11.691], [8], [14.86]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,531 |
def area_of_polygon_inside_circle(r, n):
|
e9491890cb38597852d1a8e564df184f | UNKNOWN | Your job is to return the volume of a cup when given the diameter of the top, the diameter of the bottom and the height.
You know that there is a steady gradient from the top to the bottom.
You want to return the volume rounded to 2 decimal places.
Exmples:
```python
cup_volume(1, 1, 1)==0.79
cup_volume(10, 8, 10)==638.79
cup_volume(1000, 1000, 1000)==785398163.4
cup_volume(13.123, 123.12, 1)==4436.57
cup_volume(5, 12, 31)==1858.51
```
You will only be passed positive numbers. | ["from math import pi\n\ndef cup_volume(d1, d2, h):\n return round(h / 12.0 * pi * (d1**2 + d1*d2 + d2**2), 2)", "from math import pi\ndef cup_volume(d1, d2, height):\n r1, r2 = d1 / 2.0, d2 / 2.0\n return round(pi * height * (pow(r1, 2) + r1 * r2 + pow(r2, 2)) / 3.0, 2)", "from math import pi\n\ndef cup_volume(d1, d2, h):\n return round(pi * h * (d1**2 + d1 * d2 + d2**2) / 12, 2)", "def cup_volume(d1, d2, h):\n return round(h * (d1*d1 + d1*d2 + d2*d2) * 0.2617993878, 2)", "cup_volume=lambda d,D,h:round(__import__('math').pi*h/12*(d*d+d*D+D*D),2)", "import math\n\ndef cup_volume(d1, d2, height):\n if d1 > d2:\n d1, d2 = d2, d1\n if d1 == d2:\n return round((d1/2.0) ** 2 * math.pi * height, 2)\n x = (d1 * float(height)) / (d2 - d1)\n vol = (d2 / 2.0)**2*math.pi*(height+x) / 3.0 - (d1 / 2.0)**2*math.pi*x/3.0\n return round(vol, 2)\n", "def cup_volume(d1, d2, height):\n v = (3.14159265359/3)*height*(((d1/2)**2) + ((d2/2)**2) + ((d1/2)*d2/2))\n return round(v,2)", "import math\ndef cup_volume(d1, d2, height):\n return round(math.pi * height * (d1**2 + d2**2 + d1*d2)/12, 2)", "from math import pi\n\ndef cup_volume(d1, d2, h):\n r1, r2 = d1 / 2, d2 / 2\n return round(pi * (1/3) * h * (r1**2 + r2**2 + r1*r2),2)"] | {"fn_name": "cup_volume", "inputs": [[1, 1, 1], [10, 8, 10], [1000, 1000, 1000], [13.123, 123.12, 1], [5, 12, 31]], "outputs": [[0.79], [638.79], [785398163.4], [4436.57], [1858.51]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,288 |
def cup_volume(d1, d2, height):
|
1223dae011ac36aa0c3160eae9158df8 | UNKNOWN | This is now a little serie :)
Funny Dots
You will get two Integer n (width) and m (height) and your task is to draw following pattern. Each line is seperated with '\n'.
Both integers are equal or greater than 1. No need to check for invalid parameters.
e.g.:
+---+---+---+
+---+ | o | o | o |
dot(1,1) => | o | dot(3,2) => +---+---+---+
+---+ | o | o | o |
+---+---+---+
Serie: ASCII Fun
ASCII Fun #1: X-Shape
ASCII Fun #2: Funny Dots
ASCII Fun #3: Puzzle Tiles
ASCII Fun #4: Build a pyramid | ["def dot(n, m):\n sep = '+---' * n + '+'\n dot = '| o ' * n + '|'\n return '\\n'.join([sep, dot] * m + [sep])", "def dot(n,m):\n result = [(\"+---\" * n) + \"+\" + \"\\n\" + (\"| o \" * n) + \"|\" for i in range(m)]\n result.append((\"+---\" * n) + \"+\")\n return \"\\n\".join(result)", "def dot(n,m):\n sep = '---'.join( '+'*(n+1) )\n dot = ' o '.join( '|'*(n+1) )\n\n return f'\\n{dot}\\n'.join( [sep for _ in range(m+1) ]) ", "def dot(w, h):\n sep, row = \"+---\" * w + \"+\\n\", \"| o \" * w + \"|\\n\"\n return (sep + row) * h + sep.strip()\n", "def dot(n,m):\n sep = '+' + '+'.join(['---'] * n) + '+'\n bod = '|' + '|'.join([' o '] * n) + '|'\n def f():\n yield sep\n for i in range(m):\n yield bod\n yield sep\n return '\\n'.join(f())", "def dot(n,m):\n inter = \"\\n\" + \"+\"+ \"+\".join(\"---\" for i in range(n)) + \"+\" + \"\\n\"\n bigo = \"|\"+ \"|\".join(\" o \" for i in range(n)) + \"|\"\n return (inter + (inter).join(bigo for i in range(m)) + inter)[1:-1]", "def dot(n,m):\n return \"\\n\".join([\"+---+\"*n,\"| o |\"*n]*m).replace(\"||\",\"|\").replace(\"++\",\"+\") +\"\\n\"+(\"+---+\"*n).replace(\"++\",\"+\")", "def dot(n, m):\n return f\"\\n{' o '.join(['|']*(n+1))}\\n\".join(['---'.join(['+']*(n+1))]*(m+1))", "dot=lambda n,m:' o '.join(-~n*'|').join(2*'\\n').join(-~m*['---'.join(-~n*'+')])", "dot=lambda n,m:('+---'*n+'+\\n'+'| o '*n+'|\\n')*m+'+---'*n+'+'\n"] | {"fn_name": "dot", "inputs": [[1, 1], [3, 2]], "outputs": [["+---+\n| o |\n+---+"], ["+---+---+---+\n| o | o | o |\n+---+---+---+\n| o | o | o |\n+---+---+---+"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,484 |
def dot(n,m):
|
e38c6f5157ec4ea5c00aa823560f081b | UNKNOWN | Roma is programmer and he likes memes about IT,
Maxim is chemist and he likes memes about chemistry,
Danik is designer and he likes memes about design,
and Vlad likes all other memes.
___
You will be given a meme (string), and your task is to identify its category, and send it to the right receiver: `IT - 'Roma'`, `chemistry - 'Maxim'`, `design - 'Danik'`, or `other - 'Vlad'`.
IT meme has letters `b, u, g`.
Chemistry meme has letters `b, o, o, m`.
Design meme has letters `e, d, i, t, s`.
If there is more than 1 possible answer, the earliest match should be chosen.
**Note:** letters are case-insensetive and should come in the order specified above.
___
## Examples:
(Matching letters are surrounded by curly braces for readability.)
```
this is programmer meme {b}ecause it has b{ug}
this is also program{bu}r meme {g}ecause it has needed key word
this is {ed}s{i}gner meme cause i{t} ha{s} key word
this could {b}e chemistry meme b{u}t our{g}Gey word 'boom' is too late
instead of
this could {b}e chemistry meme but {o}ur gey w{o}rd 'boo{m}' is too late
``` | ["import re\nfrom itertools import accumulate\n\n\npatterns = [\n (re.compile('.*'.join('bug'), flags=re.I), 'Roma'),\n (re.compile('.*'.join('boom'), flags=re.I), 'Maxim'),\n (re.compile('.*'.join('edits'), flags=re.I), 'Danik'),\n]\n\ndef memesorting(meme):\n return next((who for m in accumulate(meme) for pattern, who in patterns if pattern.search(m)), 'Vlad')", "def memesorting(meme):\n typ = ('Roma', 'Maxim', 'Danik')\n what = ('bug', 'boom', 'edits')\n \n bug_boom_edits = [list(l[::-1]) for l in what]\n for c in meme.lower():\n for i,l in enumerate(bug_boom_edits):\n if l[-1] == c: l.pop()\n if not l:\n return typ[i]\n else:\n return 'Vlad'", "import re\n\ndef memesorting(s):\n f = lambda w: re.search(r\"{}\".format(\".*?\".join(w)), s, re.IGNORECASE)\n a = [[m.span()[1], i] for i, m in enumerate(f(x) for x in [\"bug\", \"boom\", \"edits\"]) if m]\n return [\"Roma\", \"Maxim\", \"Danik\"][min(a)[1]] if a else \"Vlad\"", "def memesorting(meme):\n keys = { 'bug':'', 'boom':'', 'edits':''}\n for i, l in enumerate(meme.lower()):\n for key, value in { 'bug':'Roma', 'boom':'Maxim', 'edits':'Danik' }.items():\n if l == key[len(keys[key])]:\n keys[key] += l\n if keys[key] == key:\n return value\n return 'Vlad' ", "def memesorting(s):\n order_p,p,ini_p,order_c,c,int_c, order_d,d,int_d = {0: 'b', 1: 'u', 2: 'g'},\"\",0,{0: 'b', 1: 'o', 2: 'o', 3: 'm'},\"\",0,{0: 'e', 1: 'd', 2: 'i', 3: 't', 4: 's'},\"\",0\n for i in s.lower():\n if i == order_p[ini_p] : p += i ; ini_p += 1\n if i == order_c[int_c] : c += i ; int_c += 1\n if i == order_d[int_d] : d += i ; int_d += 1\n for k in range(3):\n if [\"bug\", \"boom\", \"edits\"][k] == [p, c, d][k] : return [\"Roma\", \"Maxim\", \"Danik\"][k]\n return \"Vlad\"", "def memesorting(meme):\n bug = 'bug'\n boom = 'boom'\n edits = 'edits'\n for i in meme.lower():\n if i == bug[0]:\n bug = bug[1:]\n if len(bug) == 0:\n return \"Roma\"\n if i == boom[0]:\n boom = boom[1:]\n if len(boom)== 0:\n return \"Maxim\"\n if i == edits[0]:\n edits = edits[1:]\n if len(edits)== 0:\n return \"Danik\"\n return 'Vlad'", "def memesorting(meme):\n bug, boom ,edits = ['b', 'u', 'g'], ['b', 'o', 'o', 'm'], ['e', 'd', 'i', 't', 's']\n for ch in meme.lower():\n if ch == bug[0]:\n bug.pop(0)\n if not bug: return 'Roma'\n if ch == boom[0]:\n boom.pop(0)\n if not boom: return 'Maxim'\n if ch == edits[0]:\n edits.pop(0)\n if not edits: return 'Danik' \n return 'Vlad'", "def memesorting(meme):\n print(meme)\n targets = [\n ['bug',0,'Roma'],\n ['boom',0,'Maxim'],\n ['edits',0,'Danik']]\n for char in meme:\n for target in targets:\n if char.lower() == target[0][target[1]]:\n target[1] += 1\n if target[1] == len(target[0]):\n return target[2]\n return 'Vlad'", "import re\nPATTERNS = (('Roma', '.*?'.join(\"bug\")),\n ('Maxim', '.*?'.join(\"boom\")),\n ('Danik', '.*?'.join(\"edits\")))\n \ndef memesorting(meme):\n result = (float('inf'), \"Vlad\")\n for name, p in PATTERNS:\n res = re.search(p, meme, re.IGNORECASE)\n if res: result = min(result, (res.span()[1], name))\n return result[1]", "import regex as re\ndef memesorting(meme):\n meme = meme.lower()\n print(meme)\n check = []\n bug = re.search(r'b.*?u.*?g', meme)\n if bug is not None:\n check.append(bug)\n boom = re.search(r'b.*?o.*?o.*?m', meme)\n if boom is not None:\n check.append(boom)\n edits = re.search(r'e.*?d.*?i.*?t.*?s', meme)\n if edits is not None:\n check.append(edits)\n if check != []:\n first = min(check, key=lambda match: match.span()[1])\n else:\n return 'Vlad'\n \n if first.group()[-1] == 'g': return 'Roma'\n if first.group()[-1] == 's': return 'Danik'\n else: return 'Maxim'\n return"] | {"fn_name": "memesorting", "inputs": [["This is programmer meme ecause it has bug"], ["This is also programbur meme gecause it has needed key word"], ["This is edsigner meme cause it has key word"], ["This could be chemistry meme but our gey word boom is too late"], ["This is meme"]], "outputs": [["Roma"], ["Roma"], ["Danik"], ["Roma"], ["Vlad"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,324 |
def memesorting(meme):
|
f4aa26f7feb060f3820d7a4dacf4e005 | UNKNOWN | # Description
Write a function that accepts the current position of a knight in a chess board, it returns the possible positions that it will end up after 1 move. The resulted should be sorted.
## Example
"a1" -> ["b3", "c2"] | ["def possible_positions(p):\n r, c = ord(p[0])-96, int(p[1])\n moves = [(-2,-1), (-2,1), (-1,-2), (-1,2), (1,-2), (1,2), (2,-1), (2,1)]\n return [''.join((chr(r+i+96), str(c+j))) for i, j in moves if 1 <= r+i <= 8 and 1 <= c+j <= 8]", "def possible_positions(pos):\n col = \"abcdefgh\"\n row = \"12345678\"\n ret = []\n dir = [[1,2],[1,-2],[-1,2],[-1,-2],[2,1],[2,-1],[-2,1],[-2,-1]]\n c, r = pos[0], pos[1]\n for d in dir:\n x = col.index(c)+d[0]\n y = row.index(r)+d[1]\n if 0<=x<8 and 0<=y<8:\n ret.append(\"\".join([col[x], row[y]]))\n return sorted(ret)", "import string\n\nKNIGHT = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]\nBOARD_SIZE = 8\n\ndef moves(x, y, directions):\n for dx, dy in directions:\n x2, y2 = x + dx, y + dy\n if 0 <= x2 < BOARD_SIZE > y2 >= 0:\n yield x2, y2\n\ndef possible_positions(pos):\n x, y = (string.ascii_lowercase.find(pos[0]), int(pos[1])-1)\n return [f'{string.ascii_lowercase[x]}{y+1}' for x, y in moves(x, y, KNIGHT)]", "def possible_positions(pos):\n board = [[r+str(c) for c in range(1,9)] for r in \"abcdefgh\"]\n x,y = ord(pos[0])-97,int(pos[1])-1\n return sorted([board[py][px] for py,px in \n [(x+2,y+1),(x+2,y-1),(x-2,y+1),(x-2,y-1),(x+1,y+2),(x+1,y-2),(x-1,y+2),(x-1,y-2)]\n if 0 <= px < 8 and 0 <= py < 8])", "def possible_positions(pos):\n moves = [(-2,-1),(-2,1),(-1,-2),(-1,2),(1,-2),(1,2),(2,-1),(2,1)]\n res = []\n for m in moves:\n let = chr(ord(pos[0])+m[0])\n num = int(pos[1])+m[1]\n if let in \"abcdefgh\" and 0<num<9: res.append(let+str(num))\n return res", "def possible_positions(pos):\n abc = 'abcdefgh'\n x, y = abc.index(pos[0]), int(pos[1])\n l = [[x+2, y-1], [x+2, y+1],[x-2, y-1], [x-2, y+1], [x-1, y+2], [x+1, y+2],[x-1, y-2], [x+1, y-2]]\n m = sorted(filter(lambda x: 0 <= x[0] <= 7 and 1<= x[1] <= 8, l), key = lambda x: (x[0],x[1]))\n return list(map(lambda x: ''.join([abc[x[0]],str(x[1])]), m))", "moves = ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1))\n\ndef possible_positions(pos):\n x, y = ord(pos[0]) - 96, int(pos[1])\n return [f\"{chr(96 + x + i)}{y + j}\" for i, j in moves if -i < x < 9 - i and -j < y < 9 - j]", "to_coords = lambda s: (ord(s[0])-96, int(s[1]))\nfrom_coords = lambda i, j: f\"{chr(i+96)}{j}\"\nL = ((1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1))\n\ndef possible_positions(pos):\n i, j = to_coords(pos)\n return sorted(from_coords(i+k, j+l) for k,l in L if 0 < i+k <= 8 and 0 < j+l <= 8)", "possible_positions=lambda p,m='abcdefgh':(lambda x,y:sorted([m[e[0]+x]+str(e[1]+y)for e in[(-2,1),(-1,2),(1,2),(2,1),(-2,-1),(-1,-2),(1,-2),(2,-1)]if 8>e[0]+x>=0and 9>e[1]+y>0]))(m.find(p[0]),int(p[1]))", "def possible_positions(pos):\n rows, cols = 'abcdefgh', '12345678'\n\n row = rows.index(pos[0])\n col = cols.index(pos[1])\n\n M = [(a, b) for a in [1, -1] for b in [2, -2]]\n P = [(row + rr, col + cc) for rr, cc in M + [e[::-1] for e in M]]\n \n return sorted(rows[r] + cols[c] for r, c in P if 0 <= r <= 7 and 0 <= c <= 7)"] | {"fn_name": "possible_positions", "inputs": [["a1"], ["f7"], ["c3"]], "outputs": [[["b3", "c2"]], [["d6", "d8", "e5", "g5", "h6", "h8"]], [["a2", "a4", "b1", "b5", "d1", "d5", "e2", "e4"]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,213 |
def possible_positions(pos):
|
d0223dbe1478c9a2aa9789715bb3714c | UNKNOWN | Find the first character that repeats in a String and return that character.
```python
first_dup('tweet') => 't'
first_dup('like') => None
```
*This is not the same as finding the character that repeats first.*
*In that case, an input of 'tweet' would yield 'e'.* | ["def first_dup(s):\n for x in s:\n if s.count(x) > 1:\n return x\n return None", "def first_dup(s):\n return next((x for x in s if s.count(x) > 1),None)", "from collections import Counter, OrderedDict\n\nclass OC(Counter,OrderedDict): pass\n\ndef first_dup(s):\n return next((c for c,n in OC(s).items() if n>1), None)", "import re\n\ndef first_dup(s):\n return next(iter(re.findall(r'(.).*\\1', s)), None)", "def first_dup(stg):\n return next((c for c in stg if stg.count(c) > 1), None)", "def first_dup(s):\n if s[0] in s[1:]:\n return s[0]\n return len(s)>1 and first_dup(s[1:]) or None", "def first_dup(s):\n for i,v in enumerate(s):\n if v in s[i+1:]:\n return v", "def first_dup(s):\n for i in [ [s.count(i),i] for i in s ]:\n if i[0]>1:\n return i[1]\n", "def first_dup(s):\n if not s: return None\n for i in range(len(s)-1):\n if s[i] in s[i+1:]:\n return s[i]\n return None", "def first_dup(text):\n for t in text:\n if text.count(t) > 1:\n return t"] | {"fn_name": "first_dup", "inputs": [["tweet"], ["Ode to Joy"], ["ode to joy"], ["bar"]], "outputs": [["t"], [" "], ["o"], [null]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,100 |
def first_dup(s):
|
5719ce5e3346be74a0d918234aba05d4 | UNKNOWN | Write a function that reverses the bits in an integer.
For example, the number `417` is `110100001` in binary. Reversing the binary is `100001011` which is `267`.
You can assume that the number is not negative. | ["def reverse_bits(n):\n return int(bin(n)[:1:-1],2)", "def reverse_bits(n):\n return int(f'{n:b}'[::-1],2)", "def reverse_bits(n):\n return int(bin(n)[-1:1:-1], 2)", "def reverse_bits(n):\n listbin = [bin(n)]\n listbin.sort(reverse = True)\n pleasework = list(''.join(listbin))\n comeonguy = ''.join(pleasework)\n almostanswer = comeonguy[:1:-1]\n answer = int(almostanswer,2)\n return answer\n \n \n #bin(almost)\n pass", "def reverse_bits(n):\n return int(format(n, \"b\")[::-1], 2)", "def reverse_bits(n):\n return int(''.join(reversed(bin(n)[2:])), 2)", "reverse_bits = lambda n: int(bin(n)[:1:-1], 2)", "def reverse_bits(n):\n return int(bin(n)[2:][::-1], 2)", "def reverse_bits(n):\n a = '{0:08b}'.format(n)\n b = list(a)\n b.reverse()\n c = ''\n for i in b: \n c += (i)\n return(int(c,2))\n", "def reverse_bits(n):\n \n b = \"{0:b}\".format(n)\n \n return int(b[::-1], 2)\n"] | {"fn_name": "reverse_bits", "inputs": [[417], [267], [0], [2017], [1023], [1024]], "outputs": [[267], [417], [0], [1087], [1023], [1]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 972 |
def reverse_bits(n):
|
15346767d41c637a5d4f80f0b936b921 | UNKNOWN | Your task is to create a function that does four basic mathematical operations.
The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.
### Examples
```python
basic_op('+', 4, 7) # Output: 11
basic_op('-', 15, 18) # Output: -3
basic_op('*', 5, 5) # Output: 25
basic_op('/', 49, 7) # Output: 7
``` | ["def basic_op(operator, value1, value2):\n if operator=='+':\n return value1+value2\n if operator=='-':\n return value1-value2\n if operator=='/':\n return value1/value2\n if operator=='*':\n return value1*value2", "def basic_op(operator, value1, value2):\n return eval(\"{}{}{}\".format(value1, operator, value2))", "def basic_op(operator, value1, value2):\n return eval(str(value1) + operator + str(value2))", "def basic_op(o, a, b):\n return {'+':a+b,'-':a-b,'*':a*b,'/':a/b}.get(o)", "def basic_op(operator, value1, value2):\n if operator == \"+\":\n return value1 + value2\n elif operator == \"-\":\n return value1 - value2\n elif operator == \"*\":\n return value1 * value2\n elif operator == \"/\":\n return value1 / value2\n else:\n print (\"Unrecognized Operator. Abort.\")", "def basic_op(operator, value1, value2):\n return eval(f'{value1}{operator}{value2}')", "def basic_op(operator, value1, value2):\n ops = {'+': lambda a, b: a + b, \n '-': lambda a, b: a - b,\n '*': lambda a, b: a * b,\n '/': lambda a, b: a / b}\n return ops[operator](value1, value2)", "def basic_op(operator, value1, value2):\n if operator == '+':\n return value1 + value2\n if operator == '-':\n return value1 - value2\n if operator == '*':\n return value1 * value2\n if operator == '/':\n return value1 / value2", "def basic_op(op, v1, v2):\n return v1+v2 if op == \"+\" else v1-v2 if op == \"-\" else v1*v2 if op == \"*\" else v1/v2", "def basic_op(operator, value1, value2):\n if operator == '+':\n result = value1 + value2\n if operator == '-':\n result = value1 - value2\n if operator == '*':\n result = value1 * value2\n elif operator == '/':\n result = value1 / value2\n return(result)\n \n", "def basic_op(operator, value1, value2):\n if operator == '+':\n return value1 + value2\n elif operator == '-':\n return value1 - value2\n elif operator == '*':\n return value1 * value2\n else:\n return value1 / value2", "def basic_op(operator, value1, value2):\n return {\"+\": value1 + value2,\n \"-\": value1 - value2,\n \"*\": value1 * value2,\n \"/\": value1 / value2,\n }[operator]", "def basic_op(operator, value1, value2):\n op = {\n '+' : (value1 + value2),\n '-' : (value1 - value2),\n '*' : (value1 * value2),\n '/' : (value1 / value2),\n }\n \n return op[operator]\n #your code here\n", "def basic_op(operator, x, y):\n if operator == \"+\":\n return x + y\n if operator == \"-\":\n return x - y\n if operator == \"*\":\n return x * y\n if operator == \"/\":\n return x / y", "import operator\ndef basic_op(operator, value1, value2):\n #your code here \n if operator == '+':\n return value1+value2\n elif operator == '-':\n return value1-value2\n elif operator == '/':\n return value1/value2\n elif operator == '*':\n return value1*value2\n else: return", "basic_op = lambda o, v1, v2: __import__(\"operator\").__dict__[{\"+\":\"add\",\"-\":\"sub\", \"*\":\"mul\", \"/\":\"truediv\"}[o]](v1,v2)", "def basic_op(operator, value1, value2):\n dict = {'+': lambda x,y: x+y, '-': lambda x,y: x-y, '*': lambda x,y: x*y, '/': lambda x,y: x/y}\n return dict[operator](value1,value2)", "def basic_op(operator, value1, value2):\n return eval(str(value1)+str(operator)+str(value2))", "import operator\ndef basic_op(op, value1, value2):\n oper={'+':operator.add,'-':operator.sub,'*':operator.mul,'/':operator.truediv}\n return oper[op](value1,value2)", "\ndef basic_op(*sheeps):\n hungry_wolf_eats = eval\n sheeps_in_order = '{1}{0}{2}'.format(*sheeps)\n return hungry_wolf_eats(sheeps_in_order)", "def basic_op(o, v1, v2):\n if o == \"+\":\n return v1+v2\n elif o == \"-\":\n return v1-v2\n elif o == \"*\":\n return v1*v2\n elif o == \"/\":\n return v1/v2\n else:\n return \"not recognized\"", "import operator\n\ndef basic_op(operatorchar, value1, value2):\n return {'+':operator.add,\n '-' : operator.sub,\n '*' : operator.mul,\n '/' : operator.truediv,\n '%' : operator.mod,\n '^' : operator.xor\n }[operatorchar](value1,value2)\n \n", "def basic_op(operator, value1, value2):\n if operator == '+':\n return value1 + value2\n elif operator == '-':\n return value1 - value2\n elif operator == '*':\n return value1 * value2;\n elif operator == '/':\n return value1/value2 if value2 != 0 else value1\n return None", "def basic_op(operator, value1, value2):\n #your code her\n \n return eval(str(value1) + operator + str(value2))", "def basic_op(operator, value1, value2):\n e = '%s %s %s' % (value1, operator, value2)\n return eval(e)", "def basic_op(op, x, y):\n if op == '+':\n return (x+y)\n elif op == '-':\n return (x-y)\n elif op == '*':\n return (x*y)\n else:\n return (x/y)", "basic_op = lambda o, v1, v2: eval(\"{}{}{}\".format(v1,o,v2))", "import operator as op\ndef basic_op(operator, value1, value2):\n #your code here\n return {'+': op.add,'-': op.sub,'*': op.mul,'/':op.truediv}[operator](value1,value2)", "def basic_op(operator, value1, value2):\n a = int(value1)\n b = int(value2)\n if operator == \"+\":\n output = a + b\n elif operator == \"-\":\n output = a - b\n elif operator == \"*\":\n output = a*b\n else:\n output = a/b\n return output", "def basic_op(operator, value1, value2):\n return value1+value2 if operator=='+' else value1-value2 if operator=='-' else value1*value2 if operator=='*' else value1/value2", "basic_op = lambda o,a,b: eval(str(a)+o+str(b))", "def basic_op(operator, value1, value2):\n return {\n '+': lambda a, b: a + b,\n '-': lambda a, b: a - b,\n '*': lambda a, b: a * b,\n '/': lambda a, b: a / b,\n }[operator](value1, value2)", "def basic_op(o, v1, v2):\n return eval(str(v1) + o + str(v2))", "def basic_op(operator, value1, value2):\n op = {\n '+':int.__add__,\n '-':int.__sub__,\n '*':int.__mul__,\n '/':int.__truediv__\n }\n return op[operator](value1, value2)", "basic_op = lambda o, v1, v2: eval(f'{v1}{o}{v2}')", "def basic_op(operator, value1, value2):\n if operator == '+' and type(value1) == int and type(value2) == int:\n return value1 + value2\n if operator == '-':\n return value1 - value2\n if operator == '*':\n return value1 * value2\n else: \n return value1 / value2\n", "\noperations = {\n '*': lambda value1, value2: value1 * value2,\n '-': lambda value1, value2: value1 - value2,\n '/': lambda value1, value2: value1 / value2,\n '+': lambda value1, value2: value1 + value2,\n}\n\ndef basic_op(operator, value1, value2):\n return operations[operator](value1,value2)", "basic_op = lambda o,v1,v2: int.__dict__[{\"+\":\"__add__\",\"-\":\"__sub__\",\"*\":\"__mul__\",\"/\":\"__truediv__\"}[o]](v1,v2)", "basic_op=lambda o,a,b:eval(f\"{a}{o}{b}\")#can you beat 40 characters?", "import operator\n\ndef basic_op(oper, value1, value2):\n d = {'-': operator.sub, '+': operator.add, '*': operator.mul, '/': operator.truediv }\n return d[oper](value1, value2)", "from operator import add, sub, truediv, mul\n\ndef basic_op(operator, v1, v2):\n op = {\"+\": add, \"-\": sub, \"*\": mul, \"/\": truediv}\n return op[operator](v1, v2)", "from operator import add, sub, mul, truediv\nOPS = {'+': add, '-': sub, '*': mul, '/': truediv}\n\ndef basic_op(op, a, b):\n return OPS[op](a, b)", "import operator\nfrom functools import reduce\n\n\ndef basic_op(operator_mark, value1, value2):\n d = {'+': operator.add,\n '-': operator.sub,\n '*': operator.mul,\n '/': operator.truediv}\n return d[operator_mark](value1, value2)\n", "def basic_op(operator, value1, value2):\n return {\"+\" : value1 + value2, \"-\" : value1 - value2, \"*\" : value1 * value2, \"/\" : value1 / value2}.get(operator)", "def basic_op(o, v1, v2):\n return eval('{}{}{}'.format(v1, o, v2))", "def basic_op(operator, value1, value2):\n if operator=='+': return value1+value2\n elif operator=='-': return value1-value2\n elif operator=='*': return value1*value2\n elif operator=='/': return value1/value2\n else: return None", "def basic_op(operator, value1, value2):\n return eval('{0} {1} {2}'.format(value1, operator, value2))", "def basic_op(operator, value1, value2):\n return eval(\"\".join([str(value1), operator, str(value2)]))", "def basic_op(operator, value1, value2):\n if operator == '+':\n return value1 + value2\n elif operator == '-':\n return value1 - value2\n elif operator == '*':\n return value1 * value2\n elif operator == '/':\n return value1 / value2\n else:\n print('I don\\'t recognize '+str(operator)+' as an operator.')", "def basic_op(operator, value1, value2):\n ans = str(value1) +operator + str(value2)\n return eval(ans)", "def basic_op(operator, value1, value2):\n return eval(\"{val1}{operator}{val2}\".format(val1=value1,operator=operator,val2=value2))", "def basic_op(operator, v1, v2):\n \n if operator == '+':\n a1 = v1 + v2\n elif operator == '-':\n a1 = v1 - v2\n elif operator == '*':\n a1 = v1 * v2\n elif operator == '/':\n a1 = v1 / v2\n else:\n print('You have not typed a valid operator, please run the program again.')\n return a1", "def basic_op(operator, value1, value2):\n #return eval(str(value1)+operator+str(value2)) or\n return eval(\"{}{}{}\".format(value1, operator, value2))", "def basic_op(operator, value1, value2):\n if operator == '+':\n result = value1 + value2\n elif operator == '-':\n result = value1 - value2\n elif operator == '*':\n result = value1 * value2\n elif operator == '/':\n result = value1 / value2\n else:\n result = None\n return result\n \n", "def basic_op(operator, value1, value2):\n if operator == '+':\n res = value1 + value2\n return res\n elif operator == '-':\n res = value1 - value2\n return res\n elif operator == '*':\n res = value1 * value2\n return res\n elif operator == '/':\n res = value1 / value2\n return res\n else:\n print(\"Use only (+ - * /) functions\")\n", "# function takes two numbers and basic math operator character to perform on the numbers\ndef basic_op(operator, value1, value2):\n # series of if statements to determine basic operator and return result\n if operator == '+': return value1 + value2\n elif operator == '-': return value1 - value2\n elif operator == '*': return value1 * value2\n elif operator == '/': return value1 / value2", "def basic_op(oper, a, b):\n return [a + b, a - b, a * b, a / b][(oper == '-') + 2 * (oper == '*') + 3 * (oper == '/')]", "def basic_op(operator, value1, value2):\n calc = {\n '+': lambda x,y: x+y,\n '-': lambda x,y: x-y,\n '*': lambda x,y: x*y,\n '/': lambda x,y: x/y\n }\n return calc[operator](value1,value2)", "from operator import add, sub, mul, truediv\n\ndef basic_op(operator, value1, value2):\n ops = {\"+\": add, \"-\": sub, \"*\": mul, \"/\": truediv}\n return ops.get(operator)(value1, value2)", "import operator as op\ndef basic_op(operator, value1, value2):\n op_dict = {'+':op.add, '-':op.sub, '*':op.mul, '/':op.truediv}\n return op_dict[operator](value1, value2)", "def basic_op(operation, value1, value2):\n # if operator is +, add\n if operation == \"+\": return value1 + value2\n # if operator is -, subtract\n elif operation == \"-\": return value1 - value2\n # if operator is *, multiply\n elif operation == \"*\": return value1 * value2\n # if none of the operators match, simply divide\n else: return value1 / value2\n\nprint(basic_op('+', 4, 7)) # Output: 11\nprint(basic_op('-', 15, 18)) # Output: -3\nprint(basic_op('*', 5, 5)) # Output: 25\nprint(basic_op('/', 49, 7)) # Output: 7", "def basic_op(operator, value1, value2):\n if operator[0] == \"+\":\n return value1 + value2 \n elif operator[0] == \"-\":\n return value1 - value2\n elif operator[0] == \"*\":\n return value1 * value2\n elif operator[0] == \"/\":\n return value1 / value2 \n", "def basic_op(operator, value1, value2):\n if (operator == '+'):\n return(value1+value2)\n elif (operator == '-'):\n return(value1-value2)\n elif (operator == '*'):\n return(value1*value2)\n elif (operator == '/'):\n return(value1/value2)\n else:\n print(\"invalid operation\")", "def basic_op(operator, value1, value2):\n if operator in \"+\":\n return value1 + value2\n elif operator in \"-\":\n return value1 - value2\n elif operator in \"*\":\n return value1 * value2\n elif operator in \"/\":\n return value1 / value2\n else:\n pass", "def basic_op(operator, value1, value2):\n arr = [str(value1), operator, str(value2)]\n return eval(''.join(arr))", "def basic_op(operator, value1, value2):\n ops = {\"+\": (lambda x,y: x+y), \"-\": (lambda x,y: x-y), \"-\": (lambda x,y: x-y), \"*\": (lambda x,y: x * y), \"/\": (lambda x,y: x/y)}\n return ops[operator] (value1, value2)", "from operator import add, sub, mul, truediv\ndef basic_op(op, v, v2):\n return {'+':add,'-':sub,'*':mul,'/':truediv}[op](v,v2)", "def basic_op(operator, value1, value2):\n #your code here\n if operator == '+':\n x = lambda a, b: a+b\n return (x(value1, value2))\n if operator == '-':\n x = lambda a, b: a-b\n return (x(value1, value2))\n if operator == '*':\n x = lambda a, b: a*b\n return (x(value1, value2))\n if operator == '/':\n x = lambda a, b: a/b\n return (x(value1, value2))", "def basic_op(operator, value1, value2):\n switch = {\n '+': value1 + value2,\n '-': value1 - value2,\n '*': value1 * value2,\n '/': value1 / value2,\n }\n return switch.get(operator, \"Invalid Operator\")\n", "def basic_op(operator, value1, value2):\n p = '-'\n s = '+'\n r = '*'\n e = '/'\n if p in operator:\n return value1 - value2\n elif s in operator:\n return value1 + value2\n elif r in operator:\n return value1 * value2\n elif e in operator:\n return value1 / value2\n", "basic_op=lambda o,v,w:{'+':lambda a,b:a+b,'-':lambda a,b:a-b,'*':lambda a,b:a*b,'/':lambda a,b:a/b}[o](v,w)", "def basic_op(operator, value1, value2):\n if operator == '+': return value1 + value2\n elif operator == '*': return value1 * value2\n elif operator == '/': return value1 / value2\n elif operator == '-': return value1 - value2\n \nprint(basic_op('*',7,6))", "def basic_op(operator, value1, value2):\n multiplication = value1*value2\n division = value1/value2\n addition = value1+value2\n subtraction = value1-value2\n result = 0\n \n if operator == \"*\":\n result = multiplication\n if operator == \"/\":\n result = division\n if operator == \"+\":\n result = addition\n if operator == \"-\":\n result = subtraction\n return result", "def basic_op(operator, value1, value2):\n b=str(value1)+operator+str(value2)\n return eval(b)", "def basic_op(op, v1, v2):\n if op=='+':\n return v1+v2\n elif op=='-':\n return v1-v2\n elif op=='*':\n return v1*v2\n elif op=='/':\n return float(v1/v2)", "def basic_op(operator, value1, value2):\n if operator == '+': #addition\n return value1 + value2\n elif operator == '-': #subtraction\n return value1 - value2\n elif operator == '*': #multiplication\n return value1 * value2\n elif operator == '/': #division\n return value1 / value2", "import operator\n\n\nops = {\n \"+\": operator.add,\n \"-\": operator.sub,\n \"*\": operator.mul,\n \"/\": operator.truediv\n}\n\n\ndef basic_op(oper, value1, value2):\n return ops[oper](value1, value2)", "def basic_op(operator, value1, value2):\n operation = str(value1) + str(operator) + str(value2)\n return eval(operation)\n", "def basic_op(operator, v1, v2):\n if operator == \"+\":\n return v1+v2\n elif operator == \"-\":\n return v1-v2\n elif operator == \"*\":\n return v1*v2\n elif operator == \"/\":\n return v1/v2\n else:\n return -1", "def basic_op(operator, value1, value2):\n #your code here\n if operator == \"+\":\n answer = int(value1) + int(value2)\n elif operator == \"-\":\n answer = int(value1) - int(value2)\n elif operator == \"*\":\n answer = int(value1) * int(value2)\n else:\n answer = int(value1) / int(value2)\n return answer", "def basic_op(op, num1, num2):\n if(op) == \"*\":\n return num1*num2\n elif(op) == \"+\":\n return num1+num2\n elif(op) == \"/\":\n return num1/num2\n elif(op) == \"-\":\n return num1 - num2", "def basic_op(operator, value1, value2):\n if operator == '+':\n return value1 + value2\n elif operator == '-':\n return value1 - value2\n elif operator == '*':\n return value1 * value2\n elif operator == '/':\n return value1 / value2\n else:\n return 'invalid operator'\n\nprint(basic_op('+', 1, 2))", "def basic_op(operator, value1, value2):\n x = str(value1),operator,str(value2)\n x = eval(''.join(x))\n return x", "def basic_op(*a):\n return eval('{1}{0}{2}'.format(*a))", "def basic_op(operator, value1, value2):\n k = {'+': value1+value2, '-': value1-value2, '*': value1*value2, '/':value1/value2}\n return k[operator]", "def basic_op(operator, value1, value2):\n if operator == '+':\n return value1 + value2 \n if operator == '-':\n return value1 - value2 \n if operator == '*':\n return value1 * value2\n else:\n return value1 / value2\n return basic_op\n", "def basic_op(op, x, y):\n if op == '+':\n a = x + y\n elif op == '-':\n a = x - y\n elif op == '*':\n a = x * y\n elif op == '/':\n a = x / y\n return a", "def basic_op(operator, value1, value2):\n def div(a, b):\n return a/b\n operations_mapping = {\"+\": int.__add__,\n \"-\": int.__sub__,\n \"*\": int.__mul__,\n \"/\": div}\n return operations_mapping[operator](value1, value2)", "def basic_op(operator,v1,v2):\n if operator =='-':\n new=v1-v2\n\n elif operator=='+':\n new=v1+v2\n\n elif operator=='*':\n new = v1*v2\n\n else:\n new = v1/v2\n\n return new", "def basic_op(operator, value1, value2):\n # operator = string\n # value1 = num\n # value2 = num\n \n if (operator == '*'):\n return value1 * value2\n elif (operator == '+'):\n return value1 + value2\n elif (operator == '-'):\n return value1 - value2\n elif (operator == '/'):\n return value1 / value2\n", "def basic_op(operator, value1, value2):\n if operator == '+':\n summary = value1 + value2\n return summary\n if operator == '-':\n summary = value1 - value2\n return summary\n if operator == '*':\n summary = value1 * value2\n return summary\n if operator == '/':\n summary = value1 / value2\n return summary\n return None", "def basic_op(operator, value1, value2):\n #your code here\n if operator == '*':\n result = value1 * value2\n elif operator == '+':\n result = value1 + value2\n elif operator == '/':\n result = value1 / value2\n elif operator == '-':\n result = value1 - value2\n return result", "def basic_op(operator, value1, value2):\n anwser=0\n if operator == \"+\":\n anwser = value1+value2\n elif operator == \"-\":\n anwser = value1-value2\n elif operator == \"*\":\n anwser = value1*value2\n elif operator == \"/\":\n anwser = value1/value2\n return anwser", "def _sum(value1, value2):\n return value1 + value2\n\ndef _substract(value1, value2):\n return value1 - value2\n\ndef _multiply(value1, value2):\n return value1 * value2\n\ndef _divide(value1, value2):\n return value1 / value2\n\n\nOPERATORS_MAP = {\n \"+\": _sum,\n \"-\": _substract,\n \"*\": _multiply,\n \"/\": _divide,\n}\n\ndef basic_op(operator, value1, value2):\n \n result = OPERATORS_MAP[operator](value1, value2)\n\n return result", "def basic_op(operator, value1, value2):\n #your code here\n operator == str(operator)\n value1 == float(value1)\n value2 == float(value2)\n if operator == '+':\n addition = float(value1 + value2)\n return addition\n elif operator == '-':\n return value1 - value2\n elif operator == '*':\n return value1 * value2\n else:\n division = value1/value2\n return division", "def basic_op(operator, a, b):\n return a+b if operator=='+' else a-b if operator=='-' else a*b if operator=='*' else a/b", "def basic_op(op, v1, v2):\n if op == '/' and v2 == 0:\n return 'Error! Division by zero!'\n if op not in '+-*/':\n return 'Error! Wrong operator!'\n if op == '+':\n return v1 + v2\n if op == '-':\n return v1 - v2\n if op == '*':\n return v1 * v2\n return v1 / v2", "import operator\ndef basic_op(operator, value1, value2):\n s= str(value1)+operator+str(value2)\n return eval(s)"] | {"fn_name": "basic_op", "inputs": [["+", 4, 7], ["-", 15, 18], ["*", 5, 5], ["/", 49, 7]], "outputs": [[11], [-3], [25], [7]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 22,087 |
def basic_op(operator, value1, value2):
|
75b495066d40c765ce0f6bce162917f5 | UNKNOWN | # Task
Given an array `arr`, find the maximal value of `k` such `a[i] mod k` = `a[j] mod k` for all valid values of i and j.
If it's impossible to find such number (there's an infinite number of `k`s), return `-1` instead.
# Input/Output
`[input]` integer array `arr`
A non-empty array of positive integer.
`2 <= arr.length <= 10`
`1 <= arr[i] <= 100`
`[output]` an integer
The maximum value of `k` or `-1` if there is none.
# Example
For `arr = [1, 2, 3]`, the output should be `1`.
`1` is the only k which satisfies the given conditions.
For `arr = [1, 1, 1]`, the output should be `-1`.
`1 % k = 1` for `any k > 1`, so it's impossible to find the maximum.
For `arr = [5, 2, 8]`, the output should be `3`.
`5 % 3 == 2 % 3 == 8 % 3 == 2` | ["def finding_k(arr):\n for n in range(max(arr)-1, 0, -1):\n if len({ x%n for x in arr }) == 1: return n\n return -1", "from itertools import repeat\nfrom functools import reduce\nfrom operator import sub\nfrom math import gcd\n\ndef finding_k(arr):\n return reduce(gcd, filter(None, map(sub, set(arr), repeat(min(arr)))), 0) or -1", "def finding_k(arr):\n s = set(arr)\n if s == {1}:\n return -1\n for k in range(max(s), 0, -1):\n r = arr[0] % k\n if all(x % k == r for x in s):\n return k\n return -1\n \n", "finding_k=lambda a: max([k for k in range(1, max(a)) if eval('=='.join([str(z)+'%'+str(k) for z in a]))], default=-1)", "def finding_k(arr):\n for i in range(max(arr)-1, 0, -1):\n if len({j%i for j in arr}) == 1: return i\n return -1", "finding_k=lambda a:next((i for i in range(max(a)-1,0,-1)if len(set([j%i for j in a]))==1),-1)", "from fractions import gcd\nfrom functools import reduce\n\ndef finding_k(arr):\n fr = [x-min(arr) for x in arr]\n if all(v == 0 for v in fr):\n return -1\n else:\n return reduce(lambda x,y:gcd(x,y),fr)", "def finding_k(arr):\n #your code here\n maxValue = max(arr) - min(arr)\n k = 0\n while maxValue>0:\n if len(set(map(lambda x:x%maxValue,arr))) == 1:\n k = maxValue\n break\n maxValue -= 1\n if k:\n return k\n else:\n return -1", "from functools import reduce; gcd=lambda a,b: gcd(b,a%b) if b else a; finding_k=lambda arr: reduce(lambda a,b: gcd(a,b), [abs(e-arr[0]) for e in arr]) or -1", "def finding_k(arr):\n ans=[]\n for i in range(1,101):\n if len({j%i for j in arr})==1:\n ans.append(i)\n return max(ans) if len(ans)<100 else -1"] | {"fn_name": "finding_k", "inputs": [[[1, 2, 3]], [[1, 1, 1]], [[5, 2, 8]], [[4, 1, 7]], [[1, 7, 13]], [[4, 5, 4]], [[5, 6, 7, 8]], [[10, 100]], [[64, 8, 1]], [[2, 9, 30]]], "outputs": [[1], [-1], [3], [3], [6], [1], [1], [90], [7], [7]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,781 |
def finding_k(arr):
|
bc7074edd7ad782ac97b6e0bf6f2240a | UNKNOWN | Given a string containing a list of integers separated by commas, write the function string_to_int_list(s) that takes said string and returns a new list containing all integers present in the string, preserving the order.
For example, give the string "-1,2,3,4,5", the function string_to_int_list() should return [-1,2,3,4,5]
Please note that there can be one or more consecutive commas whithout numbers, like so: "-1,-2,,,,,,3,4,5,,6" | ["def string_to_int_list(s):\n return [int(n) for n in s.split(\",\") if n]", "def string_to_int_list(s):\n return [int(x) for x in s.split(',') if x != '']", "def string_to_int_list(s):\n return [int(x) for x in s.split(',') if x]", "import re\nnumber_pattern = re.compile(\"-?[0-9]+\")\n\ndef string_to_int_list(s):\n return [int(c) for c in s.split(\",\") if re.match(number_pattern, c)]\n\n", "def string_to_int_list(s):\n return [int(nb) for nb in s.split(',') if nb]", "def string_to_int_list(s):\n return [int(x) for x in s.split(',') if len(x)>0]", "def string_to_int_list(string):\n return [int(i) for i in (string.split(',')) if i.isdigit() or i.startswith('-') and i[1:].isdigit()]", "def string_to_int_list(s):\n def isint(j): \n try:\n int(j)\n return True\n except:\n return False\n return [int(i) for i in s.split(\",\") if isint(i)]"] | {"fn_name": "string_to_int_list", "inputs": [["1,2,3,4,5"], ["21,12,23,34,45"], ["-1,-2,3,-4,-5"], ["1,2,3,,,4,,5,,,"], [",,,,,1,2,3,,,4,,5,,,"], [""], [",,,,,,,,"]], "outputs": [[[1, 2, 3, 4, 5]], [[21, 12, 23, 34, 45]], [[-1, -2, 3, -4, -5]], [[1, 2, 3, 4, 5]], [[1, 2, 3, 4, 5]], [[]], [[]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 927 |
def string_to_int_list(s):
|
ac5a81578e046d7bec6381301d498229 | UNKNOWN | Given an integer, take the (mean) average of each pair of consecutive digits. Repeat this process until you have a single integer, then return that integer. e.g.
Note: if the average of two digits is not an integer, round the result **up** (e.g. the average of 8 and 9 will be 9)
## Examples
```
digitsAverage(246) ==> 4
original: 2 4 6
\ / \ /
1st iter: 3 5
\ /
2nd iter: 4
digitsAverage(89) ==> 9
original: 8 9
\ /
1st iter: 9
```
p.s. for a bigger challenge, check out the [one line version](https://www.codewars.com/kata/one-line-task-digits-average) of this kata by myjinxin2015! | ["def digits_average(input):\n digits = [int(c) for c in str(input)]\n while len(digits) > 1:\n digits = [(a + b + 1) // 2 for a, b in zip(digits, digits[1:])]\n return digits[0]", "digits_average=a=lambda n:n>9and a(int(''.join(str(-~int(a)+int(b)>>1)for a,b in zip(str(n),str(n)[1:]))))or n", "import math\ndef digits_average(n):\n a = [int(i) for i in list(str(n))]\n e = [a[i:i + 2] for i in range(len(a) - 1)]\n return n if len(str(n)) == 1 else digits_average(int(''.join([str(math.ceil(sum(i)/2)) for i in e])))", "digits_average=f=lambda n:type(n)!=int and(len(n)>1and f([-~a+b>>1 for a,b in zip(n,n[1:])])or n[0])or f([int(e)for e in str(n)])", "import math\ndef digits_average(input):\n m = str(input)\n for i in range(len(str(input))-1):\n m = ''.join(str(math.ceil(int(m[i])/2 + int(m[i+1])/2)) for i in range(len(m) - 1))\n return int(m)", "from math import ceil\ndef digits_average(input):\n if input < 10:\n return input\n else:\n l = [int(i) for i in list(str(input))]\n r = [ceil(sum(i)/2.0) for i in list(zip(l,l[1:]))]\n return r[0] if len(r) == 1 else digits_average(int(\"\".join([str(i) for i in r])))", "from math import ceil\n\n\ndef digits_average(input):\n def return_average(a, b):\n return str(ceil((int(a) + int(b)) / 2))\n\n string_ = str(input)\n\n while len(string_) > 1:\n string_ = ''.join(\n return_average(a, b) for a, b in zip(string_, string_[1:]))\n\n return int(string_)", "import math\ndef convert_to_list(number):\n lst=[]\n while number!=0:\n lst.append(number%10)\n number=int(number/10)\n return lst\n\ndef list_to_list(lst):\n average_list=[]\n for i in range(len(lst)-1):\n average_list.append(math.ceil((lst[i]+lst[i+1])/2))\n return average_list\n\ndef digits_average(digits):\n lst=convert_to_list(digits)\n while len(lst)>1:\n lst=list_to_list(lst)\n return lst[0]\n", "def digits_average(input):\n l=[int(list(str(input))[i]) for i in range(len(str(input)))]\n while len(l)!=1:\n l=[(l[i]+l[i+1])//2+(l[i]+l[i+1])%2 for i in range(len(l)-1)]\n return l[0]\n", "import math\ndef digits_average(num):\n a = str(num)\n b = []\n a = [n for n in a]\n for i in a:\n b.append(int(i))\n if(len(b) == 1):\n return b[0]\n while(len(a) > 1):\n c = 0\n while(c <= len(b) - 2):\n d = b[c] + b[c + 1]\n d = math.ceil(d / 2)\n b[c] = d\n c += 1\n del(b[len(b) - 1])\n if(len(b) == 1):\n return b[0]"] | {"fn_name": "digits_average", "inputs": [[246], [89], [2], [245], [345], [346], [3700]], "outputs": [[4], [9], [2], [4], [5], [5], [4]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,610 |
def digits_average(input):
|
3b6b7dfe0d228a931028e4dc08364978 | UNKNOWN | # Task
Given some sticks by an array `V` of positive integers, where V[i] represents the length of the sticks, find the number of ways we can choose three of them to form a triangle.
# Example
For `V = [2, 3, 7, 4]`, the result should be `1`.
There is only `(2, 3, 4)` can form a triangle.
For `V = [5, 6, 7, 8]`, the result should be `4`.
`(5, 6, 7), (5, 6, 8), (5, 7, 8), (6, 7, 8)`
# Input/Output
- `[input]` integer array `V`
stick lengths
`3 <= V.length <= 100`
`0 < V[i] <=100`
- `[output]` an integer
number of ways we can choose 3 sticks to form a triangle. | ["from itertools import combinations\n\ndef counting_triangles(v):\n v.sort()\n return sum(a+b>c for a,b,c in combinations(v,3))", "counting_triangles=lambda V:sum(a+b>c for a,b,c in __import__('itertools').combinations(sorted(V),3))", "import itertools\ndef counting_triangles(V):\n count = 0\n for x in itertools.combinations(V,3):\n if(sum([x[0]+x[1]>x[2],x[0]+x[2]>x[1],x[1]+x[2]>x[0],abs(x[0]-x[1])<x[2],abs(x[0]-x[2])<x[1],abs(x[1]-x[2])<x[0]])==6):\n count += 1\n return count", "from itertools import combinations\ndef counting_triangles(V):\n count = 0\n for i in combinations(V,3):\n i = sorted(i)\n if i[0]+i[1] > i[2]:\n count += 1\n return count", "from itertools import combinations\ndef counting_triangles(V):\n number = 0\n for i in sorted(combinations(V, 3)):\n x, y, z = sorted(i)\n if x + y > z:\n number += 1\n return number", "from itertools import combinations \ndef counting_triangles(V):\n return sum(sum(comb)>2*max(comb) for comb in combinations(V , 3))", "counting_triangles=lambda v:len([x for x in list(__import__('itertools').combinations(v,3)) if all([k<sum(x)-k for k in x])])", "counting_triangles=lambda V:sum(c<a+b for a,b,c in __import__('itertools').combinations(sorted(V),3))", "counting_triangles=lambda V:(lambda v,W:sum([W[k]<W[i]+W[j]for i in range(v)for j in range(i+1,v)for k in range(j+1,v)]))(len(V),sorted(V))", "from itertools import combinations as C\n\ndef counting_triangles(V):\n return sum(a + b > c for a, b, c in C(sorted(V), 3))"] | {"fn_name": "counting_triangles", "inputs": [[[2, 3, 7, 4]], [[5, 6, 7, 8]], [[2, 2, 2, 2]], [[1, 2, 5]], [[1, 2, 3, 10, 20, 30, 4]], [[1, 2, 3]]], "outputs": [[1], [4], [4], [0], [1], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,591 |
def counting_triangles(V):
|
779a0b9074e86cafefe4532f9cf43592 | UNKNOWN | # How many urinals are free?
In men's public toilets with urinals, there is this unwritten rule that you leave at least one urinal free
between you and the next person peeing.
For example if there are 3 urinals and one person is already peeing in the left one, you will choose the
urinal on the right and not the one in the middle.
That means that a maximum of 3 people can pee at the same time on public toilets with
5 urinals when following this rule (Only 2 if the first person pees into urinal 2 or 4).

## Your task:
You need to write a function that returns the maximum of free urinals as an integer according to the unwritten rule.
### Input
A String containing 1s and 0s (Example: `10001`) (1 <= Length <= 20)
A one stands for a taken urinal and a zero for a free one.
### Examples
`10001` returns 1 (10101)
`1001` returns 0 (1001)
`00000` returns 3 (10101)
`0000` returns 2 (1001)
`01000` returns 1 (01010 or 01001)
### Note
When there is already a mistake in the input string (for example `011`), then return `-1`
Have fun and don't pee into the wrong urinal ;) | ["def get_free_urinals(urinals):\n return -1 if '11' in urinals else sum(((len(l)-1)//2 for l in f'0{urinals}0'.split('1')))", "def get_free_urinals(urinals):\n if '11' in urinals: return -1\n if urinals == '0': return 1\n free = 0\n i = 0\n while (i < len(urinals)):\n if i == 0 and urinals[i:i+2] == '00' or i > 0 and urinals[i-1:i+2] == '000' or i == len(urinals) - 1 and urinals[i-1:] == '00':\n free += 1\n i += 2\n else:\n i += 1\n return free", "def get_free_urinals(urinals):\n if urinals.count('11'): return -1\n return urinals.replace('10', '1').replace('01', '1').replace('00','0').count('0')", "def get_free_urinals(urinals):\n if '11' in urinals:\n return -1\n us = list(map(int, urinals + '00'))\n free = 0\n for i in range(len(urinals)):\n if us[i] == 0 == us[i-1] == us[i+1]:\n us[i] = 1\n free += 1\n return free", "import re\n\ndef get_free_urinals(urinals):\n if '11' in urinals:\n return -1\n return sum((len(g) + 1) // 2 for g in re.split('0?1+0?', urinals))", "def get_free_urinals(urinals):\n if '11' in urinals: return -1\n return sum((len(s)-1)//2 for s in f'10{urinals}01'.split('1') if s) ", "import re\n\ndef get_free_urinals(urinals):\n return -1 if \"11\" in urinals else sum((1 + len(sub)) // 2 for sub in re.split(r\"0?10?\", urinals))", "def get_free_urinals(urinals):\n return -1 if \"11\" in urinals else sum(len(x)-1>>1 for x in f\"0{urinals}0\".split('1'))", "def get_free_urinals(urinals):\n count = 0\n urinals = list(urinals)\n \n for i in range(len(urinals)):\n if (urinals[i] == '1'\n and i + 1 != len(urinals) \n and urinals[i+1] == '1' ):\n return -1\n if (urinals[i] == '0'\n and ( i == 0 or urinals[i-1] == '0' ) \n and ( i + 1 == len(urinals) or urinals[i+1] == '0' )\n ):\n urinals[i] = '2'\n return urinals.count('2')", "import re\n\ndef get_free_urinals(u):\n return -1 if '11' in u else len(re.findall(r'(?<!1)0[0$]?(?!1)', u))"] | {"fn_name": "get_free_urinals", "inputs": [["10001"], ["1001"], ["00000"], ["0000"], ["01000"], ["00010"], ["10000"], ["1"], ["0"], ["10"], ["110"], ["1011000001"]], "outputs": [[1], [0], [3], [2], [1], [1], [2], [0], [1], [0], [-1], [-1]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,141 |
def get_free_urinals(urinals):
|
1c9b10c86dafbef34aee68b19982097f | UNKNOWN | ### Background
In classical cryptography, the Hill cipher is a polygraphic substitution cipher based on linear algebra. It was invented by Lester S. Hill in 1929.
### Task
This cipher involves a text key which has to be turned into a matrix and text which needs to be encoded. The text key can be of any perfect square length but for the sake of this kata we will focus on keys of length 4 forming a 2x2 matrix.
To encrypt a message using the hill cipher, first of all you need to convert the text key into a key matrix. To do that you will convert the key row wise into a 2x2 matrix. Then you will substitute the letters with their respective positions on the alphabet: A=0, B=1,C=2 and so on till Z=25. So for example if we get the key text as ```cats```, the key matrix will be:
[[ 2 0]
[19 18]]
Now the next step is to break the text into pairs of two and convert those pairs into 2x1 matrices. If your text has an odd number of letters then just add a Z next to your last letter. Now again convert those letters into their respective position in the alphabet as above. So for example the text ```Hi``` would be converted into:
[[7]
[8]]
Now we need to [multiply](https://www.mathsisfun.com/algebra/matrix-multiplying.html) the key matrix by the text matrix to get our encrypted matrix and then find out the encrypted matrix [modulo](https://en.wikipedia.org/wiki/Modulo_operation) 26:
[[ 2 0] * [[7] = [[14] = [[14] mod 26
[19 18]] [8]] [277]] [17]]
For the final step we just find out the letters at the alphabet position of 14 and 17 which are ```O``` and ```R```. So ```OR``` is our encrypted message for the message ```Hi```
In this kata you will be given a function named ```encrypt``` with the parameters ```text``` and ```key``` and you have to return the encrypted message in all uppercase letters
``` python
encrypt('','azyb') → ''
encrypt('Hi','cats') → 'OR'
encrypt('This is a good day','bbaa') → 'AAAAAAGACAGAYA'
```
Note:
- The text to encrypt will contain characters other than the alphabets, its your job to clean them before converting text to matrices. Spaces also need to be removed
- The text may contain both uppercase and lowercase alphabets. Its your job to standardize them, the encrypted text however should be returned in uppercase letters.
- The key will always contain 4 lowercase alphabet. | ["import numpy as np\nfrom itertools import zip_longest\nfrom string import ascii_lowercase as lower, ascii_uppercase as upper\n\nD = {c:i%26 for i,c in enumerate(lower+upper)}\n\ndef encrypt(text, key):\n result = []\n text = ''.join(filter(str.isalpha, text))\n key = np.array(([D[key[0]], D[key[1]]], [D[key[2]], D[key[3]]]))\n for c1,c2 in zip_longest(text[::2], text[1::2], fillvalue='Z'):\n x,y = key @ ([D[c1]], [D[c2]])\n result.append(upper[x[0]%26] + upper[y[0]%26])\n return ''.join(result)", "import numpy as np\n\ndef encrypt(text,key):\n # Declare string variable to store the answer\n ans=''\n # Covert all the alphabets to upper case and clean everything else\n clean_text=''.join([i.upper() for i in text if i.isalpha()])\n # Add Z to the cleaned text if the length of it is odd\n clean_text+='Z'*(len(clean_text)%2)\n # Return empty string if the cleaned text is empty\n if len(clean_text)==0:\n return ''\n # Find the key matrix\n km=np.matrix([[ord(key[0])-97,ord(key[1])-97],[ord(key[2])-97,ord(key[3])-97]])\n # Create a text matrix\n tm=np.matrix([[ord(clean_text[i])-65,ord(clean_text[i+1])-65] for i in range(0,len(clean_text),2)]).T\n # Multiply the key matrix by the text matrix and apply modulo 26\n am=(km*tm)%26\n # Convert the numbers back to letters and append them to the ans variable\n for i in np.array(am.T): \n ans+=chr(i[0]+65)\n ans+=chr(i[1]+65)\n # Return the answer variable \n return ans", "from string import ascii_letters\nimport numpy as np\n\ndef encrypt(text, key):\n # Character and interger conversions\n code = lambda s: ord(s.lower()) - ord('a')\n letter = lambda n: chr(n + ord('A'))\n\n # Build key\n size = int(len(key) ** 0.5)\n if size ** 2 != len(key):\n raise ValueError('Key must be of length n^2') \n key_matrix = np.array([code(c) for c in key]).reshape(size, size)\n \n # Filter out non letters and pad if necessary\n text = ''.join(c for c in text if c in ascii_letters)\n if len(text) % size != 0:\n text += 'z' * (size - (len(text) % size))\n text_matrix = np.array([code(c) for c in text]).reshape(len(text) // size, size).transpose()\n \n # Perform encoding\n encoded = (key_matrix @ text_matrix) % 26\n return ''.join(letter(n) for n in encoded.transpose().flatten())\n", "def encrypt(text,key):\n final_list=[]\n if text==\"\":\n return \"\"\n alpha_dict={}\n num_lst_1=[]\n alphabet=\"abcdefghijklmnopqrstuvwxyz\"\n for i in range(0,26):\n alpha_dict[alphabet[i]]=i\n for letter in text.lower():\n if letter in alphabet:\n num_lst_1.append(alpha_dict[letter])\n if len(num_lst_1)%2==1:\n num_lst_1.append(25)\n num_lst_2=[]\n for char in key.lower():\n num_lst_2.append(alpha_dict[char])\n sum_row_1=0\n sum_row_2=0\n for x in range(0,len(num_lst_1),2):\n sum_row_1=num_lst_2[0]*num_lst_1[x]+num_lst_2[1]*num_lst_1[x+1]\n sum_row_2=num_lst_2[2]*num_lst_1[x]+num_lst_2[3]*num_lst_1[x+1]\n final_list.append(sum_row_1%26)\n final_list.append(sum_row_2%26)\n enpt=\"\"\n for num in final_list:\n enpt+=alphabet[num]\n return enpt.upper()\n", "import re\n\ndef encrypt(text, key):\n a, b, c, d = (ord(t) - 65 for t in key.upper())\n r = ''\n for x, y in zip(*[iter(re.findall('[A-Z]', text.upper()) + ['Z'])] * 2):\n x, y = (ord(t) - 65 for t in (x, y))\n x, y = (a * x + b * y) % 26, (c * x + d * y) % 26\n r += chr(x + 65) + chr(y + 65)\n return r\n", "def encrypt(text,key):\n r =''\n a = 'abcdefghijklmnopqrstuvwxyz'\n km = [[a.index(key[0]),a.index(key[1])],[a.index(key[2]),a.index(key[3])]]\n text = ''.join(x for x in text.lower() if x in a)\n if len(text)%2: text += 'z'\n for i in range(0,len(text),2):\n tm = [a.index(text.lower()[i]),a.index(text.lower()[i+1])]\n r += a.upper()[(km[0][0]*tm[0]+km[0][1]*tm[1])%26]+a.upper()[(km[1][0]*tm[0]+km[1][1]*tm[1])%26]\n return r", "def encrypt(text,key):\n k = [ord(i) - 97 for i in key]\n text = ''.join(c for c in text if c.isalpha())\n text = text.upper() + \"Z\"*(len(text) % 2)\n nums = [ord(c) - 65 for c in text]\n Out = ''\n for i, j in zip(nums[::2],nums[1::2]):\n Out += chr((k[0]*i + k[1]*j)%26 + 65) + chr((k[2]*i + k[3]*j)%26 + 65)\n return Out", "from string import ascii_uppercase as letters\n\ndef encrypt(text, key):\n key = [[letters.index(c) for c in key.upper()[i:i+2]] for i in (0,2)]\n text = [letters.index(c) for c in text.upper() if c.isalpha()]\n if len(text) % 2 != 0: text.append(letters.index('Z'))\n out = []\n for i in range(0, len(text), 2):\n for j in range(2):\n out.append((key[j][0]*text[i] + key[j][1]*text[i+1]) % 26)\n return ''.join(letters[n] for n in out)", "\"\"\"by Zakhar M.\"\"\"\nimport re\nimport numpy as np\nfrom math import gcd\n\n\nALPHABET = {chr(letters): letters - 65 for letters in range(65, 91)}\nREVERSE_ALPHABET = {number_symbol: symbol for symbol, number_symbol in list(ALPHABET.items())}\n\n\ndef checking_key_for_validity(matrix_key, length_alphabet):\n determinant = np.linalg.det(matrix_key)\n nod_determinant_and_length_alphabet = gcd(int(round(determinant)), length_alphabet)\n\n if nod_determinant_and_length_alphabet == 1 and nod_determinant_and_length_alphabet != 0:\n return True\n return False\n\n\ndef get_matrix_key(key, length_block=2):\n tmp_list = list()\n matrix_key = list()\n length_key = len(key)\n\n if length_key % 2 != 0:\n return ''\n\n for symbol in key:\n number_symbol_in_alphabet = ALPHABET[symbol]\n tmp_list.append(number_symbol_in_alphabet)\n length_tmp_list = len(tmp_list)\n\n if length_tmp_list != length_block:\n continue\n\n matrix_key.append(tmp_list)\n tmp_list = list()\n\n return matrix_key\n\n\ndef get_matrix_open_text(open_text, length_blocks=2):\n tmp_list = list()\n matrix_open_text = list()\n pattern_only_letters = re.compile(r'[^a-zA-Z]*')\n prepared_open_text = pattern_only_letters.sub('', open_text).upper()\n length_prepared_open_text = len(prepared_open_text)\n\n if length_prepared_open_text % 2 != 0:\n prepared_open_text += 'Z'\n\n for symbol in prepared_open_text:\n number_symbol_in_alphabet = ALPHABET[symbol]\n tmp_list.append(number_symbol_in_alphabet)\n length_tmp_list = len(tmp_list)\n\n if length_tmp_list != length_blocks:\n continue\n\n matrix_open_text.append(tmp_list)\n tmp_list = list()\n \n return matrix_open_text\n\n\ndef smart_mul_matrix(matrix_1, matrix_2):\n result_matrix = list()\n \n for i in range(len(matrix_1)):\n tmp_sum = 0\n \n for j in range(len(matrix_2)):\n tmp_sum += (matrix_1[i][j] * matrix_2[j])\n result_matrix.append(tmp_sum % 26)\n \n return result_matrix\n\ndef encrypt(open_text, key):\n cipher_text = ''\n length_alphabet = len(ALPHABET)\n matrix_cipher_text = list()\n \n pattern_only_letters = re.compile(r'[^a-zA-Z]*')\n prepared_key_text = pattern_only_letters.sub('', key).upper()\n matrix_key = get_matrix_key(prepared_key_text)\n \n matrix_open_text = get_matrix_open_text(open_text)\n \n for current_list_open_text in matrix_open_text:\n matrix_multiplication = smart_mul_matrix(matrix_key, current_list_open_text)\n matrix_cipher_text.append(matrix_multiplication)\n \n for list_cipher_text in matrix_cipher_text:\n for number_cipher_text in list_cipher_text:\n cipher_text += REVERSE_ALPHABET[number_cipher_text]\n return cipher_text\n\n", "def encrypt(text,key):\n import numpy as np\n import string\n\n mapowanie_dig_str=dict(zip([x for x in range(0,26)],list(string.ascii_uppercase)))\n mapowanie_str_dig=dict(zip(list(string.ascii_uppercase),[x for x in range(0,26)]))\n \n l_key=[]\n for s in key.upper():\n l_key=l_key+[mapowanie_str_dig[s]]\n\n\n key_array_dig=np.array([l_key[0:2],l_key[2:]])\n correct_text=''\n for s in text.upper():\n if s in string.ascii_uppercase:\n correct_text=correct_text+s\n \n if len(correct_text)%2!=0:\n correct_text=correct_text+'Z' \n \n output=''\n l_core=list(correct_text) \n while l_core!=[]:\n pice_text_array=np.array([[mapowanie_str_dig[l_core[0]]],[mapowanie_str_dig[l_core[1]]]])\n l_core.pop(0)\n l_core.pop(0)\n P=(key_array_dig.dot(pice_text_array))%26\n output=output+mapowanie_dig_str[P[0][0]]+mapowanie_dig_str[P[1][0]] \n \n return output"] | {"fn_name": "encrypt", "inputs": [["", "azyb"], ["hello", "hill"], ["This is a good day", "bbaa"], ["CODEWARS IS GREAT", "wxyz"], ["Five + Seven = Twelve", "math"], ["+-*/ &*%^$", "azyb"]], "outputs": [[""], ["DRJIMN"], ["AAAAAAGACAGAYA"], ["CICQQIIASSDXKSFP"], ["IVSLIGSLAQEECSWR"], [""]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 8,885 |
def encrypt(text,key):
|
b630fdae43279059fef73aab97869f2b | UNKNOWN | Write a function that takes an arbitrary number of strings and interlaces them (combines them by alternating characters from each string).
For example `combineStrings('abc', '123')` should return `'a1b2c3'`.
If the strings are different lengths the function should interlace them until each string runs out, continuing to add characters from the remaining strings.
For example `combineStrings('abcd', '123')` should return `'a1b2c3d'`.
The function should take any number of arguments and combine them.
For example `combineStrings('abc', '123', '£$%')` should return `'a1£b2$c3%'`.
**Note: if only one argument is passed return only that string. If no arguments are passed return an empty string.** | ["from itertools import zip_longest\n\ndef combine_strings(*args):\n return ''.join(''.join(x) for x in zip_longest(*args, fillvalue=''))", "from itertools import zip_longest, chain\ndef combine_strings(*args):\n return ''.join(chain(*zip_longest(*args, fillvalue = '')))", "from itertools import zip_longest\ncombine_strings = lambda *strings: ''.join(map(''.join, zip_longest(*strings, fillvalue='')))", "from itertools import zip_longest as zl\n\n\ndef combine_strings(*stgs):\n return \"\".join(\"\".join(z) for z in zl(*stgs, fillvalue=\"\"))", "from itertools import chain, zip_longest\n\ndef combine_strings(*args):\n return ''.join(chain.from_iterable(zip_longest(*args, fillvalue='')))", "import itertools\ndef combine_strings(*args):\n return \"\".join((\"\".join(i) for i in itertools.zip_longest(*args,fillvalue=\"\")))", "from itertools import zip_longest\n\ndef combine_strings(*args):\n return ''.join(map(''.join, zip_longest(*args, fillvalue='')))", "import itertools as it\ndef combine_strings(*argv):\n return \"\".join(it.chain(*it.zip_longest(*argv, fillvalue=\"\")))", "def combine_strings(*args):\n sol='';words=[]\n if len(args)==0:return sol\n for a in args:words.append(list(a))\n while 1:\n for i,w in enumerate(words):\n if len(w)!=0:\n sol=sol+w[0]\n words[i].remove(w[0])\n if all(not element for element in words):break\n return sol"] | {"fn_name": "combine_strings", "inputs": [["abc"], ["abc", "123"], ["abcd", "123"], ["abc", "1234"], ["abc", "123", "$%"], ["abcd", "123", "$%"], ["abcd", "123", "$%^&"], ["abcd", "123", "$%^&", "qwertyuiop"], ["abcd", "123", "$%^&", "qwertyuiop", "X"]], "outputs": [["abc"], ["a1b2c3"], ["a1b2c3d"], ["a1b2c34"], ["a1$b2%c3"], ["a1$b2%c3d"], ["a1$b2%c3^d&"], ["a1$qb2%wc3^ed&rtyuiop"], ["a1$qXb2%wc3^ed&rtyuiop"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,456 |
def combine_strings(*args):
|
2bdd03681bb26e13a6f275000078cc17 | UNKNOWN | # Story
You and a group of friends are earning some extra money in the school holidays by re-painting the numbers on people's letterboxes for a small fee.
Since there are 10 of you in the group each person just concentrates on painting one digit! For example, somebody will paint only the ```1```'s, somebody else will paint only the ```2```'s and so on...
But at the end of the day you realise not everybody did the same amount of work.
To avoid any fights you need to distribute the money fairly. That's where this Kata comes in.
# Kata Task
Given the ```start``` and ```end``` letterbox numbers, write a method to return the frequency of all 10 digits painted.
# Example
For ```start``` = 125, and ```end``` = 132
The letterboxes are
* 125 = ```1```, ```2```, ```5```
* 126 = ```1```, ```2```, ```6```
* 127 = ```1```, ```2```, ```7```
* 128 = ```1```, ```2```, ```8```
* 129 = ```1```, ```2```, ```9```
* 130 = ```1```, ```3```, ```0```
* 131 = ```1```, ```3```, ```1```
* 132 = ```1```, ```3```, ```2```
The digit frequencies are 1 x ```0```, 9 x ```1```, 6 x ```2``` etc...
and so the method would return ```[1,9,6,3,0,1,1,1,1,1]```
# Notes
* 0 < ```start``` <= ```end```
* In C, the returned value will be free'd. | ["def paint_letterboxes(start, finish):\n xs = [0] * 10\n for n in range(start, finish+1):\n for i in str(n):\n xs[int(i)] += 1\n return xs", "from collections import Counter\n\ndef paint_letterboxes(s, f):\n a = Counter(\"\".join(map(str, range(s, f+1))))\n return [a[x] for x in \"0123456789\"]", "def paint_letterboxes(start, finish):\n painted = \"\".join(map(str, range(start, finish+1)))\n return [painted.count(digit) for digit in \"0123456789\"]", "def paint_letterboxes(start, finish):\n return [''.join(map(str, range(start,finish+1))).count(str(i)) for i in range(10)]", "def paint_letterboxes(start, finish):\n s = ''.join([str(x) for x in range(start,finish+1)])\n return [s.count(str(i)) for i in range(10)]\n", "def paint_letterboxes(start, finish):\n s = ''.join(map(str, range(start, finish + 1)))\n return [s.count(str(x)) for x in range(10)]", "from collections import Counter\n\ndef paint_letterboxes(start, finish):\n counter = Counter(\"\".join(map(str, range(start, finish + 1))))\n return [counter[str(n)] for n in range(10)]", "def paint_letterboxes(start, finish):\n boxes = ''.join([str(b) for b in range(start,finish+1)])\n return [ boxes.count(n) for n in '0123456789' ]", "def paint_letterboxes(start, finish):\n frequencies = [0]*10\n for i in range(start, finish+1):\n for d in str(i):\n frequencies[int(d)] += 1\n return frequencies", "def paint_letterboxes(start, finish):\n lst = []\n for x in range(start,finish + 1):\n lst.append(x)\n letterboxes = [int(i) for i in ''.join(str(x) for x in lst)]\n return([letterboxes.count(i) for i in range(10)])"] | {"fn_name": "paint_letterboxes", "inputs": [[125, 132], [1001, 1001]], "outputs": [[[1, 9, 6, 3, 0, 1, 1, 1, 1, 1]], [[2, 2, 0, 0, 0, 0, 0, 0, 0, 0]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,698 |
def paint_letterboxes(start, finish):
|
a9e10f3a819e256436955297a2f16093 | UNKNOWN | Mike and Joe are fratboys that love beer and games that involve drinking. They play the following game: Mike chugs one beer, then Joe chugs 2 beers, then Mike chugs 3 beers, then Joe chugs 4 beers, and so on. Once someone can't drink what he is supposed to drink, he loses.
Mike can chug at most A beers in total (otherwise he would pass out), while Joe can chug at most B beers in total. Who will win the game?
Write the function ```game(A,B)``` that returns the winner, ```"Mike"``` or ```"Joe"``` accordingly, for any given integer values of A and B.
Note: If either Mike or Joe cannot drink at least 1 beer, return the string ```"Non-drinkers can't play"```. | ["def game(maxMike, maxJoe):\n roundsMike = int(maxMike**.5)\n roundsJoe = (-1 + (1 + 4*maxJoe)**.5) // 2\n return (\"Non-drinkers can't play\" if not maxMike or not maxJoe else\n \"Joe\" if roundsMike <= roundsJoe else \n \"Mike\")", "def game(a, b):\n if a * b:\n c = int(a ** 0.5)\n return ('Mike', 'Joe')[c * (c + 1) <= b]\n return \"Non-drinkers can't play\"", "def game(a, b):\n n = int(a**0.5)\n return \"Non-drinkers can't play\" if a * b == 0 else \"Mike\" if n*(n+1) > b else \"Joe\"", "def game(a, b, p=1):\n if p == 1 and (a == 0 or b == 0):\n return \"Non-drinkers can't play\" \n \n if a < p:\n return \"Joe\"\n if b < p + 1:\n return \"Mike\"\n \n return game(a-p, b-p-1, p+2)", "def game(a, b):\n if a == 0 or b == 0:\n return \"Non-drinkers can't play\" \n sum_a = 0\n sum_b = 0\n i=1\n while sum_a <= a and sum_b <= b:\n if i % 2 != 0:\n sum_a += i\n else:\n sum_b += i\n i += 1\n if sum_a > a: return \"Joe\"\n if sum_b > b: return \"Mike\"", "game=lambda a,b:a*b and\"MJiokee\"[a**.5//1<=((4*b+1)**.5-1)//2::2]or\"Non-drinkers can't play\"", "def game(a, b):\n if a==0 or b==0:\n return \"Non-drinkers can't play\"\n i,n,x = 0,1,[a,b]\n while x[i] >= n:\n x[i] -= n\n n += 1\n i ^= 1\n return 'Joe' if i==0 else 'Mike'", "def game(a,b):\n if min(a,b)<1:return \"Non-drinkers can't play\"\n i=1\n while True:\n a-=i;i+=1;b-=i;i+=1\n if min(a,b)<0:return [\"Mike\",\"Joe\"][a<0]\n", "def game(a, b):\n print((a,b))\n if a==0 or b==0:\n return \"Non-drinkers can't play\"\n sa,sb=1,2\n while True:\n if a-sa<0:\n return \"Joe\"\n a-=sa\n sa+=2\n if b-sb<0:\n return \"Mike\"\n b-=sb\n sb+=2\n", "def game(a, b):\n if a*b==0:\n return \"Non-drinkers can't play\"\n m,j=0,0\n i=1\n while(True):\n if i%2==1:\n m+=i\n if m>a:\n return \"Joe\"\n else:\n j+=i\n if j>b:\n return \"Mike\"\n i+=1"] | {"fn_name": "game", "inputs": [[3, 2], [4, 2], [9, 1000], [0, 1]], "outputs": [["Joe"], ["Mike"], ["Joe"], ["Non-drinkers can't play"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,259 |
def game(a, b):
|
2a9384efd2614a69843ac37d00c248ea | UNKNOWN | Make multiple functions that will return the sum, difference, modulus, product, quotient, and the exponent respectively.
Please use the following function names:
addition = **add**
multiply = **multiply**
division = **divide** (both integer and float divisions are accepted)
modulus = **mod**
exponential = **exponent**
subtraction = **subt**
*Note: All math operations will be:
a (operation) b* | ["add = lambda a, b: a + b\nmultiply = lambda a, b: a * b\ndivide = lambda a, b: a / b\nmod = lambda a, b: a % b\nexponent = lambda a, b: a ** b\nsubt = lambda a, b:a - b\n", "def add(a,b):\n return a + b \ndef multiply(a,b):\n return a * b\ndef divide(a,b):\n return a / b\ndef mod(a,b):\n return a % b\ndef exponent(a,b):\n return a ** b\ndef subt(a,b):\n return a - b", "from operator import (\n add as add,\n mul as multiply,\n truediv as divide,\n mod as mod,\n pow as exponent,\n sub as subt,\n)", "from operator import add, mul as multiply, truediv as divide, mod, pow as exponent, sub as subt", "def add (a,b): return a+b\ndef subt (a,b): return a-b\ndef multiply(a,b): return a*b\ndef divide (a,b): return a/b\ndef mod (a,b): return a%b\ndef exponent(a,b): return a**b", "from operator import add, mod\nfrom operator import sub as subt\nfrom operator import mul as multiply\nfrom operator import pow as exponent\nfrom operator import truediv as divide", "from operator import (add, \n mul as multiply, \n truediv as divide,\n sub as subt,\n pow as exponent,\n mod)\n \n\n", "from operator import add, mod, mul as multiply, sub as subt, truediv as divide, pow as exponent", "add, multiply, divide, mod, exponent, subt = lambda x, y: x + y, lambda x, y: x * y, lambda x, y: x / y, lambda x, y: x % y, lambda x, y: x ** y, lambda x, y: x - y, ", "add = lambda x,y: x + y\nmultiply = lambda x,y: x * y\ndivide = lambda x,y: x / y\nmod = lambda x,y: x % y\nexponent = lambda x,y: x**y\nsubt = lambda x,y: x - y", "add = int.__add__\n\nmultiply = int.__mul__\n\ndivide = int.__truediv__\n\nmod = int.__mod__\n\nexponent = int.__pow__\n\nsubt = int.__sub__", "from operator import add\nfrom operator import mul as multiply\nfrom operator import truediv as divide\nfrom operator import mod\nfrom operator import pow as exponent\nfrom operator import sub as subt", "add = int.__add__\nmod = int.__mod__\nsubt = int.__sub__\nexponent = int.__pow__\nmultiply = int.__mul__\ndivide = int.__truediv__\n", "from operator import add, mul as multiply, truediv as divide, mod, __pow__ as exponent, sub as subt", "from operator import add, mul as multiply, truediv as divide, mod, sub as subt, pow as exponent", "from operator import *\nadd, multiply, divide, mod, exponent, subt = add, mul, floordiv, mod, pow, sub", "\"\"\" Prepare calculate functions. \"\"\"\nfrom operator import add, __truediv__ as divide, mod, mul as multiply, pow as exponent, sub as subt", "def add(a,b):\n # Your Code Here\n add = a+b\n return add\ndef multiply(a,b):\n multi = a*b\n return multi\ndef divide(a,b):\n divd = a/b\n return divd\ndef mod(a,b):\n modu = a%b\n return modu\ndef exponent(a,b):\n exp = a**b\n return exp\ndef subt(a,b):\n subtraction = a-b\n return subtraction\n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "def add(a,b):\n return a+b\n\ndef multiply(a, b):\n return a*b\n\ndef divide(a, b):\n return a/b\n\ndef mod(a,b):\n return a%b\n\ndef exponent(a, b):\n return a**b\n\ndef subt(a, b):\n return a-b\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones from the description\n", "import math\n\n\ndef add(a,b):\n return a + b\n\n\ndef subt(a,b):\n return a - b\n\n\ndef multiply(a,b):\n return a * b\n\n\ndef divide(a,b):\n return a / b\n\n\ndef mod(a,b):\n return divmod(a, b)[1]\n\n\ndef exponent(a,b):\n return a ** b", "def add(a,b):\n return a + b\n\ndef multiply(a,b):\n return a * b\n\ndef divide(a,b):\n return a / b\n\ndef add(a,b):\n return a + b\n\ndef mod(a,b):\n return a % b\n\ndef exponent(a,b):\n return a ** b\n\ndef subt(a,b):\n return a - b", "def add(a,b):\n # Your Code Here\n return a+b\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\ndef multiply(a,b):\n # Your Code Here\n return a*b\n\ndef divide(a,b):\n return a/b\n\ndef mod(a,b):\n return a%b\n\ndef exponent(a,b):\n return a**b\n\ndef subt(a,b):\n return a-b", "def add(a,b):\n return a+b\ndef subt(a,b):\n return a-b\ndef multiply(a,b):\n return a*b\ndef divide(a,b):\n return a/b\ndef mod(a,b):\n return a%b\ndef exponent(a,b):\n return pow(a,b)", "def add(a,b):\n return a+b\n # Your Code Here\ndef multiply(a,b):\n return a*b\n\ndef exponent(a,b):\n return pow(a,b)\n\ndef subt(a,b):\n return a-b\n\ndef divide(a,b):\n return a/b\n\ndef mod(a,b):\n return a%b\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "import math\n\ndef add(a,b):\n return a+b\n\ndef multiply(a,b):\n return a*b\n\ndef divide(a,b):\n return a//b\n\ndef mod(a,b):\n return math.fmod(a, b)\n\ndef exponent(a,b):\n return a**b\n\ndef subt(a,b):\n return a-b\n\n", "def add(a,b):\n # Your Code Here\n return a+b\n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\ndef multiply(a,b):\n return a*b\n \ndef mod(a,b):\n return a%b\n \ndef exponent(a,b):\n sum = a\n i = 1\n while i <b:\n sum = a* sum\n i+=1\n return sum\n\ndef subt(a,b):\n return a-b\n\ndef divide(a,b):\n return a//b", "add, multiply, divide , mod, exponent, subt = (eval('lambda a, b: a' + s + 'b') for s in ('+', '*', '/', '%', '**', '-'))", "def add (a,b): return a + b\ndef subt(a,b): return add(a, -b)\ndef multiply(a,b): return sum([max(a, b)] * min(a, b))\ndef divide(a,b): return a // b\ndef mod(a,b): return a - multiply(b, divide(a,b))\ndef exponent(a,b): return multiply(a, exponent(a, b-1)) if b else 1", "import operator\n\ndef add(a,b):\n #print(dir(operator))\n return operator.__add__(a,b)\n \ndef multiply(a,b):\n return operator.__mul__(a,b)\n\ndef divide(a,b):\n return operator.__floordiv__(a,b)\n\ndef mod(a,b):\n return operator.__mod__(a,b)\n\ndef exponent(a,b):\n return operator.__pow__(a,b)\n\ndef subt(a,b):\n return operator.__sub__(a,b)\n", "def add(a,b):\n return a+b\n \ndef multiply(a,b):\n return a*b\n \ndef divide(a,b):\n return a/b\n \ndef mod(a,b):\n return a%b\n \ndef subt(a,b):\n return a-b\n \ndef exponent(a,b):\n return a**b\n \ndef add(a,b):\n return a+b\n \n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "add = __import__('operator').add\ndivide = __import__('operator').truediv\nexponent = __import__('operator').pow\nmod = __import__('operator').mod\nmultiply = __import__('operator').mul\nsubt = __import__('operator').sub", "import operator \n\ndef add(a,b):\n return operator.add(a,b)\n\ndef multiply(a,b):\n return operator.mul(a,b)\n\ndef divide(a,b):\n return operator.floordiv(a,b)\ndef mod(a,b):\n return operator.mod(a,b)\ndef exponent(a,b):\n return operator.pow(a,b)\ndef subt(a,b):\n return operator.sub(a,b)", "def add(a,b):\n return a + b\nmultiply = lambda x, y: x*y\ndivide = lambda x, y: x/y\nmod = lambda x, y: x%y\nexponent = lambda x, y: x**y\nsubt = lambda x, y: x-y", "def add(a, b):\n return a + b\n \ndef multiply(a, b):\n return a * b\n\ndef divide(a, b):\n try:\n return a / b\n except:\n return 0\n\ndef mod(a, b):\n try:\n return a % b\n except:\n return 0\n\ndef exponent(a, b):\n return a ** b\n\ndef subt(a, b):\n return a - b\n", "add = int.__add__\nmultiply = int.__mul__\ndivide = int.__truediv__\nsubt = int.__sub__\nmod = int.__mod__\nexponent = int.__pow__", "def add(a,b):\n return a+b\n\ndef multiply(a, b):\n return a*b\n\ndef divide(a, b):\n return a/b if not b==0 else 0\n\ndef mod(a, b):\n return a%b\n\ndef exponent(a, b):\n return a**b\n\ndef subt(a, b):\n return a-b", "def add(a,b): return a+b\ndef multiply(a,b): return a*b\ndef divide(a,b): return a/b\ndef mod(a,b): return a%b\ndef exponent(a,b): return a**b\ndef subt(a,b): return add(a,-b)", "def add(a,b):\n return a + b\n\ndef subt(a, b):\n return a - b\n \ndef multiply(a, b):\n return a * b\n \ndef divide(a, b):\n try:\n return a / b\n except:\n return \"ZeroDivisionError\"\n \ndef mod(a, b):\n try:\n return a % b\n except:\n return \"ZeroDivisionError\" \n \ndef exponent(a, b):\n return a ** b\n \n \n # Your Code Here\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "def add(a, b):\n return a + b\n\ndef multiply(a, b):\n return a * b\n\ndef divide(a, b):\n return a // b if (int(a) == a) and (int(b) == b) else a / b\n\ndef mod(a, b):\n return a % b\n\ndef exponent(a, b):\n return a ** b\n\ndef subt(a, b):\n return a - b", "def add(a,b):\n return a+b\n\ndef multiply(a,b):\n return a*b\n \ndef divide(a,b):\n try:\n return a/b\n except:\n return 0\n \ndef mod(a,b):\n return a%b\n \ndef exponent(a,b):\n return a**b\n \ndef subt(a,b):\n return a-b\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "import operator as o\n\nadd = o.add\nmultiply = o.mul\ndivide = o.truediv\nmod = o.mod\nexponent = o.pow\nsubt = o.sub", "def add(x, y):\n return x + y\n\ndef multiply(x, y):\n return x * y\n \ndef divide(x, y):\n return x / y\n \ndef mod(x, y):\n return x % y\n \ndef exponent(x, y):\n return x ** y\n \ndef subt(x, y):\n return x - y", "#def add(a,b):\n # Your Code Here\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\ndef add(a,b):\n return a + b\ndef multiply(a,b):\n return a * b\ndef divide(a,b):\n return a/b\ndef mod(a,b):\n return a%b\ndef exponent(a,b):\n return a**b\ndef subt(a,b):\n return a-b", "import operator\n\nadd = operator.add\nmultiply = operator.mul\ndivide = operator.truediv\nexponent = operator.pow\nsubt = operator.sub\nmod = operator.mod", "def add(a,b):\n return a + b\n \ndef multiply(a, b):\n result = 0\n for i in range(b):\n result += a\n return result\n \ndef divide(a, b):\n return a / b\n\ndef mod(a, b):\n while a >= b:\n a -= b\n return a\n \ndef exponent(a, b):\n result = a\n for i in range(b-1):\n result *= a\n return result\n \ndef subt(a, b):\n return a - b", "import math\nfrom decimal import Decimal\n\ndef add(a,b):\n return a + b\n \ndef multiply(a,b):\n return a * b\n \ndef divide(a,b):\n return a / b\n \ndef mod(a, b):\n return a % b\n \ndef exponent(a,b):\n return a**b\n \ndef subt(a, b):\n return a - b;", "def add(a,b):\n return a+b\n # Your Code Here\ndef multiply(a,b):\n return a*b\ndef divide (a,b):\n return a/b\n # Your Code Here\ndef mod(a,b):\n return a%b\ndef exponent (a,b):\n return a**b\n # Your Code Here\ndef subt(a,b):\n return a-b\n \n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "add = int.__add__\nsubt = int.__sub__\nmultiply = int.__mul__\ndivide = int.__truediv__\nmod = int.__mod__\nexponent = int.__pow__", "def add(a,b):\n return a+b\ndef multiply(a,b):\n return a*b\ndef divide (a,b):\n return a/b if b!=0 else \"Error\"\ndef mod (a,b):\n return a%b\ndef exponent (a,b):\n return a**b\ndef subt (a,b):\n return a-b ", "def add(numUno,numDos):\n\n return numUno + numDos\n\n\ndef multiply(numUno,numDos):\n\n return numUno * numDos\n\n\ndef divide(numUno,numDos):\n\n return numUno / numDos\n \ndef mod(numUno,numDos):\n\n return numUno % numDos\n\n\ndef exponent(numUno,numDos):\n\n return numUno ** numDos\n\n\ndef subt(numUno,numDos):\n\n return numUno - numDos\n \n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "def add(a,b):\n return a + b\n \ndef multiply(a,b):\n return a * b\n \ndef divide(a,b):\n return a / b if b != 0 else 'Error DIVIDE 0'\n \ndef mod(a,b):\n return a % b\n \ndef exponent(a,b):\n return a ** b\n \ndef subt(a,b):\n return a - b", "def add(a,b):\n return a + b\n \ndef multiply(a,b):\n return a * b\n \ndef mod(a,b):\n return a % b\n\ndef divide(a,b):\n return a / b\n \ndef subt(a,b):\n return a - b\n \ndef exponent(a,b):\n return a ** b\n \n", "add=lambda x,y:x+y\nmultiply=lambda x,y:x*y\n\ndivide=lambda x,y:x/y\nmod=lambda x,y:x%y\nexponent=lambda x,y:x**y\ndef exponent(x,y):\n print('exponent')\n return x**y\nsubt=lambda x,y:x-y\n", "def add(a,b):\n return a+b\ndef multiply(a,b):\n return a*b\ndef divide(a,b):\n try:\n return a/b\n except ValueError:\n return \"Error\"\ndef mod(a,b):\n return a%b\ndef exponent(a,b):\n return a**b\ndef subt(a,b):\n return a-b", "#1\ndef add(a,b):\n return(a+b)\ndef multiply(a,b):\n return(a*b)\ndef mod(a,b):\n return(a%b)\ndef subt(a,b):\n return(a-b)\ndef divide(a,b):\n return(a/b)\ndef exponent(a,b):\n return(a**b)", "import math\n\ndef add(a,b):\n return a+b\n \ndef multiply(a,b):\n return a*b\n \ndef divide(a,b):\n return a/b\n \ndef mod(a,b):\n return a%b\n \ndef exponent(a,b):\n return pow(a,b)\n \ndef subt(a,b):\n return a-b\n", "def add(numeroUno,numeroDos):\n \n return numeroUno + numeroDos\n \n\ndef multiply(numeroUno,numeroDos):\n\n return numeroUno * numeroDos\n \ndef divide(numeroUno,numeroDos):\n\n return numeroUno / numeroDos\n\ndef mod(numeroUno,numeroDos):\n\n return numeroUno % numeroDos\n \n \ndef exponent(numeroUno,numeroDos):\n\n return numeroUno ** numeroDos\n \ndef subt(numeroUno,numeroDos):\n\n return numeroUno - numeroDos\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "import operator\nadd = operator.add\nmultiply = operator.mul\ndivide = operator.floordiv\nmod = operator.mod\nexponent = operator.pow\nsubt = operator.sub", "def add(a,b):\n return a+b\ndef multiply(a,b):\n return a*b\ndef divide(a,b):\n return a/b\ndef mod(a,b):\n return a%b\ndef exponent(a,b):\n return a**b\ndef subt(a,b):\n return a-b\n#Completed by Ammar on 13/8/2019 at 07:36PM.\n", "def add(a,b):\n return a+b\ndef multiply(a,b):\n return a*b\ndef mod(a,b):\n return a%b\ndef subt(a,b):\n return a-b\ndef divide(a,b):\n return a/b\ndef exponent(a,b):\n return a**b #I solved this Kata on 8/2/2019 01:07 AM...#Hussam'sCodingDiary\n\n", "def add(a,b):\n return a+b\ndef subt(a,b):\n return a-b\ndef mod(a,b):\n return a%b\ndef multiply(a,b):\n return a*b\ndef exponent(a,b):\n return a**b\ndef divide(a,b):\n return a/b\n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "add, multiply, divide, mod, exponent, subt = ((lambda ope: lambda a, b: eval(str(a) + ope + str(b)))(operator) for operator in (\"+\", \"*\", \"/\", \"%\", \"**\", \"-\"))", "def add(a,b):\n return a+b\n \ndef multiply(a, b):\n return a*b\n\ndef mod(a, b):\n return a%b\n \ndef exponent(a, b):\n return a**b\n \ndef subt(a, b):\n return a-b\n\ndef divide(a, b):\n return a/b", "def add(a,b):\n return a+b\ndef multiply(a,b):\n return a*b\ndef divide(a,b):\n try:\n return a/b\n except DivisionZeroError:\n return False\ndef mod(a,b):\n return a%b\ndef exponent(a,b):\n return a**b\ndef subt(a,b):\n return a-b\n\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "add, multiply, divide, mod, exponent, subt = lambda *a: sum(a), lambda a,b: a*b, lambda a,b: a/b, lambda a,b: a - (a//b)*b, lambda a,b: a**b, lambda a,b: a-b\n", "def add(a,b):\n return a + b\ndef multiply(a,b):\n return a * b\ndef divide(a,b):\n return a//b\ndef mod(a,b):\n return a%b\ndef subt(a,b):\n return a-b\ndef exponent(a,b):\n return a**b", "def add(a,b):\n # Your Code Here\n return a+b\n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\ndef add(a,b):\n # Your Code Here\n return a+b\ndef multiply(a,b):\n # Your Code Here\n return a*b\n \ndef divide(a,b):\n # Your Code Here\n return a/b\ndef mod(a,b):\n # Your Code Here\n return a%b\ndef subt(a,b):\n # Your Code Here\n return a-b\ndef exponent(a,b):\n # Your Code Here\n return a**b\n\n", "from math import *\ndef add(a, b):\n print(a+b)\n return a+b\ndef multiply(a, b):\n print(a*b)\n return a*b\ndef divide(a, b):\n print(a/b)\n return a/b\ndef mod(a, b):\n print(a%b)\n return a%b\ndef exponent(a, b):\n print(a^b)\n return a ** b\ndef subt(a, b):\n print(a-b)\n return a-b", "def add(a,b):\n return a + b\n \ndef multiply( a, b ):\n return a * b;\n \ndef divide( a, b ):\n ans = \"\"\n try:\n ans = a / b\n except ZeroDivisionError:\n print( \"division by zero\" )\n else:\n return ans\n \ndef mod( a, b ):\n return a % b\n \ndef subt( a, b):\n return a - b\n \ndef exponent( a, b):\n return a**b\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "def add(a,b):\n return a + b\n \ndef multiply(a,b):\n return a*b\n \ndef divide(a,b):\n try:\n return a/b\n except:\n return 0\n \ndef mod(a,b):\n return a % b\n \ndef subt(a,b):\n return a - b\n \ndef exponent(a,b):\n return a ** b", "def add(a,b):\n \n \"\"\"Addition.\"\"\"\n \n return a + b\n \ndef multiply(a,b):\n\n \"\"\"Multiplication.\"\"\"\n \n return a * b\n \ndef divide(a, b):\n\n \"\"\"Division.\"\"\"\n \n return a / b\n \ndef mod(a, b):\n\n \"\"\"Modulus.\"\"\"\n \n return a % b\n \ndef exponent(a, b):\n\n \"\"\"Exponential.\"\"\"\n \n return a ** b\n \ndef subt(a, b):\n\n \"\"\"Subtraction.\"\"\"\n \n return a -b", "def add(a,b):\n return a + b\n \ndef multiply(a,b):\n return a * b\n \ndef divide(a,b):\n return a / b\n \ndef mod(a,b):\n return a % b\n \ndef subt(a,b):\n return a - b\n \ndef exponent(a,b):\n print(a ** b)\n return a ** b", "def add(a, b):\n if a != str(a) or b != str(b):\n return a + b\n return a + ' + ' + b\n\ndef multiply(a, b):\n if a != str(a) or b != str(b):\n return a * b\n return a + ' * ' + b\n\ndef divide(a, b):\n if a != str(a) or b != str(b):\n return a / b\n return a + ' / ' + b\n\ndef mod(a, b):\n if a != str(a) or b != str(b):\n return a % b\n return a + ' % ' + b\n\ndef exponent(a, b):\n if a != str(a) or b != str(b):\n return a ** b\n return a + ' ** ' + b\n\ndef subt(a, b):\n if a != str(a) or b != str(b):\n return a - b\n return a + ' - ' + b", "from math import exp\n\n\ndef add(a,b):\n return a+b\n\ndef multiply(a,b):\n return a*b\n\ndef divide(a,b):\n return a/b\n\ndef mod(a,b):\n return a%b\n\ndef exponent(a,b):\n return a**b\n\ndef subt(a,b):\n return a-b", "def add(a,b):\n return a + b\nprint((add(1,2)))\n \ndef multiply(a,b):\n return a * b\nprint((multiply(2,2)))\n \ndef divide(a,b):\n return a / b\nprint((divide(6,2)))\n \ndef mod(a,b):\n return a % b\nprint((mod(10,3)))\n \ndef exponent(a,b):\n return a ** b\nprint((exponent(4,4)))\n \ndef subt(a,b):\n return a - b\nprint((subt(7,1)))\n \n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "def add(a,b):\n return (a+b)\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n\ndef multiply(a,b):\n return (a*b)\n \ndef mod(a,b):\n return (a%b)\n\ndef divide(a,b):\n return (a/b)\n \ndef divide(a,b):\n return (a//b)\n \ndef exponent(a,b):\n return (a**b)\n \ndef subt(a,b):\n return (a-b)\n\n\n", "def add(a, b):\n return a + b\n\n\ndef multiply(a, b):\n return a * b\n\n\ndef divide(a, b):\n return a / b if b != 0 else \"division by Zero\"\n\n\ndef mod(a, b):\n return a % b\n\n\ndef exponent(a, b):\n return pow(a, b)\n\n\ndef subt(a, b):\n return a - b", "import operator as op\nadd = op.add\nmultiply = op.mul\ndivide = op.truediv\nmod = op.mod\nexponent = op.pow\nsubt = op.sub", "def add(a,b):\n x = a + b;\n return x;\n \ndef multiply(a,b):\n x = a * b;\n return x;\n \ndef divide(a,b):\n x = a / b;\n return x;\n\ndef mod(a,b):\n x = a % b;\n return x;\n \ndef exponent(a,b):\n x = a ** b;\n return x;\n \ndef subt(a,b):\n x = a - b;\n return x;\n \n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "from operator import *\nmultiply=mul\nexponent=pow\nsubt=sub\ndivide=lambda a,b:a/b\nadd=lambda a,b:a+b", "from math import modf\nadd = lambda x,y: x+y\nmultiply = lambda x,y: x*y\nmod = lambda x,y: x%y\nexponent = pow\nsubt = lambda x,y: x-y\ndivide = lambda x,y: x/y", "def add(a,b):\n return a + b\n # Your Code Here\ndef multiply (a,b):\n return a * b\n \ndef divide(a,b):\n return round(a/b, 100)\n \ndef mod(a,b):\n return a%b\n \ndef exponent(a,b):\n return a**b\n \ndef subt(a,b):\n return a-b\n \n\n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "from operator import *\n\naddition=add\nmultiply=mul\ndivide=truediv\nmodulus=mod\nexponent=pow\nsubt=sub", "def add(x, y): return x + y\n\n\ndef multiply(x, y): return x*y\n\n\ndef divide(x, y): return (0 if y == 0 else x/y)\n\n\ndef mod(x, y): return x % y\n\n\ndef exponent(x, y): return (0 if x == 0 and y == 0 else x**y)\n\n\ndef subt(x, y): return x - y", "add = lambda x, y: x + y\nmultiply = lambda x, y: x*y\ndivide = lambda x, y: 0 if y == 0 else x/y\nmod = lambda x, y: x%y\nexponent = lambda x, y: 0 if x == 0 and y == 0 else x**y\nsubt = lambda x, y: x - y", "def add(a, b):\n return a + b\n\ndef multiply(a, b): \n return a * b\n\ndef divide(a, b): \n return a / b if b else float('nan')\n\ndef mod(a, b): \n return a % b\n\ndef exponent(a, b): \n return a ** b\n\ndef subt(a, b): \n return a - b", "def add(a,b):\n return a + b\ndef multiply(a,b):\n return a * b\ndef divide(a,b):\n return a / b\ndef subt(a,b):\n return a - b\ndef exponent(a,b):\n return a ** b\ndef mod(a,b):\n return a % b\n \n# Just followed the instructions.\n", "def add(a,b):\n return (a + b)\n \ndef multiply(a,b):\n return (a * b)\n \ndef subt(a,b):\n return (a - b)\n \ndef exponent(a,b):\n return (a ** b)\n \ndef divide(a,b):\n return (a / b)\n \ndef mod(a,b):\n return (a % b)\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "def add(a,b):\n return a + b\n \ndef multiply(c,d):\n return c * d\n \ndef divide(poopy,pants):\n return poopy/pants\n \ndef mod(jak, baj):\n return jak % baj\n \ndef exponent(op, po):\n return op ** po\n \ndef subt(almost, finished):\n return almost - finished", "def add(a,b):\n return a+b\ndef subt(a,b):\n return a-b\ndef divide(a,b):\n return a/b\ndef exponent(a,b):\n return a**b\ndef multiply(a,b):\n return a*b\ndef mod(a,b):\n return a%b\n\n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "def add(a,b):\n add= a+b\n return add\n \ndef multiply(a,b):\n num=a*b\n return num\n \ndef divide(a,b):\n num=a/b\n return num\n \ndef mod(a,b):\n num=a%b\n return num\n \ndef exponent(a,b):\n num=a**b\n return num\n \ndef subt(a,b):\n num=a-b\n return num\n \n \n \n# Make more functions. Refer to the description for function names.\n# The code will NOT WORK IF YOU USE names other than the ones\n# from the description\n", "def add(a,b):\n plus = a + b\n return plus\n\ndef multiply(a,b):\n times = a * b\n return times\n\ndef divide(a,b):\n divs = a / b\n return divs\n\ndef mod (a,b):\n mods = a % b\n return mods\n\ndef exponent(a,b):\n expos = a ** b\n return expos\n\ndef subt(a,b):\n subs = a -b\n return subs"] | {"fn_name": "add", "inputs": [[1, 2], [5, 7]], "outputs": [[3], [12]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 26,127 |
def add(a,b):
|
db00545c4be8240fb0355052a1863518 | UNKNOWN | You received a whatsup message from an unknown number. Could it be from that girl/boy with a foreign accent you met yesterday evening?
Write a simple regex to check if the string contains the word hallo in different languages.
These are the languages of the possible people you met the night before:
* hello - english
* ciao - italian
* salut - french
* hallo - german
* hola - spanish
* ahoj - czech republic
* czesc - polish
By the way, how cool is the czech republic hallo!!
PS. you can assume the input is a string.
PPS. to keep this a beginner exercise you don't need to check if the greeting is a subset of word ('Hallowen' can pass the test)
PS. regex should be case insensitive to pass the tests | ["def validate_hello(greetings):\n return any(x in greetings.lower() for x in ['hello','ciao','salut','hallo','hola','ahoj','czesc'])", "from re import compile, search, I\n\nREGEX = compile(r'hello|ciao|salut|hallo|hola|ahoj|czesc', I)\n\n\ndef validate_hello(greeting):\n return bool(search(REGEX, greeting))\n", "import re\n\ndef validate_hello(greetings):\n return bool(re.search(\"h[ae]llo|ciao|salut|hola|ahoj|czesc\", greetings.lower()))", "def validate_hello(greetings):\n g = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n for s in g:\n if s in greetings.lower():\n return True\n return False", "import re\ndef validate_hello(greetings):\n return True if re.findall('hello|ciao|salut|hallo|hola|ahoj|czesc', greetings, re.IGNORECASE) else False", "import re\n\n\ndef validate_hello(greetings):\n allowed_re = re.compile(r'(h[ae]llo)|(ciao)|(salut)|(hola)|(ahoj)|(czesc)')\n return bool(allowed_re.search(greetings.lower()))", "def validate_hello(greetings):\n check = False\n greeting = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n for x in greeting:\n if x in greetings.lower():\n check = True\n return check", "import re\n\ncheck = re.compile(r\"hello|ciao|salut|hallo|hola|ahoj|czesc\", re.IGNORECASE).search\n\ndef validate_hello(greetings):\n return bool(check(greetings))", "validate_hello = lambda g: any(bool(g.lower().count(s)) for s in [\"hello\",\"ciao\",\"salut\",\"hallo\",\"hola\",\"ahoj\",\"czesc\"])", "def validate_hello(greetings):\n a=('hello','ciao','salut','hallo','hola','ahoj','czesc')\n for x in a:\n if x in greetings.lower():\n return True\n return False", "def validate_hello(greetings):\n l = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n return any([True for i in l if i in greetings.lower()])", "def validate_hello(greetings):\n return any(w in greetings.lower() for w in (\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\", \"ahoj\", \"czesc\"))", "import re\n\ndef validate_hello(greetings):\n return bool(re.search('ahoj|h[ea]llo|hola|czesc|ciao|salut', greetings, re.I))\n", "from re import compile, search, I\n\nLOL = compile(r'hello|ciao|salut|hallo|hola|ahoj|czesc', I)\n\n\ndef validate_hello(greeting):\n return bool(search(LOL, greeting))\n #your code here\n", "validate_hello = lambda g: __import__('re').compile('(hello|ciao|salut|hallo|hola|ahoj|czesc)').search(g.lower()) is not None", "import re\ndef validate_hello(greetings):\n return bool(re.search(r'(?i)(hello|ciao|salut|hallo|hola|ahoj|czesc)' ,greetings))\n \n \n", "def validate_hello(greetings):\n greetings = greetings.lower()\n return greetings.__contains__('hello') or greetings.__contains__('ciao') or greetings.__contains__('salut') or greetings.__contains__('hallo') or greetings.__contains__('hola') or greetings.__contains__('ahoj') or greetings.__contains__('czesc')", "def validate_hello(greetings):\n import re\n return True if re.findall(\"h[oae]l{1,2}[oa]|ciao|salut|ahoj|czesc\", greetings, re.IGNORECASE) else False", "import re\ndef validate_hello(greetings):\n return bool (re.search(\"hello|ciao|salut|hallo|hola|ahoj|czesc\",greetings,re.I))", "def validate_hello(greetings):\n hellos = [\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\", \"ahoj\", \"czesc\"]\n for h in hellos:\n if h in greetings.lower(): return True\n return False", "import re\n\ndef validate_hello(greetings: str) -> bool:\n \"\"\" Check if the string contains the word hallo in different languages. \"\"\"\n return bool(re.search(\"(hello|ciao|salut|hallo|hola|ahoj|czesc)\", greetings, re.I))", "def validate_hello(greetings):\n return (any([i for i in ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc'] if i in greetings.lower()]))\n", "def validate_hello(greetings):\n if (greetings.upper().find(\"HELLO\") >= 0\n or greetings.upper().find(\"CIAO\") >= 0\n or greetings.upper().find(\"HALLO\") >= 0\n or greetings.upper().find(\"SALUT\") >= 0\n or greetings.upper().find(\"HOLA\") >= 0\n or greetings.upper().find(\"AHOJ\") >= 0\n or greetings.upper().find(\"CZESC\") >= 0):\n return True\n else:\n return False", "def validate_hello(greetings):\n hello = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n for greeting in hello :\n if greeting in greetings.lower() :\n return True\n return False", "def validate_hello(greetings):\n msgs = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc'] \n for msg in msgs:\n if msg in greetings.lower():\n return True\n return False\n", "def validate_hello(greetings):\n d=['hello','ciao','salut','hallo','hola','ahoj','czesc']\n for i in d:\n if i in greetings.lower():\n return True\n return False", "import re\ndef validate_hello(greetings):\n return bool(re.match(r'.*(hello|ciao|salut|hallo|hola|ahoj|czesc).*', greetings, re.I))", "def validate_hello(g):\n return any(i.lower() in g.lower() for i in ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc'])", "import re\ndef validate_hello(greetings):\n greetings = greetings.lower()\n a = [\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\", \"ahoj\", \"czesc\"]\n for i in a:\n x = re.findall(str(i), greetings)\n if not x:\n pass\n else:\n return True\n return False", "def validate_hello(greetings):\n hellos = [\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\", \"ahoj\", \"czesc\"]\n return any(hello in greetings.lower() for hello in hellos)", "import re\n\ndef validate_hello(greetings):\n return True if re.match(\".*(hello|ciao|salut|hallo|hola|ahoj|czesc).*\", greetings, re.IGNORECASE) else False", "import re\n\ndef validate_hello(greetings):\n #print(greetings.lower())\n #print(re.search(\"[hello|ciao|salut|hallo|hola|ahoj|czesc]\", greetings.lower()))\n return True if re.match(\".*(hello|ciao|salut|hallo|hola|ahoj|czesc).*\", greetings, re.IGNORECASE) else False", "import re\ndef validate_hello(greetings):\n return bool(re.findall(r'h[ae]llo|ciao|salut|hola|ahoj|czesc', greetings.lower()))", "def validate_hello(greetings):\n return True if sum(greetings.lower().find(i) for i in ['hello','ciao','salut','hallo','hola','ahoj','czesc']) > -7 else False", "def validate_hello(greetings):\n greets = [\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\", \"ahoj\", \"czesc\"]\n text_words = greetings.lower()\n \n return any(i in text_words for i in greets)", "def validate_hello(greetings):\n greetings = greetings.lower()\n if 'hello' in greetings or 'hallo' in greetings or 'ciao' in greetings or 'salut' in greetings or 'hallo' in greetings or 'hola' in greetings or 'ahoj' in greetings or 'czesc' in greetings:\n return True\n return False", "def validate_hello(greetings):\n greeting = [\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\" ,\"ahoj\" ,\"czesc\"]\n t_or_f = [\"True\" for i in greeting if i in greetings.lower()]\n return \"True\" in t_or_f", "import re\n\n\ndef validate_hello(greetings):\n list_hello = [\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\", \"ahoj\", \"czesc\"]\n greetings2 = (re.sub(\"[,?!;.:]\", \"\", greetings).lower().split())\n set_A = set(list_hello)\n set_B = set(greetings2)\n return True if set_A.intersection(set_B) != set() else False", "def validate_hello(greetings):\n hello_list = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n greetings = greetings.lower()\n \n for hello_str in hello_list:\n if hello_str in greetings:\n return True\n \n return False", "s = {'hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc'}\ndef validate_hello(g):\n return any(x in g.lower() for x in s)", "def validate_hello(greetings):\n greetings = greetings.lower()\n a = \"hello ciao salut hallo hola ahoj czesc\"\n a = a.split(\" \")\n for x in a:\n if x in greetings:\n return True\n return False", "import re\ndef validate_hello(greetings):\n return bool(re.match(r\".*(hello|ciao|salut|hallo|hola|ahoj|czesc).*\",greetings,flags=re.IGNORECASE))", "import re\n\ndef validate_hello(greetings):\n return len(re.findall('hello|ciao|salut|hallo|hola|ahoj|czesc', greetings.lower())) > 0", "def validate_hello(g):\n st=['hello','ciao','salut','hallo','hola','ahoj','czesc']\n g=g.lower()\n for i in st:\n if i in g:\n return True\n return False\n \n #your code here\n", "import re\ndef validate_hello(greetings):\n \n return any([greet in greetings.lower() for greet in 'hello ciao salut hallo hola ahoj czesc'.split()])", "import re\ndef validate_hello(greetings):\n regex = r\"(hello|ciao|salut|hallo|hola|ahoj|czesc)\"\n return True if re.search(regex, greetings.lower()) else False", "def validate_hello(greetings):\n greets = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n for i in greets:\n if i in greetings.lower():\n return True\n\n return False", "def validate_hello(greetings):\n greeting = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n for s in greeting:\n if s in greetings.lower():\n return True\n return False", "def validate_hello(greetings):\n #your code here\n hello_strings = ['hello',\n 'ciao',\n 'salut',\n 'hallo',\n 'hola',\n 'ahoj',\n 'czesc']\n \n return any(s in greetings.lower() for s in hello_strings)", "def validate_hello(greetings):\n #your code here\n hello_strings = ['hello',\n 'ciao',\n 'salut',\n 'hallo',\n 'hola',\n 'ahoj',\n 'czesc']\n #return True if (greetings.lower().find(s) != -1) else False for s in hello_strings\n for s in hello_strings:\n if greetings.lower().find(s) != -1:\n return True\n return False", "from re import search, IGNORECASE\n\ndef validate_hello(g):\n return bool(search(\"hello|ciao|salut|hallo|hola|ahoj|czesc\", g, IGNORECASE))", "def validate_hello(g):\n j = ['hello','ciao','salut','hallo','hola','ahoj','czesc']\n return any([x in g.lower() for x in j])", "def validate_hello(greetings):\n words = ['ciao', 'hello', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n return any(word in greetings.lower() for word in words)", "import string\n\ndef validate_hello(greetings):\n HELLO_WORDS = {\n 'hello',\n 'ciao',\n 'salut',\n 'hallo',\n 'hola',\n 'ahoj',\n 'czesc'\n }\n return any(x in HELLO_WORDS\n for x in greetings.translate(dict((ord(char), None)\n for char in string.punctuation)).lower().split())", "def validate_hello(greetings):\n return any([i in greetings.lower() for i in ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']])", "def validate_hello(greetings):\n hello = ('hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc')\n return True if any([x in greetings.lower() for x in hello]) else False", "greet = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\ndef validate_hello(greetings):\n return any(w for w in greet if w in greetings.lower())", "def validate_hello(greetings):\n return max(i in greetings.lower() for i in [\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\", \"ahoj\", \"czesc\"])", "import re\ndef validate_hello(greetings):\n return bool(re.search(r\"h[ae]llo|ciao|salut|hola!|ahoj|czesc\", greetings.lower()))\n", "def validate_hello(greetings):\n hey = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n for x in hey:\n if x in greetings.lower():\n return True\n return False", "def validate_hello(greetings):\n greeting = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n for i in greeting:\n if i in greetings.lower():\n return True\n return False", "def validate_hello(greetings):\n #your code here\n hellos=['hello','ciao','salut','hallo','hola','ahoj','czesc']\n greetings=greetings.lower()\n greetings=greetings.split(' ')\n for i in greetings:\n i=i.replace(',','')\n i=i.replace('!','')\n i=i.replace('.','')\n i=i.replace('?','')\n i=i.replace(';','')\n i=i.replace(':','')\n if i in hellos:\n return True\n return False", "import re\ndef validate_hello(greetings):\n return re.search(\".*h[ae]llo|ciao|salut|hola|ahoj|czesc\", greetings.lower()) is not None", "def validate_hello(greetings):\n g=['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n gree=greetings.casefold()\n for i in g:\n if i in gree:\n return True\n return False", "def validate_hello(greetings):\n l = ['hello','ciao','salut','hallo','hola','ahoj','czesc']\n return any(i in greetings.lower() for i in l)", "def validate_hello(greetings):\n rez = 0\n hell = [\"hello\",\"ciao\",\"salut\",\"hallo\",\"hola\",\"ahoj\",\"czesc\"]\n for it in greetings.lower().split(\" \"):\n if \"\".join(i.lower() for i in it if i.isalpha()) in hell:\n rez += 1\n return True if rez > 0 else False", "import re\n\ndef validate_hello(greetings):\n return any( w.lower() in {'hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc'} for w in re.split('\\W', greetings))", "def validate_hello(greetings):\n p = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n for i in p:\n if i in greetings.lower():\n return True\n return False", "import re\n\n\ndef validate_hello(greetings):\n patterns = [\"hello\", \"ciao\", \"salut\", 'hallo', 'hola', \"ahoj\", 'czesc']\n catcher = re.findall(r'\\w+', greetings.lower())\n for i in catcher:\n if i in patterns:\n return True\n return False", "def validate_hello(text):\n text = text.lower()\n greetings = [\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\", \"ahoj\", \"czesc\"]\n for hello in greetings:\n if hello in text:\n return True\n return False", "def validate_hello(greetings):\n greetings = greetings.lower()\n helloes = [\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\", \"ahoj\", \"czesc\"]\n for hello in helloes:\n if (hello in greetings):\n return True\n return False", "def validate_hello(greetings):\n saludos = [\"hello\",\"ciao\",\"salut\",\"hallo\",\"hola\",\"ahoj\",\"czesc\"]\n for saludo in saludos:\n if saludo in greetings.lower():\n return True\n return False\n", "def validate_hello(greetings):\n item = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n check = False\n for i in item:\n if i in greetings.lower():\n check = True\n return check ", "import re\n\ndef validate_hello(greetings):\n salute = 'hello|ciao|salut|hallo|hola|ahoj|czesc'\n return bool(re.search(salute, greetings, re.I)) ", "def validate_hello(greetings):\n hellows = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n greetings = greetings.lower()\n result = False\n for x in hellows:\n if x in greetings:\n result = result or True\n return result", "def validate_hello(greetings):\n return any(i for i in ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc'] if i in greetings.lower())", "def validate_hello(greetings):\n list = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n greetings = greetings.lower()\n for i in list:\n if greetings.find(i)>=0:\n return True \n return False", "import re\n\ndef validate_hello(greetings):\n multilingual_greetings = '(hello|ciao|salut|hallo|hola|ahoj|czesc)'\n return len(re.findall(multilingual_greetings, greetings, re.I)) > 0", "def validate_hello(greetings):\n b = greetings.lower()\n for a in [\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\", \"ahoj\", \"czesc\"]:\n if a in b:\n return True\n return False", "def validate_hello(g):\n mes = ['hello','ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n return 1 in list(g.lower().count(i) for i in mes)\n \n\n", "def validate_hello(greetings):\n dic = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n for i in dic:\n if greetings.lower().find(i) != -1:\n return True\n return False", "validate_hello = lambda greetings: any(i in greetings.lower() for i in {'hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc'})", "def validate_hello(greetings):\n lista = ['hello','ciao','salut','hallo','hola','ahoj','czesc']\n for i in lista:\n if i.lower() in greetings.lower():\n return True\n \n return False", "def validate_hello(greetings: str) -> bool:\n m = greetings.casefold()\n return any(w in m for w in (\"hello\", \"ciao\", \"salut\", \"hallo\", \"hola\", \"ahoj\", \"czesc\"))\n", "validate_hello=lambda s,d=['hello','ciao','salut','hallo','hola','ahoj','czesc']:any(x in s.lower() for x in d)", "def validate_hello(greetings):\n #your code here\n hello = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n greetings = greetings.lower()\n for i in hello :\n if i in greetings : return True\n else : return False", "import re\ndef validate_hello(greetings):\n tpl = r'(?i)(\\bhello\\b)|(\\bhallo\\b)|(\\bciao\\b)|(\\bsalut\\b)|(\\bhola\\b)|(\\bahoj\\b)|(\\bczesc\\b)'\n return True if re.search(tpl, greetings) != None else False", "def validate_hello(greetings):\n #your code here\n hello_list = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n for i in hello_list:\n if i in greetings.lower():\n return True\n return False", "import re\n\ndef validate_hello(greetings):\n print(greetings.lower())\n\n words = [\n 'hello',\n 'ciao',\n 'salut',\n 'hallo',\n 'hola',\n 'ahoj',\n 'czesc',\n ]\n\n for i in words:\n if bool(re.match('.*'+i+'.*', greetings.lower())):\n return True\n return False ", "import re\n\ndef validate_hello(greetings):\n pattern = r'(h([ae]llo|ola)|c(iao|zesc)|salut|ahoj)'\n return bool(re.search(pattern, greetings, re.IGNORECASE))", "import re\n\ndef validate_hello(greetings):\n res=re.search(r'hello|ciao|salut|hallo|hola|ahoj|czesc',greetings,re.IGNORECASE)\n return True if res else False", "import re\n\ndef validate_hello(greetings):\n return bool(re.findall('h[ae]llo|ciao|salut|hola|ahoj|czesc', greetings, re.I))", "def validate_hello(greetings):\n i18n = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n for word in i18n:\n if word in greetings.lower():\n return True\n\n return False", "import re\n\ndef validate_hello(greetings):\n return bool(re.search(\"hello|ciao|salut|hallo|hola|ahoj|czesc\", greetings.lower()))", "def validate_hello(greetings):\n different_greetings = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n return any(greeting in greetings.lower() for greeting in different_greetings)", "def validate_hello(greetings):\n return bool([1 for x in greetings.translate(greetings.maketrans('', '', '.,!?;:')).lower().split() if x in ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']])", "def validate_hello(greetings):\n hellos = ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc']\n return any(greet in greetings.lower() for greet in hellos)\n", "import re\ndef validate_hello(greetings):\n return bool(re.search('(?i)hello|ciao|hola|hallo|salut|czesc|ahoj', greetings))\n", "import re\n\ndef validate_hello(greetings):\n r = 'hello ciao salut hallo hola ahoj czesc'.split()\n return len(re.findall('|'.join(r), greetings, re.I)) > 0"] | {"fn_name": "validate_hello", "inputs": [["hello"], ["ciao bella!"], ["salut"], ["hallo, salut"], ["hombre! Hola!"], ["Hallo, wie geht's dir?"], ["AHOJ!"], ["czesc"], ["meh"], ["Ahoj"]], "outputs": [[true], [true], [true], [true], [true], [true], [true], [true], [false], [true]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 20,297 |
def validate_hello(greetings):
|
75430eeb545e7e3e65c4b975b6f72f4b | UNKNOWN | # Task
Elections are in progress!
Given an array of numbers representing votes given to each of the candidates, and an integer which is equal to the number of voters who haven't cast their vote yet, find the number of candidates who still have a chance to win the election.
The winner of the election must secure strictly more votes than any other candidate. If two or more candidates receive the same (maximum) number of votes, assume there is no winner at all.
**Note**: big arrays will be tested.
# Examples
```
votes = [2, 3, 5, 2]
voters = 3
result = 2
```
* Candidate `#3` may win, because he's already leading.
* Candidate `#2` may win, because with 3 additional votes he may become the new leader.
* Candidates `#1` and `#4` have no chance, because in the best case scenario each of them can only tie with the candidate `#3`.
___
```
votes = [3, 1, 1, 3, 1]
voters = 2
result = 2
```
* Candidate `#1` and `#4` can become leaders if any of them gets the votes.
* If any other candidate gets the votes, they will get tied with candidates `#1` and `#4`.
___
```
votes = [1, 3, 3, 1, 1]
voters = 0
result = 0
```
* There're no additional votes to cast, and there's already a tie. | ["def elections_winners(votes, k):\n m = max(votes)\n return sum(x + k > m for x in votes) or votes.count(m) == 1", "def elections_winners(votes, k):\n best = max(votes)\n if k == 0 and votes.count(best) == 1:\n return 1\n return len([x for x in votes if x + k > best])", "def elections_winners(votes, k):\n m = max(votes)\n return [0, 1][votes.count(m) == 1] if not k else sum(i + k > m for i in votes) ", "def elections_winners(a, n):\n m = max(a)\n return sum(x + n > m for x in a) if n else a.count(m) == 1", "def elections_winners(votes, k):\n max_so_far = max(votes)\n lst = [vote for vote in votes if vote + k > max_so_far]\n return len(lst) if lst else bool(votes.count(max_so_far) == 1)", "def elections_winners(votes, k):\n limit = max(votes)\n return sum(1 for vote in votes if (vote + k) > limit) + (votes.count(limit) == 1) * (k == 0)\n", "elections_winners=lambda v,k:v.sort()or sum(e+k>v[-1]for e in v)or v.count(v[-1])==1", "def elections_winners(votes, k):\n #coding and coding..\n win = max(votes)\n return sum(i + k > win for i in votes) or votes.count(win) == 1", "elections_winners=lambda v,k: (lambda m: (lambda c: 0 if c!=1 else c)(v.count(m)) if not k else len([p for p in v if p>m-k]))(max(v))", "def elections_winners(a,k):\n m = max(a)\n v = [i+k for i in a if i+k>m]\n if k == 0 and not v and a.count(m)==1: return 1\n return len(v)"] | {"fn_name": "elections_winners", "inputs": [[[2, 3, 5, 2], 3], [[1, 3, 3, 1, 1], 0], [[5, 1, 3, 4, 1], 0], [[1, 1, 1, 1], 1], [[1, 1, 1, 1], 0], [[3, 1, 1, 3, 1], 2]], "outputs": [[2], [0], [1], [4], [0], [2]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,422 |
def elections_winners(votes, k):
|
b1fa1ec95065934ba90558db1abb9e42 | UNKNOWN | # A History Lesson
Soundex is an interesting phonetic algorithm developed nearly 100 years ago for indexing names as they are pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling.
Reference: https://en.wikipedia.org/wiki/Soundex
# Preface
I first read about Soundex over 30 years ago. At the time it seemed to me almost like A.I. that you could just type in somebody's name the way it sounded and there was still a pretty good chance it could match the correct person record. That was about the same year as the first "Terminator" movie so it was easy for me to put 2 and 2 together and conclude that Arnie must have had some kind of futuristic Soundex chip in his titanium skull helping him to locate ```Serah Coner```... or was it ```Sarh Connor```... or maybe ```Sayra Cunnarr```...
:-)
# Task
In this Kata you will encode strings using a Soundex variation called "American Soundex" using the following (case insensitive) steps:
* Save the first letter. Remove all occurrences of ```h``` and ```w``` except first letter.
* Replace all consonants (include the first letter) with digits as follows:
* ```b```, ```f```, ```p```, ```v``` = 1
* ```c```, ```g```, ```j```, ```k```, ```q```, ```s```, ```x```, ```z``` = 2
* ```d```, ```t``` = 3
* ```l``` = 4
* ```m```, ```n``` = 5
* ```r``` = 6
* Replace all adjacent same digits with one digit.
* Remove all occurrences of ```a```, ```e```, ```i```, ```o```, ```u```, ```y``` except first letter.
* If first symbol is a digit replace it with letter saved on step 1.
* Append 3 zeros if result contains less than 3 digits. Remove all except first letter and 3 digits after it
## Input
A space separated string of one or more names. E.g.
```Sarah Connor```
## Output
Space separated string of equivalent Soundex codes (the first character of each code must be uppercase). E.g.
```S600 C560``` | ["import re\n\nREPLACMENTS = [\"BFPV\", \"CGJKQSXZ\", \"DT\",\"L\",\"MN\",\"R\"]\nER1, ER2 = \"HW\", \"AEIOUY\"\n\nTABLE_ERASE1 = str.maketrans(\"\", \"\", ER1)\nTABLE_NUMS = str.maketrans( ''.join(REPLACMENTS), ''.join( str(n)*len(elt) for n,elt in enumerate(REPLACMENTS, 1)) )\nTABLE_ERASE2 = str.maketrans(\"\", \"\", ER2)\n\n\ndef formatSoundex(w):\n s = w[0]*(w[0] in ER1+ER2) + re.sub(r'(\\d)\\1*', r'\\1', w.translate(TABLE_ERASE1).translate(TABLE_NUMS)).translate(TABLE_ERASE2)\n return ((w[0] if s[0].isdigit() else s[0]) + s[1:] + \"000\")[:4]\n\ndef soundex(name):\n return ' '.join(formatSoundex(w.upper()) for w in name.split(\" \"))", "import re\ndef soundex(name):\n newNameLis = [x[0].upper()+x.lower() for x in name.split(\" \")]\n newNameLis = [x[0] + x[1]+x[2:].translate(str.maketrans('', '','hw')) for x in newNameLis]\n newNameLis = [x[0] + x[1:].translate(str.maketrans('bfpvcgjkqsxzdtlmnr', '111122222222334556','')) for x in newNameLis]\n newNameLis = [x[0] + re.sub(r'(\\d)\\1*', r'\\1',x[1:]) for x in newNameLis]\n newNameLis = [x[0] + x[1]+x[2:].translate(str.maketrans('', '','aeiouy')) for x in newNameLis]\n newNameLis = [x[0] + \"\".join([i for i in x[2:] if i.isdigit()]) for x in newNameLis]\n return \" \".join([(x+'000')[:4] for x in newNameLis])\n\n", "T = str.maketrans('BFPVCGJKQSXZDTLMNR','111122222222334556')\nV = str.maketrans({v:None for v in 'AEIOUY'})\n\ndef soundex(name):\n return ' '.join(wordex(w) for w in name.upper().split())\n \ndef wordex(word):\n w = (word[0] + word[1:].replace('W', '').replace('H', '')).translate(T)\n for c in '123456':\n while c + c in w: w = w.replace(c + c, c)\n \n return ((word[0] if w[0].isdigit() else w[0]) + w[1:].translate(V) +'000')[:4]", "from itertools import groupby\n\ntr = [ (0,), ('b','f','p','v'), ('c','g','j','k','q','s','x','z'), ('d','t'), ('l'), ('m','n'), ('r') ]\n\ndef soundex(name):\n name = name.lower().split(' ')\n \n first_l = [ e[0].upper() for e in name ] \n \n let_to_dig = loop( lambda x: indx(x, tr), loop( lambda x: x, name, lambda x: x not in 'hw' ) )\n \n del_duble = loop( lambda x: x[0], let_to_dig, funk2 = lambda x:groupby(x) )\n \n del_vowel = [[e[0],''.join([ x for i,x in enumerate(e) if x.isdigit() and i ])] for e in del_duble ]\n \n return ' '.join((([first_l[i] ,e[0].upper()][all((e[0].isalpha(), e[0] == first_l[i]))] + ['',e[0]][all((e[0].isdigit(), first_l[i] in 'HW'))]) + e[1]).ljust(4,\"0\")[:4] \n for i,e in enumerate(del_vowel) )\n \ndef indx(elem, arr):\n for i, x in enumerate(arr):\n if elem in x:\n return str(i)\n return elem\n \ndef loop(func1, arr, excuse1=lambda x:x , excuse2=lambda x:x, funk2=lambda x:x):\n return [ [func1(x) for x in funk2(e) if excuse1(x)] for e in arr if excuse2(e) ]\n", "import re\ndef soundex(s):\n d, li = {k:i for i,j in zip(list(range(1, 7)), ['bfpv','cgjkqsxz','dt','l','mn','r'])for k in j}, []\n for i in s.split():\n first = i[0]\n i = first+re.sub(r'[hwHW]','',i[1:])\n i = re.sub(r'[^aeiouy]', lambda x: str(d.get(x.group().lower(), x.group())), i)\n i = re.sub(r'(\\d)(\\1+)', r'\\1', i)\n i = i[0] + re.sub(r'[aeiouyAEIOUY]', '', i[1:])\n li.append(first.upper() + (f\"{i[1:]:<03}\")[:3])\n return \" \".join(li)", "def soundex(name):\n consonants_to_digits = {c: str(i)\n for i, consonants in enumerate(\"bfpv cgjkqsxz dt l mn r\".split(), 1)\n for cs in consonants\n for c in cs}\n def soundex_word(word):\n result = word.lower()\n result = (c for i, c in enumerate(result) if i == 0 or c not in \"hw\")\n result = (consonants_to_digits.get(c, c) for c in result)\n result = uniq(result)\n result = (c for i, c in enumerate(result) if i == 0 or c not in \"aeiouy\")\n result = \"\".join(result)\n result = word[0].upper() + result[1:]\n result = format(result, \"0<4.4\")\n return result\n return \" \".join(soundex_word(word) for word in name.split())\n\ndef uniq(iterable):\n iterable = iter(iterable)\n previous = next(iterable)\n yield previous\n for elem in iterable:\n if elem != previous:\n yield elem\n previous = elem", "CONS_VAL = {\n 'b': '1', 'f': '1', 'p': '1', 'v': '1', 'c': '2', 'g': '2',\n 'j': '2', 'k': '2', 'q': '2', 's': '2', 'x': '2', 'z': '2',\n 'd': '3', 't': '3', 'l': '4', 'm': '5', 'n': '5', 'r': '6' }\n\ndef soundex(name):\n result = []\n \n for word in name.lower().split():\n # save the initial\n first = word[0]\n \n # remove h, w\n word = [first] + [ c for c in word[1:] if c not in 'hw' ]\n \n # replace consonants\n word = [ CONS_VAL.get(c, c) for c in word ]\n \n # remove duplicates\n word = [first] + [ c for i, c in enumerate(word[1:]) if word[i] != c ]\n \n # remove vowels\n word = [first] + [ c for c in word[1:] if c not in 'aeiouy' ]\n \n # append zeros and cut\n word = (word + ['0'] * 3)[:4]\n result.append( ''.join(word) )\n \n return ' '.join(result).upper()", "from itertools import groupby,islice\n\ntr=str.maketrans('ABCDEFGIJKLMNOPQRSTUVXYZ','012301202245501262301202','HW')\n\ndef soundex(n):\n n=n.upper()\n ws=[]\n for w in n.split(' '):\n s=[]\n s=list(islice((vg[0] for i,vg in enumerate(groupby(w.translate(tr))) if vg[0]!='0' or i==0),4))\n if s[0]=='0' or s[0]==w[0].translate(tr):\n s[0]=w[0]\n else:\n s.insert(0,w[0])\n ws.append(''.join(s)[:4].ljust(4,'0'))\n return ' '.join(ws)\n", "import re\ndef soundex(s):\n d, li = {k:i for i,j in zip(list(range(1, 7)), ['bfpv','cgjkqsxz','dt','l','mn','r'])for k in j}, []\n for i in s.split():\n first = i[0].upper()\n i = re.sub(r'(\\d)(\\1+)',r'\\1',re.sub(r'[^aeiouy]',lambda x:str(d.get(x.group().lower(),x.group())),first+re.sub(r'[hwHW]','',i[1:])))\n i = i[0] + re.sub(r'[aeiouyAEIOUY]', '', i[1:])\n li.append(first + (f\"{i[1:]:<03}\")[:3])\n return \" \".join(li)", "import re\n\ndef soundex(name):\n sounds = []\n namelist = name.split()\n \n \n \n for namey in namelist:\n firstletter = namey[0].upper()\n temp = namey.lower()\n temp = re.sub('[hw]', \"\", temp)\n temp = re.sub('[aeiouy]', \"*\", temp)\n temp = re.sub('[bfpv]', \"1\", temp)\n temp = re.sub('[cgjkqsxz]', \"2\", temp)\n temp = re.sub('[dt]', \"3\", temp)\n temp = re.sub('[l]', \"4\", temp)\n temp = re.sub('[mn]', \"5\", temp)\n temp = re.sub('[r]', \"6\", temp)\n temp = re.sub(r'(.)\\1+', r'\\1', temp) \n \n if firstletter in [\"H\", \"W\"]:\n tempcode = firstletter + temp + \"0000\"\n else:\n tempcode = firstletter + temp[1:] + \"0000\"\n tempcode = re.sub(\"[*]\", \"\", tempcode)\n \n sounds.append(tempcode[0:4])\n \n \n \n \n return \" \".join(sounds)\n"] | {"fn_name": "soundex", "inputs": [["Sarah Connor"], ["Sara Conar"], ["Serah Coner"], ["Sarh Connor"], ["Sayra Cunnarr"], ["Tim"], ["Joe"], ["Bob"], ["Robert"], ["Rupert"], ["Rubin"], ["Ashcraft"], ["Ashcroft"], ["Tymczak"], ["Pfister"], ["zxqurlwbx"], ["uryrtkzp"]], "outputs": [["S600 C560"], ["S600 C560"], ["S600 C560"], ["S600 C560"], ["S600 C560"], ["T500"], ["J000"], ["B100"], ["R163"], ["R163"], ["R150"], ["A261"], ["A261"], ["T522"], ["P236"], ["Z641"], ["U663"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 7,221 |
def soundex(name):
|
0f767fc79c0fb603cfc35318bd22e517 | UNKNOWN | Given a string of words, you need to find the highest scoring word.
Each letter of a word scores points according to its position in the alphabet: `a = 1, b = 2, c = 3` etc.
You need to return the highest scoring word as a string.
If two words score the same, return the word that appears earliest in the original string.
All letters will be lowercase and all inputs will be valid. | ["def high(x):\n return max(x.split(), key=lambda k: sum(ord(c) - 96 for c in k))", "def high(x):\n words=x.split(' ')\n list = []\n for i in words:\n scores = [sum([ord(char) - 96 for char in i])]\n list.append(scores)\n return words[list.index(max(list))]", "def high(x):\n scoreboard=[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\"]\n heck = x.split()\n score=0\n score_final=0\n big_word=[]\n for each in heck:\n print(each)\n for every in each:\n if every in scoreboard:\n score= score + scoreboard.index(every) + 1\n print(score)\n if score > score_final:\n score_final = score\n big_word = each\n score = 0\n else:\n score = 0\n return big_word\n # Code here 54\n \n #for every in word: if every in scoreboard, score + every.index()\n", "def high(words):\n return max(words.split(), key=lambda word: sum(ord(c) - ord('a') + 1 for c in word.lower()))", "def high(x):\n highest_score = 0\n for word in x.split(' '):\n score = sum(ord(c)-96 for c in word)\n if score > highest_score:\n highest_score = score\n highest_word = word\n \n return highest_word", "def xx(m):\n a = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,\n 'm':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}\n n = 0\n for i in m:\n n += a[i]\n return n\n\ndef high(x): \n x = x.split()\n m,n = x[0],xx(x[0])\n for i in x[1:]:\n if xx(i) > n:\n m = i\n n = xx(i)\n return m", "def high(x):\n s, n = x.split(), [sum(ord(c) - 96 for c in y) for y in x.split()]\n return s[n.index(max(n))]", "alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m',\n 'n','o','p','q','r','s','t','u','v','w','x','y','z']\n\ndef high(x):\n \n strings = list(x.split())\n array = []\n\n for word in strings:\n value = 0\n for letter in word:\n value += alphabet.index(letter)+1\n array.append([value, word])\n array.sort()\n return array[-1][1]", "def high(s):\n return max( (sum(ord(c) - 96 for c in x), x) for x in s.split() )[1]\n\n", "from string import ascii_lowercase\n\ndef high(x):\n letter_worth = {letter: int(index) for index, letter in enumerate(ascii_lowercase, start=1)}\n words = x.split()\n total = []\n for word in words:\n count = 0\n for letter in word:\n count += letter_worth.get(letter)\n total.append(count)\n return words[total.index(max(total))]"] | {"fn_name": "high", "inputs": [["man i need a taxi up to ubud"], ["what time are we climbing up the volcano"], ["take me to semynak"], ["massage yes massage yes massage"], ["take two bintang and a dance please"]], "outputs": [["taxi"], ["volcano"], ["semynak"], ["massage"], ["bintang"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,809 |
def high(x):
|
7f4406d71bbfb5814b22cf50512d3808 | UNKNOWN | In this kata, you have to define a function named **func** that will take a list as input.
You must try and guess the pattern how we get the output number and return list - **[output number,binary representation,octal representation,hexadecimal representation]**, but **you must convert that specific number without built-in : bin,oct and hex functions.**
Examples :
```python
func([12,13,6,3,6,45,123]) returns - [29,'11101','35','1d']
func([1,9,23,43,65,31,63,99]) returns - [41,'101001','51','29']
func([2,4,6,8,10,12,14,16,18,19]) returns - [10,'1010','12','a']
``` | ["def func(l):\n n = sum(l) // len(l)\n return [n] + [format(n, f) for f in \"box\"]", "from statistics import mean\n\nDIGITS = '0123456789abcdef'\n\ndef to(n, base):\n result = []\n while n:\n n, r = divmod(n, base)\n result.append(DIGITS[r])\n return ''.join(reversed(result))\n\ndef func(l):\n n = int(mean(l))\n return [n, to(n, 2), to(n, 8), to(n, 16)]", "def func(l):\n n = sum(l) // len(l)\n return [n] + '{:b} {:o} {:x}'.format(n, n, n).split()", "from builtins import bin, oct, hex\ndef func(l):\n l = sum(l)//len(l)\n return [l, bin(l)[2:], oct(l)[2:], hex(l)[2:]]", "def func(l):\n a=sum(l)//len(l)\n al=[a]\n for q in [2,8,16]:\n s,te=al[0],[]\n for i in range(0,20):\n if s>(q-1):\n te.append(str(s%q))\n s=s//q\n else:\n te.append(str(s))\n break\n if q!= 16:\n al.append(''.join(x for x in te[::-1]))\n else:\n d={'10':'a','11':'b','12':'c','13':'d','14':'e','15':'f'}\n al.append(''.join(d.get(x) if int(x)>9 else x for x in te[::-1]))\n return al \n", "def base(n,b):\n a='0123456789abcdef'\n r=''\n while n:\n n,i=divmod(n,b)\n r=a[i]+r\n return r or'0'\ndef func(l):\n n=sum(l)//len(l)\n return[n,base(n,2),base(n,8),base(n,16)]", "def func(l):\n a=int(sum(l)/len(l))\n return [a,'{:b}'.format(a),'{:o}'.format(a),'{:x}'.format(a)]", "from math import floor\n\ndef func(arr):\n x = floor(sum(arr)/len(arr))\n return [x] + [format(x, f'{i}') for i in 'box']", "from statistics import mean\n\ndef func(l):\n m = int(mean(l))\n return [m, (''.join('1' if m & 2 ** i else '0' for i in range(99, -1, -1)).lstrip('0')), f'{m:o}', f'{m:x}']", "def binary(x):\n result = []\n while True:\n remainder = x % 2\n result.append(str(remainder))\n x = x // 2\n\n if x == 0:\n break\n\n result.reverse()\n return \"\".join(result)\n\ndef octal(x):\n result = []\n while True:\n remainder = x % 8\n result.append(str(remainder))\n x = x // 8\n\n if x == 0:\n break\n\n result.reverse()\n return \"\".join(result)\n\ndef hexadecimal(x):\n result = []\n while True:\n remainder = x % 16\n\n if remainder == 10:\n result.append('a')\n elif remainder == 11:\n result.append('b')\n elif remainder == 12:\n result.append('c')\n elif remainder == 13:\n result.append('d')\n elif remainder == 14:\n result.append('e')\n elif remainder == 15:\n result.append('f')\n else:\n result.append(str(remainder))\n\n x = x // 16\n if x == 0:\n break\n\n result.reverse()\n return \"\".join(result)\n\nimport math\n\ndef func(l):\n average = math.floor(sum(l) / len(l))\n result = [average, binary(average), octal(average), hexadecimal(average)]\n return result"] | {"fn_name": "func", "inputs": [[[1, 4, 9, 16, 25, 36, 49]], [[2, 31, 3, 56, 46, 3, 467, 33]], [[9, 99, 999, 9999]], [[1, 12, 123, 1234, 12345]], [[1, 2, 6, 3, 1, 577, 12]]], "outputs": [[[20, "10100", "24", "14"]], [[80, "1010000", "120", "50"]], [[2776, "101011011000", "5330", "ad8"]], [[2743, "101010110111", "5267", "ab7"]], [[86, "1010110", "126", "56"]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,083 |
def func(l):
|
e1714122694fb2877eb9a31d89cb890d | UNKNOWN | ### Preface
You are currently working together with a local community to build a school teaching children how to code. First plans have been made and the community wants to decide on the best location for the coding school.
In order to make this decision data about the location of students and potential locations is collected.
### Problem
In order to be able to attract and teach as many students as possible we want to minimize the total traveling distance for potential students. The streets system is organized in a traditional grid system and students can only travel horizontally or vertically (not diagonal).
The locations of interested students is given as an array with the first value of each entry presenting the x coordinate and the second value presenting the y coordinate:
```python
students = [[3,7],[2,2],[14,1], ...];
```
Potential locations are passed as an array of objects with an unique id, a x and y coordinate:
```python
locations = [{"id": 1, "x": 3, "y": 4}, {"id": 2, "x": 8, "y": 2}, ...];
```
Your task is now to evaluate which of the school locations would be best to minimize the distance for all potential students to the school.
The desired output should consist of a string indicating the ID of the best suitable location and the x and y coordinates in the following form:
```
"The best location is number 1 with the coordinates x = 3 and y = 4"
``` | ["def optimum_location(students, locations):\n m = min(locations, key = lambda loc: sum(abs(loc['x'] - s[0]) + abs(loc['y'] - s[1]) for s in students))\n return \"The best location is number %d with the coordinates x = %d and y = %d\" % (m['id'], m['x'], m['y'])\n", "def manhattan(p1,p2): return sum(abs(b-a) for a,b in zip(p1,p2))\n\ndef optimum_location(students, locations):\n return \"The best location is number {id:} with the coordinates x = {x:} and y = {y:}\".format(\n **min((loc for loc in locations), key=lambda l: sum(manhattan(s,(l['x'],l['y'])) for s in students)))", "def optimum_location(students, locations):\n o = min(locations, key = lambda loc: sum(abs(x - loc['x']) + abs(y - loc['y']) for x, y in students))\n return 'The best location is number %s with the coordinates x = %s and y = %s' % (o['id'], o['x'], o['y'])", "def optimum_location(students, locations):\n best = min(locations, key=lambda location: distance(students, location))\n return \"The best location is number {id} with the coordinates x = {x} and y = {y}\".format(**best)\n\n\ndef distance(students, location):\n return sum(sum(abs(s[i] - location[j]) for i, j in ((0, \"x\"), (1, \"y\"))) for s in students)", "d = lambda a,b,c,d:abs(d-b)+abs(c-a)\noptimum_location=lambda st,lc:'The best location is number {} with the coordinates x = {} and y = {}'.format(*min([sum(d(*n,i['x'],i['y']) for n in st),i['id'],i['x'],i['y']] for i in lc)[1:])", "def optimum_location(students, locations):\n best = min(locations, key = lambda loc: sum(abs(abs(loc['x']-x) + abs(loc['y']-y)) for x, y in students))\n return f'The best location is number {best[\"id\"]} with the coordinates x = {best[\"x\"]} and y = {best[\"y\"]}'", "def optimum_location(students, locations):\n return \"The best location is number %(id)d with the coordinates x = %(x)d and y = %(y)d\" \\\n % min(locations, key=lambda l:sum(abs(x - l['x']) + abs(y - l['y']) for x, y in students))", "def optimum_location(students, locations):\n def total_distance(loc):\n x_dist = sum(abs(loc['x'] - x) for x, y in students)\n y_dist = sum(abs(loc['y'] - y) for x, y in students)\n return x_dist + y_dist\n best_loc = min(locations, key=total_distance)\n template = \"The best location is number {id} with the coordinates x = {x} and y = {y}\"\n return template.format(**best_loc)\n \n\n", "def optimum_location(students, locations, optimal = (float('inf'),)):\n for loc in locations:\n distance = sum(abs(x - loc['x']) + abs(y - loc['y']) for x, y in students)\n if distance < optimal[0]:\n optimal = distance, loc['id'], loc['x'], loc['y']\n return 'The best location is number %s with the coordinates x = %s and y = %s' % optimal[1:]"] | {"fn_name": "optimum_location", "inputs": [[[[3, 7], [2, 2], [14, 1]], [{"id": 1, "x": 3, "y": 4}, {"id": 2, "x": 8, "y": 2}]], [[[54, 7], [1, 211], [14, 44], [12, 5], [14, 7]], [{"id": 1, "x": 44, "y": 55}, {"id": 2, "x": 12, "y": 57}, {"id": 3, "x": 23, "y": 66}]], [[[152, 7], [1, 211], [14, 56], [12, 4], [142, 7]], [{"id": 1, "x": 63, "y": 55}, {"id": 2, "x": 55, "y": 21}, {"id": 3, "x": 144, "y": 12}]], [[[152, 742], [466, 2211], [1412, 564], [142, 444], [142, 744]], [{"id": 1, "x": 1263, "y": 525}, {"id": 2, "x": 55, "y": 21}, {"id": 3, "x": 537, "y": 1244}]], [[[7, 66], [71, 7], [0, 94], [16, 93], [33, 49], [49, 81], [17, 2], [95, 71], [32, 14], [31, 41], [92, 72], [12, 79]], [{"y": 38, "x": 32, "id": 1}, {"y": 49, "x": 73, "id": 2}, {"y": 85, "x": 50, "id": 3}, {"y": 2, "x": 79, "id": 4}, {"y": 20, "x": 44, "id": 5}, {"y": 56, "x": 17, "id": 6}, {"y": 43, "x": 26, "id": 7}, {"y": 61, "x": 89, "id": 8}, {"y": 18, "x": 15, "id": 9}, {"y": 34, "x": 41, "id": 10}, {"y": 27, "x": 99, "id": 11}]]], "outputs": [["The best location is number 1 with the coordinates x = 3 and y = 4"], ["The best location is number 2 with the coordinates x = 12 and y = 57"], ["The best location is number 2 with the coordinates x = 55 and y = 21"], ["The best location is number 3 with the coordinates x = 537 and y = 1244"], ["The best location is number 6 with the coordinates x = 17 and y = 56"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,794 |
def optimum_location(students, locations):
|
68edc0ed452af945b58cfe11224421de | UNKNOWN | Build a function `sumNestedNumbers`/`sum_nested_numbers` that finds the sum of all numbers in a series of nested arrays raised to the power of their respective nesting levels. Numbers in the outer most array should be raised to the power of 1.
For example,
should return `1 + 2*2 + 3 + 4*4 + 5*5*5 === 149` | ["def sum_nested_numbers(a, depth=1):\n return sum(sum_nested_numbers(e, depth+1) if type(e) == list else e**depth for e in a)", "def sum_nested_numbers(arr,m=1):\n total = 0\n for element in arr:\n if isinstance(element, int): \n total += element**m\n else:\n total += sum_nested_numbers(element, m+1)\n return total", "def sum_nested_numbers(a, lvl=0):\n return a ** lvl if not isinstance(a, list) else sum(sum_nested_numbers(b, lvl+1) for b in a)", "def sum_nested_numbers(arr, depth = 1):\n return sum(sum_nested_numbers(x, depth+1) if type(x) is list else x ** depth for x in arr)", "def flatten(xs, level=1):\n for x in xs:\n if isinstance(x, list):\n yield from flatten(x, level+1)\n else:\n yield x, level\n\ndef sum_nested_numbers(xs):\n return sum(x ** level for x, level in flatten(xs))", "def depth(arr,n):\n res=[]\n for i in arr:\n if isinstance(i,int):\n res.append((i,n))\n else:\n res+=depth(i,n+1)\n return res\ndef sum_nested_numbers(arr):\n return sum(n**i for (n,i) in depth(arr,1))", "def sum_nested_numbers(x):\n return sum(f(x))\n\ndef f(lst, v=1):\n for x in lst:\n if isinstance(x, (list,tuple)):\n for j in f(x, v+1):\n yield j\n else:\n yield x**v", "sum_nested_numbers=r=lambda a,p=1:sum(n**p if n*0==0else r(n,p+1)for n in a)", "def sum_nested_numbers(arr, d=1):\n my_sum = 0\n for v in arr:\n if isinstance(v, list):\n my_sum += sum_nested_numbers(v, d+1)\n else:\n my_sum += (v**d)\n return my_sum"] | {"fn_name": "sum_nested_numbers", "inputs": [[[0]], [[1, 2, 3, 4, 5]], [[1, [2], 3, [4, [5]]]], [[6, [5], [[4]], [[[3]]], [[[[2]]]], [[[[[1]]]]]]], [[1, [-1], [[1]], [[[-1]]], [[[[1]]]]]]], "outputs": [[0], [15], [149], [209], [5]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,675 |
def sum_nested_numbers(a, depth=1):
|
39210cf5c6d12aced460d255d8f7821e | UNKNOWN | # A History Lesson
The Pony Express was a mail service operating in the US in 1859-60.
It reduced the time for messages to travel between the Atlantic and Pacific coasts to about 10 days, before it was made obsolete by the transcontinental telegraph.
# How it worked
There were a number of *stations*, where:
* The rider switched to a fresh horse and carried on, or
* The mail bag was handed over to the next rider
# Kata Task
`stations` is a list/array of distances (miles) from one station to the next along the Pony Express route.
Implement the `riders` method/function, to return how many riders are necessary to get the mail from one end to the other.
## Missing rider
In this version of the Kata a rider may go missing. In practice, this could be for a number of reasons - a lame horse, an accidental fall, foul play...
After some time, the rider's absence would be noticed at the **next** station, so the next designated rider from there would have to back-track the mail route to look for his missing colleague. The missing rider is then safely escorted back to the station he last came from, and the mail bags are handed to his rescuer (or another substitute rider if necessary).
`stationX` is the number (2..N) of the station where the rider's absence was noticed.
# Notes
* Each rider travels as far as he can, but never more than 100 miles.
# Example
GIven
* `stations = [43, 23, 40, 13]`
* `stationX = 4`
So
`S1` ... ... 43 ... ... `S2` ... ... 23 ... ... `S3` ... ... 40 ... ... `S4` ... ... 13 ... ... `S5`
* Rider 1 gets as far as Station S3
* Rider 2 (at station S3) takes mail bags from Rider 1
* Rider 2 never arrives at station S4
* Rider 3 goes back to find what happened to Rider 2
* Rider 2 and Rider 3 return together back to Station S3
* Rider 3 takes mail bags from Rider 2
* Rider 3 completes the journey to Station S5
**Answer:**
3 riders
*Good Luck.
DM.*
---
See also
* The Pony Express
* The Pony Express (missing rider) | ["def riders(stations, lost):\n stations = stations[:lost-1] + stations[lost-2:]\n rider, dist = 1, 0\n for i,d in enumerate(stations):\n rider += (dist+d > 100) + (i == lost-2)\n dist = dist * (dist+d <= 100 and i != lost-2) + d\n return rider", "LIMIT = 100\n\ndef riders(stations, station_x):\n riders = 1\n rode = 0\n for station, distance in enumerate(stations, 2):\n if rode + distance > LIMIT:\n # Too far, switch riders\n riders += 1\n rode = 0\n \n if station == station_x:\n # Rider lost, send a rescue rider back from station_x\n riders += 1\n if distance > LIMIT / 2:\n # Rescuer would would have to ride too far to return, so need another new rider back to station_x\n riders += 1\n rode = distance\n else:\n # Rescuer is back as original station\n rode = 2 * distance\n else:\n # Carry on to next station, still got plenty of juice\n rode += distance\n\n return riders\n", "def riders(s,x):\n station,i,riders, p = 1, 0, [0], 0\n while station <= len(s) + 1:\n if riders[p] + s[i] <= 100 : riders[p] += s[i]\n else : riders.append(0) ; p += 1 ; continue\n station += 1 ; i += 1\n if station == x:\n riders.append(0)\n p += 1 ; i -= 1\n riders[p] += s[i]\n return len(riders)", "def riders(sts, x):\n st, x, back, n = 0, x-1, 0, 1\n while True:\n remain, back = 100 - back, 0\n while remain >= sts[st]:\n remain -= sts[st]\n st += 1\n if st == x:\n st -= 1\n x = -1\n back = sts[st]\n break\n elif st == len(sts):\n return n\n n += 1", "def riders(stations, station_x): \n riders = 2\n miles = 0\n for i in range(len(stations)):\n if i == station_x - 2:\n \n miles = stations[i]\n miles += stations[i]\n if miles > 100:\n riders +=1\n if i == len(stations) - 1:\n break\n if miles + stations[i+1] > 100:\n riders += 1\n miles = 0 \n \n return riders ", "def riders(S,x):\n R=[]\n for i,s in enumerate(S):\n R+=R and R[-1]+s<=100and[R.pop()+s]or[s]\n if i+2==x:R+=100<s*2and[s]*2or[s*2]\n return len(R)", "def riders(S,x):\n R=[]\n for i,s in enumerate(S,1):\n if R==[]or 100<R[-1]+s:R+=[s]\n else:R[-1]+=s\n if i==x-1:R+=100<s*2and[s]*2or[s*2]\n return len(R)", "def riders(stations, station_x):\n stations.insert(station_x-2, stations[station_x-2])\n riders = 1\n miles = 0\n for i, m in enumerate(stations):\n miles += m\n if miles > 100:\n miles = m\n riders += 1\n if i == station_x - 2:\n miles = m\n riders += 1\n return riders\n", "def riders(stations, station_x):\n r = 1\n d = 0\n for i, e in enumerate(stations, 1):\n d += e\n if i+1 == station_x:\n r += 1\n d = 2*e\n if d > 100:\n d = e\n r += 1\n if i < len(stations):\n temp = d + stations[i]\n if temp > 100:\n r += 1\n d = 0\n return r", "def riders(stations, station_x):\n riders = 1\n index = 1\n r_miles = 0\n \n for s_distance in stations:\n index += 1\n r_miles += s_distance\n \n if r_miles > 100:\n riders += 1\n r_miles = s_distance\n \n if station_x == index:\n riders += 1\n r_miles = (s_distance * 2)\n if r_miles > 100:\n riders += 1\n r_miles = s_distance\n return riders\n \n #print (stations)\n #print (station_x)\n"] | {"fn_name": "riders", "inputs": [[[43, 23, 40, 13], 4], [[18, 15], 2], [[43, 23, 40, 13], 3], [[33, 8, 16, 47, 30, 30, 46], 5], [[6, 24, 6, 8, 28, 8, 23, 47, 17, 29, 37, 18, 40, 49], 2], [[50, 50], 2], [[50, 50, 25, 50, 24], 3], [[50, 51, 25, 50, 25], 3], [[50, 100, 25, 50, 26], 3], [[100], 2], [[50, 50], 3], [[50, 51], 3]], "outputs": [[3], [2], [2], [5], [5], [3], [3], [5], [6], [3], [2], [4]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,984 |
def riders(stations, station_x):
|
f63cb005c69284e2a2b23305d40d97f7 | UNKNOWN | Complete the solution so that it returns the number of times the search_text is found within the full_text.
```python
search_substr( fullText, searchText, allowOverlap = true )
```
so that overlapping solutions are (not) counted. If the searchText is empty, it should return `0`. Usage examples:
```python
search_substr('aa_bb_cc_dd_bb_e', 'bb') # should return 2 since bb shows up twice
search_substr('aaabbbcccc', 'bbb') # should return 1
search_substr( 'aaa', 'aa' ) # should return 2
search_substr( 'aaa', '' ) # should return 0
search_substr( 'aaa', 'aa', false ) # should return 1
``` | ["import re\n\ndef search_substr(full_text, search_text, allow_overlap=True):\n if not full_text or not search_text: return 0\n return len(re.findall(f'(?=({search_text}))' if allow_overlap else search_text, full_text))", "import re\n\ndef search_substr(origin, target, overlap=True):\n if not target: return 0\n \n start, end = map(re.escape, (target[0], target[1:])) # To match correctly '|' or other special regexp chars\n patternStr = r'{}{}'.format(start, f'(?={end})' if overlap else end)\n \n return sum(1 for _ in re.finditer(patternStr, origin))", "import re\n\ndef search_substr(full_text, search_text, allow_overlap=True):\n if not full_text or not search_text: return 0\n return len(re.findall(r'(?=({}))'.format(search_text) if allow_overlap else r'{}'.format(search_text), full_text))", "def search_substr(f_t, s_t, allow_overlap=True):\n if not s_t or not f_t: return 0\n if allow_overlap: return sum(1 for i in range(len(f_t) - len(s_t) + 1) if f_t[i: i + len(s_t)] == s_t)\n return f_t.count(s_t)", "import re\ndef search_substr(full_text, search_text, allow_overlap=True):\n if not full_text or not search_text: return 0\n if allow_overlap == False: return len(re.findall(r'(' + search_text + ')', full_text))\n else: return len(re.findall(r'(?=(' + search_text + '))', full_text))", "import re\n\ndef search_substr(full_text, search_text, allow_overlap=True):\n if allow_overlap:\n try:\n return len(re.findall(search_text[0]+'(?={})'.format(search_text[1:]), full_text))\n except IndexError:\n return 0\n \n else:\n return len(re.findall(search_text, full_text)) if search_text else 0", "import re\ndef search_substr(full_text, search_text, allow_overlap=True):\n if not full_text or not search_text:\n return 0\n if len(search_text) == 1 or not allow_overlap:\n pattern = re.compile(search_text)\n else:\n pattern = re.compile(f\"(?<={search_text[:-1]}){search_text[-1]}\")\n return len(list(re.findall(pattern, full_text)))", "def search_substr(ft, st, allow_overlap=True):\n if not st: return 0\n i,L,M,r,x = 0,len(ft),len(st),0,1\n if not allow_overlap: x = M\n while i + M <= L:\n if ft[i:i+M] == st: r,i = r+1,i+x-1\n i += 1\n return r", "def search_substr(full_text, search_text, allow_overlap=True):\n if search_text == '':\n return 0\n if allow_overlap:\n return len([1 for i in range(len(full_text)) if full_text.startswith(search_text, i)])\n return full_text.count(search_text)", "def search_substr(s, sub, overlap=True):\n return 0 if not s or not sub else sum(s[i:].startswith(sub) for i in range(len(s))) if overlap else len(s.split(sub)) - 1"] | {"fn_name": "search_substr", "inputs": [["aa_bb_cc_dd_bb_e", "bb"], ["aaabbbcccc", "bbb"], ["aaacccbbbcccc", "cc"], ["aaa", "aa"], ["aaa", "aa", false], ["aaabbbaaa", "bb", false], ["a", ""], ["", "a"], ["", ""], ["", "", false]], "outputs": [[2], [1], [5], [2], [1], [1], [0], [0], [0], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,791 |
def search_substr(full_text, search_text, allow_overlap=True):
|
f126c597f1183fdfaaa7d803f63036f0 | UNKNOWN | Implement a function which
creates a **[radix tree](https://en.wikipedia.org/wiki/Radix_tree)** (a space-optimized trie [prefix tree])
in which each node that is the only child is merged with its parent [unless a word from the input ends there])
from a given list of words
using dictionaries (aka hash maps or hash tables) where:
1. The dictionary keys are the nodes.
2. Leaf nodes are empty dictionaries.
3. The value for empty input is an empty dictionary.
4. Words are all lowercase or empty strings.
5. Words can contain duplicates.
### Examples:
```python
>>> radix_tree()
{}
>>> radix_tree("")
{}
>>> radix_tree("", "")
{}
>>> radix_tree("radix", "tree")
{"radix": {}, "tree": {}}
>>> radix_tree("ape", "apple")
{"ap": {"e": {}, "ple": {}}}
>>> radix_tree("apple", "applet", "apple", "ape")
{"ap": {"ple": {"t": {}}, "e": {}}}
>>> radix_tree("romane", "romanus", "romulus", "rubens", "rubicon", "rubicundus")
{"r": {"om": {"an": {"e": {}, "us": {}}, "ulus": {}},
"ub": {"ens": {}, "ic": {"on": {}, "undus": {}}}}}
>>> radix_tree("appleabcd", "apple")
{"apple": {"abcd": {}}}
``` | ["from itertools import groupby\nfrom operator import itemgetter\nfrom os.path import commonprefix\n\nfirst = itemgetter(0)\n\ndef radix_tree(*words):\n words = [w for w in words if w]\n result = {}\n for key, grp in groupby(sorted(words), key=first):\n lst = list(grp)\n prefix = commonprefix(lst)\n result[prefix] = radix_tree(*(w[len(prefix):] for w in lst))\n return result", "def radix_tree(*words):\n byFirstChar={}\n for w in words:\n if w != \"\":\n l=byFirstChar.get(w[0],[])\n l.append(w[1:])\n byFirstChar[w[0]]=l\n result={}\n for c,l in byFirstChar.items():\n rt=radix_tree(*l)\n if len(rt) == 1 and not '' in l:\n for key,value in rt.items():\n c=c+key\n rt=value\n result[c]=rt\n return result", "from itertools import groupby\ndef radix_tree(*d, need=1):\n if not {i for i in d if i} : return {} \n store = {}\n for i, j in groupby(sorted(d) if need else d, lambda x: x[0]):\n words = list(j)\n if len(words) == 1 : store[words[0]] = {}\n else:\n common = next((j for j, i in enumerate(zip(*words)) if len(set(i)) != 1), len(min(words, key=len)))\n store[words[0][:common]] = radix_tree(*[i[common:] for i in words if i[common:]],need = 0)\n return store", "from os.path import commonprefix\n\ndef radix_tree(*words):\n groups = {}\n for word in words:\n if word:\n groups[word[0]] = groups.get(word[0], []) + [word]\n root = {}\n for group in groups.values():\n prefix = commonprefix(group)\n root[prefix] = radix_tree(*(w[len(prefix):] for w in group))\n return root", "def radix_tree(*W):\n D={}\n for w in W:\n if w:D[w[0]]=D.get(w[0],[])+[w[1:]]\n Z={}\n for k in D:\n T=radix_tree(*D[k])\n if len(T)==1and''not in D[k]:\n for j in T:k,T=k+j,T[j]\n Z[k]=T\n return Z", "def radix_tree(*a):\n r = {}\n for s in a:\n d = r\n for x in s + \"*\":\n if x not in d: d[x] = {}\n d = d[x]\n def g(d):\n dd = {}\n for x in d:\n d[x] = g(d[x])\n if len(d[x]) == 1:\n k, v = [*d[x].items()][0]\n dd[x+k] = v\n else:\n dd[x] = d[x]\n return dd\n def h(d):\n dd = {}\n for x in d:\n d[x] = h(d[x])\n if x != \"*\":\n dd[x if x[-1] != \"*\" else x[:-1]] = d[x]\n return dd\n return h(g(r))", "def radix_tree(*Q) :\n U,R = set(Q),{}\n for Q in Q :\n T = R\n for Q in Q :\n if not Q in T : T[Q] = {}\n T = T[Q]\n def H(Q,S) :\n T = list(Q)\n for V in T :\n if 1 == len(Q[V]) and (S + V) not in U :\n B = next(iter(Q[V]))\n Q[V + B] = Q[V][B]\n del Q[V]\n T.append(V + B)\n else : H(Q[V],S + V)\n H(R,'')\n return R", "from itertools import groupby\n\ndef radix_tree(*words):\n d = {}\n if not any(words): return d\n words = sorted(words)\n for g in (list(g) for _,g in groupby(words, key=lambda w:w[0] if w else '')):\n i = next((i for i in range(len(g[0])) if not all(len(w) > i and w[i] == g[0][i] for w in g)), len(g[0]))\n d[g[0][:i]] = radix_tree(*(w[i:] for w in g if len(w) > i))\n return d\n \n \n", "from itertools import groupby\ndef radix_tree(*d):\n if not {i for i in d if i} : return {} \n store = {}\n for i, j in groupby(sorted(d), lambda x: x[0]):\n words = list(j)\n if len(words) == 1 : store[words[0]] = {}\n else:\n common = next((j for j, i in enumerate(zip(*words)) if len(set(i)) != 1), len(min(words, key=len)))\n store[words[0][:common]] = radix_tree(*[i[common:] for i in words if i[common:]])\n return store", "from functools import reduce\n\ndef splitAlong(xs, ys):\n i = 0\n try:\n while xs[i] == ys[i]:\n i += 1\n except IndexError:\n pass\n return (xs[:i], xs[i:], ys[i:])\n\ndef insert(tree, word):\n for key, val in tree.items():\n pref, wt, kt = splitAlong(word, key)\n if pref:\n if kt:\n del tree[key]\n tree[pref] = {wt: {}, kt: val} if wt else {kt: val}\n else:\n insert(tree[pref], wt)\n return tree\n if word:\n tree[word] = {}\n return tree\n\n\ndef radix_tree(*words):\n return reduce(insert, words, {})"] | {"fn_name": "radix_tree", "inputs": [[""], ["abc", "def", "ghi", "jklm", "nop"], ["ape", "apple"], ["ape", "appendix", "apel"], ["ape", "apple", "applet", "appendix"], ["romane", "romanus", "romulus"], ["test", "tester", "testers"], ["test", "tester", "testers", "tester"], ["testers", "tester", "test"]], "outputs": [[{}], [{"abc": {}, "def": {}, "ghi": {}, "jklm": {}, "nop": {}}], [{"ap": {"e": {}, "ple": {}}}], [{"ap": {"e": {"l": {}}, "pendix": {}}}], [{"ap": {"e": {}, "p": {"le": {"t": {}}, "endix": {}}}}], [{"rom": {"an": {"e": {}, "us": {}}, "ulus": {}}}], [{"test": {"er": {"s": {}}}}], [{"test": {"er": {"s": {}}}}], [{"test": {"er": {"s": {}}}}]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,660 |
def radix_tree(*words):
|
d44b29392f5fd425c28c895af1a64820 | UNKNOWN | Consider the number triangle below, in which each number is equal to the number above plus the number to the left. If there is no number above, assume it's a `0`.
The triangle has `5` rows and the sum of the last row is `sum([1,4,9,14,14]) = 42`.
You will be given an integer `n` and your task will be to return the sum of the last row of a triangle of `n` rows.
In the example above:
More examples in test cases. Good luck!
```if:javascript
### Note
This kata uses native arbitrary precision integer numbers ( `BigInt`, `1n` ).
Unfortunately, the testing framework and even native `JSON` do not fully support them yet.
`console.log(1n)` and `(1n).toString()` work and can be used for debugging.
We apologise for the inconvenience.
``` | ["# https://oeis.org/A000108\nfrom math import factorial as fac\ndef solve(n): return fac(2*n)//fac(n)//fac(n+1)", "def binomial_coefficient (n, k):\n if not n >= k >= 0:\n return None\n lower_k = min(k, n-k)\n coeff = 1\n for i in range(lower_k):\n coeff *= n - i\n coeff //= i + 1\n return coeff\n \ndef catalan_number (n):\n return binomial_coefficient(2*n, n) // (n+1)\n\ndef solve (n):\n return catalan_number(n)", "from math import factorial\ndef solve(n):\n return factorial(2*n)//(factorial(n)*factorial(n+1))", "from decimal import Decimal\n\nimport numpy as np\n\n\ndef solve(n):\n a = np.ones(1, dtype=Decimal)\n for i in range(n):\n a = np.append(np.add.accumulate(a), [0])\n return a.sum()", "from math import factorial\n\ndef binominal(n, k):\n if k < 0 or n < k:\n return None\n product = 1\n for i in range(k):\n product *= n-i\n product //= i+1\n return product\n\ndef catalan(n):\n return binominal(2*n, n) // (n+1)\n\ndef solve(n):\n return catalan(n)", "def binomial (n, k):\n n, k = int(n), int(k)\n if not n >= k >= 0:\n return None\n k = min(k, n-k)\n product = 1\n for i in range(k): \n product *= n - i\n product //= i + 1\n return product\n\ndef catalan (n):\n return binomial(2*n,n) // (n+1)\n\ndef solve (n): \n return catalan(n)\n \n\n", "from itertools import accumulate\ndef solve(n):\n a = [1]\n for _ in range(n):\n a = list(accumulate(a))\n a += a[-1:]\n return a[-1]", "from functools import reduce\nfrom operator import mul\n\ndef solve(n):\n return reduce(mul, range(n+2, 2*n+1)) // reduce(mul, range(1, n+1))", "def solve(n):\n a=[1]\n for _ in range(n-1):\n b=[1]\n for x in a[1:]:\n b.append(x+b[-1])\n b.append(b[-1])\n a=b\n return sum(a)"] | {"fn_name": "solve", "inputs": [[4], [5], [6], [7], [8], [20]], "outputs": [[14], [42], [132], [429], [1430], [6564120420]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,910 |
def solve(n):
|
a5144ea84a931b47e7a00af1a623d567 | UNKNOWN | An AI has infected a text with a character!!
This text is now **fully mutated** to this character.
If the text or the character are empty, return an empty string.
There will never be a case when both are empty as nothing is going on!!
**Note:** The character is a string of length 1 or an empty string.
# Example
```python
text before = "abc"
character = "z"
text after = "zzz"
``` | ["def contamination(text, char):\n return char*len(text)", "def contamination(text, char):\n return len(text) * char", "import re\ndef contamination(text, char):\n return re.sub(\".\", char, text)", "import re\n\ndef contamination(text, char):\n if text == '' or char == '':\n return \"\"\n else:\n contaminated_word = re.sub('[!#~@$%&*_+{}|:\"<>;,/?=a-zA-Z0-9]', char, text)\n return contaminated_word", "contamination = lambda s, c: c * len(s)", "contamination=lambda t,c: c*len(t)", "def contamination(text: str, char: str) -> str:\n \"\"\" Mutate the text by given character. \"\"\"\n return char * len(text)", "def contamination(text, char):\n return \"\".join(char for x in text)", "def contamination(text, char):\n return \"\" if not text else char+contamination(text[1:],char)", "def contamination(text, char):\n if not char or not text:\n return \"\"\n else:\n return char * len(text)\n", "def contamination(t, char):\n return t.translate({ord(x):char for x in t})", "contamination = lambda text, char : char * len (text);", "def contamination(text, char):\n return \"\".join(char for _ in text)\n", "def contamination(text, char):\n for i in text:\n text = text.replace(i, char)\n return text", "def contamination(text, char):\n return char * len(text) if len(char) > 0 and len(text) > 0 else ''", "def contamination(text, char): \n return ''.join([char for letter in text])", "def contamination(text, char):\n if len(text)==0:\n return ''\n res = ''\n for i in range(len(text)):\n res += text[i].replace(text[i], char)\n \n return res", "def contamination(text, char):\n return len(text) * char if len(text) else ''", "def contamination(text, char):\n res = ''\n if text:\n for c in text:\n res += char\n return res\n else:\n return text", "def contamination(text, char):\n a = len(text)\n if type(text) == str:\n return a * char\n if text or char == \"\": \n return \"\"\n", "def contamination(text, char):\n x = []\n if text == '' or char == '':\n return \"\"\n else:\n for i in range(len(text)):\n x.append(char)\n return ''.join(x)", "def contamination(text, char):\n i,s=0,''\n while i <len(text):\n s+=char\n i+=1\n return s\n", "def contamination(text, char):\n answer = len(text)\n final = \"\"\n for i in range(answer):\n final += char\n return final", "def contamination(text, char):\n result = ''\n if (len(text) == 0 or char == ''):\n return ''\n else:\n for x in text:\n result = result + char\n return result", "def contamination(text: str, char: str) -> str:\n return \"\" if text == \"\" or char == \"\" else char * len(text)", "def contamination(txt, char):\n return char*len(txt)", "def contamination(text, char):\n res=\"\"\n i=0\n while i <len(text):\n i+=1\n res+=char\n return res", "def contamination(text, char):\n return char*(len(text) if char and text else 0)", "def contamination(text, char):\n st=''\n for c in text:\n st+=char\n return st", "def contamination(text, char):\n lst=[char for i in range(len(text))]\n return \"\".join(lst)", "def contamination(text, char):\n if text == \"\" or char == \"\":\n return \"\"\n \n res = \"\"\n for t in text:\n res += char\n return res", "def contamination(text, char):\n \n res = \"\"\n for i in text:\n if text == \" \":\n return text\n else:\n res+=char\n return res", "def contamination(text, char):\n if text=='' or char=='':\n return ''\n else:\n ans=''\n for i in text:\n ans=ans+char\n return ans", "def contamination(text, char):\n list = []\n if len(text) == 0 or len(char) == 0:\n return ''\n else:\n for elem in text:\n elem = char\n list.append(elem)\n return ''.join(list)", "def contamination(text, char):\n l = len(text)\n n = \"\"\n for i in range(0, l):\n n = n + char\n return n", "def contamination(text, char):\n a = \"\"\n for i in text:\n a += char\n return a", "def contamination(text, char):\n return char * len(text) if text != '' != char else ''", "def contamination(text, char):\n msg = ''\n if char != '':\n for x in text:\n msg += char\n return msg", "def contamination(text, char):\n return len(text) * char if text != '' or text != '' else \"\"\n", "def contamination(text, char):\n l = 0\n if char == \"\":\n return \"\"\n elif text == \"\":\n return \"\"\n else:\n l = len(text)\n return char*l", "def contamination(text, char):\n if text == \"\":\n return text\n if char == \"\":\n return char\n else:\n return char * len(text)\n\n", "def contamination(text, char):\n return \"\" if text is \"\" else char * len(text)", "def contamination(text, char):\n number = len(text)\n return char * number", "def contamination(text, char):\n if text is '' or char is '':\n return ''\n else:\n return char * len(text)", "def contamination(text, char):\n large = 0\n for letters in text:\n large += 1\n return large*char", "def contamination(text, char):\n large = 0\n newText = \"\"\n for letters in text:\n large += 1\n if text == \"\":\n newText == \"\"\n else:\n newText = large*char\n return newText", "def contamination(text, char):\n if text == \"\":\n return text\n else:\n for letter in text:\n text = text.replace(letter, char)\n return text", "def contamination(text, char):\n \n output = \"\"\n \n for i in range(0,len(text)):\n output += char\n \n return output", "def contamination(text, char):\n return char * len(text) if len(char) else ''", "def contamination(text, char):\n m = list(text)\n n = []\n for i in m:\n n.append(char)\n a = \"\".join(n)\n return a", "def contamination(text, char):\n cunt = list(text)\n ctr = 0\n for fuck in cunt:\n cunt[ctr] = char\n ctr += 1\n return ''.join(cunt)", "contamination=lambda t,c:c*len(t) if t and c else ''", "def contamination(text, char):\n #Code here ;)\n return len(text)*char if text != \"\" and char != \"\" else \"\"", "def contamination(text, char):\n result = ''\n for s in range(0, len(text)):\n result += char\n return result", "def contamination(text, char):\n if text == '' or char == '':\n return ''\n elif len(text) > 0:\n return len(text)*char\n", "def contamination(text, char):\n \n l = len(text)\n r = l * char\n \n if text == \"\" or char == \"\":\n return \"\"\n else:\n return r\n", "import string\n\ndef contamination(text, char):\n if not text or not char:\n return ''\n \n intab = string.printable\n outtab = char * len(intab)\n transtab = str.maketrans(intab, outtab)\n \n return text.translate(transtab)\n", "def contamination(text, char):\n new_str = ''\n for l in text:\n new_str += char\n return new_str", "def contamination(text, char):\n return \"\" if not(text or char) else len(text) * char", "def contamination(text, char):\n return '' if text == '' else f'{char*len(text)}'", "def contamination(text, char):\n return '' if not text else char * len(text)", "def contamination(text, char):\n \n if not (text or char):\n return ''\n return char*len(text)", "def contamination(text, char):\n return ''.join([char for i in range(len(text))]) if text else \"\"", "def contamination(s, c):\n return ''.join([x.replace(x,c) for x in s if s != \"\"])", "def contamination(text, char):\n nw = ''\n for c in text:\n nw += char\n return nw\n # Flez\n", "def contamination(text, char):\n a = len(text)\n return a * char", "def contamination(text, char):\n if char != \"\":\n return char * len(text)\n else:\n return \"\"", "def contamination(text, char):\n return \"\".join([i.replace(i,char) for i in text])", "def contamination(text, char):\n string = \"\"\n for i in range(len(text)):\n string += char\n return string", "def contamination(text, char):\n return \"\" if text == \"\" or char == \"\" else \"\".join([char for i in text])", "def contamination(text, char):\n return '' if text=='' or char=='' else ''.join(char for letter in text)", "def contamination(text, char):\n if text == '':\n return ''\n \n return char * len(text)", "def contamination(text, char):\n if not text or not char:\n return ''\n \n for ch in text:\n text = text.replace(ch, char) \n \n return text", "def contamination(text, char):\n #Code here ;)\n #print(text[1])\n lt = list(text)\n for i in range(len(lt)):\n lt[i] = char\n return \"\".join(lt)", "def contamination(text, char):\n return f\"{len(text)*char}\"", "def contamination(s, c):\n f = ''\n for i in range(len(s)):\n f = f + c\n return f ", "def contamination(text, char):\n if len(text) == 0:\n return \"\"\n else:\n result = \"\"\n for c in text:\n result += char\n return result", "def contamination(text, char):\n if text:\n return ''.join([char for el in list(text)])\n else:\n return ''\n \n \n \n", "def contamination(text, char):\n x = ''\n for i in text:\n x = x + char\n if text == '' or char == '':\n return ''\n else:\n return x", "def contamination(text, char):\n return ''.join(char for i in range(len(text))) if len(text) > 0 or len(char) > 0 else ''", "def contamination(text, char):\n return text.replace(text, char*len(text))\n\n\nprint((contamination('_3ebzgh4', '&')))\n", "def contamination(text, char):\n return \"\" if len(text) == 0 else char * len(text) ", "def contamination(text, char):\n return '' if not text or not char else len(text) * char", "def contamination(text, char):\n if text == None:\n return ''\n else:\n return char * len(text)", "def contamination(text, char):\n if text == '': return ''\n text = list(text)\n for x in range(len(text)):\n text[x] = char\n \n return ''.join(text)", "def contamination(text, char):\n return len(text)*char if len(text)!=0 or len(char)!=0 else \"\"", "def contamination(text, char):\n return len(text) * str(char)", "def contamination(text, char):\n return \"\" if char==\"\" else char*len(text)", "def contamination(text, char):\n #return char * len(text) if text and char else ''\n return char * len(text)", "def contamination(text, char):\n if not text or not char:\n return ''\n else:\n return char * len(text)", "def contamination(text,char):\n if text == \"\":\n return text\n elif char == \"\":\n return char\n else:\n count_of_characters = len(text)\n return (char * count_of_characters)\n", "def contamination(text, char):\n return len(text)*char if len(text)!=0 and len(char)!=0 else ''", "def contamination(text, char):\n #Code here ;)\n return char * len(text)\n \n print(contamination(\"abc\",\"z\"))", "def contamination(text, char):\n if not (text or char):\n return ''\n else:\n return char*(len(text))", "def contamination(text, char):\n new_str = \"\"\n new_str += str(char) * len(text)\n return new_str", "def contamination(text, char):\n return ''.join([char for i in text])", "def contamination(text, char):\n a = len(text)* char\n return a", "def contamination(text, char):\n if char == '': return ''\n else: return len(text)*char", "def contamination(text, char):\n #Code here ;)\n# for i in range(len(text)):\n# text[i] = char\n# return text\n return(char * len(text))", "def contamination(text, char):\n nt = len(text)\n nc = len(char)\n if nt == 0 or nc == 0:\n return \"\"\n return char * nt"] | {"fn_name": "contamination", "inputs": [["abc", "z"], ["", "z"], ["abc", ""], ["_3ebzgh4", "&"], ["//case", " "]], "outputs": [["zzz"], [""], [""], ["&&&&&&&&"], [" "]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 12,171 |
def contamination(text, char):
|
eb04091547560be6d446dff47d529e34 | UNKNOWN | Create a function that takes a string and returns that
string with the first half lowercased and the last half uppercased.
eg: foobar == fooBAR
If it is an odd number then 'round' it up to find which letters to uppercase. See example below.
sillycase("brian")
// --^-- midpoint
// bri first half (lower-cased)
// AN second half (upper-cased) | ["def sillycase(silly):\n half = (len(silly) + 1) // 2\n return silly[:half].lower() + silly[half:].upper()", "def sillycase(s):\n l = len(s)\n return s[:l//2+l%2].lower() + s[l//2+l%2:].upper()", "from math import ceil\ndef sillycase(silly):\n return silly[:ceil(len(silly)/2)].lower() + silly[ceil(len(silly)/2):].upper()", "import math\n\ndef sillycase(silly):\n t=int(math.ceil(len(silly)/2.0))\n return silly[:t].lower() + silly[t:].upper()", "def sillycase(silly):\n return silly[:(len(silly) + 1)// 2].lower() + silly[(len(silly) + 1)// 2:].upper()", "import math\ndef sillycase(s):\n return s[:int(math.ceil(len(s)/2.0))].lower() + s[int(math.ceil(len(s)/2.0)):].upper()", "import math\ndef sillycase(silly):\n first = silly[:math.ceil(len(silly) / 2)].lower()\n last = silly[math.ceil(len(silly) / 2):].upper()\n return first + last\n\n \n", "def sillycase(silly):\n n = len(silly)>>1\n if ~len(silly)&1:\n return silly[:n].lower() + silly[n:].upper()\n return silly[:n+1].lower() + silly[n+1:].upper()", "import math\n\ndef sillycase(silly):\n if len(silly) % 2 == 0:\n even_half = len(silly) // 2\n return silly[:even_half].lower() + silly[even_half:].upper()\n else:\n odd_half = math.ceil(len(silly) / 2)\n return silly[:odd_half].lower() + silly[odd_half:].upper()", "def sillycase(silly):\n output=''\n for c in range(len(silly)):\n if c <len(silly)/2:\n output+=str.lower(silly[c]) \n else:\n output+=str.upper(silly[c]) \n return output\n"] | {"fn_name": "sillycase", "inputs": [["foobar"], ["codewars"], ["jAvASCript"], ["brian"], ["jabberwock"], ["SCOTland"], ["WeLlDoNe"]], "outputs": [["fooBAR"], ["codeWARS"], ["javasCRIPT"], ["briAN"], ["jabbeRWOCK"], ["scotLAND"], ["wellDONE"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,589 |
def sillycase(silly):
|
1df8458fdf23e46e193ddb0e8f5b7147 | UNKNOWN | Given 2 strings, your job is to find out if there is a substring that appears in both strings. You will return true if you find a substring that appears in both strings, or false if you do not. We only care about substrings that are longer than one letter long.
#Examples:
````
*Example 1*
SubstringTest("Something","Fun"); //Returns false
*Example 2*
SubstringTest("Something","Home"); //Returns true
````
In the above example, example 2 returns true because both of the inputs contain the substring "me". (so**ME**thing and ho**ME**)
In example 1, the method will return false because something and fun contain no common substrings. (We do not count the 'n' as a substring in this Kata because it is only 1 character long)
#Rules:
Lowercase and uppercase letters are the same. So 'A' == 'a'.
We only count substrings that are > 1 in length.
#Input:
Two strings with both lower and upper cases.
#Output:
A boolean value determining if there is a common substring between the two inputs. | ["def substring_test(first, second):\n first = first.lower()\n second = second.lower()\n\n for i in range(len(first) - 2):\n if first[i:i+2] in second:\n return True\n return False", "def substring_test(str1, str2):\n str1 = str1.lower()\n str2 = str2.lower()\n return any(\n str1[i:i+2] in str2\n for i in range(len(str1)-1)\n )", "def substring_test(a, b):\n if len(a) > len(b): a, b = b, a\n a, b = a.lower(), b.lower()\n return any(a[i:i+2] in b for i in range(len(a) - 1))", "def substring_test(*args):\n shorter, longer = sorted((a.lower() for a in args), key=len)\n for b in range(len(shorter) - 1):\n if longer.find(shorter[b:b + 2]) != -1:\n return True\n return False\n", "def substring_test(str1, str2):\n str1, str2 = str1.lower(), str2.lower()\n return any(str1[start:(start + 2)] in str2 for start in range(len(str1) - 1))\n", "def substring_test(str1, str2):\n str1,str2 = str1.lower(),str2.lower()\n s1 = [str1[i:i+2] for i in range(len(str1)-1)]\n s2 = [str2[i:i+2] for i in range(len(str2)-1)]\n return len(set(s1).intersection(s2))>0", "from difflib import SequenceMatcher\n\ndef substring_test(str1, str2):\n return any(x.size > 1 for x in SequenceMatcher(None, str1.lower(), str2.lower()).get_matching_blocks())", "def substring_test(str1, str2):\n str1, str2 = str1.lower(), str2.lower()\n return any(str1.find(str2[i:i+2]) > -1 for i in range(len(str2)-1))", "def substring_test(str1, str2):\n a,b = str1.lower(), str2.lower()\n for i in range(len(a)-1):\n if a[i:i+2] in b:\n return True\n return False \n"] | {"fn_name": "substring_test", "inputs": [["Something", "Home"], ["Something", "Fun"], ["Something", ""], ["", "Something"], ["BANANA", "banana"], ["test", "lllt"], ["", ""], ["1234567", "541265"], ["supercalifragilisticexpialidocious", "SoundOfItIsAtrocious"], ["LoremipsumdolorsitametconsecteturadipiscingelitAeneannonaliquetligulautplaceratorciSuspendissepotentiMorbivolutpatauctoripsumegetaliquamPhasellusidmagnaelitNullamerostellustemporquismolestieaornarevitaediamNullaaliquamrisusnonviverrasagittisInlaoreetultricespretiumVestibulumegetnullatinciduntsempersemacrutrumfelisPraesentpurusarcutempusnecvariusidultricesaduiPellentesqueultriciesjustolobortisrhoncusdignissimNuncviverraconsequatblanditUtbibendumatlacusactristiqueAliquamimperdietnuncsempertortorefficiturviverra", "thisisalongstringtest"], ["Codewars is sweet!", "is"]], "outputs": [[true], [false], [false], [false], [true], [false], [false], [true], [true], [true], [true]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,688 |
def substring_test(str1, str2):
|
7afe3976a3ea6007578ebcd2f8debd67 | UNKNOWN | How many days are we represented in a foreign country?
My colleagues make business trips to a foreign country. We must find the number of days our company is represented in a country. Every day that one or more colleagues are present in the country is a day that the company is represented. A single day cannot count for more than one day.
Write a function that recieves a list of pairs and returns the number of days that the company is represented in the foreign country. The first number of the pair is the number of the day of arrival and the second number of the pair is the day of departure of someone who travels, i.e. 1 january is number 1 and 31 of december is 365.
Example:
```python
days_represented([[10,17],[200,207]])
```
Returns 16 because there are two trips of 8 days, which add up to 16.
Happy coding and rank this kata if you wish ;-) | ["def days_represented(a):\n return len({i for x, y in a for i in range(x, y + 1)})", "def days_represented(trips):\n L=[]\n for i in trips:\n for j in range(i[0],i[1]+1):\n L.append(j)\n a=set(L)\n return len(a)", "def days_represented(trips):\n return len({i for (start, stop) in trips for i in range(start, stop + 1)})", "def days_represented(trips):\n arr = [0] * 365\n for a, b in trips:\n arr[a:b + 1] = [1] * (b - a + 1)\n return sum(arr)", "def days_represented(trips):\n total = 0\n visited = []\n for i in range(len(trips)):\n trip = trips[i]\n arrival = trip[1]\n departure = trip[0] \n for j in range(departure, arrival+1):\n if j not in visited:\n visited.append(j)\n else:\n continue\n return len(visited)", "def days_represented(trips):\n trips.sort()\n print(trips)\n previous_end = trips[0][1]\n days = previous_end - trips[0][0] + 1\n trips.pop(0)\n for trip in trips:\n start, end = trip\n if start > previous_end:\n days += end-start+1\n previous_end = end\n elif end > previous_end:\n days += end - previous_end\n previous_end = end\n return days", "def days_represented(trips):\n accumulator = set()\n for a,b in trips:\n accumulator |= set(range(a, b+1))\n return len(accumulator)", "def days_represented(trips):\n new = []\n for days in trips:\n for day in range(days[0],days[1] + 1):\n new.append(day)\n p = set(new)\n return len(p) \n \n", "from itertools import chain\n\ndef days_represented(trips):\n return len(set(chain(*(range(a,b+1) for a,b in trips))))", "from itertools import chain\n\ndef days_represented(trips):\n return len(set(chain(*(range(b, e+1) for b, e in trips))))"] | {"fn_name": "days_represented", "inputs": [[[[10, 15], [25, 35]]], [[[2, 8], [220, 229], [10, 16]]]], "outputs": [[17], [24]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,900 |
def days_represented(trips):
|
457b2b72b501b2e775c1293ef92bda0e | UNKNOWN | When a warrior wants to talk with another one about peace or war he uses a smartphone. In one distinct country warriors who spent all time in training kata not always have enough money. So if they call some number they want to know which operator serves this number.
Write a function which **accepts number and return name of operator or string "no info"**, if operator can't be defined. number always looks like 8yyyxxxxxxx, where yyy corresponds to operator.
Here is short list of operators:
* 039 xxx xx xx - Golden Telecom
* 050 xxx xx xx - MTS
* 063 xxx xx xx - Life:)
* 066 xxx xx xx - MTS
* 067 xxx xx xx - Kyivstar
* 068 xxx xx xx - Beeline
* 093 xxx xx xx - Life:)
* 095 xxx xx xx - MTS
* 096 xxx xx xx - Kyivstar
* 097 xxx xx xx - Kyivstar
* 098 xxx xx xx - Kyivstar
* 099 xxx xx xx - MTS Test [Just return "MTS"] | ["OPERATORS = {\n '039': 'Golden Telecom', '050': 'MTS', '063': 'Life:)', '066': 'MTS',\n '067': 'Kyivstar', '068': 'Beeline', '093': 'Life:)', '095': 'MTS',\n '096': 'Kyivstar', '097': 'Kyivstar', '098': 'Kyivstar', '099': 'MTS'}\n\n\ndef detect_operator(num):\n return OPERATORS.get(str(num)[1:4], 'no info')\n", "def detect_operator(num):\n operators = {\n \"039\": \"Golden Telecom\",\n \"050\": \"MTS\",\n \"063\": \"Life:)\",\n \"066\": \"MTS\",\n \"067\": \"Kyivstar\",\n \"068\": \"Beeline\",\n \"093\": \"Life:)\",\n \"095\": \"MTS\",\n \"096\": \"Kyivstar\",\n \"097\": \"Kyivstar\",\n \"098\": \"Kyivstar\",\n \"099\": \"MTS\"\n }\n return operators.get(str(num)[1:4],\"no info\")", "OPERATORS = {\n '039': 'Goldem Telecom',\n '050': 'MTS',\n '063': 'Life:)',\n '066': 'MTS',\n '067': 'Kyivstar',\n '068': 'Beeline',\n '093': 'Life:)',\n '095': 'MTS',\n '096': 'Kyivstar',\n '097': 'Kyivstar',\n '098': 'Kyivstar',\n '099': 'MTS'\n}\n\n\ndef detect_operator(num):\n try:\n code = str(num)[1:4]\n return OPERATORS[code]\n except KeyError:\n return 'no info'\n", "OPERATORS = {\n '039': 'Goldem Telecom', '050': 'MTS', '063': 'Life:)', '066': 'MTS',\n '067': 'Kyivstar', '068': 'Beeline', '093': 'Life:)', '095': 'MTS',\n '096': 'Kyivstar', '097': 'Kyivstar', '098': 'Kyivstar', '099': 'MTS'}\n\n\ndef detect_operator(num):\n return OPERATORS.get(str(num)[1:4], 'no info')\n", "import re\ndef detect_operator(num):\n d = {r\"0(66|50|9[59])\": \"MTS\",\n r\"0[69]3\": \"Life:)\",\n r\"0(9[6-8]|67)\": \"Kyivstar\",\n r\"068\": \"Beeline\",\n r\"039\": \"Golden Telecom\"\n }\n for temp in d:\n if re.fullmatch(temp, num[1:4]):\n return d[temp]\n return \"no info\"", "def detect_operator(num):\n d = {'Golden Telecom': ['039'], 'MTS': ['050', '066', '095', '099'], 'Life:)': ['063', '093'], \n 'Kyivstar': ['067', '096', '097', '098'], 'Beeline': ['068'] }\n return next((k for k in d if num[1: 4] in d[k]), 'no info')", "info = {\n'039': 'Golden Telecom',\n'050': 'MTS',\n'063': 'Life:)',\n'066': 'MTS',\n'067': 'Kyivstar',\n'068': 'Beeline',\n'093': 'Life:)',\n'095': 'MTS',\n'096': 'Kyivstar',\n'097': 'Kyivstar',\n'098': 'Kyivstar',\n'099': 'MTS'\n}\n\ndef detect_operator(num):\n return info.get(str(num)[1:4], 'no info')", "operators = {\n \"039\": \"Goldem Telecom\",\n \"050\": \"MTS\",\n \"063\": \"Life:)\",\n \"066\": \"MTS\",\n \"067\": \"Kyivstar\",\n \"068\": \"Beeline\",\n \"093\": \"Life:)\",\n \"095\": \"MTS\",\n \"096\": \"Kyivstar\",\n \"097\": \"Kyivstar\",\n \"098\": \"Kyivstar\",\n \"099\": \"MTS\"\n}\n\ndef detect_operator(num):\n return operators.get(str(num)[1:4], 'no info')", "r = dict(__import__(\"re\").findall(r\"(\\d{3}).*-\\s(.+)\",\n \"\"\"\n 039 xxx xx xx - Golden Telecom\n 050 xxx xx xx - MTS\n 063 xxx xx xx - Life:)\n 066 xxx xx xx - MTS\n 067 xxx xx xx - Kyivstar\n 068 xxx xx xx - Beeline\n 093 xxx xx xx - Life:)\n 095 xxx xx xx - MTS\n 096 xxx xx xx - Kyivstar\n 097 xxx xx xx - Kyivstar\n 098 xxx xx xx - Kyivstar\n 099 xxx xx xx - MTS\n \"\"\"))\ndetect_operator = lambda s: r.get(s[1:4], \"no info\")", "\nimport re\ndef detect_operator(num):\n s = ''' \n 039 xxx xx xx - Golden Telecom\n 050 xxx xx xx - MTS\n 063 xxx xx xx - Life:)\n 066 xxx xx xx - MTS\n 067 xxx xx xx - Kyivstar\n 068 xxx xx xx - Beeline\n 093 xxx xx xx - Life:)\n 095 xxx xx xx - MTS\n 096 xxx xx xx - Kyivstar\n 097 xxx xx xx - Kyivstar\n 098 xxx xx xx - Kyivstar\n 099 xxx xx xx - MTS Test [Just return \"MTS\"]\n'''\n rs = re.findall('0(\\d\\d).+ - (.*)\\n',s)\n rm = re.findall('80(\\d\\d)\\d{7}',num)\n for i in rs:\n if rm[0] in i:\n if 'Test' in i[1]:\n return 'MTS'\n return i[1]\n return 'no info'\n"] | {"fn_name": "detect_operator", "inputs": [["80661111841"], ["80671991111"], ["80631551111"], ["80931551111"], ["80111551111"]], "outputs": [["MTS"], ["Kyivstar"], ["Life:)"], ["Life:)"], ["no info"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,135 |
def detect_operator(num):
|
1bac18b89ab9579abf41c60888c5da4e | UNKNOWN | # Task
Given a position of a knight on the standard chessboard, find the number of different moves the knight can perform.
The knight can move to a square that is two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from it. The complete move therefore looks like the letter L. Check out the image below to see all valid moves for a knight piece that is placed on one of the central squares.

# Example
For `cell = "a1"`, the output should be `2`.

For `cell = "c2"`, the output should be `6`.

# Input/Output
- `[input]` string `cell`
String consisting of letter+number - coordinates of the knight on an 8 × 8 chessboard in chess notation.
- `[output]` an integer | ["def chess_knight(cell):\n x, y = (ord(c) - ord(origin) for c, origin in zip(cell, 'a1'))\n return sum(0 <= x + dx < 8 and 0 <= y + dy < 8 for dx, dy in (\n (-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)))", "moves = {(-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2)}\ndef chess_knight(cell):\n x, y = ord(cell[0]) - ord('a') + 1, int(cell[1])\n return sum(0 < x + mx < 9 and 0 < y + my < 9 for mx, my in moves)", "def chess_knight(cell):\n x,y = ord(cell[0])-96,int(cell[1])\n return sum([1 for dx in [-2,-1,1,2] for dy in [-2,-1,1,2] if all([abs(dx/dy)!=1, 0<x+dx<9, 0<y+dy<9])])", "result = (2, 3, 4, 3, 4, 6, 4, 6, 8)\n\ndef chess_knight(cell):\n x, y = ord(cell[0])-97, int(cell[1])-1\n x, y = min(2, x, 7-x), min(2, y, 7-y)\n return result[3*x + y]", "def chess_knight(cell):\n file = cell[0]\n rank = cell[1]\n if cell in ['a1', 'a8', 'h1', 'h8']: \n return 2\n if cell in ['a2', 'a7', 'b1', 'b8', 'g1', 'g8', 'h2', 'h7']: \n return 3\n if 'c' <= file <= 'f':\n if '3' <= rank <= '6':\n return 8\n if file in ['b', 'g'] and '3' <= rank <= '6':\n return 6\n if rank in ['2', '7'] and 'c' <= file <= 'f':\n return 6\n return 4\n", "def chess_knight(k):\n x,y=ord(k[0])-ord('a'),ord(k[1])-ord('1') \n moves=0\n if x-2 in range(8) and y-1 in range(8): moves+=1\n if x-2 in range(8) and y+1 in range(8): moves+=1\n if x-1 in range(8) and y-2 in range(8): moves+=1\n if x-1 in range(8) and y+2 in range(8): moves+=1\n if x+1 in range(8) and y-2 in range(8): moves+=1\n if x+1 in range(8) and y+2 in range(8): moves+=1\n if x+2 in range(8) and y-1 in range(8): moves+=1\n if x+2 in range(8) and y+1 in range(8): moves+=1\n return moves", "from string import ascii_lowercase\n\n_MOVES = [complex(a * c, b * d) for a, b in ((1, 2), (2, 1)) for c in (1, -1) for d in (1, -1)]\n_BOARD = [complex(a, b) for a in range(1, 9) for b in range(1, 9)]\n\ndef chess_knight(cell):\n file, rank = cell\n start = complex(ascii_lowercase.index(file) + 1, int(rank))\n return sum(start + move in _BOARD for move in _MOVES)\n", "def chess_knight(cell):\n col, row = cell\n col, row = ord(col) - 97, int(row) - 1\n return sum(abs(y-row)**2 + abs(x-col)**2 == 5 for y in range(8) for x in range(8))", "def chess_knight(pos):\n i, j = int(8-int(pos[1])),\"abcdefgh\".index(pos[0])\n A,B,C,D,E,F,G,H=i>0,i<7,j-2>=0,j+2<8,i+2<8,i-2>=0,j>0,j<7\n return sum([A and D,A and C,B and C,B and D,F and H,F and G,E and H,E and G])", "def chess_knight(cell):\n return sum( 1 <= ord(cell[0])-96+d1 <= 8 and 1 <= int(cell[1])+d2 <= 8 for h in [2,-2] for w in [1,-1] for d1,d2 in [(h,w), (w,h)] )"] | {"fn_name": "chess_knight", "inputs": [["a1"], ["c2"], ["d4"], ["g6"]], "outputs": [[2], [6], [8], [6]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,777 |
def chess_knight(cell):
|
ea40d0d6c22563cd617aff19301e218d | UNKNOWN | # Fourier transformations are hard. Fouriest transformations are harder.
This Kata is based on the SMBC Comic on fourier transformations.
A fourier transformation on a number is one that converts the number to a base in which it has more `4`s ( `10` in base `6` is `14`, which has `1` four as opposed to none, hence, fourier in base `6` ).
A number's fouriest transformation converts it to the base in which it has the most `4`s.
For example: `35353` is the fouriest in base `6`: `431401`.
This kata requires you to create a method `fouriest` that takes a number and makes it the fouriest, telling us in which base this happened, as follows:
```python
fouriest(number) -> "{number} is the fouriest ({fouriest_representation}) in base {base}"
```
## Important notes
* For this kata we don't care about digits greater than `9` ( only `0` to `9` ), so we will represent all digits greater than `9` as `'x'`: `10` in base `11` is `'x'`, `119` in base `20` is `'5x'`, `118` in base `20` is also `'5x'`
* When a number has several fouriest representations, we want the one with the LOWEST base
```if:haskell,javascript
* Numbers below `9` will not be tested
```
```if:javascript
* A `BigNumber` library has been provided; documentation is [here](https://mikemcl.github.io/bignumber.js/)
```
## Examples
```python
"30 is the fouriest (42) in base 7"
"15 is the fouriest (14) in base 11"
``` | ["def transform(num, base):\n digits = []\n \n while num > 0:\n num, remainder = divmod(num, base)\n digits.append( remainder if remainder < 10 else \"x\" )\n \n return digits\n\n\ndef fouriest(i):\n max_fours, base, best = 0, 5, [None, None]\n \n while i >= base**(max_fours):\n digits = transform(i, base)\n \n if digits.count(4) > max_fours:\n max_fours = digits.count(4)\n best = base, \"\".join(map(str, digits[::-1]))\n \n base += 1\n \n base, transformed = best\n return \"%s is the fouriest (%s) in base %s\" % (i, transformed, base)", "def change_base(n, b):\n result = ''\n while n > 0:\n rem = n % b if n % b <=9 else 'x'\n result = str(rem) + result\n n //= b\n return result\n\ndef fouriest(n):\n bb, br = None, 0\n for i in range(2, n):\n res = list(change_base(n, i))\n nf = res.count('4') \n if br >= len(res):\n break\n elif nf > br:\n br, bb = nf, i\n \n return f\"{n} is the fouriest ({change_base(n, bb)}) in base {bb}\"", "def fouriest(i):\n b=4\n m=0\n l=i\n B=b\n while m<l:\n b+=1\n f,x,l=base(i,b)\n if f>m:\n m=f\n N=x;B=b\n return \"%d is the fouriest (%s) in base %d\"%(i,N,B)\n \ndef base(n,b):\n f=0\n s=''\n while n:\n x=n%b\n s=(str(x)if x<10 else 'x')+s\n n//=b\n return s.count('4'),s,len(s)", "import re\ndef dec_to_base(num,base):\n res=''\n while num>0:\n dig = int(num%base)\n if dig<10:\n rem = num%base\n else:\n rem = 'x'\n \n res = str(rem) + res\n num //= base\n\n return res\n\ndef fouriest(i):\n \n lst, lst2 = [],[]\n for j in range(2,500):\n n = str(dec_to_base(i,j))\n lst.append(n)\n lst2.append(n.count('4'))\n \n ind = lst2.index(max(lst2))+2\n \n return f'{i} is the fouriest ({lst[ind-2]}) in base {ind}'", "import re\ndef dec_to_base(num,base): #Maximum base - 36\n base_num = \"\"\n while num>0:\n dig = int(num%base)\n if dig<10:\n base_num += str(dig)\n else:\n base_num += chr(ord('A')+dig-10) #Using uppercase letters\n num //= base\n base_num = base_num[::-1] #To reverse the string\n return base_num\n\ndef fouriest(i):\n \n if i == 1000000243: return '1000000243 is the fouriest (24x44) in base 149'\n if i == 2679388715912901287113185885289513476: return '2679388715912901287113185885289513476 is the fouriest (444444444444444444) in base 128'\n if i == 640614569414659959863091616350016384446719891887887380: return '640614569414659959863091616350016384446719891887887380 is the fouriest (44444444444444444444444444444444) in base 52'\n if i == 2579111107964987025047536361483312385374008248282655401675211033926782006920415224913494809688581314878892733564: return '2579111107964987025047536361483312385374008248282655401675211033926782006920415224913494809688581314878892733564 is the fouriest (4444444444444444444444444444444444444444444444) in base 290'\n \n lst = []\n for j in range(2,37):\n lst.append(str(dec_to_base(i,j)))\n \n lst2 = []\n for j in lst:\n lst2.append(j.count('4'))\n \n ind = lst2.index(max(lst2))+2\n \n lst = [re.sub(r'[A-Z]','x',j) for j in lst]\n \n return f'{i} is the fouriest ({lst[ind-2]}) in base {ind}'", "def trans_base(n,b):\n r=''\n while(n>0):\n d=n%b\n r+=str(d) if d<10 else 'x'\n n//=b\n return r[::-1]\n\ndef fouriest(i):\n m=[0,None,None]\n for b in range(2,300):\n s=trans_base(i,b)\n if len(s)<m[0]:\n break\n c=s.count('4')\n if c>m[0]:\n m=[c,s,b]\n return '{} is the fouriest ({}) in base {}'.format(i,m[1],m[2])", "def to_base(x,b):\n r = ''\n while x:\n x,d = divmod(x,b)\n r = f\"{d if d<10 else 'x'}\" + r\n return r\n\ndef fouriest(i):\n best, base = 0, 1\n for b in range(2,i):\n x = to_base(i,b)\n if x.count('4')>best:\n best, base = x.count('4'),b\n if b**best>=i:\n break\n return f\"{i} is the fouriest ({to_base(i,base)}) in base {base}\"\n", "def count_fours(n, base):\n fours = 0\n while n > 0:\n if n % base == 4:\n fours += 1\n n //= base\n return fours\n\ndef int_to_str_in_base(n, base):\n result = \"\"\n while n > 0:\n result = str(n % base) + result if n % base < 10 else \"x\" + result\n n //= base\n return result\n\ndef fouriest(i):\n highscore = 0\n winner = 5\n for base in range(5, i-3, 1):\n fours = count_fours(i, base)\n if fours > highscore:\n highscore = fours\n winner = base\n elif 4*base**(highscore) > i:\n break\n result = int_to_str_in_base(i, winner)\n return \"{} is the fouriest ({}) in base {}\".format(i, result, winner)", "def fouriest(i):\n highscore = 0\n winner = 5\n for base in range(5, i-3, 1):\n fours = 0\n n = i\n while n > 0:\n if n % base == 4:\n fours += 1\n n //= base\n if fours > highscore:\n highscore = fours\n winner = base\n elif 4*base**(highscore) > i:\n break\n n = i\n result = \"\"\n while n > 0:\n result = str(n % winner) + result if n % winner < 10 else \"x\" + result\n n //= winner\n return \"{} is the fouriest ({}) in base {}\".format(i, result, winner)", "def fouriest(numb):\n ans = \"\"\n temp = 0\n baz=0\n for i in range(5, 300):\n converted_string, modstring = \"\", \"\"\n currentnum = numb\n base = i\n while currentnum:\n mod = currentnum % base\n currentnum = currentnum // base\n converted_string = chr(48 + mod + 7*(mod > 10)) + converted_string\n if str(converted_string).count(\"4\") > temp:\n temp = str(converted_string).count(\"4\")\n ans = str(converted_string)\n baz = i\n ans = \"\".join([i if i.isdigit() else \"x\" for i in str(ans)])\n return \"{} is the fouriest ({}) in base {}\".format(numb, ans, baz)"] | {"fn_name": "fouriest", "inputs": [[30], [15], [9999], [35353], [100], [1000000243], [142042158218941532125212890], [2679388715912901287113185885289513476], [640614569414659959863091616350016384446719891887887380], [2579111107964987025047536361483312385374008248282655401675211033926782006920415224913494809688581314878892733564]], "outputs": [["30 is the fouriest (42) in base 7"], ["15 is the fouriest (14) in base 11"], ["9999 is the fouriest (304444) in base 5"], ["35353 is the fouriest (431401) in base 6"], ["100 is the fouriest (244) in base 6"], ["1000000243 is the fouriest (24x44) in base 149"], ["142042158218941532125212890 is the fouriest (14340031300334233041101030243023303030) in base 5"], ["2679388715912901287113185885289513476 is the fouriest (444444444444444444) in base 128"], ["640614569414659959863091616350016384446719891887887380 is the fouriest (44444444444444444444444444444444) in base 52"], ["2579111107964987025047536361483312385374008248282655401675211033926782006920415224913494809688581314878892733564 is the fouriest (4444444444444444444444444444444444444444444444) in base 290"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 6,436 |
def fouriest(i):
|
597a074d3864be5d1d4ff2419ae0b54d | UNKNOWN | Complete the function that takes an array of words.
You must concatenate the `n`th letter from each word to construct a new word which should be returned as a string, where `n` is the position of the word in the list.
For example:
```
["yoda", "best", "has"] --> "yes"
^ ^ ^
n=0 n=1 n=2
```
**Note:** Test cases contain valid input only - i.e. a string array or an empty array; and each word will have enough letters. | ["def nth_char(words):\n return ''.join(w[i] for i,w in enumerate(words))\n", "def nth_char(words):\n return \"\".join( word[i] for i,word in enumerate(words))\n", "def nth_char(words):\n result = \"\"\n\n for index, word in enumerate(words):\n result += word[index]\n\n return result\n", "def nth_char(words):\n return ''.join(words[i][i] for i in range(len(words)))\n", "def nth_char(words):\n return ''.join(words[n][n] for n in range(len(words)))\n", "def nth_char(w):\n return ''.join(w[i][i] for i in range(len(w)))\n", "def nth_char(words):\n return ''.join(v[i] for i,v in enumerate(words))\n", "nth_char=lambda l:''.join(e[i]for i,e in enumerate(l))", "def nth_char(words):\n return ''.join(k[i] for i,k in enumerate(words))\n", "nth_char = lambda w:''.join(x[i] for i,x in enumerate(w))\n"] | {"fn_name": "nth_char", "inputs": [[["yoda", "best", "has"]], [[]], [["X-ray"]], [["No", "No"]], [["Chad", "Morocco", "India", "Algeria", "Botswana", "Bahamas", "Ecuador", "Micronesia"]]], "outputs": [["yes"], [""], ["X"], ["No"], ["Codewars"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 837 |
def nth_char(words):
|
f6de22babeca524e42bff861d0a3d9b9 | UNKNOWN | Given a string S.
You have to return another string such that even-indexed and odd-indexed characters of S are grouped and groups are space-separated (see sample below)
Note:
0 is considered to be an even index.
All input strings are valid with no spaces
input:
'CodeWars'
output
'CdWr oeas'
S[0] = 'C'
S[1] = 'o'
S[2] = 'd'
S[3] = 'e'
S[4] = 'W'
S[5] = 'a'
S[6] = 'r'
S[7] = 's'
Even indices 0, 2, 4, 6, so we have 'CdWr' as the first group
odd ones are 1, 3, 5, 7, so the second group is 'oeas'
And the final string to return is 'Cdwr oeas'
Enjoy. | ["def sort_my_string(s):\n return '{} {}'.format(s[::2], s[1::2])", "def sort_my_string(s):\n return s[::2] + ' ' + s[1::2]", "def sort_my_string(S):\n return (S[0::2] + \" \" + S[1::2])", "def sort_my_string(S):\n return str(S[0::2] + ' ' + S[1::2])", "def sort_my_string(s):\n return f'{s[::2]} {s[1::2]}'", "def sort_my_string(s):\n odd, even = [], []\n for i, char in enumerate(s):\n even.append(char) if i % 2 == 0 else odd.append(char)\n return \"\".join(even) + \" \" + \"\".join(odd)", "def sort_my_string(s):\n l = list(s)\n return \"\".join(l[::2]+[\" \"]+l[1::2])", "def sort_my_string(str):\n \n evenChar = str[::2]\n oddChar = str[1::2]\n\n return evenChar + ' ' + oddChar\n\n#end function sort_my_string\n", "def sort_my_string(s):\n return '%s %s' % (s[::2], s[1::2])", "sort_my_string=lambda w:w[::2]+' '+w[1::2]"] | {"fn_name": "sort_my_string", "inputs": [["Wolfeschlegelsteinhausenbergerdorff"], ["METHIONYLTHREONYLTHREONYGLUTAMINYLARGINYL"], ["PNEUMONOULTRAMICROSCOPICSILICOVOLCANOCONIOSIS"], ["PSEUDOPSEUDOHYPOPARATHYROIDISM"], ["FLOCCINAUCINIHILIPILIFICATION"], ["SUBDERMATOGLYPHIC"]], "outputs": [["Wleclgltihuebredrf ofsheesenasnegrof"], ["MTINLHENLHENGUAIYAGNL EHOYTROYTROYLTMNLRIY"], ["PEMNUTAIRSOISLCVLAOOISS NUOOLRMCOCPCIIOOCNCNOI"], ["PEDPEDHPPRTYODS SUOSUOYOAAHRIIM"], ["FOCNUIIIIIIIAIN LCIACNHLPLFCTO"], ["SBEMTGYHC UDRAOLPI"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 883 |
def sort_my_string(s):
|
1da9e40545122d4a273ac1bdde4b7473 | UNKNOWN | # Task
John won the championship of a TV show. He can get some bonuses.
He needs to play a game to determine the amount of his bonus.
Here are `n` rows and `m` columns of cards were placed on the ground. A non-negative number is written on each card.
The rules of the game are:
- Player starts from the top-left coner, walk to the bottom-right coner.
- Players can only walk downward or right.
- The sum of the numbers collected by the players will be used as the bonus.
John has two chances to play this game on a game map. Specifically, when John finishes the game, the card on his path will be removed, and then he can walk again.
Your task is to help John calculate the maximum amount of bonuses he can get.
# Input
- `gameMap/gamemap`: A `n` x `m` integer array. Each element represents the number on the card.
- `4 <= n,m <= 40(Pyhon)/100(JS)`
- All inputs are valid.
# Output
An integer. the maximum amount of bonuses John can get.
# Eaxmple
For
```
gameMap=
[
[1, 3, 9],
[2, 8, 5],
[5, 7, 4]
]
```
The output should be `39`.
One of the possible solution is:
```
1st game:
[
[>, >, v],
[2, 8, v],
[5, 7, v]
]
1+3+9+5+4=22
2nd game:
[
[v, 0, 0],
[>, v, 0],
[5, >, >]
]
0+2+8+7+0=17
Final bonus = 22 + 17 = 39
``` | ["def calc(gamemap):\n nr, nc = len(gamemap), len(gamemap[0])\n def _i(ra, rb):\n return ra*nr + rb\n vs, ws = [0] * nr**2, [0] * nr**2\n for s in range(nr + nc - 1):\n for ra in range(max(0, s - nc + 1), min(s + 1, nr)):\n for rb in range(ra, min(s + 1, nr)):\n ws[_i(ra, rb)] = (\n gamemap[ra][s - ra] +\n (gamemap[rb][s - rb] if ra != rb else 0) +\n max(vs[_i(ra - da, rb - db)]\n for da in (0, 1) if da <= ra\n for db in (0, 1) if db <= rb))\n vs, ws = ws, vs\n return vs[-1]", "def calc(gamemap):\n nr, nc = len(gamemap), len(gamemap[0])\n def _i(ra, rb):\n return ra*nr + rb\n vs, ws = [0] * nr**2, [0] * nr**2\n for s in range(nr + nc - 1):\n for ra in range(max(0, s - nc + 1), min(s + 1, nr)):\n for rb in range(ra, min(s + 1, nr)):\n ws[_i(ra, rb)] = (\n gamemap[ra][s - ra] +\n (gamemap[rb][s - rb] if ra != rb else 0) +\n max(vs[_i(ra - da, rb - db)]\n for da in (0, 1) if da <= ra\n for db in (0, 1) if db <= rb))\n vs, ws = ws, vs\n return vs[-1]\n \"\"\"SUPER_MAN\"\"\"", "from itertools import product\nfrom functools import lru_cache\n\n\ndef calc(gamemap):\n @lru_cache(None)\n def calc0(p1, p2):\n (y1, x1), (y2, x2) = p1, p2\n cost = gamemap[y1][x1] \n if p1 != p2:\n cost += gamemap[y2][x2]\n res = 0\n for (dy1, dx1), (dy2, dx2) in moves:\n p1 = (y1 + dy1, x1 + dx1)\n if p1 not in playground:\n continue\n p2 = (y2 + dy2, x2 + dx2)\n if p2 not in playground:\n continue\n r = calc0(p1, p2) if p1 < p2 else calc0(p2, p1)\n if r > res:\n res = r\n return cost + res\n \n playground = set(product(range(len(gamemap)), range(len(gamemap[0]))))\n moves = list(product(((0, 1), (1, 0)), repeat=2))\n return calc0((0,0), (0,0))", "from itertools import combinations\n\n\ndef calc(gamemap):\n x_max, y_max = len(gamemap)-1, len(gamemap[0])-1\n last_step = x_max + y_max - 1\n best_paths = {((0, 1), (1, 0)): gamemap[0][0] + gamemap[0][1] + gamemap[1][0] + gamemap[-2][-1] + gamemap[-1][-2] + gamemap[-1][-1]}\n for step in range(2, last_step):\n new_best_paths, x_lower_limit, x_upper_limit = {}, max(0, step-y_max), min(step, x_max)\n for x1, x2 in combinations(range(x_lower_limit, x_upper_limit+1), 2):\n y1, y2 = step-x1, step-x2\n # find potential previous steps\n previous_steps = set(((_x1, _y1), (_x2, _y2)) for _x1, _y1 in ((x1-1, y1), (x1, y1-1)) for _x2, _y2 in ((x2-1, y2), (x2, y2-1)))\n best_path_value = max([best_paths[points] for points in previous_steps if points in best_paths])\n # evaluate current path best value\n new_best_paths[((x1, y1), (x2, y2))] = gamemap[x1][y1] + gamemap[x2][y2] + best_path_value\n best_paths = new_best_paths\n return max(best_paths.values())", "from itertools import combinations\n\n\ndef calc(gamemap):\n x_max, y_max = len(gamemap)-1, len(gamemap[0])-1\n last_step = x_max + y_max - 1\n dynamic_table = {((0, 1), (1, 0)): gamemap[0][0] + gamemap[0][1] + gamemap[1][0] + gamemap[-2][-1] + gamemap[-1][-2] + gamemap[-1][-1]}\n for step in range(2, last_step):\n _dynamic_table = {}\n x_lower_limit = max(0, step-y_max)\n x_upper_limit = min(step+1, x_max+1)\n for x1, x2 in combinations(range(x_lower_limit, x_upper_limit), 2):\n y1, y2 = step-x1, step-x2\n # store potential previous steps\n previous_steps = set()\n d1 = []\n if x1:\n d1.append((-1, 0))\n if y1:\n d1.append((0, -1))\n d2 = []\n if x2:\n d2.append((-1, 0))\n if y2:\n d2.append((0, -1))\n for _dx1, _dy1 in d1:\n for _dx2, _dy2 in d2:\n _x1, _y1 = x1 + _dx1, y1 + _dy1\n _x2, _y2 = x2 + _dx2, y2 + _dy2\n if _x1 != _x2:\n previous_steps.add(((_x1, _y1), (_x2, _y2)))\n best_path_value = max([dynamic_table[points] for points in previous_steps])\n # evaluate current path best value\n _dynamic_table[((x1, y1), (x2, y2))] = gamemap[x1][y1] + gamemap[x2][y2] + best_path_value\n dynamic_table = _dynamic_table\n return max(dynamic_table.values())", "def calc(gamemap):\n nr, nc = len(gamemap), len(gamemap[0])\n vs, ws = [0] * nr**2, [0] * nr**2\n vs[0] = gamemap[0][0]\n for s in range(nr + nc - 2):\n for ra in range(min(s + 1, nr)):\n ca = s - ra\n for rb in range(ra, min(s + 1, nr)):\n cb = s - rb\n v = vs[ra*nr + rb]\n for da in (0, 1):\n ra_, ca_ = ra + da, ca + (1 - da)\n if ra_ < nr and ca_ < nc:\n for db in (0, 1):\n rb_, cb_ = rb + db, cb + (1 - db)\n if rb_ < nr and cb_ < nc:\n v_ = v + gamemap[ra_][ca_] + (gamemap[rb_][cb_] if ra_ != rb_ else 0)\n ws[ra_*nr + rb_] = max(ws[ra_*nr + rb_], v_)\n vs, ws = ws, vs\n return vs[-1]\n\n\n# # Unoptimized:\n# from collections import defaultdict, namedtuple\n\n# def calc(gamemap):\n# nr, nc = len(gamemap), len(gamemap[0])\n# vs = {(Point(0, 0), Point(0, 0)): gamemap[0][0]}\n# for _ in range(nr + nc - 2):\n# ws = defaultdict(int)\n# for (a, b), v in vs.items():\n# for a_ in a.next_points(nr, nc):\n# for b_ in b.next_points(nr, nc):\n# v_ = v + gamemap[a_.r][a_.c] + (gamemap[b_.r][b_.c] if a_ != b_ else 0)\n# ws[a_, b_] = max(ws[a_, b_], v_)\n# vs = ws\n# return vs[Point(nr-1, nc-1), Point(nr-1, nc-1)]\n\n# class Point(namedtuple('Point', 'r c')):\n# def next_points(self, nr, nc):\n# if self.c < nc - 1:\n# yield Point(self.r, self.c + 1)\n# if self.r < nr - 1:\n# yield Point(self.r + 1, self.c)\n", "from itertools import combinations\n\ndef calc(game_map):\n \"\"\" A state is denoted a NE-SW diagonal of :game_map: and two different cells contained in it. \n Its key is a triplet (diagonal, row_cell_1, row_cell_2), where holds the invariant\n diagonal == row_cell_1 + column_cell_1 == row_cell_2 + column_cell_2\n Its value is the sum of the points scored by respective paths from the top left to the cells.\n \"\"\"\n rows = len(game_map)\n cols = len(game_map[0])\n \n states = {\n (1, 0, 1): game_map[0][0] + game_map[0][1] + game_map[1][0]\n }\n \n state_keys = []\n for diagonal in range(2, rows + cols - 1):\n min_row = max(0, diagonal - cols + 1)\n max_row = min(rows - 1, diagonal)\n row_codes = range(min_row, max_row + 1)\n for (row_cell_1, row_cell_2) in combinations(row_codes, 2):\n state_keys.append((diagonal, row_cell_1, row_cell_2))\n\n for (diagonal, row_cell_1, row_cell_2) in state_keys: \n prev_values = []\n \n # Both paths downwards\n if row_cell_1 > 0:\n prev_values.append(states[(diagonal - 1, row_cell_1 - 1, row_cell_2 - 1)])\n \n # Cell 1 downwards and cell 2 rightwards\n if row_cell_1 > 0 and row_cell_2 < diagonal:\n prev_values.append(states[(diagonal - 1, row_cell_1 - 1, row_cell_2)])\n \n # Cell 1 rightwards and cell 2 downwards. Excluded the case\n # where both paths come from a common cell for efficiency.\n if row_cell_2 > row_cell_1 + 1:\n prev_values.append(states[(diagonal - 1, row_cell_1, row_cell_2 - 1)])\n \n # Both paths rightwards\n if row_cell_2 < diagonal:\n prev_values.append(states[(diagonal - 1, row_cell_1, row_cell_2)])\n \n prev_value = max(prev_values)\n col_cell_1 = diagonal - row_cell_1\n col_cell_2 = diagonal - row_cell_2\n new_value = prev_value + game_map[row_cell_1][col_cell_1] + game_map[row_cell_2][col_cell_2]\n states[(diagonal, row_cell_1, row_cell_2)] = new_value\n \n final_diagonal = (rows + cols - 3, rows - 2, rows - 1)\n return states[final_diagonal] + game_map[rows - 1][cols - 1]", "def calc(Q) :\n H,W,M,N,G = len(Q),~-len(Q[0]),[0] * len(Q) ** 2,[0] * len(Q) ** 2,lambda Q,S : M[H * Q + S]\n for S in range(1,~-H + W) :\n for V in range(max(0,S - W),min(-~S,H)) :\n for B in range(-~V,min(-~S,H)) :\n N[H * V + B] = Q[V][S - V] + Q[B][S - B] + max(G(V,B),G(~-V,B),G(V,~-B),G(~-V,~-B))\n M,N = N,M\n return Q[0][0] + Q[~-H][W] + G(~-~-H,~-H)", "def calc(mp):\n h=len(mp)\n w=len(mp[0])\n dp=[[[0 for j in range(h+1)]for i in range(h+1)]for k in range(h+w+1)]\n for s in range(1,h+w+1):\n for i1 in range(1,h+1):\n j1=s-i1+1\n if j1>0 and j1<=w:\n for i2 in range(1,h+1):\n j2=s-i2+1\n if j2>0 and j2<=w:\n dp[s][i1][i2]=max(dp[s-1][i1][i2-1],dp[s-1][i1-1][i2],dp[s-1][i1-1][i2-1],dp[s-1][i1][i2])+mp[i1-1][j1-1]+mp[i2-1][j2-1]\n if i1==i2: dp[s][i1][i2]-=mp[i1-1][j1-1]\n return dp[h+w-1][h][h]"] | {"fn_name": "calc", "inputs": [[[[1, 3, 9], [2, 8, 5], [5, 7, 4]]], [[[11, 72, 38], [80, 69, 65], [68, 96, 99]]], [[[1, 5, 1, 1], [1, 5, 5, 1], [5, 5, 5, 1], [1, 1, 5, 1]]], [[[0, 0, 2, 3, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 4, 0, 0], [0, 0, 0, 0, 4, 0, 0], [0, 0, 2, 0, 4, 0, 0], [0, 0, 0, 0, 0, 0, 0]]]], "outputs": [[39], [560], [40], [25]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 9,720 |
def calc(gamemap):
|
c644a46841187f36ae13a4488dcb5ea5 | UNKNOWN | Let's say take 2 strings, A and B, and define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings `abc` and `abd` is 2, while the similarity of strings `aaa` and `aaab` is 3.
write a function that calculates the sum of similarities of a string S with each of it's **suffixes**.
```python
string_suffix('ababaa') => returns 11
string_suffix('abc') => returns 3
```
Explanation:
In the first case, the suffixes of the string are `ababaa`, `babaa`, `abaa`, `baa`, `aa` and `a`. The similarities of each of these strings with the string `ababaa` are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.
For the second case, the answer is simply 3 + 0 + 0 = 3.
Note : Each string will have at least one character - no need to check for empty strings :) | ["from os.path import commonprefix\n\ndef string_suffix(s):\n return sum(len(commonprefix([s, s[i:]])) for i in range(len(s)))", "def similarity(strng1, strng2):\n result = 0\n for c1, c2 in zip(strng1, strng2):\n if c1 != c2:\n break\n result += 1\n return result\n\ndef string_suffix(strng):\n return sum(similarity(strng[i:], strng) for i in range(len(strng)))\n", "def string_suffix(s):\n length = len(s)\n counter = 0\n for i in range(length):\n for i,c in enumerate(s[i:]):\n if c == s[i]:\n counter += 1\n else: break\n return counter", "def string_suffix(s):\n total = len(s)\n suffixes = [s[y:] for y in range(len(s)) if s[y] == s[0]][1:]\n for suff in suffixes:\n for y,l in zip(s,suff):\n if l == y:\n total += 1\n else:\n break\n return total", "def string_suffix(s):\n sim = lambda s1, s2: ([c1 == c2 for c1, c2 in zip(s1, s2)]+[False]).index(False)\n return sum(sim(s, s[i:]) for i in range(len(s)))", "string_suffix=lambda s:sum(s[:j-i]==s[i:j] for j in range(1,len(s)+1) for i in range(j))", "def string_suffix(str_):\n return sum(next((c for c, (a, b) in enumerate(zip(str_, str_[d:])) if a != b), len(str_[d:])) for d in range(len(str_)))", "def string_suffix(str_): \n return sum(next((j for j,(a,b) in enumerate(zip(str_[i:],str_)) if a!=b),len(str_)-i) for i in range(len(str_)))"] | {"fn_name": "string_suffix", "inputs": [["aa"], ["abc"], ["ababaa"], ["aaaa"], ["aaaaa"], ["aaaaaa"], ["mnsomn"], ["apple"], ["a"], ["pippi"]], "outputs": [[3], [3], [11], [10], [15], [21], [8], [5], [1], [8]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,478 |
def string_suffix(s):
|
f964652cff2405ca0e8c5f1dde4e7edc | UNKNOWN | Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering.
Write a function which takes a list of strings and returns each line prepended by the correct number.
The numbering starts at 1. The format is `n: string`. Notice the colon and space in between.
**Examples:**
```python
number([]) # => []
number(["a", "b", "c"]) # => ["1: a", "2: b", "3: c"]
``` | ["def number(lines):\n return ['%d: %s' % v for v in enumerate(lines, 1)]", "def number(lines):\n return [f\"{n}: {ligne}\" for n, ligne in enumerate(lines, 1)]\n", "def number(lines):\n return ['{}: {}'.format(n, s) for (n, s) in enumerate(lines, 1)]", "def number(lines):\n return [f\"{counter}: {line}\" for counter, line in enumerate(lines, start=1)]", "def number(lines):\n return [\"{}: {}\".format(*line) for line in enumerate(lines, start=1)]", "def number(lines):\n return [str(x+1) + \": \" + lines[x] for x in range(len(lines))]\n", "def number(lines):\n #your code here\n a=[]\n for i,c in enumerate(lines,1):\n str_var = str(i) + ': ' + str(c) #make sure to add another space\n a.append(str_var)\n return a\n", "def number(lines):\n return [f\"{i}: {j}\" for i,j in enumerate(lines,1)] ", "from itertools import starmap\n\ndef number(lines):\n return list(starmap(\"{}: {}\".format, enumerate(lines,1)))", "def number(lines):\n x = 1\n for i in range(len(lines)):\n lines[i] = str(x) + \": \" + lines[i]\n x+=1\n return lines", "number=lambda l:list(f\"{i}: {e}\"for i,e in enumerate(l,1))", "def number(lines):\n #your code here\n i=1\n l=[]\n for item in lines:\n l.append((str(i)+\": \"+item)) \n i+=1 # for line counter\n return l", "def number(lines):\n cur_index = 0\n for l in lines:\n lines [cur_index] = \"{}: {}\".format (cur_index + 1, l)\n cur_index += 1\n return lines\n\n \n \n", "def number(lines):\n #your code here\n result = {}\n count = 1\n for i in lines:\n result[count] = i\n count +=1\n final = []\n for i in result:\n final.append(str(i)+\":\"+\" \"+result[i])\n \n return(final)\n", "def number(a):\n \n lineCount = 1\n lineList = []\n\n\n while a: #Scenario: While the list is not empy... \n lineList.append( str(lineCount) + ': ' + a.pop(0) )\n lineCount +=1\n\n return lineList\n#end function number\n", "def number(lines):\n ans = []\n for x in range(1, len(lines) + 1):\n ans.append(f'{x}: {lines[x - 1]}')\n return ans", "def number(lines):\n formatted=[]\n for x in range(len(lines)):\n formatted.append(str(x+1)+\": \"+lines[x])\n return formatted", "def number(lines):\n count,dictionary = 1,{}\n for element in lines:\n dictionary[count] = element\n count += 1\n return [(str(key) + \": \" + str(value)) for key,value in list(dictionary.items())]\n", "def number(lines):\n lines = [f\"{i}: {j}\" for i, j in enumerate(lines, start = 1)]\n return lines", "def number(lines):\n return [f\"{idx}: {x}\" for idx, x in enumerate(lines, 1)]", "def number(lines):\n return [f\"{n+1}: {l}\" for n,l in enumerate(lines)]", "def number(coder):\n return [ str(x+1) + \": \" + coder[x] for x in range(len(coder)) ]", "import itertools\n\ndef number(lines):\n counter=itertools.count(1)\n return [str( next(counter) ) + \": \" + x for x in lines]", "def number(lines):\n if len(lines) == 0:\n return []\n \n results = []\n for i, value in enumerate(lines, start=1):\n results.append(str(i) + \": \" + value)\n return results", "def number(lines):\n return [\"%i: %s\" % (i+1, x) for i, x in enumerate(lines)]", "def number(lines):\n n = 1\n n1 = []\n for i in lines:\n x = (str(n) + \": \" + i)\n n1.append(x)\n n = n + 1\n return n1\n", "def number(lines):\n return ['{}: {}'.format(*xs) for xs in enumerate(lines, 1)]", "def number(lines):\n return ['{}: {}'.format(i, x) for i, x in enumerate(lines, 1)]", "def number(lines):\n return [str(i+1) + ': ' + str(j) for i,j in enumerate(lines)]", "def number(lines):\n return list('%d: %s' % (n, s) for (n, s) in enumerate(lines, 1))", "number = lambda ___:[str(_+1)+': '+__ for _,__ in enumerate(___)]", "def number(arr):\n return ['%d: %s' % i for i in enumerate(arr, 1)]", "def number(lines):\n return [\"{0}: {1}\".format(x+1, lines[x]) for x in range(len(lines))]", "def number(lines):\n return ['{}: {}'.format(i, a) for i, a in enumerate(lines, 1)]\n", "def number(lines):\n return list(map(lambda x,y: str(y) + \": \" + x, lines, range(1, len(lines)+1)))", "from typing import List\n\ndef number(lines: List[str]) -> List[str]:\n \"\"\" Add a line number (starting at 1) to every element of the list. \"\"\"\n return list(map(lambda _it: \"{}: {}\".format(*_it), enumerate(lines, start=1)))", "def number(lines):\n return [str(i + 1) + ': ' + str(line) for i, line in enumerate(lines)]", "def number(lines):\n return [str(i+1)+\": \"+line for i, line in enumerate(lines)]", "def number(lines):\n\n out = [] \n for i in range(len(lines)):\n out.append('{}: {}'.format(i+1,lines[i]))\n \n return out", "def number(lines):\n s=[]\n [s.append(str(i+1)+': '+lines[i])for i in range(len(lines))]\n return s \n", "def number(lines):\n index = 0\n for line in lines:\n lines[index] = str(index+1) + \": \" + line\n index += 1\n return lines", "def number(lines):\n i=1\n res=[]\n for line in lines:\n res.append(f\"{i}: {line}\")\n i+=1\n return res", "def number(lines):\n #your code here\n #x=lines.split(\" \")\n x=lines\n y=[]\n z=0\n for i in range(len(lines)):\n z+=i\n y.append(str(i+1)+\":\"+\" \"+x[i])\n return y\n", "def number(lines):\n new_list = []\n index = 0\n new_el = 1\n while len(lines) != index:\n el = lines[index]\n sum_el = f\"{new_el}: {el}\"\n new_list.append(sum_el)\n index+=1\n new_el+=1\n return(new_list)", "def number(lines):\n sum=[]\n for i in range(len(lines)):\n a = str(i+1)+\": \"+lines[i]\n sum.append(a)\n return sum", "def number(lines):\n return [str(i+1) + ': ' + k for i,k in enumerate(lines)]", "def number(l): return [f\"{i+1}: {l[i]}\" for i in range(0,len(l))]", "def number(lines):\n for i in lines:\n lines[lines.index(i)] = '{0}: {1}'.format(lines.index(i) + 1, i)\n return lines", "def number(lines):\n keks = []\n for index, i in enumerate(lines):\n keks.append(str(index + 1) + \": \" + i)\n return keks", "def number(lines):\n ls = []\n for i, l in enumerate(lines):\n ls.append(str(i+1) + ': ' + l)\n return ls", "def number(lines):\n count = 1\n out = []\n for i in lines:\n out.append(str(count) + \": \" + i)\n count += 1\n return out", "def number(lines):\n return list(f'{no}: {line}'for no, line in enumerate(lines, 1))", "def number(lines):\n line_number = 1\n formatted = []\n for string in lines:\n formatted.append(str(line_number) + \": \" + string)\n line_number += 1\n return formatted", "def number(lines):\n count = 0\n temp_list = []\n\n for i in lines:\n count += 1\n temp_list.append(str(count) + \": \" + i)\n\n return temp_list", "def number(lines):\n return [str(x)+\": \"+str(y) for x,y in enumerate(lines,1)]", "def number(lines):\n output = []\n for i, v in enumerate(lines, 1):\n output.append(str(i) + ': ' + str(v))\n return output\n", "def number(lines):\n i = 0;\n \n if lines == []:\n return [];\n else:\n while i < len(lines):\n lines[i] = (str(i+1)+': '+lines[i]);\n i = i + 1;\n return (lines);", "def number(lines):\n return [f\"{str(x+1)}: {y}\" for x,y in enumerate(lines)]", "def number(lines):\n return [f\"{num}: {line}\" for num, line in zip([i for i in range(1,len(lines) + 1)],lines)]", "def number(lines):\n numlist = []\n numb = 1\n for x in lines:\n numlist.append(str(numb) + \": \" + x)\n numb+=1\n\n return numlist", "def number(lines):\n if len(lines) == 0:\n return []\n else:\n count = 1\n for x in lines:\n lines[count-1] = str(count) + \": \" + x\n count += 1\n return lines", "def number(lines):\n i = 1\n list_lines = []\n for x in lines:\n list_lines.append(f'{i}: {x}')\n i += 1\n return list_lines", "def number(lines):\n line_number = 1\n text_editor = []\n for line in lines:\n text_editor.append(f\"{line_number}: {line}\")\n line_number += 1\n return text_editor\n", "def number(lines):\n res = []\n for i, v in enumerate(lines, 1):\n item = \"{}: {}\".format(i, v)\n res.append(item)\n \n return res\n", "def number(lines):\n res = []\n for i in range(1, len(lines)+1):\n res.append(f'{i}: {lines[i-1]}')\n return res", "def number(lines):\n if not lines: return []\n return [f'{x}: {y}' for x,y in enumerate(lines, 1)]", "def number(lines):\n if lines == []:\n return []\n \n out = []\n num = 1\n for line in lines:\n res = str(num) + \": \" + line\n out.append(res)\n num += 1\n \n return out", "def number(lines):\n ans =[]\n if len(lines)>0:\n for i in range(len(lines)):\n ans.append(str(i+1)+': '+ lines[i])\n return ans\n else:\n return ans\n \n", "def number(lines):\n return [f\"{x[0]}: {x[1]}\" for x in enumerate(lines, 1)]", "def number(lines):\n return ['%s: %s' % (n, lines[n-1]) for n in range(1,len(lines)+1) ] if lines else lines\n\n \n\n\n\n\n\n\n", "def number(lines):\n new_lines=[]\n cadena = ''\n if lines != []:\n \n for i in range(len(lines)):\n cadena = str(i+1)+':'+' '+lines[i]\n new_lines.append(cadena)\n return new_lines\n else:\n return lines\n \n #your code here\n", "def number(lines):\n if lines != [] or None:\n for i in range(len(lines)):\n lines[i] = str(i+1) + \": \" + lines[i]\n return lines\n else:\n return []", "def number(lines):\n enum_array = list(enumerate(lines, 1))\n return [f'{i}: {letter}' for i, letter in enum_array]", "def number(lines):\n lines = [] if lines==[] else [(str(i+1)+\": \"+str(lines[i])) for i in range(len(lines))]\n return lines", "def number(lines):\n lis = []\n x = 1\n for i in lines:\n lis.append(str(str(x) + \": \" + i))\n x += 1\n return(lis)", "def number(lines):\n return [str(num)+': '+line for num,line in enumerate(lines, start=1)]", "def number(lines):\n \"\"\"Returns a list with each line prepended with the line number.\"\"\"\n return [f\"{n}: {string}\" for n, string in enumerate(lines, 1)]", "def number(lines):\n # If lines is empty, return empty\n if len(lines) == 0:\n return []\n \n # If not empty, return enumeration into string formatting\n return [\"{}: {}\".format(i + 1, item) for i, item in enumerate(lines)]", "def number(lines):\n out_lst = []\n line_num = 1\n for item in lines:\n out_lst.append(f'{line_num}: {item}')\n line_num += 1\n return out_lst", "def number(lines):\n if len(lines)>0:\n for i in range(0,len(lines)):\n lines[i] = f\"{i+1}: {lines[i]}\"\n return lines\n #your code here\n", "def number(lines):\n \n output = []\n char = 1\n \n for n in lines:\n output.append(str(char) + \": \" + n)\n char += 1\n \n return output\n \n", "def number(lines):\n x2 = 1\n new_list = []\n for x in lines:\n new_list.append(f\"{str(x2)}: {x}\")\n x2+=1\n return new_list", "def number(lines):\n new_lines= []\n for i, ele in enumerate(lines):\n new_lines.append(str(i+1) + \": \" + ele)\n return new_lines", "def number(lines):\n result = []\n for i,j in enumerate(lines):\n result.append(str(i+1)+\": \"+str(j))\n \n return result", "def number(arr):\n new_list = []\n for index, value in enumerate(arr):\n new_list.append(\"{}: {}\".format(index +1, value))\n return new_list", "def number(lines):\n res = []\n count = 0\n for item in lines:\n st = str(count + 1) + \": \" + item\n count += 1\n res.append(st)\n return res", "def number(lines):\n _=1\n for i in range (0, len(lines)):\n lines[i]=str(_)+\": \"+str(lines[i])\n _+=1\n \n return lines\n \n\n \n #your code here\n", "def number(lines):\n n = 0\n l = []\n for i in lines:\n n += 1\n l.append(str(n) +': '+ i)\n return l", "def number(lines):\n print(lines)\n if not lines:\n return lines\n lelist = []\n \n for c, value in enumerate(lines, 1):\n lelist.append(str(c) + \": \" + value)\n \n return lelist\n \n #your code here\n", "def number(lines):\n lines = [f\"{str(i+1)}: {lines[i]}\" for i in range(len(lines))]\n return lines", "def number(lines):\n new_lines = [\n \": \".join([str(i+1), line]) for i, line in enumerate(lines)\n ]\n \n return new_lines", "def number(lines):\n lt = []\n for i,j in enumerate(lines,1):\n lt.append(f\"{i}: {j}\") \n return lt", "def number(lines):\n\n for index, char in enumerate(lines):\n lines[index] = f\"{index + 1}: {char}\"\n \n return lines", "def number(l):\n return [f\"{idx+1}: {i}\" for idx, i in enumerate(l)]", "def number(lines):\n if not lines:\n return []\n else:\n return ['%s: %s'%(str(i),str(j)) for i,j in enumerate(lines,start=1)]", "def number(lines):\n for i in range(len(lines)):\n n=i+1\n n=str(n)\n s=str(lines[i])\n lines[i]= n +\":\" +\" \" + s\n n=int(n)\n return lines", "def number(lines):\n list = []\n for i, c in enumerate(lines, 1):\n value = str(i) + \": \" + str(c)\n list.append( value)\n return (list)\n \n \n \n #your code here\n", "def number(lines):\n r = []\n n = 1\n for s in lines:\n r.append(str(n) + ': '+ s)\n n +=1\n return r", "def number(lines):\n numbered_lst = []\n line_num = 1\n for line in lines:\n numbered_lst.append(str(line_num)+\": \"+line)\n line_num += 1\n return numbered_lst\n \n"] | {"fn_name": "number", "inputs": [[[]], [["a", "b", "c"]], [["", "", "", "", ""]], [["", "b", "", "", ""]]], "outputs": [[[]], [["1: a", "2: b", "3: c"]], [["1: ", "2: ", "3: ", "4: ", "5: "]], [["1: ", "2: b", "3: ", "4: ", "5: "]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 14,378 |
def number(lines):
|
7677c111d193ddfe0a64f3167fb17880 | UNKNOWN | # Explanation
It's your first day in the robot factory and your supervisor thinks that you should start with an easy task. So you are responsible for purchasing raw materials needed to produce the robots.
A complete robot weights `50` kilogram. Iron is the only material needed to create a robot. All iron is inserted in the first machine; the output of this machine is the input for the next one, and so on. The whole process is sequential. Unfortunately not all machines are first class, so a given percentage of their inputs are destroyed during processing.
# Task
You need to figure out how many kilograms of iron you need to buy to build the requested number of robots.
# Example
Three machines are used to create a robot. Each of them produces `10%` scrap. Your target is to deliver `90` robots.
The method will be called with the following parameters:
```
CalculateScrap(scrapOfTheUsedMachines, numberOfRobotsToProduce)
CalculateScrap(int[] { 10, 10, 10 }, 90)
```
# Assumptions
* The scrap is less than `100%`.
* The scrap is never negative.
* There is at least one machine in the manufacturing line.
* Except for scrap there is no material lost during manufacturing.
* The number of produced robots is always a positive number.
* You can only buy full kilograms of iron. | ["from math import ceil\n\ndef calculate_scrap(arr,n):\n x = 50\n for i in arr:\n x /= (1-i/100)\n return ceil(n*x)", "from functools import reduce\nfrom operator import mul\nfrom math import ceil\n\ndef calculate_scrap(scraps, number_of_robots):\n return ceil(50 * number_of_robots * 100**len(scraps) / reduce(mul, (100-x for x in scraps)))", "from fractions import Fraction\nfrom functools import reduce\nfrom math import ceil\nfrom operator import mul\n\ndef calculate_scrap(scraps, n):\n return ceil(n * 50 * reduce(mul, (Fraction(100, 100-scrap) for scrap in scraps)))", "def calculate_scrap(scraps, number_of_robots):\n \n iron=50*number_of_robots\n \n for x in range(len(scraps)):\n iron=iron/(1-scraps[x]/100)\n return round(iron+0.5)", "from fractions import Fraction as F\nfrom math import ceil\n\n\ndef calculate_scrap(scraps, number_of_robots):\n cost = 50\n for pct in scraps:\n factor = F(100, 100 - pct)\n cost *= factor\n return ceil(cost * number_of_robots)", "from math import ceil\ndef calculate_scrap(scraps, number_of_robots):\n if len(scraps) == 1:\n return ceil(50 * number_of_robots/((100-scraps[0])/100))\n else:\n divisor = 1\n for i in scraps:\n divisor *= (100-i)/100\n return ceil(50 * number_of_robots/(divisor))\n \n", "from functools import reduce\nfrom operator import mul\nfrom math import ceil\ndef calculate_scrap(scraps, number_of_robots):\n return ceil(number_of_robots*50/reduce(mul,[(100-s)/100 for s in scraps]))", "import math\ndef calculate_scrap(scraps, num):\n mat = num*50\n for x in scraps:\n mat = mat/(0.01*(100-x))\n return math.ceil(mat)\n", "from math import ceil\n\ndef calculate_scrap(scraps, number_of_robots):\n factor = 1\n for x in scraps:\n factor *= 1 - x / 100\n return ceil(50 / factor * number_of_robots)", "from functools import reduce\n\ndef calculate_scrap(scraps, number_of_robots):\n ans = reduce(lambda x, y: x / (100 - y) * 100, scraps, number_of_robots * 50)\n return int(ans) if ans.is_integer() else int(ans) + 1"] | {"fn_name": "calculate_scrap", "inputs": [[[10], 90], [[20, 10], 55], [[0], 90], [[0, 0, 0], 90], [[10, 0], 90], [[0, 10], 90], [[10, 0, 0, 10], 81], [[0, 10, 0, 10], 81], [[0, 10, 10, 0], 81], [[10, 20, 30, 40, 50, 60, 70, 80, 90], 25], [[90, 80, 70, 60, 50, 40, 30, 20, 10], 20], [[10, 0, 30, 0, 50, 0, 70, 0, 90], 25], [[22, 33, 44, 10, 0, 0, 0, 88, 12], 33], [[22, 33, 44, 10, 0, 0, 0, 88, 12, 10, 0, 30, 0, 50, 0, 70, 0, 90], 13], [[47, 69, 28, 20, 41, 71, 84, 56, 62, 3, 74, 35, 25, 4, 57, 73, 64, 35, 78, 51], 8], [[38, 38, 73, 9, 3, 47, 86, 67, 75, 52, 46, 86, 30, 37, 80, 48, 52, 0, 85, 72], 11], [[71, 82, 47, 72, 5, 75, 69, 30, 16, 43, 10, 11, 64, 53, 12, 78, 23, 7, 24, 85], 12], [[81, 31, 24, 55, 42, 10, 68, 28, 12, 38, 60, 62, 66, 96, 51, 54, 89, 1, 4, 27], 9]], "outputs": [[5000], [3820], [4500], [4500], [5000], [5000], [5000], [5000], [5000], [3444665], [2755732], [132276], [59323], [2472964], [2671381450], [29229344539], [1465387910], [4301282783]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,135 |
def calculate_scrap(scraps, number_of_robots):
|
c5d5b86fa7a763da8c3198061465a895 | UNKNOWN | ```if-not:rust
Your task is to write a function `toLeetSpeak` that converts a regular english sentence to Leetspeak.
```
```if:rust
Your task is to write a function `to_leet_speak` that converts a regular english sentence to Leetspeak.
```
More about LeetSpeak You can read at wiki -> https://en.wikipedia.org/wiki/Leet
Consider only uppercase letters (no lowercase letters, no numbers) and spaces.
For example:
```if-not:rust
~~~
toLeetSpeak("LEET") returns "1337"
~~~
```
```if:rust
~~~
to_leet_speak("LEET") returns "1337"
~~~
```
In this kata we use a simple LeetSpeak dialect. Use this alphabet:
```
{
A : '@',
B : '8',
C : '(',
D : 'D',
E : '3',
F : 'F',
G : '6',
H : '#',
I : '!',
J : 'J',
K : 'K',
L : '1',
M : 'M',
N : 'N',
O : '0',
P : 'P',
Q : 'Q',
R : 'R',
S : '$',
T : '7',
U : 'U',
V : 'V',
W : 'W',
X : 'X',
Y : 'Y',
Z : '2'
}
``` | ["def to_leet_speak(str):\n return str.translate(str.maketrans(\"ABCEGHILOSTZ\", \"@8(36#!10$72\"))", "def to_leet_speak(str):\n leet = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H': '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n}\n for key in leet:\n str = str.replace(key, leet[key])\n return str", "table = str.maketrans(\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n '@8(D3F6#!JK1MN0PQR$7UVWXY2'\n)\n\ndef to_leet_speak(text):\n return text.translate(table)\n", "def to_leet_speak(s):\n r = {\".\": \".\", \"!\": \"!\", \"?\": \"?\", \",\": \",\",\" \": \" \", \"A\":'@', \"B\":'8', \"C\":'(', \"D\":'D', \"E\":'3', \"F\":'F', \"G\":'6', \"H\":'#', \"I\":'!', \"J\":'J', \"K\":'K', \"L\":'1', \"M\":'M', \"N\":'N', \"O\":'0', \"P\":'P', \"Q\":'Q', \"R\":'R', \"S\":'$', \"T\":'7', \"U\":'U', \"V\":'V', \"W\":'W', \"X\":'X', \"Y\":'Y', \"Z\":'2'}\n return ''.join(r[c] for c in s)\n", "from string import ascii_uppercase\n\ntr = str.maketrans(ascii_uppercase, '@8(D3F6#!JK1MN0PQR$7UVWXY2')\n\ndef to_leet_speak(s):\n return s.translate(tr)\n", "def to_leet_speak(s):\n return s.translate(str.maketrans(\"ABCEGHILOSTZ\", \"@8(36#!10$72\"))", "LEET = {'A': '@', 'B': '8', 'C': '(', 'E': '3', 'G': '6', 'H': '#',\n 'I': '!', 'L': '1', 'O': '0', 'S': '$', 'T': '7', 'Z': '2'}\n\n\ndef to_leet_speak(s):\n return ''.join(LEET.get(a, a) for a in s)", "def to_leet_speak(str):\n leet = {'A': '@', 'B': '8', 'C': '(', 'E': '3', 'G': '6', 'H': '#', 'I': '!', 'L': '1', 'O': '0', 'S': '$', 'T': '7', 'Z': '2'}\n return \"\".join([leet[letter] if letter in leet.keys() else letter for letter in str])", "table = str.maketrans(\"ABCEGHILOSTZ\", \"@8(36#!10$72\")\n\ndef to_leet_speak(stg):\n return stg.translate(table)\n\n", "leet_dic = { 'A' : '@', 'B' : '8', 'C' : '(', 'D' : 'D', 'E' : '3', 'F' : 'F',\n 'G' : '6', 'H' : '#', 'I' : '!', 'J' : 'J', 'K' : 'K', 'L' : '1', 'M' : 'M',\n 'N' : 'N', 'O' : '0', 'P' : 'P', 'Q' : 'Q', 'R' : 'R', 'S' : '$', 'T' : '7',\n 'U' : 'U', 'V' : 'V', 'W' : 'W', 'X' : 'X', 'Y' : 'Y', 'Z' : '2' }\ndef to_leet_speak(str):\n return ''.join([leet_dic[c] if c.isalpha() else c for c in str ])\n", "def to_leet_speak(str):\n return str.translate(str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ', '@8(D3F6#!JK1MN0PQR$7UVWXY2'))", "def to_leet_speak(str):\n return str.replace('A', '@').replace('B', '8').replace('C', '(').replace('E', '3').replace('G', '6').replace('H', '#').replace('I', '!').replace('L', '1').replace('O', '0').replace('S', '$').replace('T', '7').replace('Z', '2')", "LEET_ALPHABET = '@8(D3F6#!JK1MN0PQR$7UVWXY2'\n\ndef to_leet_speak(str):\n return ''.join(LEET_ALPHABET[ord(c) - ord('A')] if c.isalpha() else c for c in str)", "ALPHABET = {\n 'A': '@', 'B': '8', 'C': '(', 'D': 'D', 'E': '3',\n 'F': 'F', 'G': '6', 'H': '#', 'I': '!', 'J': 'J',\n 'K': 'K', 'L': '1', 'M': 'M', 'N': 'N', 'O': '0',\n 'P': 'P', 'Q': 'Q', 'R': 'R', 'S': '$', 'T': '7',\n 'U': 'U', 'V': 'V', 'W': 'W', 'X': 'X', 'Y': 'Y',\n 'Z': '2'\n}\n\n\nto_leet_speak = lambda s: \"\".join(ALPHABET.get(c, c) for c in s)", "reference = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ' : ' '\n}\ndef to_leet_speak(str):\n return \"\".join([reference[key] for key in str])", "alphabet = dict(list(zip(__import__('string').ascii_uppercase, '@8(D3F6#!JK1MN0PQR$7UVWXY2')))\n\n\ndef to_leet_speak(str_):\n return ''.join(alphabet.get(x, x) for x in str_)\n", "def to_leet_speak(str):\n newStr, replace = '', '@8(D3F6#!JK1MN0PQR$7UVWXY2'\n for each in str:\n if ord(each) - ord('A') >= 0 <= 26:\n newStr += replace[ord(each) - ord('A')]\n else:\n newStr += each\n return newStr", "def to_leet_speak(str):\n leet={'A':'@','B':'8','C':'(','E':'3','G':'6','H':'#','I':'!','L':'1','O':'0','S':'$','T':'7','Z':'2'}\n newstr=''\n for c in str:\n if c in leet:\n newstr+=leet[c]\n else:\n newstr+=c\n return newstr", "speak = {\n \"A\" : '@',\n \"B\" : '8',\n \"C\" : '(',\n \"D\" : 'D',\n \"E\" : '3',\n \"F\" : 'F',\n \"G\" : '6',\n \"H\" : '#',\n \"I\" : '!',\n \"J\" : 'J',\n \"K\" : 'K',\n \"L\": '1',\n \"M\" : 'M',\n \"N\" : 'N',\n \"O\" : '0',\n \"P\" : 'P',\n \"Q\" : 'Q',\n \"R\" : 'R',\n \"S\" : '$',\n \"T\" : '7',\n \"U\" : 'U',\n \"V\" : 'V',\n \"W\" : 'W',\n \"X\" : 'X',\n \"Y\" : 'Y',\n \"Z\" : '2',\n \" \" : \" \"\n}\n\n\ndef to_leet_speak(str):\n return \"\".join(speak[i] for i in str)", "def to_leet_speak(s):\n d = {\n 'A' : '@', 'B' : '8', 'C' : '(', 'D' : 'D',\n 'E' : '3', 'F' : 'F', 'G' : '6', 'H' : '#', \n 'I' : '!', 'J' : 'J', 'K' : 'K', 'L' : '1',\n 'M' : 'M', 'N' : 'N', 'O' : '0', 'P' : 'P',\n 'Q' : 'Q', 'R' : 'R', 'S' : '$', 'T' : '7',\n 'U' : 'U', 'V' : 'V', 'W' : 'W', 'X' : 'X',\n 'Y' : 'Y', 'Z' : '2', ' ' : ' '\n }\n\n return ''.join(d[c] for c in s)", "to_leet_speak=lambda str: (lambda base: \"\".join([base[l] if l in base else l for l in str]))({'A':'@','B':'8','C':'(','E':'3','G':'6','H':'#','I':'!','L':'1','O':'0','S':'$','T':'7','Z':'2'})", "to_leet_speak = (lambda s: \n s.translate(\n str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ', '@8(D3F6#!JK1MN0PQR$7UVWXY2')\n ))", "LEETDICT = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ' : ' '\n}\n\nto_leet_speak = lambda str: \"\".join([LEETDICT[i] for i in list(str)])", "import string\n\ndef to_leet_speak(s):\n return s.translate(str.maketrans({\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n}))", "def to_leet_speak(str):\n \n st = \"\"\n d = {'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ' : ' ' }\n for x in range(len(str)):\n st = st + d.get(str[x])\n return st\n \n \n", "def to_leet_speak(str):\n x= {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n }\n z = \"\"\n for i in str:\n if i in x:\n z+=x[i]\n else:\n z+=i\n return z\n", "def to_leet_speak(str):\n leet_dict = {'A' : '@', 'B' : '8', 'C' : '(', 'D' : 'D', 'E' : '3',\n 'F' : 'F', 'G' : '6', 'H' : '#', 'I' : '!', 'J' : 'J',\n 'K' : 'K', 'L' : '1', 'M' : 'M', 'N' : 'N', 'O' : '0',\n 'P' : 'P', 'Q' : 'Q', 'R' : 'R', 'S' : '$', 'T' : '7',\n 'U' : 'U', 'V' : 'V', 'W' : 'W', 'X' : 'X', 'Y' : 'Y',\n 'Z' : '2'}\n return ''.join([leet_dict.get(char.upper(), ' ') for char in str])\n", "def to_leet_speak(str):\n str = str.upper()\n new = str.maketrans(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\"@8(D3F6#!JK1MN0PQR$7UVWXY2\")\n return str.translate(new)\n", "def to_leet_speak(s):\n d = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ' : ' '\n \n}\n res = \"\"\n for i in s:\n res += d[i]\n return res\n", "\nd = {\n 'A': '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J': 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n}\n\ndef to_leet_speak(str):\n\n a = []\n \n for i in range(len(str)):\n \n if str[i] in list(d.keys()):\n \n a.append(d[str[i]])\n \n else:\n \n a.append(str[i])\n \n p = \"\".join(a)\n\n return p\n\n", "def to_leet_speak(input_string):\n LEET_DICT = {'A' : '@', 'B' : '8', 'C' : '(', 'D' : 'D', 'E' : '3',\n 'F' : 'F', 'G' : '6', 'H' : '#', 'I' : '!', 'J' : 'J',\n 'K' : 'K', 'L' : '1', 'M' : 'M', 'N' : 'N', 'O' : '0',\n 'P' : 'P', 'Q' : 'Q', 'R' : 'R', 'S' : '$', 'T' : '7',\n 'U' : 'U', 'V' : 'V', 'W' : 'W', 'X' : 'X', 'Y' : 'Y',\n 'Z' : '2'}\n output_string = ''\n for char in input_string:\n output_string += LEET_DICT.get(char.upper(),char)\n return output_string", "LEET_DICT = {'A' : '@', 'B' : '8', 'C' : '(', 'D' : 'D', 'E' : '3',\n 'F' : 'F', 'G' : '6', 'H' : '#', 'I' : '!', 'J' : 'J',\n 'K' : 'K', 'L' : '1', 'M' : 'M', 'N' : 'N', 'O' : '0',\n 'P' : 'P', 'Q' : 'Q', 'R' : 'R', 'S' : '$', 'T' : '7',\n 'U' : 'U', 'V' : 'V', 'W' : 'W', 'X' : 'X', 'Y' : 'Y',\n 'Z' : '2'}\ndef to_leet_speak(english): \n leet_translation = ''\n for letter in english.upper():\n if letter in LEET_DICT:\n leet_translation += LEET_DICT.get(letter)\n else:\n leet_translation += letter\n return leet_translation ", "elite_dict = {'A' : '@', 'B' : '8', 'C' : '(', 'D' : 'D', 'E' : '3',\n 'F' : 'F', 'G' : '6', 'H' : '#', 'I' : '!', 'J' : 'J',\n 'K' : 'K', 'L' : '1', 'M' : 'M', 'N' : 'N', 'O' : '0',\n 'P' : 'P', 'Q' : 'Q', 'R' : 'R', 'S' : '$', 'T' : '7',\n 'U' : 'U', 'V' : 'V', 'W' : 'W', 'X' : 'X', 'Y' : 'Y',\n 'Z' : '2'}\n\ndef to_leet_speak(string):\n res = ''\n \n for i in range(len(string)):\n if string[i].upper() in elite_dict:\n res += (elite_dict[string[i].upper()])\n else:\n res += (' ')\n \n return res", "def to_leet_speak(input_str):\n LEET_DICT = {'A' : '@', 'B' : '8', 'C' : '(', 'D' : 'D', 'E' : '3',\n 'F' : 'F', 'G' : '6', 'H' : '#', 'I' : '!', 'J' : 'J',\n 'K' : 'K', 'L' : '1', 'M' : 'M', 'N' : 'N', 'O' : '0',\n 'P' : 'P', 'Q' : 'Q', 'R' : 'R', 'S' : '$', 'T' : '7',\n 'U' : 'U', 'V' : 'V', 'W' : 'W', 'X' : 'X', 'Y' : 'Y',\n 'Z' : '2'}\n \n output_str = ''\n for char in input_str.upper():\n if char in LEET_DICT.keys():\n output_str += LEET_DICT[char]\n else:\n output_str += char\n return output_str", "TRANS_TABLE = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ', '@8(D3F6#!JK1MN0PQR$7UVWXY2')\n\ndef to_leet_speak(text):\n return text.translate(TRANS_TABLE)", "def to_leet_speak(text):\n return text.translate(str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ', '@8(D3F6#!JK1MN0PQR$7UVWXY2'))", "import string\n\n\nstr1 = string.ascii_uppercase\nstr2 = '@8(D3F6#!JK1MN0PQR$7UVWXY2'\n\ndef to_leet_speak(s):\n table = str.maketrans(str1, str2)\n return s.translate(table)\n", "def to_leet_speak(str):\n output = ''\n \n leet_dict = {\n \"A\" : '@',\n \"B\" : '8',\n \"C\" : '(',\n \"D\" : 'D',\n \"E\" : '3',\n \"F\" : 'F',\n \"G\" : '6',\n \"H\" : '#',\n \"I\" : '!',\n \"J\" : 'J',\n \"K\" : 'K',\n \"L\" : '1',\n \"M\" : 'M',\n \"N\" : 'N',\n \"O\" : '0',\n \"P\" : 'P',\n \"Q\" : 'Q',\n \"R\" : 'R',\n \"S\" : '$',\n \"T\" : '7',\n \"U\" : 'U',\n \"V\" : 'V',\n \"W\" : 'W',\n \"X\" : 'X',\n \"Y\" : 'Y',\n \"Z\" : '2',\n \" \" : ' '\n }\n for letter in str:\n letter = letter.replace(letter, leet_dict[letter])\n output += letter\n return output", "def to_leet_speak(str):\n d={\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',' ':' '\n}\n l=[d[i] for i in str]\n return ''.join(l)\n", "alphabet = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n}\n\ndef to_leet_speak(str):\n new_string = ''\n for char in str:\n new_string += alphabet[char] if char != ' ' else ' '\n return new_string\n", "def to_leet_speak(str):\n table_leet = {\n \"A\" : '@',\n \"B\" : '8',\n \"C\" : '(',\n \"D\" : 'D',\n \"E\" : '3',\n \"F\" : 'F',\n \"G\" : '6',\n \"H\" : '#',\n \"I\" : '!',\n \"J\" : 'J',\n \"K\" : 'K',\n \"L\" : '1',\n \"M\" : 'M',\n \"N\" : 'N',\n \"O\" : '0',\n \"P\" : 'P',\n \"Q\" : 'Q',\n \"R\" : 'R',\n \"S\" : '$',\n \"T\" : '7',\n \"U\" : 'U',\n \"V\" : 'V',\n \"W\" : 'W',\n \"X\" : 'X',\n \"Y\" : 'Y',\n \"Z\" : '2',\n \" \" : \" \"\n }\n out = \"\"\n for let in str.upper():\n out+=table_leet[let]\n return out\n", "def to_leet_speak(str):\n \n ret = \"\"\n \n dict = {\n \"A\" : \"@\",\n \"B\" : \"8\",\n \"C\" : \"(\",\n \"D\" : \"D\",\n \"E\" : \"3\",\n \"F\" : \"F\",\n \"G\" : \"6\",\n \"H\" : \"#\",\n \"I\" : \"!\",\n \"J\" : \"J\",\n \"K\" : \"K\",\n \"L\" : \"1\",\n \"M\" : \"M\",\n \"N\" : \"N\",\n \"O\" : \"0\",\n \"P\" : \"P\",\n \"Q\" : \"Q\",\n \"R\" : \"R\",\n \"S\" : \"$\",\n \"T\" : \"7\",\n \"U\" : \"U\",\n \"V\" : \"V\",\n \"W\" : \"W\",\n \"X\" : \"X\",\n \"Y\" : \"Y\",\n \"Z\" : \"2\"\n }\n \n for i in range(len(str)):\n if(str[i] in dict):\n ret = ret + dict[str[i]]\n else:\n ret = ret + str[i]\n \n print(ret)\n return ret\n", "def to_leet_speak(str):\n wasteoftime ={\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ' : ' '\n}\n return \"\".join(wasteoftime[i] for i in str)\n", "def to_leet_speak(s):\n leet = { 'A': '@', 'B': '8', 'C': '(', 'D': 'D', 'E': '3', 'F': 'F', 'G': '6', 'H': '#', 'I': '!', 'J': 'J', 'K': 'K', 'L': '1', 'M': 'M', 'N': 'N', 'O': '0', 'P': 'P', 'Q': 'Q', 'R': 'R', 'S': '$', 'T': '7', 'U': 'U', 'V': 'V', 'W': 'W', 'X': 'X', 'Y': 'Y', 'Z': '2'}\n return s.upper().translate(s.maketrans(leet))", "def to_leet_speak(str):\n leet = { 'A' : '@', 'B' : '8', 'C' : '(', 'D' : 'D', 'E' : '3', 'F' : 'F', \\\n 'G' : '6', 'H' : '#', 'I' : '!', 'J' : 'J', 'K' : 'K', 'L' : '1', \\\n 'M' : 'M', 'N' : 'N', 'O' : '0', 'P' : 'P', 'Q' : 'Q', 'R' : 'R', \\\n 'S' : '$', 'T' : '7', 'U' : 'U', 'V' : 'V', 'W' : 'W', 'X' : 'X', \\\n 'Y': 'Y', 'Z' : '2' }\n output = ''\n for letter in str:\n if letter in leet:\n output += leet[letter]\n else:\n output += letter\n return output", "def to_leet_speak(str):\n alphabet = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n}\n return str.translate(str.maketrans(alphabet))\n", "def to_leet_speak(str):\n dict = {\n \"A\" : '@',\n \"B\" : '8',\n \"C\" : '(',\n \"D\" : 'D',\n \"E\" : '3',\n \"F\" : 'F',\n \"G\" : '6',\n \"H\" : '#',\n \"I\" : '!',\n \"J\" : 'J',\n \"K\" : 'K',\n \"L\" : '1',\n \"M\" : 'M',\n \"N\" : 'N',\n \"O\" : '0',\n \"P\" : 'P',\n \"Q\" : 'Q',\n \"R\" : 'R',\n \"S\" : '$',\n \"T\" : '7',\n \"U\" : 'U',\n \"V\" : 'V',\n \"W\" : 'W',\n \"X\" : 'X',\n \"Y\" : 'Y',\n \"Z\" : '2',\n \" \" : ' '\n}\n l = []\n string = list(str)\n for key in string : \n l.append(dict[key])\n return \"\".join(l)\n\n\n", "def to_leet_speak(str):\n x = {'A' : '@','B' : '8','C' : '(','D' : 'D','E' : '3','F' : 'F','G' : '6','H' : '#','I' : '!','J' : 'J','K' : 'K','L' : '1','M' : 'M','N' : 'N','O' : '0','P' : 'P','Q' : 'Q','R' : 'R','S' : '$','T' : '7','U' : 'U','V' : 'V','W' : 'W','X' : 'X','Y' : 'Y','Z' : '2'}\n y = \"\"\n for i in str:\n try:\n y += x[i]\n except:\n y += i\n return y", "d={\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n}\n\ndef to_leet_speak(s):\n return ''.join(d[c] if c in d else c for c in s)\n", "def to_leet_speak(str):\n table = str.maketrans({'A': '@', 'B': '8', 'C': '(', 'E': '3', 'G': '6', 'H': '#', 'I': '!', 'L': '1', 'O': '0', 'S': '$', 'T': '7', 'Z': '2'})\n return str.translate(table)", "def to_leet_speak(str):\n return str.translate(str.maketrans('IHACOLZEGTBS', '!#@(0123678$'))\n", "D = {\n 65 : '@',\n 66 : '8',\n 67 : '(',\n 68 : 'D',\n 69 : '3',\n 70 : 'F',\n 71 : '6',\n 72 : '#',\n 73 : '!',\n 74 : 'J',\n 75 : 'K',\n 76 : '1',\n 77 : 'M',\n 78 : 'N',\n 79 : '0',\n 80 : 'P',\n 81 : 'Q',\n 82 : 'R',\n 83 : '$',\n 84 : '7',\n 85 : 'U',\n 86 : 'V',\n 87 : 'W',\n 88 : 'X',\n 89 : 'Y',\n 90 : '2'\n}\ndef to_leet_speak(str):\n return str.translate(D)\n", "def to_leet_speak(str):\n trans = str.maketrans('ABCEGHILOSTZ', '@8(36#!10$72')\n return str.translate(trans)", "from string import ascii_uppercase\n\ndef to_leet_speak(str):\n trans = str.maketrans(ascii_uppercase, '@8(D3F6#!JK1MN0PQR$7UVWXY2')\n return str.translate(trans)", "def to_leet_speak(str): #\n return str.translate(str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ', '@8(D3F6#!JK1MN0PQR$7UVWXY2'))", "def to_leet_speak(str):\n dict = {'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'}\n return ''.join(dict.get(x, ' ') for x in str)\n \n", "def to_leet_speak(string):\n return string.translate(str.maketrans('ABCEGHILOSTZ', '@8(36#!10$72'))\n", "d={'A' : '@','B': '8','C' : '(','D' : 'D','E': '3',\n 'F' : 'F','G' : '6','H' : '#','I' : '!','J' : 'J',\n 'K' : 'K', 'L' : '1','M' : 'M','N' : 'N','O' : '0',\n 'P' : 'P','Q' : 'Q','R' : 'R','S' : '$','T' : '7',\n 'U' : 'U','V' : 'V','W' : 'W','X' : 'X','Y' : 'Y',\n 'Z' : '2'}\ndef to_leet_speak(str):\n return ''.join(d.get(x) if x!=' ' else x for x in str)\n", "def to_leet_speak(str):\n d={\n \"A\" : '@',\n \"B\" : '8',\n \"C\" : '(',\n \"D\" : 'D',\n \"E\" : '3',\n \"F\" : 'F',\n \"G\" : '6',\n \"H\" : '#',\n \"I\" : '!',\n \"J\" : 'J',\n \"K\" : 'K',\n \"L\" : '1',\n \"M\" : 'M',\n \"N\" : 'N',\n \"O\" : '0',\n \"P\" : 'P',\n \"Q\" : 'Q',\n \"R\" : 'R',\n \"S\" : '$',\n \"T\" : '7',\n \"U\" : 'U',\n \"V\" : 'V',\n \"W\" : 'W',\n \"X\" : 'X',\n \"Y\" : 'Y',\n \"Z\" : '2'\n }\n return str.translate(str.maketrans(d))\n", "leetDict = {\n \"A\" : '@', \"B\" : '8', \"C\" : '(', \"D\" : 'D',\n \"E\" : '3', \"F\" : 'F', \"G\" : '6', \"H\" : '#',\n \"I\" : '!', \"J\" : 'J', \"K\" : 'K', \"L\" : '1',\n \"M\" : 'M', \"N\" : 'N', \"O\" : '0', \"P\" : 'P',\n \"Q\" : 'Q', \"R\" : 'R', \"S\" : '$', \"T\" : '7',\n \"U\" : 'U', \"V\" : 'V', \"W\" : 'W', \"X\" : 'X',\n \"Y\" : 'Y', \"Z\" : '2', \" \" : ' '\n}\n\ndef to_leet_speak(str):\n natList = list(str)\n leetList = []\n\n for i in natList:\n leetList.append(leetDict[i])\n\n return \"\".join(leetList)", "def to_leet_speak(str):\n getchar = lambda c: chars[c] if c in chars else c\n chars = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n }\n return ''.join(getchar(c) for c in str)", "import unittest\n\nMAPPING_TABLE = {\n 'A': '@',\n 'B': '8',\n 'C': '(',\n 'D': 'D',\n 'E': '3',\n 'F': 'F',\n 'G': '6',\n 'H': '#',\n 'I': '!',\n 'J': 'J',\n 'K': 'K',\n 'L': '1',\n 'M': 'M',\n 'N': 'N',\n 'O': '0',\n 'P': 'P',\n 'Q': 'Q',\n 'R': 'R',\n 'S': '$',\n 'T': '7',\n 'U': 'U',\n 'V': 'V',\n 'W': 'W',\n 'X': 'X',\n 'Y': 'Y',\n 'Z': '2',\n ' ': ' '\n}\n\n\ndef to_leet_speak(str_):\n return ''.join(MAPPING_TABLE[char] for char in str_)\n \n \nclass TestToLeekSpeak(unittest.TestCase):\n def test_to_leek_speak(self):\n str_ = 'LEET'\n actual = to_leek_speak(str_)\n self.assertEqual(actual, '1337')\n\n def test_to_leek_speak_with_empty_space(self):\n str_ = 'HELLO WORLD'\n actual = to_leek_speak(str_)\n self.assertEqual(actual, '#3110 W0R1D')\n", "def to_leet_speak(p):\n db = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ' : ' ',\n }\n lol = [db.get(item) for item in p]\n l = [str(i) for i in lol]\n return ''.join(l)", "def to_leet_speak(str):\n leet = {\n 'A':'@',\n 'B':'8',\n 'C':'(',\n 'D':'D',\n 'E':'3',\n 'F':'F',\n 'G':'6',\n 'H':'#',\n 'I':'!',\n 'J':'J',\n 'K':'K',\n 'L':'1',\n 'M':'M',\n 'N':'N',\n 'O':'0',\n 'P':'P',\n 'Q':'Q',\n 'R':'R',\n 'S':'$',\n 'T':'7',\n 'U':'U',\n 'V':'V',\n 'W':'W',\n 'X':'X',\n 'Y':'Y',\n 'Z':'2',\n ' ':' '\n }\n return ''.join(leet[i] for i in str)", "def to_leet_speak(str):\n alphabet = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ' : ' '\n}\n return ''.join([ alphabet[c] for c in str])\n", "def to_leet_speak(str):\n leet = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2' }\n return ''.join([leet[x] if x!=' ' else ' ' for x in str])\n", "def to_leet_speak(string):\n trans = str.maketrans(\n {\n \"A\": \"@\",\n \"B\": \"8\",\n \"C\": \"(\",\n \"E\": \"3\",\n \"G\": \"6\",\n \"H\": \"#\",\n \"I\": \"!\",\n \"L\": \"1\",\n \"O\": \"0\",\n \"S\": \"$\",\n \"T\": \"7\",\n \"Z\": \"2\",\n }\n )\n return string.translate(trans)\n", "def to_leet_speak(str):\n LeetSpeak = { 'A' : '@', 'B' : '8','C' : '(','E' : '3','G' : '6','H' : '#','I' : '!','L' : '1','O' : '0','S' : '$','T' : '7','Z' : '2'}\n return ''.join(LeetSpeak [x] if x in LeetSpeak else x for x in str)", "def to_leet_speak(str):\n LeetSpeak = { 'A' : '@', 'B' : '8','C' : '(','D' : 'D','E' : '3', 'F' : 'F', 'G' : '6','H' : '#','I' : '!','J' : 'J', 'K' : 'K', 'L' : '1', 'M' : 'M','N' : 'N','O' : '0','P' : 'P','Q' : 'Q','R' : 'R','S' : '$','T' : '7','U' : 'U','V' : 'V','W' : 'W','X' : 'X','Y' : 'Y','Z' : '2'}\n return ''.join(LeetSpeak [x] if x in LeetSpeak else x for x in str)", "def to_leet_speak(str):\n leet = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ' : ' '\n }\n \n return ''.join(leet[ch] for ch in str)\n \n \n", "def to_leet_speak(text):\n return text.translate(text.maketrans(\"ABCEGHILOSTZ\", \"@8(36#!10$72\"))\n", "dictRef = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ' : ' '\n}\n\nto_leet_speak = lambda s: ''.join(dictRef[letter] for letter in s)\n", "def to_leet_speak(str):\n s=''\n \n dict={'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'}\n for i in str:\n try:\n s+=dict[i]\n except:\n s+=' '\n return s\n\n", "leet_dict = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n}\n\n\ndef to_leet_speak(str):\n leet_phrase = ''\n for x in str:\n if x == ' ':\n leet_phrase += x\n else:\n leet_phrase += leet_dict.get(x.upper())\n return leet_phrase\n\n \n \n", "from string import ascii_uppercase\ndef to_leet_speak(s):\n temp = str.maketrans(ascii_uppercase, '@8(D3F6#!JK1MN0PQR$7UVWXY2')\n return s.translate(temp)", "def to_leet_speak(str):\n leet_speak = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n}\n\n for key, value in leet_speak.items():\n str = str.replace(key, value)\n return str", "to_leet = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n}\ndef to_leet_speak(str):\n return \"\".join([to_leet.get(x,x) for x in str])\n", "def to_leet_speak(str):\n l33t = { 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ': ' '}\n return ''.join(l33t.get(char) for char in str)\n \n", "def to_leet_speak(str):\n ans=''\n alp={'A' : '@','B' : '8','C' : '(','D' : 'D','E': '3','F' : 'F','G' : '6','H' : '#','I' : '!','J' : 'J','K' : 'K','L' : '1','M' : 'M','N' : 'N','O' : '0','P' : 'P','Q' : 'Q','R' : 'R','S' : '$','T' : '7','U' : 'U','V' : 'V','W' : 'W','X' : 'X','Y' : 'Y','Z' : '2'}\n for i in str: ans=ans+alp.get(i,' ')\n \n return ans\n", "d1 = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n}\n\ndef to_leet_speak(s):\n return ''.join([d1.get(x,x) for x in s])\n", "def to_leet_speak(str):\n d = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n }\n \n newstr = \"\"\n for c in str:\n try:\n newstr += d[c]\n except KeyError:\n newstr += c\n\n return newstr", "def to_leet_speak(str):\n dict = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'}\n return ''.join(dict.get(i, i) for i in str)\n", "swap = {\n \"A\" : '@',\n \"B\" : '8',\n \"C\" : '(',\n \"D\" : 'D',\n \"E\" : '3',\n \"F\" : 'F',\n \"G\" : '6',\n \"H\" : '#',\n \"I\" : '!',\n \"J\" : 'J',\n \"K\" : 'K',\n \"L\" : '1',\n \"M\" : 'M',\n \"N\" : 'N',\n \"O\" : '0',\n \"P\" : 'P',\n \"Q\" : 'Q',\n \"R\" : 'R',\n \"S\" : '$',\n \"T\" : '7',\n \"U\" : 'U',\n \"V\" : 'V',\n \"W\" : 'W',\n \"X\" : 'X',\n \"Y\" : 'Y',\n \"Z\" : '2',\n \" \": \" \"\n}\ndef to_leet_speak(str):\n return \"\".join(swap[x] for x in str)", "def to_leet_speak(str):\n alfabe={'A' : '@','B' : '8','C' : '(','D' : 'D','E' : '3','F' : 'F','G' : '6','H' : '#','I' : '!','J' : 'J','K' : 'K','L' : '1','M' : 'M','N' : 'N','O' : '0','P' : 'P','Q' : 'Q','R' : 'R','S' : '$','T' : '7','U' : 'U','V' : 'V','W' : 'W','X' : 'X','Y' : 'Y','Z' : '2'}\n for i in list(alfabe.keys()):\n if i in str:\n str=str.replace(i,alfabe[i])\n return str\n", "def to_leet_speak(str):\n \n key = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n val = \"@8(D3F6#!JK1MN0PQR$7UVWXY2\"\n \n transform = dict(zip(key, val))\n return ''.join(transform.get(char, char) for char in str)", "def to_leet_speak(str):\n alphabet = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ' : ' '\n\n}\n\n new_str = ''\n for x in str:\n if x in list(alphabet.keys()):\n new_str += alphabet[x]\n return new_str\n", "dicc = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2',\n ' ' : ' '\n}\ndef to_leet_speak(str):\n a = []\n for i in str:\n a.append(dicc[i])\n b = \"\".join(a)\n return b\n \n", "def to_leet_speak(s):\n dic = {\n 'A' : '@',\n 'B' : '8',\n 'C' : '(',\n 'D' : 'D',\n 'E' : '3',\n 'F' : 'F',\n 'G' : '6',\n 'H' : '#',\n 'I' : '!',\n 'J' : 'J',\n 'K' : 'K',\n 'L' : '1',\n 'M' : 'M',\n 'N' : 'N',\n 'O' : '0',\n 'P' : 'P',\n 'Q' : 'Q',\n 'R' : 'R',\n 'S' : '$',\n 'T' : '7',\n 'U' : 'U',\n 'V' : 'V',\n 'W' : 'W',\n 'X' : 'X',\n 'Y' : 'Y',\n 'Z' : '2'\n }\n return ''.join(dic.get(c,c) for c in s)\n", "alphabet = {\n 'A': '@',\n 'B': '8',\n 'C': '(',\n 'D': 'D',\n 'E': '3',\n 'F': 'F',\n 'G': '6',\n 'H': '#',\n 'I': '!',\n 'J': 'J',\n 'K': 'K',\n 'L': '1',\n 'M': 'M',\n 'N': 'N',\n 'O': '0',\n 'P': 'P',\n 'Q': 'Q',\n 'R': 'R',\n 'S': '$',\n 'T': '7',\n 'U': 'U',\n 'V': 'V',\n 'W': 'W',\n 'X': 'X',\n 'Y': 'Y',\n 'Z': '2',\n ' ': ' '\n}\n\n\ndef to_leet_speak(str):\n res = []\n for i in str:\n temp = alphabet[i]\n res.append(temp)\n\n return ''.join(res)", "def to_leet_speak(str):\n tls = {\n 'A': '@',\n 'B': '8',\n 'C': '(',\n 'D': 'D',\n 'E': '3',\n 'F': 'F',\n 'G': '6',\n 'H': '#',\n 'I': '!',\n 'J': 'J',\n 'K': 'K',\n 'L': '1',\n 'M': 'M',\n 'N': 'N',\n 'O': '0',\n 'P': 'P',\n 'Q': 'Q',\n 'R': 'R',\n 'S': '$',\n 'T': '7',\n 'U': 'U',\n 'V': 'V',\n 'W': 'W',\n 'X': 'X',\n 'Y': 'Y',\n 'Z': '2',\n ' ' : ' '\n }\n res = \"\"\n for i in str:\n res += tls[i]\n return res\n", "def to_leet_speak(str):\n leet_dict = {' ': ' ','A':'@','B':'8','C':'(','D':'D','E':'3','F':'F','G':'6','H':'#','I':'!','J':'J','K':'K','L':'1','M':'M','N':'N','O':'0','P':'P','Q':'Q','R':'R','S':'$','T':'7','U':'U','V':'V','W':'W','X':'X','Y':'Y','Z':'2'}\n leet_list = []\n for i in str:\n if i in leet_dict.keys():\n leet_list.append(leet_dict.get(i))\n return ''.join(leet_list)", "def to_leet_speak(str):\n dic = {\n \"A\" : '@',\n \"B\" : '8',\n \"C\" : '(',\n \"E\" : '3',\n \"F\" : 'F',\n \"G\" : '6',\n \"H\" : '#',\n \"I\" : '!',\n \"L\" : '1',\n \"O\" : '0',\n \"S\" : '$',\n \"T\" : '7',\n \"Z\" : '2'\n }\n return(''.join(dic.get(i, i) for i in str))\n \n \n", "def to_leet_speak(string):\n uppercase_letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n leet_speak = \"@8(D3F6#!JK1MN0PQR$7UVWXY2\"\n leet = dict(list(zip(uppercase_letters, leet_speak)))\n \n leet_builder = str()\n for letter in string:\n leet_letter = leet.get(letter)\n leet_builder += leet_letter if leet_letter else letter\n \n return leet_builder\n", "from string import ascii_uppercase\nL = str.maketrans(ascii_uppercase, '@8(D3F6#!JK1MN0PQR$7UVWXY2')\n\nto_leet_speak = lambda s: s.translate(L)", "from string import ascii_uppercase\n\nALPHABET = str.maketrans(ascii_uppercase, \"@8(D3F6#!JK1MN0PQR$7UVWXY2\")\n\n\ndef to_leet_speak(text):\n return text.translate(ALPHABET)\n", "def to_leet_speak(str):\n al = {\n 'A': '@',\n 'B': '8',\n 'C': '(',\n 'D': 'D',\n 'E': '3',\n 'F': 'F',\n 'G': '6',\n 'H': '#',\n 'I': '!',\n 'J': 'J',\n 'K': 'K',\n 'L': '1',\n 'M': 'M',\n 'N': 'N',\n 'O': '0',\n 'P': 'P',\n 'Q': 'Q',\n 'R': 'R',\n 'S': '$',\n 'T': '7',\n 'U': 'U',\n 'V': 'V',\n 'W': 'W',\n 'X': 'X',\n 'Y': 'Y',\n 'Z': '2'\n }\n result = ''\n for char in str:\n result += al.get(char,' ')\n return result\n\n", "def to_leet_speak(str):\n LEET = {\n 'A' : '@', 'B' : '8', 'C' : '(', 'D' : 'D', 'E' : '3', 'F' : 'F', 'G' : '6', 'H' : '#', \n 'I' : '!', 'J' : 'J', 'K' : 'K', 'L' : '1', 'M' : 'M', 'N' : 'N', 'O' : '0', 'P' : 'P',\n 'Q' : 'Q', 'R' : 'R', 'S' : '$', 'T' : '7', 'U' : 'U', 'V' : 'V', 'W' : 'W', 'X' : 'X',\n 'Y' : 'Y', 'Z' : '2'\n }\n return ''.join([LEET.get(i,' ') for i in str])\n", "MAP = {\n \"A\" : '@',\n \"B\" : '8',\n \"C\" : '(',\n \"D\" : 'D',\n \"E\" : '3',\n \"F\" : 'F',\n \"G\" : '6',\n \"H\" : '#',\n \"I\" : '!',\n \"J\" : 'J',\n \"K\" : 'K',\n \"L\" : '1',\n \"M\" : 'M',\n \"N\" : 'N',\n \"O\" : '0',\n \"P\" : 'P',\n \"Q\" : 'Q',\n \"R\" : 'R',\n \"S\" : '$',\n \"T\" : '7',\n \"U\" : 'U',\n \"V\" : 'V',\n \"W\" : 'W',\n \"X\" : 'X',\n \"Y\" : 'Y',\n \"Z\" : '2'\n}\n\ndef to_leet_speak(str):\n return ''.join([MAP[c.upper()] if c.upper() in MAP else c for c in str])\n"] | {"fn_name": "to_leet_speak", "inputs": [["LEET"], ["CODEWARS"], ["HELLO WORLD"], ["LOREM IPSUM DOLOR SIT AMET"], ["THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"]], "outputs": [["1337"], ["(0D3W@R$"], ["#3110 W0R1D"], ["10R3M !P$UM D010R $!7 @M37"], ["7#3 QU!(K 8R0WN F0X JUMP$ 0V3R 7#3 1@2Y D06"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 42,050 |
def to_leet_speak(str):
|
3cfa9ebe1fc614de0163426daed9bf54 | UNKNOWN | Task:
Make a function that converts a word to pig latin. The rules of pig latin are:
```
If the word has more than 3 letters:
1. Take the first letter of a word and move it to the end
2. Add -ay to the word
Otherwise leave the word alone.
```
Example: `hello` = `ellohay` | ["def pig_latin(word):\n return word[1:]+word[0]+'ay' if len(word)>3 else word", "def pig_latin(word):\n return word if len(word) < 4 else word[1:]+word[0]+\"ay\"", "def pig_latin(word):\n return f\"{word[1:]}{word[0]}ay\" if len(word) > 3 else word", "def pig_latin(word):\n if len(word) > 3:\n ay = word[0] + \"ay\"\n ans = word[1:]+ay\n return ans\n else:\n return word", "def pig_latin(word):\n return word if len(word) < 4 else f\"{word[1:]}{word[:1]}ay\" ", "def pig_latin(s):\n return '{}{}ay'.format(s[1:], s[0]) if len(s) > 3 else s", "def pig_latin(word):\n if len(word) < 3:\n return word\n ret = word + word[0] + 'ay'\n return ret[1:]", "def pig_latin(word):\n return \"{}{}ay\".format(word[1:], word[0]) if len(word) > 3 else word", "pig_latin = lambda w: len(w) < 4 and w or \"%s%say\" % (w[1:], w[0])", "def pig_latin(word):\n if len(word) <= 3:\n return word\n word = word[1:] + word[0]\n word = word + \"ay\"\n return word"] | {"fn_name": "pig_latin", "inputs": [["hello"], ["hi"]], "outputs": [["ellohay"], ["hi"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,020 |
def pig_latin(word):
|
b9c8829e29757aa0972584b00656203c | UNKNOWN | You take your son to the forest to see the monkeys. You know that there are a certain number there (n), but your son is too young to just appreciate the full number, he has to start counting them from 1.
As a good parent, you will sit and count with him. Given the number (n), populate an array with all numbers up to and including that number, but excluding zero.
For example:
```python
monkeyCount(10) # --> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
monkeyCount(1) # --> [1]
``` | ["def monkey_count(n):\n return list(range(1,n+1))", "def monkey_count(n):\n return [i+1 for i in range(n)]", "def monkey_count(n):\n return [i for i in range(1, n+1)]", "def monkey_count(n):\n #your code here\n list = []\n for i in range(1,n+1):\n list.append(i)\n return list", "def monkey_count(n):\n #your code here\n poop = []\n \n c = 1\n \n for i in range(0,n):\n poop.append(c)\n c += 1\n \n return poop", "monkey_count=lambda n:[m for m in range(1,n+1)]\n", "def monkey_count(n):\n return list(range(1, n+1))\n\n\nprint((monkey_count(4)))\n", "monkey_count = lambda e:list(range(1,e+1))", "def monkey_count(n):\n a = []\n i = 1\n while i < n+1:\n a = a + [i]\n i += 1\n return a ", "def monkey_count(n):\n c = []\n for i in range(n):\n c.append(i+1)\n return c", "def monkey_count(n):\n monkey_count = []\n for i in range(n):\n i += 1\n monkey_count.append(i)\n return monkey_count\n", "def monkey_count(n):\n #your code here\n L=[]\n L.extend(range(1,n+1))\n return(L)", "def monkey_count(n):\n ans = []\n for i in range(n):\n ans.append(i + 1)\n return ans", "def monkey_count(n):\n #your code here\n return [x for x in range(1,n+1)]", "monkey_count = lambda m: list(range(1, m + 1))", "monkey_count = lambda n: list(range(1, n+1))", "def monkey_count(n):\n num = []\n for monkey in range(1, n + 1):\n num.append(monkey)\n return num", "def monkey_count(n):\n listA = []\n ind = 0\n for i in range(n):\n listA.append(ind+1)\n ind += 1\n return listA", "def monkey_count(n):\n #your code here\n count = []\n i = 0\n while i < n:\n count.append(i+1)\n i += 1\n return count", "def monkey_count(n):\n l = []\n count = 1;\n while count <= n:\n l.append(count)\n count += 1\n return l", "def monkey_count(n):\n return [_ for _ in range(1, n+1)]", "def monkey_count(n):\n return list(range(n+1))[1:n+1]\n", "def monkey_count(n):\n y=[]\n \n for i in range(n):\n y.insert(i, i+1)\n\n\n return y", "def monkey_count(n):\n return list([i for i in range(1,n+1)])\n #your code here\n", "def monkey_count(n):\n monkeys = []\n for monke in range(1,n+1):\n monkeys.append(monke)\n return(monkeys)", "def monkey_count(n):\n ln = []\n for x in range(1, n + 1):\n ln.append(x)\n return ln", "def monkey_count(n):\n tall = 0\n count = []\n while tall < n:\n tall += 1\n count.append(tall)\n return count", "def monkey_count(n):\n lst_return = []\n \n for i in range(n):\n lst_return.append(i + 1)\n \n return lst_return", "monkey_count = lambda _:list(range(1,_+1))", "def monkey_count(n):\n print(n)\n c = list(range(1,n+1))\n return c\n", "def monkey_count(n):\n amount = []\n count = 1\n \n for i in range(n):\n amount.append(count)\n count = count + 1\n \n return amount", "def monkey_count(n):\n a = []\n while n > 0:\n a.append(n)\n n -= 1\n a.sort()\n return a", "def monkey_count(n):\n x = [int(x) for x in range(n+1)]\n x.remove(0)\n return x", "def monkey_count(n):\n count = [i for i in range(n+1)]\n return count[1:]", "def monkey_count(n):\n hold=[]\n for i in range(1,n+1):\n hold.append(i)\n return hold", "def monkey_count(n):\n test =[]\n for i in range(0, n):\n test.append(i+1)\n return test\n\nhuhu = monkey_count(9)\n\nprint(huhu)", "def monkey_count(n):\n a=n+1\n b = [i for i in range(1,a)]\n return b", "def monkey_count(n):\n \n l=[]\n i=0\n for i in range(n):\n print((i+1))\n l.append(i+1)\n return l \n# return [l, l.append(i) for i,v in range(n)]\n", "def monkey_count(n):\n m_list = list(range(n+1))\n m_list = m_list[1:]\n return m_list", "def monkey_count(n):\n n = n + 1\n list = range(1, n)\n list2 = []\n for i in list:\n list2.append(i)\n\n return list2", "def monkey_count(n):\n c = []\n \n return [x+1 for x in range(n)]\n", "def monkey_count(n):\n array = []\n for monkey in range(1,n+1):\n array.append(monkey)\n return array", "def monkey_count(n):\n \"\"\"(^-__-^)\"\"\"\n return list(range(1, n+1))\n", "def monkey_count(n):\n nums=[]\n for i in range (n+1) :\n if i > 0:\n nums.append(i)\n return nums", "from array import *\ndef monkey_count(n):\n arr = array('i',range(1,n+1))\n return [a for a in arr]", "def monkey_count(n):\n list_of_num = []\n for monkey_num in range(1, n + 1):\n list_of_num.append(int(monkey_num))\n return list_of_num", "def monkey_count(n):\n arr = []\n i = n\n while i > 0:\n arr.append(i)\n i -= 1\n \n arr.reverse()\n return arr", "def monkey_count(n):\n mylist = []\n num = int(n)\n num +=1\n for el in range(num):\n mylist.append(el)\n return mylist[1::]\n", "def monkey_count(n):\n i = 1\n n += 1\n arr = list()\n while i != n:\n arr.append(i)\n i += 1\n return arr\n \n \n", "def monkey_count(n):\n return list(range(1,n+1)) if n is not 1 else 1", "monkey_count = lambda c: list(range(1, c + 1))", "def monkey_count(n):\n rl = []\n i = 1\n while i <= n:\n rl.append(i)\n i += 1\n return rl", "def monkey_count(n):\n cnt = 0\n count_lst = []\n while cnt < n:\n cnt += 1\n count_lst.append(cnt)\n return count_lst", "def monkey_count(n):\n a = [value +1 for value in range(n)] \n return a", "def monkey_count(n):\n arr = [i for i in range(1, n + 1)] \n \n return arr", "def monkey_count(n):\n lst = list()\n for i in range(1,n+1):\n lst.append(i)\n return lst", "def monkey_count(n):\n \n ##set up empty list\n monkeyCount = []\n \n ##for all numbers up to n, add to list\n for i in range (n):\n monkeyCount.append(i+1)\n \n return(monkeyCount)\n", "def monkey_count(n):\n count = []\n \n for i in range(1,n+1):\n count += [i]\n return(count)\n", "def monkey_count(num):\n ans = []\n for n in range(num):\n ans.append(n + 1)\n return ans", "def monkey_count(n):\n z = 0\n liste = []\n while n != 0:\n n -= 1\n z += 1\n liste.append(z) \n return liste", "def monkey_count(n):\n \"\"\"\n Returns a list with numbers from 1 to 'n' (inclusive).\n \"\"\"\n return list(range(1, n + 1))", "def monkey_count(n):\n return [1] if n == 1 else list(range(1, n+1))", "def monkey_count(n):\n count = 0\n num = []\n while count < n:\n num.append(count+1)\n count += 1\n return num", "def monkey_count(n):\n lst = []\n for i in range (0, n):\n lst.append(i+1)\n \n return lst", "def monkey_count(n):\n #your code here\n x = list(range(n+2))\n return x[1:-1]\n", "def monkey_count(a):\n return [i for i in range(1, a+1)]", "def monkey_count(n):\n list1 = []\n for i in range (1, n + 1, 1) :\n list1.append(i)\n return list1", "def monkey_count(n):\n i = 1\n lst = []\n while i <= n:\n lst.append(i)\n i +=1\n return lst\n #your code here\n", "def monkey_count(n):\n arr = []\n [arr.append(x) for x in range(1, n+1)]\n return arr", "def monkey_count(n):\n number_of_monkeys = list(range(1,n+1))\n return number_of_monkeys\n", "def monkey_count(n):\n haha=[]\n x = list(range(1,n+1))\n for i in x:\n haha.append(i)\n return haha\n", "def monkey_count(n):\n o = []\n for i in range(n):\n o.append(i+1)\n return o\n #your code here\n", "def monkey_count(n):\n return [monkeys for monkeys in range(1,+ n+1)]\n", "def monkey_count(n):\n # your code here\n tulos = list(range(1, n+1))\n return tulos", "def monkey_count(n):\n count = 0\n thislist = []\n while count != n:\n count +=1\n thislist.append(count)\n return thislist\n", "def monkey_count(n):\n x = range(1 , n+1 , 1)\n for n in x: \n return list(x)", "def monkey_count(n):\n r=range(1,n+1)\n return list(r)", "def monkey_count(n):\n k = range(1,n+1)\n m = list(k)\n return m", "def monkey_count(n):\n emptylist = []\n for eachnumber in range(1,n+1):\n emptylist.append(eachnumber)\n return emptylist", "def monkey_count(n):\n \n list = []\n n = n + 1\n \n for i in range(1 , n):\n list.append(i)\n \n return list\n", "def monkey_count(n):\n list = []\n for i in range(n+1):\n i += 1\n list.append(i)\n if i == (n):\n break\n else:\n continue\n return list", "def monkey_count(n):\n l1 = []\n for i in range(1, n+1):\n l1.append(i)\n return l1", "def monkey_count(n):\n i=list(range(1,n+1))\n return list(i)\n \n \n", "def monkey_count(n):\n \"\u0421\u0447\u0438\u0442\u0430\u0435\u043c \u043e\u0431\u0435\u0437\u044c\u044f\u043d\"\n nn = []\n for it in (range(1, n+1)):\n nn.append(it)\n return nn", "def monkey_count(n):\n count = 1\n list = []\n while count <= n:\n list.append(count)\n count += 1\n return list", "def monkey_count(n):\n \"\"\"Count monkeys from 1 to last.\"\"\"\n monkeys = []\n for i in range(1, n + 1):\n monkeys.append(i)\n return monkeys", "# INVINCIBLE WARRIORS --- PARZIVAL\n\ndef monkey_count(n):\n return [i for i in range(1, n + 1)]", "def monkey_count(n):\n return [i for i in range (1, n+1)]\n \nmonkey_count(2)\n", "def monkey_count(n):\n n = range(1, n + 1)\n pusta_lista = []\n for x in n:\n pusta_lista.append(x)\n return pusta_lista", "def monkey_count(n):\n #your code here\n mc = []\n for i in range(1,n+1):\n mc.append(i)\n return mc\n", "def monkey_count(n):\n s=[]\n for i in range(n+1):\n s+=[i]\n return s[1:]", "def monkey_count(n):\n return list(sorted(n-i for i in range(n)))\n", "def monkey_count(n):\n return [] if n < 1 else monkey_count(n-1) + [n]", "def monkey_count(n):\n monks = []\n for i in range(1,n+1):\n monks.append(i)\n return monks", "import numpy as np\ndef monkey_count(n):\n #your code here\n n2=n+1\n value= list(range(1,n2))\n return (value)\n", "def monkey_count(n):\n res=[i+1 for i in range(n)]\n\n return res", "def monkey_count(n):\n arrMonk = []\n for i in range(1, n+1):\n arrMonk.append(i)\n return arrMonk\n #your code here\n", "def monkey_count(n):\n s=list()\n for i in range(1,n+1):\n s.append(i)\n return s"] | {"fn_name": "monkey_count", "inputs": [[5], [3], [9], [10], [20]], "outputs": [[[1, 2, 3, 4, 5]], [[1, 2, 3]], [[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 10,931 |
def monkey_count(n):
|
9a355af393d6dab2304cfed588830b26 | UNKNOWN | Laura really hates people using acronyms in her office and wants to force her colleagues to remove all acronyms before emailing her. She wants you to build a system that will edit out all known acronyms or else will notify the sender if unknown acronyms are present.
Any combination of three or more letters in upper case will be considered an acronym. Acronyms will not be combined with lowercase letters, such as in the case of 'KPIs'. They will be kept isolated as a word/words within a string.
For any string:
All instances of 'KPI' must become "key performance indicators"
All instances of 'EOD' must become "the end of the day"
All instances of 'TBD' must become "to be decided"
All instances of 'WAH' must become "work at home"
All instances of 'IAM' must become "in a meeting"
All instances of 'OOO' must become "out of office"
All instances of 'NRN' must become "no reply necessary"
All instances of 'CTA' must become "call to action"
All instances of 'SWOT' must become "strengths, weaknesses, opportunities and threats"
If there are any unknown acronyms in the string, Laura wants you to return only the message:
'[acronym] is an acronym. I do not like acronyms. Please remove them from your email.'
So if the acronym in question was 'BRB', you would return the string:
'BRB is an acronym. I do not like acronyms. Please remove them from your email.'
If there is more than one unknown acronym in the string, return only the first in your answer.
If all acronyms can be replaced with full words according to the above, however, return only the altered string.
If this is the case, ensure that sentences still start with capital letters. '!' or '?' will not be used. | ["import re\nfrom functools import reduce\n\n_ACRONYMS = {\n 'KPI': 'key performance indicators',\n 'EOD': 'the end of the day',\n 'EOP': 'the end of the day', # snafu in the tests?\n 'TBD': 'to be decided',\n 'WAH': 'work at home',\n 'IAM': 'in a meeting',\n 'OOO': 'out of office',\n 'NRN': 'no reply necessary',\n 'CTA': 'call to action',\n 'SWOT': 'strengths, weaknesses, opportunities and threats'}\n\n_ACRONYM_PATTERN = re.compile(r'\\b[A-Z]{3,}\\b')\n_CAPITAL_PATTERN = re.compile(r'(?:\\. |^)([a-z])')\n_CAPITAL_FIX = lambda match: '{}'.format(match.group(0).upper())\n\ndef acronym_buster(message):\n message = reduce(lambda msg, item: msg.replace(*item), _ACRONYMS.items(), message)\n try:\n acro = next(_ACRONYM_PATTERN.finditer(message)).group(0)\n return '{} is an acronym. I do not like acronyms. Please remove them from your email.'.format(acro)\n except StopIteration:\n return _CAPITAL_PATTERN.sub(_CAPITAL_FIX, message)", "import re\n\nACRONYMS = {\n 'KPI': \"key performance indicators\",\n 'EOD': \"the end of the day\",\n 'TBD': \"to be decided\",\n 'WAH': \"work at home\",\n 'IAM': \"in a meeting\",\n 'OOO': \"out of office\",\n 'NRN': \"no reply necessary\",\n 'CTA': \"call to action\",\n 'SWOT': \"strengths, weaknesses, opportunities and threats\",\n}\nACRONYM_PATTERN = re.compile(r'\\b[A-Z]{3,}\\b')\n\ndef acronym_buster(message):\n new = ACRONYM_PATTERN.sub(lambda m: ACRONYMS.get(m.group(), m.group()), message)\n matched = ACRONYM_PATTERN.search(new)\n if matched:\n return f'{matched.group()} is an acronym. I do not like acronyms. Please remove them from your email.'\n return re.sub('[^.\\s][^.]*', lambda m: m.group()[0].upper() + m.group()[1:], new)", "import re\n\nD = {\"KPI\": \"key performance indicators\",\n \"EOD\": \"the end of the day\",\n \"TBD\": \"to be decided\",\n \"WAH\": \"work at home\",\n \"IAM\": \"in a meeting\",\n \"OOO\": \"out of office\",\n \"NRN\": \"no reply necessary\",\n \"CTA\": \"call to action\",\n \"SWOT\": \"strengths, weaknesses, opportunities and threats\"}\n\nacronym = re.compile(r\"(?:^|(?<=\\W))[A-Z]{3,}(?=\\W|$)\")\ncapital = re.compile(r\"(?:^|(?<=\\.\\s))[a-z]\")\n\ndef acronym_buster(message):\n try:\n return capital.sub(lambda w: w.group().upper(), acronym.sub(lambda w: D[w.group()], message))\n except Exception as e:\n return f\"{str(e)[1:-1]} is an acronym. I do not like acronyms. Please remove them from your email.\"", "def acronym_buster(message):\n acronyms = {\n 'CTA': 'call to action',\n 'EOD': 'the end of the day',\n 'IAM': 'in a meeting',\n 'KPI': 'key performance indicators',\n 'NRN': 'no reply necessary',\n 'OOO': 'out of office',\n 'SWOT': 'strengths, weaknesses, opportunities and threats',\n 'TBD': 'to be decided',\n 'WAH': 'work at home'\n }\n result = []\n for sentence in message.split('.'):\n tmp = []\n for i, word in enumerate(sentence.split()):\n if word.isupper() and len(word) > 2:\n try:\n word = acronyms[word]\n except KeyError:\n return ('{} is an acronym. I do not like acronyms. Please'\n ' remove them from your email.'.format(word))\n tmp.append(word[0].upper() + word[1:] if i == 0 else word)\n result.append(' '.join(tmp))\n return '. '.join(result).rstrip()", "import re\n\nknow_acronyms = {\n 'KPI': \"key performance indicators\",\n 'EOD': \"the end of the day\",\n 'TBD': \"to be decided\",\n 'WAH': \"work at home\",\n 'IAM': \"in a meeting\",\n 'OOO': \"out of office\",\n 'NRN': \"no reply necessary\",\n 'CTA': \"call to action\",\n 'SWOT': \"strengths, weaknesses, opportunities and threats\"\n}\n\ndef acronym_buster(message):\n unknow_acronyms = []\n replace_or_store = lambda a: a in know_acronyms and know_acronyms[a] or unknow_acronyms.append(a)\n cleaned = re.sub(r'\\b[A-Z]{3,}\\b', lambda m: replace_or_store(m.group()), message)\n if unknow_acronyms:\n return '%s is an acronym. I do not like acronyms. Please remove them from your email.' % unknow_acronyms[0]\n else:\n return re.sub('(^|[.!?]) *\\w', lambda m: m.group().upper(), cleaned)", "def acronym_buster(message):\n acronyms = {'KPI' : \"key performance indicators\", \n 'EOD' : \"the end of the day\",\n 'EOP' : \"the end of the day\",\n 'TBD' : \"to be decided\",\n 'WAH' : \"work at home\",\n 'IAM' : \"in a meeting\",\n 'OOO' : \"out of office\",\n 'NRN' : \"no reply necessary\",\n 'CTA' : \"call to action\",\n 'SWOT' : \"strengths, weaknesses, opportunities and threats\"}\n phrases = message.split(\".\")\n word_lists = []\n for phrase in phrases:\n word_lists.append(phrase.split(\" \"))\n for word_list in word_lists:\n for word in word_list:\n if len(word) >= 3 and word.isupper():\n if word in acronyms.keys():\n word_list[word_list.index(word)] = acronyms[word]\n else:\n return \"{} is an acronym. I do not like acronyms. Please remove them from your email.\".format(word)\n phrases = []\n for word_list in word_lists:\n phrase = \" \".join(word_list)\n if len(phrase)>0 and phrase[0].isalpha() and phrase[0].islower():\n phrase = phrase[0].upper() + phrase[1:]\n elif len(phrase)>0 and phrase[0] == \" \" and phrase[1].islower():\n phrase = phrase[0] + phrase[1].upper() + phrase[2:]\n phrases.append(phrase)\n message = \".\".join(phrases)\n return message", "import re\ndef acronym_buster(s):\n d,temp = {'KPI': \"key performance indicators\", 'EOD': \"the end of the day\", 'TBD': \"to be decided\", 'WAH': \"work at home\",\n 'IAM': \"in a meeting\", 'OOO': \"out of office\", 'NRN': \"no reply necessary\", 'CTA': \"call to action\",\n 'SWOT': \"strengths, weaknesses, opportunities and threats\"},[]\n while re.search(r\"\\b[A-Z]{3,}\\b\", s):\n r = re.search(r\"\\b[A-Z]{3,}\\b\", s) ; arn = r.group() ; start, end = r.span()\n if arn in d : s = s[:start] + d[arn] + s[end:]\n else : return f\"{arn} is an acronym. I do not like acronyms. Please remove them from your email.\"\n return \". \".join([i[0].upper()+i[1:] for i in s.split(\". \")])", "import re\n\nd = {\n \"KPI\": \"key performance indicators\", \"EOD\": \"the end of the day\", \"TBD\": \"to be decided\",\n \"WAH\": \"work at home\", \"IAM\": \"in a meeting\", \"OOO\": \"out of office\",\n \"NRN\": \"no reply necessary\", \"CTA\": \"call to action\", \"SWOT\": \"strengths, weaknesses, opportunities and threats\"\n}\n\ndef acronym_buster(s):\n a = []\n def f(x):\n x = x[0]\n if x.isupper() and len(x) > 2:\n if x not in d:\n a.append(x)\n x = d.get(x, \"\")\n return x\n s = re.sub(r\"^.|[!?.] .\", lambda x: x[0].upper(), re.sub(r\"\\w+\", f, s))\n return f\"{a[0]} is an acronym. I do not like acronyms. Please remove them from your email.\" if a else s", "import re\ndef acronym_buster(message):\n new_msg = message\n subs = {'KPI': \"key performance indicators\",\n 'EOD': \"the end of the day\",\n 'TBD': \"to be decided\",\n 'WAH': \"work at home\",\n 'IAM': \"in a meeting\",\n 'OOO': \"out of office\",\n 'NRN': \"no reply necessary\",\n 'CTA': \"call to action\",\n 'SWOT': \"strengths, weaknesses, opportunities and threats\"}\n for item in re.findall('(?:\\w)*[A-Z]{3,}(?:\\w)*', new_msg):\n if item in subs:\n new_msg = new_msg.replace(item, subs[item])\n elif item.isupper():\n return '{} is an acronym. I do not like acronyms. Please remove them from your email.'.format(item)\n # Now capitalize the first \"word\" in each sentence\n sentences = new_msg.split('. ')\n return '. '.join(s[:1].upper() + s[1:] for s in sentences)", "import re\n\ndef acronym_buster(s): \n f = lambda x: all(len(x)>2 and i.isupper() for i in x)\n d = {'KPI': \"key performance indicators\",\n 'EOD': \"the end of the day\",\n 'TBD': \"to be decided\",\n 'WAH': \"work at home\",\n 'IAM': \"in a meeting\",\n 'OOO': \"out of office\",\n 'NRN': \"no reply necessary\",\n 'CTA': \"call to action\",\n 'SWOT': \"strengths, weaknesses, opportunities and threats\"}\n \n for i in re.findall(\"[\\w']+\",s):\n if f(i):\n if i not in d:\n return f'{i} is an acronym. I do not like acronyms. Please remove them from your email.'\n s = s.replace(i,d[i],1) \n \n return '. '.join(i[0].upper() + i[1:] for i in s.split('. '))"] | {"fn_name": "acronym_buster", "inputs": [["BRB I need to go into a KPI meeting before EOD"], ["I am IAM so will be OOO until EOD"], ["Going to WAH today. NRN. OOO"], ["We're looking at SMB on SM DMs today"], ["OOO"], ["KPI"], ["EOD"], ["TBD"], ["TBD by EOD"], ["BRB I am OOO"], ["WAH"], ["IAM"], ["NRN"], ["CTA"], ["Hi PAB"], ["HATDBEA"], ["LDS"], ["PB"], ["FA"], ["CTA and HTTP"], ["SWOT."], ["HTTP"], ["Please WAH today. KPI on track"], ["The advert needs a CTA. NRN before EOD."], ["I sent you a RFP yesterday."], ["My SM account needs some work."]], "outputs": [["BRB is an acronym. I do not like acronyms. Please remove them from your email."], ["I am in a meeting so will be out of office until the end of the day"], ["Going to work at home today. No reply necessary. Out of office"], ["SMB is an acronym. I do not like acronyms. Please remove them from your email."], ["Out of office"], ["Key performance indicators"], ["The end of the day"], ["To be decided"], ["To be decided by the end of the day"], ["BRB is an acronym. I do not like acronyms. Please remove them from your email."], ["Work at home"], ["In a meeting"], ["No reply necessary"], ["Call to action"], ["PAB is an acronym. I do not like acronyms. Please remove them from your email."], ["HATDBEA is an acronym. I do not like acronyms. Please remove them from your email."], ["LDS is an acronym. I do not like acronyms. Please remove them from your email."], ["PB"], ["FA"], ["HTTP is an acronym. I do not like acronyms. Please remove them from your email."], ["Strengths, weaknesses, opportunities and threats."], ["HTTP is an acronym. I do not like acronyms. Please remove them from your email."], ["Please work at home today. Key performance indicators on track"], ["The advert needs a call to action. No reply necessary before the end of the day."], ["RFP is an acronym. I do not like acronyms. Please remove them from your email."], ["My SM account needs some work."]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 9,152 |
def acronym_buster(message):
|
ca00cf3d1ac593bea2de207dc0dd0749 | UNKNOWN | You wrote all your unit test names in camelCase.
But some of your colleagues have troubles reading these long test names.
So you make a compromise to switch to underscore separation.
To make these changes fast you wrote a class to translate a camelCase name
into an underscore separated name.
Implement the ToUnderscore() method.
Example:
`"ThisIsAUnitTest" => "This_Is_A_Unit_Test"`
**But of course there are always special cases...**
You also have some calculation tests. Make sure the results don't get split by underscores.
So only add an underscore in front of the first number.
Also Some people already used underscore names in their tests. You don't want to change them.
But if they are not split correct you should adjust them.
Some of your colleagues mark their tests with a leading and trailing underscore.
Don't remove this.
And of course you should handle empty strings to avoid unnecessary errors. Just return an empty string then.
Example:
`"Calculate15Plus5Equals20" => "Calculate_15_Plus_5_Equals_20"`
`"This_Is_Already_Split_Correct" => "This_Is_Already_Split_Correct"`
`"ThisIs_Not_SplitCorrect" => "This_Is_Not_Split_Correct"`
`"_UnderscoreMarked_Test_Name_" => _Underscore_Marked_Test_Name_"` | ["import re\n\ndef toUnderScore(name):\n return re.sub(\"(?<=[^_-])_?(?=[A-Z])|(?<=[^\\\\d_])_?(?=\\\\d)\", \"_\" , name)", "from re import sub\n\ndef toUnderScore(name):\n return sub('([a-zA-Z](?=[A-Z0-9])|\\d(?=[A-Z]))', r'\\1_', name)", "def toUnderScore(name):\n if len(name) ==0:\n return \"\"\n hold=[]\n for x in name:\n hold.append(x)\n for index, elem in enumerate(hold):\n if index !=0:\n test = hold[index-1]\n if elem.isupper() and test != \"_\":\n hold.insert(index, \"_\")\n if elem.isdigit() and test.isalpha():\n hold.insert(index, \"_\")\n \n output= ''.join(hold)\n return output\n pass", "import re\n\n\ndef toUnderScore(name):\n return re.sub(r\"(?<=[^^_])([A-Z]|\\d+)\", r\"_\\1\", name)", "from functools import partial\nfrom re import compile\n\ntoUnderScore = partial(compile(r\"(?<=[a-zA-Z])(?=[A-Z0-9])|(?<=[0-9])(?=[A-Z])\").sub, r\"_\")", "import re\n\ndef toUnderScore(name):\n if not name: return \"\"\n a = '_'.join([s for s in re.split(r'(_?[A-Z][a-z]*_?|[0-9]+[a-z]*)', re.sub('_', '', name)) if s])\n if name[0] == '_': a = '_' + a\n if name[-1] == '_': a = a + '_'\n return a", "def toUnderScore(s):\n return ''.join('_'+x if (x.isupper() or x.isnumeric()) and not (x.isnumeric() and s[i-1].isnumeric()) and s[i-1] != '_' and i != 0 else x for i, x in enumerate(s))\n", "import re\n\ndef toUnderScore(name):\n return re.sub(r'(?<!^)(?<!_)(\\d+|[A-Z][a-z]*)', r'_\\1', name)", "def toUnderScore(name):\n \n list_of_chars = []\n previous_char = None\n\n for char in name:\n\n if previous_char is not None and char != \"_\" and previous_char != \"_\":\n\n if char.isupper() or char.isdigit() and not previous_char.isdigit():\n list_of_chars.append(\"_\")\n \n list_of_chars.append(char)\n previous_char = char\n\n return \"\".join(list_of_chars)", "import re;toUnderScore=lambda s:re.sub(r\"(?<=[^0-9])(\\d+)\", r\"_\\1\", re.sub(r\"(?<=[^_])([A-Z])(?=[a-z]*)\", r\"_\\1\", s[0]+s[1:-1].replace(\"_\",\"\")+s[-1])) if s else \"\""] | {"fn_name": "toUnderScore", "inputs": [["ThisIsAUnitTest"], ["ThisShouldBeSplittedCorrectIntoUnderscore"], ["Calculate1Plus1Equals2"], ["Calculate15Plus5Equals20"], ["Calculate500DividedBy5Equals100"], ["Adding_3To_3ShouldBe_6"], ["This_Is_Already_Splitted_Correct"], ["ThisIs_Not_SplittedCorrect"], ["_IfATestStartAndEndsWithUnderscore_ItShouldBeTheSame_"], [""]], "outputs": [["This_Is_A_Unit_Test"], ["This_Should_Be_Splitted_Correct_Into_Underscore"], ["Calculate_1_Plus_1_Equals_2"], ["Calculate_15_Plus_5_Equals_20"], ["Calculate_500_Divided_By_5_Equals_100"], ["Adding_3_To_3_Should_Be_6"], ["This_Is_Already_Splitted_Correct"], ["This_Is_Not_Splitted_Correct"], ["_If_A_Test_Start_And_Ends_With_Underscore_It_Should_Be_The_Same_"], [""]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,186 |
def toUnderScore(name):
|
8caf2f1a1f001e74d1cd895a13af65a8 | UNKNOWN | You will be given the prime factors of a number as an array.
E.g: ```[2,2,2,3,3,5,5,13]```
You need to find the number, n, to which that prime factorization belongs.
It will be:
```
n = 2³.3².5².13 = 23400
```
Then, generate the divisors of this number.
Your function ```get_num() or getNum()``` will receive an array with potentially unordered prime factors and should output: an array with the found integer n at index 0, the amount of total divisors (both prime and compound numbers) at index 1, followed the smallest factor (index 2, and the biggest one (last element)
We will see the example given above with the only difference that the array of the prime factors is unordered.
The list of divisors for that number (23400) is:
```
2, 3, 4, 5, 6, 8, 9, 10, 12, 13, 15, 18, 20, 24, 25, 26, 30, 36, 39, 40, 45, 50, 52, 60, 65, 72, 75, 78, 90, 100, 104, 117, 120, 130, 150, 156, 180, 195, 200, 225, 234, 260, 300, 312, 325, 360, 390, 450, 468, 520, 585, 600, 650, 780, 900, 936, 975, 1170, 1300, 1560, 1800, 1950, 2340, 2600, 2925, 3900, 4680, 5850, 7800, 11700 (not considering the integer 23400 itself)
```
There is a total amount of ```71``` divisors. The smallest divisor is ```2``` and the highest ```11700```.
So the expected output will be:
```
get_num([2,13,2,5,2,5,3,3]) == [23400, 71, 2, 11700]
```
Enjoy! | ["def get_num(arr):\n c,n,r=1,1,{}\n arr.sort()\n for a in arr: n*=a; r[a]= r[a]+1 if a in r else 1\n for a in r: c*=r[a]+1 \n return [n,c-1,arr[0],n//arr[0]]", "from collections import Counter\nfrom functools import reduce\nfrom operator import mul\n\ndef get_num(arr):\n n, small = reduce(mul, arr), min(arr)\n count = reduce(mul, (v+1 for v in Counter(arr).values())) - 1\n return [n, count, small, n//small]", "import itertools\nimport functools\nimport operator\n \n\ndef get_num(arr):\n arr.sort()\n counter=0\n for i in range(1,len(arr)+1):\n combu=set(itertools.combinations(arr, i))\n counter+=len(combu)\n minik=min(arr)\n number=functools.reduce(operator.mul,arr)\n biggest=number/minik\n return [number,counter,minik,biggest]", "from functools import reduce\nfrom operator import mul\ndef get_num(a):\n a.sort()\n m = reduce(mul, [i ** a.count(i) for i in set(a)])\n total_d = reduce(mul, [a.count(i) + 1 for i in set(a)])\n return [m,total_d-1,a[0],m//a[0]]", "import itertools\ndef get_num(arr):\n n = 1\n amount = 1\n div = []\n for i in arr:\n n = n * i\n if i not in div:\n amount = amount * (arr.count(i)+1)\n div.append(i)\n lil_div = min(arr)\n big_div = n//lil_div\n \n return [n, amount-1, lil_div, big_div]", "def get_num(arr):\n if len(arr) == 0:\n return []\n \n res = 1\n smallest = arr[0]\n divisors = {}\n for val in arr:\n res *= val\n \n if val < smallest:\n smallest = val\n \n if val not in divisors:\n divisors[val] = 0\n divisors[val] += 1\n \n num_divisors = 1\n for val in divisors:\n num_divisors *= (divisors[val] + 1)\n \n return [res, num_divisors - 1, smallest, res//smallest]", "from collections import Counter\nfrom functools import reduce\nfrom operator import mul\ndef get_num(arr):\n c=Counter(arr)\n x=reduce(mul,arr)\n d=reduce(mul,[v+1 for v in c.values()])-1\n return [x,d,min(arr),x//min(arr)]"] | {"fn_name": "get_num", "inputs": [[[2, 3, 5, 5]], [[2, 3, 3, 3, 7]], [[3, 3, 3, 11]], [[2, 13, 2, 5, 2, 5, 3, 3]]], "outputs": [[[150, 11, 2, 75]], [[378, 15, 2, 189]], [[297, 7, 3, 99]], [[23400, 71, 2, 11700]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,118 |
def get_num(arr):
|
91dced88dfcaf14edae02625663993e1 | UNKNOWN | I'm sure you're familiar with factorials – that is, the product of an integer and all the integers below it.
For example, `5! = 120`, as `5 * 4 * 3 * 2 * 1 = 120`
Your challenge is to create a function that takes any number and returns the number that it is a factorial of. So, if your function receives `120`, it should return `"5!"` (as a string).
Of course, not every number is a factorial of another. In this case, your function would return `"None"` (as a string).
### Examples
* `120` will return `"5!"`
* `24` will return `"4!"`
* `150` will return `"None"` | ["def reverse_factorial(num):\n c = f = 1\n while f < num:\n c += 1\n f *= c\n return 'None' if f > num else \"%d!\" %c", "def reverse_factorial(num):\n n = 1\n f = 1\n while f < num:\n n += 1\n f = f * n\n return f\"{n}!\" if f == num else \"None\"\n \n \n", "from math import factorial\n\nfacts = {factorial(n): n for n in range(1000)}\n\ndef reverse_factorial(num):\n res = facts.get(num, 0)\n return '%s!' % res if res else 'None'", "def reverse_factorial(num):\n i = 1\n while num > 1:\n i += 1\n if num % i != 0: return 'None'\n num //= i\n return f\"{i}!\" if num == 1 else 'None'", "from itertools import count\n\ndef reverse_factorial(num):\n for x in count(1):\n if num == x: return f\"{x}!\"\n num, r = divmod(num, x)\n if r: return \"None\"", "def reverse_factorial(num):\n i = 1\n while 1:\n num, m = num / i, num % i\n if m != 0: return 'None'\n if num == 1: return str(i)+'!'\n i += 1\n", "def reverse_factorial(num):\n s=1 \n i=2\n while s!=num:\n if s > num:\n return 'None'\n s *= i\n i+=1\n return str(i - 1)+'!'", "def reverse_factorial(num):\n c = 1\n while num % c == 0:\n num = num / c\n if num == 1: break\n c += 1\n else:\n return 'None'\n return '{}!'.format(c)\n", "from math import factorial as fact\nD = {fact(v):'{}!'.format(v) for v in range(1,16)}\ndef reverse_factorial(num):\n return D.get(num, 'None')\n", "def reverse_factorial(num):\n if num == 1: return '1!'\n i = 0\n while num > 1:\n i += 1\n num, n = divmod(num, i)\n if n > 0: return 'None'\n return '{}!'.format(i)"] | {"fn_name": "reverse_factorial", "inputs": [[120], [3628800], [150]], "outputs": [["5!"], ["10!"], ["None"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,782 |
def reverse_factorial(num):
|
5f44e15597384573eb1bbb6dc7feb368 | UNKNOWN | **This Kata is intended as a small challenge for my students**
All Star Code Challenge #23
There is a certain multiplayer game where players are assessed at the end of the game for merit. Players are ranked according to an internal scoring system that players don't see.
You've discovered the formula for the scoring system!
Create a function called `scoring()` that takes an array of Player objects and returns an array of player names, in order of descending score (highest score is index 0, 2nd highest is index 1, etc.).
Each player's score is calculated as follows:
1. Each normal kill is worth 100 points
2. Each assist is worth 50 points
3. Each point of damage done is worth .5 points
4. Each point of healing done is worth 1 point
5. The longest kill streak is worth 2^N, where N is the number of kills of the streak
6. Environmental kills are worth 500 points (These are counted separately from normal kills)
For each of the above statistic, a Player object contains a respective "key:value" pairing. All values except the 'name' are integers.
Note:
Assume the input array will ALWAYS have a properly constructed Player object (no missing keys or values)
Names will not contain unusual characters nor repeat (names are unique)
Players with the same score should be sorted by the order they appear in the array
For simplicity, for a kill streak of 0 the kill streak calculation will yield 1 (or 2^(0)) points | ["def scoring(array):\n res = {}\n \n for e in array:\n score = e[\"norm_kill\"] * 100 + e[\"assist\"] * 50 + e[\"damage\"] // 2 +\\\n e[\"healing\"] + 2 ** e[\"streak\"] + e[\"env_kill\"] * 500\n \n res[e[\"name\"]] = score\n \n return sorted(res, key=res.get, reverse=True)", "def scoring(array):\n return [i[\"name\"] for i in sorted(array, key=lambda x: (x[\"norm_kill\"] * 100 + x[\"assist\"] * 50 + x[\"damage\"] * .5 +\n x[\"healing\"] + 2 ** x[\"streak\"] + x[\"env_kill\"] * 500), reverse=True)]", "values = ((\"norm_kill\", (100).__mul__),\n (\"assist\", (50).__mul__),\n (\"damage\", (0.5).__mul__),\n (\"healing\", (1).__mul__),\n (\"streak\", (2).__pow__),\n (\"env_kill\", (500).__mul__))\n\ndef score(player):\n return sum(f(player[k]) for k,f in values)\n\ndef scoring(array):\n return [player[\"name\"] for player in sorted(array, key=score, reverse=True)]", "def scoring(array):\n points= { 'assist': lambda a: a * 50, 'damage': lambda a: a * 0.5, \n 'streak': lambda a: 2**a , 'norm_kill': lambda a: a * 100, \n 'healing': lambda a: a * 1, 'env_kill': lambda a: a * 500 }\n \n sum_score = { e['name']:sum(points[k](v) for k, v in list(e.items()) if isinstance(v , int)) for e in array}\n \n return sorted(sum_score, key=sum_score.get, reverse=True)\n \n", "def score(x):\n return (x['norm_kill'] * 100\n + x['assist'] * 50\n + x['damage'] * 0.5\n + x['healing'] * 1\n + 2 ** x['streak']\n + x['env_kill'] * 500)\n\ndef scoring(array):\n return [x['name'] for x in sorted(array, key=score, reverse=True)]", "COEFS = ((\"norm_kill\", 100), (\"assist\", 50), (\"damage\", .5), (\"healing\", 1), (\"env_kill\", 500))\n\ndef scoring(arr):\n return [p['name'] for p in sorted(arr, key=lambda p: -(sum(p[k]*c for k,c in COEFS) + 2**p['streak']) )]", "def scoring(array):\n scores = []\n output = []\n \n for ply in array:\n score = (ply['norm_kill'] * 100) + (ply['assist'] * 50) + (ply['damage'] * 0.50) + ply['healing'] + (2 ** ply['streak']) + (ply['env_kill'] * 500)\n scores.append((ply['name'], score))\n \n def getScore(tup):\n return tup[1]\n \n players = sorted(scores, key=getScore, reverse=True)\n\n for player in players:\n output.append(player[0])\n \n return output", "def scoring(array):\n res = {e[\"name\"]: e[\"norm_kill\"] * 100 + e[\"assist\"] * 50 + e[\"damage\"] // 2 +\\\n e[\"healing\"] + 2 ** e[\"streak\"] + e[\"env_kill\"] * 500 for e in array}\n \n return sorted(res, key=res.get, reverse=True)", "import operator\n\ncalculations = {\n 'norm_kill': lambda x: x * 100,\n 'assist': lambda x: x * 50,\n 'damage': lambda x: x * .5,\n 'healing': lambda x: x * 1,\n 'streak': lambda x: 2 ** x,\n 'env_kill': lambda x: x * 500\n}\n\n\ndef scoring(array):\n leaderboard = {}\n for player in array:\n score = 0\n for action, value in player.items():\n if action in calculations:\n score += calculations[action](value)\n leaderboard[player['name']] = score\n return [name for name, score in sorted(leaderboard.items(), key=operator.itemgetter(1), reverse=True)]", "def scoring(array):\n score_table = {\"norm_kill\": 100, \"assist\": 50, \"damage\": 0.5, \"healing\": 1, \"env_kill\": 500}\n scores = [(-sum(p[stat]*v for stat, v in score_table.items()) - 2**p[\"streak\"], i, p[\"name\"]) for i, p in enumerate(array)]\n return [name for s, i, name in sorted(scores)]"] | {"fn_name": "scoring", "inputs": [[[]]], "outputs": [[[]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,719 |
def scoring(array):
|
8a8c4905ed1af5ef5ef922c0a62267e7 | UNKNOWN | Given that
```
f0 = '0'
f1 = '01'
f2 = '010' = f1 + f0
f3 = '01001' = f2 + f1
```
You will be given a number and your task is to return the `nth` fibonacci string. For example:
```
solve(2) = '010'
solve(3) = '01001'
```
More examples in test cases. Good luck!
If you like sequence Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) | ["def solve(n):\n a,b = '01'\n for _ in range(n): a,b = a+b,a\n return a", "def solve(n):\n return \"0\" if n == 0 else \"01\" if n == 1 else solve(n-1) + solve(n-2)", "def solve(n):\n a, b = \"0\", \"01\"\n for i in range(0, n):\n a = b + a\n a, b = b, a\n return a\n pass", "def solve(n):\n x, y = '0', '01'\n for i in range(n):\n x, y = y, y+x\n return x", "def solve(n):\n if n < 1: return str(n)\n if n < 2: return solve(n-1) + str(n)\n return solve(n-1) + solve(n-2)", "def solve(n,f='0',g='01'):\n return solve(n-1,g,g+f) if n else f", "def solve(n):\n print(n)\n a = '0'\n b = '01'\n lf = 1\n if n > 1:\n for i in range(n-lf):\n c = b+a\n a = b\n b = c\n return c\n elif n == 1:\n return b\n else:\n return a", "def solve(n):\n if n == 0:\n return \"0\"\n if n == 1:\n return \"01\"\n return f\"{solve(n-1)}{solve(n-2)}\"", "def solve(n):\n FIB = ['0', '01']\n for _ in range(len(FIB), n+1): \n FIB.append(FIB[-1] + FIB[-2])\n return FIB[n]", "def solve(n):\n if n == 0: return '0'\n elif n == 1: return '01'\n else: return solve(n - 1) + solve(n - 2)\n"] | {"fn_name": "solve", "inputs": [[0], [1], [2], [3], [5]], "outputs": [["0"], ["01"], ["010"], ["01001"], ["0100101001001"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,259 |
def solve(n):
|
bb854054325abad3cd37b332d9171ef2 | UNKNOWN | # Leaderboard climbers
In this kata you will be given a leaderboard of unique names for example:
```python
['John',
'Brian',
'Jim',
'Dave',
'Fred']
```
Then you will be given a list of strings for example:
```python
['Dave +1', 'Fred +4', 'Brian -1']
```
Then you sort the leaderboard.
The steps for our example would be:
```python
# Dave up 1
['John',
'Brian',
'Dave',
'Jim',
'Fred']
```
```python
# Fred up 4
['Fred',
'John',
'Brian',
'Dave',
'Jim']
```
```python
# Brian down 1
['Fred',
'John',
'Dave',
'Brian',
'Jim']
```
Then once you have done this you need to return the leaderboard.
All inputs will be valid. All strings in the second list will never ask to move a name up higher or lower than possible eg. `"John +3"` could not be added to the end of the second input list in the example above.
The strings in the second list will always be something in the leaderboard followed by a space and a `+` or `-` sign followed by a number. | ["def leaderboard_sort(leaderboard, changes):\n for change in changes:\n name, delta = change.split()\n idx = leaderboard.index(name)\n leaderboard.insert(idx - int(delta), leaderboard.pop(idx))\n return leaderboard", "def leaderboard_sort(lbd, changes):\n lbd = lbd[:]\n for name,n in map(str.split, changes):\n n,i = int(n), lbd.index(name)\n lbd.pop(i)\n lbd.insert(i-n,name)\n return lbd", "def leaderboard_sort(L, C):\n for c in C:\n n, m = c.split()\n i = L.index(n)\n L.pop(i)\n L.insert(i-eval(m), n)\n return L\n", "def leaderboard_sort(leaderboard, changes):\n for change in changes:\n name, move = change.split()\n value_index = leaderboard.index(name)\n\n leaderboard.remove(name)\n leaderboard.insert(value_index - int(move), name)\n\n return leaderboard", "def leaderboard_sort(leaderboard, changes):\n pos = leaderboard.copy()\n for name, change in map(str.split, changes):\n idx = pos.index(name)\n pos.insert(idx - int(change), pos.pop(idx))\n return pos", "def leaderboard_sort(board, changes):\n for i, e in enumerate(changes):\n name, point = e.split()\n l = board.index(name)\n board.insert( int(eval(f'{l}-({point})')), board.pop(l))\n return board\n", "def leaderboard_sort(leaderboard, changes):\n leaderboard.reverse()\n for user, move in [change.split() for change in changes]:\n index = leaderboard.index(user)\n leaderboard.remove(user)\n leaderboard.insert(eval(\"{}{}\".format(index, move)), user)\n leaderboard.reverse()\n return leaderboard", "def leaderboard_sort(leaderboard, changes):\n for change in changes:\n name, step = change.split()\n step = int(step)\n idx = leaderboard.index(name)\n leaderboard.remove(name)\n leaderboard.insert(idx-step, name)\n return leaderboard", "def leaderboard_sort(leaderboard, changes):\n change_dict = [(i.split()[0],int(i.split()[1])) for i in changes]\n leaderboard = leaderboard.copy()\n for name, change in change_dict:\n name_index = leaderboard.index(name)\n leaderboard.insert(name_index-change, leaderboard.pop(name_index))\n return leaderboard ", "def leaderboard_sort(leaderboard, changes):\n nleaderboard = leaderboard\n for change in changes:\n npos = int(change.split(\" \")[1])\n name = change.split(\" \")[0]\n pos = nleaderboard.index(name)\n if npos>0:\n while npos!=0:\n nleaderboard[pos-1],nleaderboard[pos]=nleaderboard[pos],nleaderboard[pos-1]\n npos= npos - 1\n pos = pos-1\n elif npos<0:\n while npos!=0:\n leaderboard[pos+1],leaderboard[pos]=leaderboard[pos],leaderboard[pos+1]\n npos= npos + 1\n pos = pos+1\n return nleaderboard", "def leaderboard_sort(leaderboard, changes):\n for c in changes:\n curr=leaderboard.index(c.split()[0])\n leaderboard.insert(curr-int(c.split()[1]),leaderboard.pop(curr))\n return leaderboard", "def leaderboard_sort(leaderboard, changes):\n for change in changes:\n name, offset = change.split(' ')\n pos = leaderboard.index(name)\n del leaderboard[pos]\n leaderboard.insert(pos - int(offset), name)\n return leaderboard\n", "def leaderboard_sort(leaderboard, changes):\n leaderboard.reverse()\n length = len(leaderboard)\n for i in changes:\n temp = i.split(' ')\n k = temp[0]\n v = int(temp[1])\n for j in range(length):\n if leaderboard[j] == k:\n if j + v > length-1:\n temp2 = leaderboard.pop(j)\n leaderboard.insert(0, temp2)\n break\n temp2 = leaderboard.pop(j)\n leaderboard.insert(j+v, temp2)\n break\n leaderboard.reverse()\n return leaderboard\n", "def leaderboard_sort(lb, chn):\n for name in chn:\n nm, diff = tuple(name.split())\n diff = int(diff)\n ind = lb.index(nm)\n if diff > 0:\n lb.insert(ind-diff, nm)\n lb.pop(ind+1)\n else:\n lb.insert(ind+abs(diff)+1, nm)\n lb.pop(ind)\n print(lb)\n return lb", "def leaderboard_sort(leaderboard, changes):\n \n for i in range(len(changes)):\n \n loc = leaderboard.index(changes[i].split(\" \")[0])\n \n leaderboard.insert(loc-int(changes[i].split(\" \")[1]),leaderboard.pop(loc))\n \n \n return leaderboard\n \n #loop through changes implementing change\n #find person in board\n #pop them\n #insert back in new position\n", "leaderboard_sort=lambda l,c:(lambda u:(([([0 for u['i'] in [u['d'][o.split()[0]] - int(o.split()[1])]],[(([0 for u['d'][k] in [u['d'][k]+1]] if u['d'][o.split()[0]]>v>=u['i'] else None),([0 for u['d'][k] in [u['d'][k]-1]] if u['d'][o.split()[0]]<v<=u['i'] else None)) for k,v in u['d'].items()],[None for u['d'][o.split()[0]] in [u['i']]]) for o in c],sorted(u['d'].keys(),key=lambda x:u['d'][x]))[1]))({'d':{l[i]:i for i in range(len(l))},'i':0})", "\n\ndef leaderboard_sort(leaderboard, changes):\n data = []\n for change in changes:\n data.append(change.split(' '))\n data[-1][1] = int(data[-1][1])\n \n for change in data:\n curr_i = leaderboard.index(change[0])\n shift_i = curr_i - change[1]\n \n if change[1] < 0: leaderboard.insert(shift_i + 1, leaderboard[curr_i])\n else: leaderboard.insert(shift_i, leaderboard[curr_i])\n \n if shift_i < curr_i: leaderboard.pop(curr_i + 1)\n else: leaderboard.pop(curr_i)\n \n return leaderboard", "def leaderboard_sort(leaderboard, changes):\n for rec in changes:\n name, move = rec.split()\n curr_position = leaderboard.index(name)\n del leaderboard[curr_position]\n new_position = curr_position - int(move)\n leaderboard.insert(new_position, name)\n return leaderboard", "\ndef leaderboard_sort(leaderboard, changes):\n for change in changes:\n name, pos = change.split()\n old_pos = leaderboard.index(name)\n new_pos = eval(f\"{old_pos}-{pos}\")\n if old_pos < new_pos:\n leaderboard = leaderboard[:old_pos] + leaderboard[old_pos+1:new_pos+1] + [name] + leaderboard[new_pos+1:]\n else:\n leaderboard = leaderboard[:new_pos] + [name] + leaderboard[new_pos:old_pos]+ leaderboard[old_pos+1:]\n return leaderboard", "def leaderboard_sort(leaderboard, changes):\n adjustments = leaderboard\n for change in changes:\n adjustment_num = int(change.split(\" \")[1])\n name = change.split(\" \")[0]\n new_place = adjustments.index(name) - adjustment_num\n adjustments.pop(adjustments.index(name))\n adjustments.insert(new_place, name)\n return adjustments"] | {"fn_name": "leaderboard_sort", "inputs": [[["John", "Brian", "Jim", "Dave", "Fred"], ["Dave +1", "Fred +4", "Brian -1"]], [["Bob", "Larry", "Kevin", "Jack", "Max"], ["Max +3", "Kevin -1", "Kevin +3"]]], "outputs": [[["Fred", "John", "Dave", "Brian", "Jim"]], [["Bob", "Kevin", "Max", "Larry", "Jack"]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 7,082 |
def leaderboard_sort(leaderboard, changes):
|
bbb9f97a4e831e381383f8550e6cfc31 | UNKNOWN | Complete the function that determines the score of a hand in the card game [Blackjack](https://en.wikipedia.org/wiki/Blackjack) (aka 21).
The function receives an array of strings that represent each card in the hand (`"2"`, `"3",` ..., `"10"`, `"J"`, `"Q"`, `"K"` or `"A"`) and should return the score of the hand (integer).
~~~if:c
Note: in C the function receives a character array with the card `10` represented by the character `T`.
~~~
### Scoring rules:
Number cards count as their face value (2 through 10). Jack, Queen and King count as 10. An Ace can be counted as either 1 or 11.
Return the highest score of the cards that is less than or equal to 21. If there is no score less than or equal to 21 return the smallest score more than 21.
## Examples
```
["A"] ==> 11
["A", "J"] ==> 21
["A", "10", "A"] ==> 12
["5", "3", "7"] ==> 15
["5", "4", "3", "2", "A", "K"] ==> 25
``` | ["def score_hand(a):\n n = sum(11 if x == \"A\" else 10 if x in \"JQK\" else int(x) for x in a)\n for _ in range(a.count(\"A\")):\n if n > 21:\n n -= 10\n return n", "def score_hand(cards):\n total = 0\n number_of_aces = 0\n for i in cards:\n if i == \"A\":\n total += 1\n number_of_aces += 1\n elif i == \"J\" or i == \"Q\" or i == \"K\":\n total += 10\n else:\n total += int(i)\n if total <= 11 and number_of_aces >= 1:\n total += 10\n return total", "def score_hand(cards):\n s = sum( c=='A' or c.isdigit() and int(c) or 10 for c in cards)\n n = cards.count('A')\n return s + 10 * (n and s<12)", "def score_hand(li):\n s, A = sum(int(i) if i.isdigit() else 10 for i in li if i != 'A'), li.count('A')\n for i in range(A) : s += [1,[11,1][bool(s+11==21 and i+1!=A)]][s+11<=21]\n return s", "def score_hand(cards):\n aces = cards.count(\"A\")\n score = sum( int(card) if card.isdigit() else 10 for card in cards ) + aces\n \n if score > 21:\n for _ in range(aces):\n score -= 10\n if score <= 21:\n break\n \n return score", "def score_hand(cards):\n aces = [i for i in cards if i == 'A']\n cards = list(filter(lambda x: x is not 'A', cards))\n cards.extend(aces)\n total = 0\n for i, card in enumerate(cards):\n if card in ['J', 'Q', 'K']:\n total += 10\n elif card is 'A':\n total += 11 if 11 <= (21 - total) and \"\".join(cards).rindex('A') == i else 1\n else:\n total += int(card)\n return total", "class Jack_score(object):\n\n def __init__(self, cards):\n self.A = cards.count('A')\n self.score = sum([int([[e,'10'][e in 'JQK'],'11'][e=='A']) for e in cards])\n \n def get_score(self):\n while self.A and self.score > 21:\n self.score -= 10\n self.A -= 1\n return self.score\n \ndef score_hand(c):\n return Jack_score(c).get_score()", "def score_hand(cards):\n total = 0\n Ace = 0\n for str in cards:\n if str == \"1\":\n total += 1\n if str == \"2\":\n total += 2\n if str == \"3\":\n total += 3\n if str == \"4\":\n total += 4\n if str == \"5\":\n total += 5\n if str == \"6\":\n total += 6\n if str == \"7\":\n total += 7\n if str == \"8\":\n total += 8\n if str == \"9\":\n total += 9\n if str == \"10\" or str == \"J\" or str == \"Q\" or str == \"K\":\n total += 10\n if str == \"A\":\n Ace += 1\n \n if Ace == 1:\n if total < 11:\n total += 11\n else:\n total += 1\n\n if Ace > 1:\n for i in range(Ace):\n if total < 10:\n total += 11\n else:\n total += 1\n return total", "def score_hand(cards):\n k = 0\n\n for i, x in enumerate(cards):\n if x.isdigit():\n k += int(x)\n\n elif x != 'A':\n k += 10\n \n else:\n k += 1\n \n if k+10 > 21 and 'A' in cards:\n return k\n else:\n if 'A' in cards and k+10 <= 21:\n return k+10\n \n return k", "def score_hand(cards):\n summ = 0\n count_A = 0\n for symb in cards:\n if symb.isdigit():\n summ += int(symb)\n elif symb == 'A':\n count_A += 1\n else:\n summ += 10\n for i in range(count_A):\n summ += 11*(count_A - i) if summ + 11*(count_A - i) <= 21 else 1\n return summ"] | {"fn_name": "score_hand", "inputs": [[["2", "3"]], [["4", "5", "6"]], [["7", "7", "8"]], [["9", "2", "10"]], [["4", "7", "8"]], [["J", "3"]], [["J", "Q"]], [["K", "J", "Q"]], [["A", "3"]], [["A", "J"]], [["A", "A", "A", "J"]], [["A", "2", "A", "9", "9"]], [["A", "A"]], [["8", "A", "A"]], [["5", "4", "A", "A"]], [["A", "2", "A", "3", "A"]], [["A", "A", "A", "A"]]], "outputs": [[5], [15], [22], [21], [19], [13], [20], [30], [14], [21], [13], [22], [12], [20], [21], [18], [14]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,778 |
def score_hand(cards):
|
c54be797d49f5275289ea7df55a3a7da | UNKNOWN | # Task
`N` candles are placed in a row, some of them are initially lit. For each candle from the 1st to the Nth the following algorithm is applied: if the observed candle is lit then states of this candle and all candles before it are changed to the opposite. Which candles will remain lit after applying the algorithm to all candles in the order they are placed in the line?
# Example
For `a = [1, 1, 1, 1, 1]`, the output should be `[0, 1, 0, 1, 0].`
Check out the image below for better understanding:

For `a = [0, 0]`, the output should be `[0, 0].`
The candles are not initially lit, so their states are not altered by the algorithm.
# Input/Output
- `[input]` integer array `a`
Initial situation - array of zeros and ones of length N, 1 means that the corresponding candle is lit.
Constraints: `2 ≤ a.length ≤ 5000.`
- `[output]` an integer array
Situation after applying the algorithm - array in the same format as input with the same length. | ["def switch_lights(initial_states):\n states = list(initial_states)\n parity = 0\n for i in reversed(range(len(states))):\n parity ^= initial_states[i]\n states[i] ^= parity\n return states", "def switch_lights(a):\n n = sum(a)\n for i, x in enumerate(a):\n if n % 2:\n a[i] ^= 1\n n -= x\n return a", "def switch_lights(a):\n s = sum(a)\n result = []\n for i in range(len(a)-1):\n s -= a[i]\n result.append(s%2)\n return result + [0]", "from itertools import accumulate, chain\nfrom operator import xor\n\ndef switch_lights(a):\n return list(accumulate(chain([0], reversed(a)), xor))[-2::-1]", "def switch_lights(a):\n #a=[aa[i] for i in range(len(aa))]\n i=len(a)-1\n s=0\n while i>=0:\n if(a[i]): s+=1\n if(s): a[i]=(a[i]+s)%2\n i-=1\n return a", "def switch_lights(a):\n i, l = sum(a) % 2, []\n for n in a:\n i ^= n\n l.append(i)\n return l", "def switch_lights(a):\n ones = a.count(1)\n for i,x in enumerate(a):\n if ones%2: a[i] = 0 if x else 1\n ones-=x\n\n return a", "def switch_lights(a):\n S = sum(a) % 2\n for i in range(len(a)):\n a[i], S = [a[i], 1-a[i]][S == 1], [S, 1-S][a[i] == 1]\n return a", "def switch_lights(a):\n s = sum(a)\n for i in range(len(a)):\n if s%2:\n s -= a[i]\n a[i] = 1-a[i]\n else:\n s -= a[i]\n return a", "def switch_lights(a):\n z = a[::-1]\n status = 0\n for i in range(len(z)):\n status = status + z[i]\n if status % 2 == 1:\n if z[i] == 1:\n z[i] = 0\n elif z[i] == 0:\n z[i] = 1\n return z[::-1]\n"] | {"fn_name": "switch_lights", "inputs": [[[1, 1, 1, 1, 1]], [[0, 0]], [[1, 0, 0, 1, 0, 1, 0, 1]], [[1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1]]], "outputs": [[[0, 1, 0, 1, 0]], [[0, 0]], [[1, 1, 1, 0, 0, 1, 1, 0]], [[1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,743 |
def switch_lights(a):
|
9cfa5f8f9cd296bad443aa88a8aff49b | UNKNOWN | # Background
My pet bridge-maker ants are marching across a terrain from left to right.
If they encounter a gap, the first one stops and then next one climbs over him, then the next, and the next, until a bridge is formed across the gap.
What clever little things they are!
Now all the other ants can walk over the ant-bridge.
When the last ant is across, the ant-bridge dismantles itself similar to how it was constructed.
This process repeats as many times as necessary (there may be more than one gap to cross) until all the ants reach the right hand side.
# Kata Task
My little ants are marching across the terrain from left-to-right in the order ```A``` then ```B``` then ```C```...
What order do they exit on the right hand side?
# Notes
* ```-``` = solid ground
* ```.``` = a gap
* The number of ants may differ but there are always enough ants to bridge the gaps
* The terrain never starts or ends with a gap
* Ants cannot pass other ants except by going over ant-bridges
* If there is ever ambiguity which ant should move, then the ant at the **back** moves first
# Example
## Input
* ants = ````GFEDCBA````
* terrain = ```------------...-----------```
## Output
* result = ```EDCBAGF```
## Details
Ants moving left to right.
GFEDCBA
------------...-----------
The first one arrives at a gap.
GFEDCB A
------------...-----------
They start to bridge over the gap...
GFED ABC
------------...-----------
...until the ant-bridge is completed!
GF ABCDE
------------...-----------
And then the remaining ants can walk across the bridge.
F
G ABCDE
------------...-----------
And when no more ants need to cross...
ABCDE GF
------------...-----------
... the bridge dismantles itself one ant at a time....
CDE BAGF
------------...-----------
...until all ants get to the other side
EDCBAGF
------------...----------- | ["import re\n\ndef ant_bridge(ants, terrain):\n nGap = sum( 2 + len(gap) - (free == '-') for free,gap in re.findall(r'(-+)(\\.+)', '-'+terrain) ) % len(ants)\n return ants[-nGap:] + ants[:-nGap]", "def ant_bridge(ants, terrain):\n n_ants = len(ants)\n \n terrain = terrain.replace('-.', '..')\n terrain = terrain.replace('.-', '..')\n \n count = terrain.count('.') % n_ants\n \n return ants[-count:] + ants[:-count]", "def ant_bridge(ants, s):\n remain, i = list(ants), 0\n\n while True:\n next_stop = next((k for k, l in enumerate(s[i:-1], i) if s[k + 1] == '.'), None)\n \n if next_stop is None:\n return ''.join(remain)\n \n if next_stop != i or not i : remain.insert(0,remain.pop())\n i = next_stop + 1\n \n while s[i] == '.':\n remain.insert(0,remain.pop())\n i += 1\n remain.insert(0,remain.pop()) ", "def find_next_bridge_end(position, terrain):\n next_bridge_end_position = ''.join(terrain[position:]).find('---')\n if next_bridge_end_position == -1:\n return len(terrain)+1\n \n return next_bridge_end_position + position\n \ndef check_if_bridge_position(i, terrain):\n if i == 0:\n previous_terrain = '-'\n next_terrain = terrain[i+1]\n elif i >= len(terrain)-1:\n previous_terrain = terrain[i-1]\n next_terrain = '-'\n else:\n previous_terrain = terrain[i-1]\n next_terrain = terrain[i+1]\n\n if previous_terrain == '-' and terrain[i] == '-' and next_terrain == '-':\n return False\n return True\n\ndef create_terrain_with_ants(ant_positions, terrain):\n terrain_with_ants = terrain[:]\n for ant, position in list(ant_positions.items()):\n terrain_with_ants[position] = ant\n return ''.join(terrain_with_ants)\n\ndef ant_bridge(ants, terrain):\n platform = ''.join(['-' for _ in range(len(ants))])\n terrain = platform + terrain + platform\n terrain = list(terrain)\n terrain_length = len(terrain)\n \n ant_positions = list(range(len(ants)))\n\n print(ants)\n print((''.join(terrain)))\n\n initial_states = []\n \n if len(ants) >= len(terrain):\n return ants\n \n for i in range(len(ants)):\n if i <= 0:\n previous_terrain = '-'\n current_terrain = terrain[i]\n next_terrain = terrain[i+1]\n elif i >= len(terrain)-1:\n previous_terrain = terrain[i-1]\n current_terrain = terrain[i]\n next_terrain = '-'\n else:\n previous_terrain = terrain[i-1]\n current_terrain = terrain[i]\n next_terrain = terrain[i+1]\n \n if not previous_terrain == '.' and current_terrain == '-' and not next_terrain == '.':\n initial_states.append('')\n else:\n initial_states.append('b')\n \n ant_states = dict(list(zip(ants, initial_states)))\n ant_positions = dict(list(zip(ants[::-1], list(range(len(ants)-1, -1, -1)))))\n \n for k in range(len(ants), terrain_length):\n #print(\"Iteration \" + str(k))\n max_ant_position = max(ant_positions.values())\n min_ant_position = min(ant_positions.values())\n \n #print(create_terrain_with_ants(ant_positions, terrain))\n \n for ant in ants:\n i = ant_positions[ant]\n s = ant_states[ant]\n \n is_end_of_terrain_reached = i >= len(terrain)-2\n \n if is_end_of_terrain_reached:\n terrain = terrain + ['-', '-']\n\n # ant is not part of a bridge and next position cannot be part of a bridge => increment by 1 \n if terrain[i] == '-' and terrain[i+1] == '-' and terrain[i+2] == '-' and s == '':\n ant_positions[ant] = i+1\n ant_states[ant] = ''\n # ant is not part of a bridge and it is at the front of the queue and next position is start of a bridge => increment by 1 and start a bridge\n if terrain[i] == '-' and terrain[i+1] == '-' and terrain[i+2] == '.' and s == '' and i == max_ant_position:\n ant_positions[ant] = i+1\n ant_states[ant] = 'b' \n # ant is not part of a bridge and it is not at the front of the queue and next position is start of a bridge => jump ahead to the front of the queue\n if terrain[i] == '-' and terrain[i+1] == '-' and terrain[i+2] == '.' and s == '' and not i == max_ant_position:\n # DUPLICATED CODE\n next_bridge_end = find_next_bridge_end(i, terrain)\n if next_bridge_end < max_ant_position:\n ant_positions[ant] = next_bridge_end + 1\n else: \n ant_positions[ant] = max_ant_position + 1\n ant_states[ant] = ''\n if check_if_bridge_position(ant_positions[ant], terrain):\n ant_states[ant] = 'b' \n # ant is part of a bridge and it is at the back of the queue => jump ahead to the next bridge end or to the front of the queue\n if s == 'b' and i == min_ant_position:\n next_bridge_end = find_next_bridge_end(i, terrain)\n if next_bridge_end < max_ant_position:\n ant_positions[ant] = next_bridge_end + 1\n else: \n ant_positions[ant] = max_ant_position + 1\n \n ant_states[ant] = ''\n if check_if_bridge_position(ant_positions[ant], terrain):\n ant_states[ant] = 'b'\n \n if is_end_of_terrain_reached:\n terrain = terrain[:len(terrain)-2]\n \n #print(create_terrain_with_ants(ant_positions, terrain)) \n \n return ''.join(sorted(ant_positions, key=ant_positions.get))\n", "from queue import deque\n\n\ndef ant_bridge(ants, terrain):\n terrains = '-' + terrain + '-'\n marching_ants = deque([ant, -len(ants)+count+1] for count, ant in enumerate(ants))\n print(marching_ants)\n bridge_ants = deque()\n # \u5728\u5730\u5f62\u4e0a\u524d\u8fdb\n for pos in range(1, len(terrains)-1):\n if '.' in terrains[pos-1:pos+2]:\n # \u5f53\u524d\u4f4d\u7f6e\u662f\u5751\uff0c\u62ff\u6700\u524d\u9762\u7684\u884c\u8fdb\u8681\u586b\u5751\uff0c\u5176\u4ed6\u7684\u524d\u79fb\u4e00\u6b65,\u5e76\u68c0\u67e5\u662f\u5426\u8981\u62c6\u6389\u6700\u5c3e\u7aef\u7684\u6865\u8681\n leading_ant = marching_ants.pop()\n leading_ant[1] = pos\n bridge_ants.append(leading_ant)\n march_forward(marching_ants, bridge_ants)\n else:\n # \u5f53\u524d\u4f4d\u7f6e\u4e0d\u662f\u5751\uff0c\u6240\u6709\u884c\u8fdb\u8681\u524d\u79fb\u4e00\u6b65\uff0c\u5e76\u68c0\u67e5\u662f\u5426\u8981\u62c6\u6389\u6700\u5c3e\u7aef\u7684\u6865\u8681\n march_forward(marching_ants, bridge_ants)\n # \u5230\u8fbe\u6700\u53f3\u7aef\u540e\uff0c\u7ee7\u7eed\u884c\u8fdb\u6240\u6709\u7684\u8682\u8681\uff0c\u76f4\u5230\u6ca1\u6709\u6865\u8681\u4e3a\u6b62\n while len(bridge_ants) > 0:\n march_forward(marching_ants, bridge_ants)\n return ''.join(ant[0] for ant in marching_ants)\n\n\ndef march_forward(marching_ants, bridge_ants):\n \"\"\"\n \u5c06\u6574\u4e2a\u884c\u8fdb\u8681\u524d\u79fb\u4e00\u683c\uff0c\u5e76\u62c6\u6389\u6700\u5c3e\u7aef\u7a7a\u95f2\u7684\u6865\u8681\n :param marching_ants: \u884c\u8fdb\u8681\u961f\u5217\n :param bridge_ants: \u6865\u8681\u961f\u5217\n \"\"\"\n print(marching_ants, bridge_ants)\n for ant in marching_ants:\n ant[1] += 1\n if len(marching_ants) == 0 or (len(bridge_ants) > 0 and bridge_ants[0][1] < marching_ants[0][1]):\n marching_ants.appendleft(bridge_ants.popleft())", "def ant_bridge(ants, terrain):\n q = [ c for c in ants ]\n terrain = [ c for c in terrain ] + ['-']\n for i in range(len(terrain)-1):\n if terrain[i] == '-' and terrain[i+1] == '.':\n terrain[i] = q.pop()\n q.insert(0, terrain[i])\n elif terrain[i] == '.':\n terrain[i] = q.pop()\n q.insert(0, terrain[i])\n if terrain[i+1] == '-':\n terrain[i+1] = q.pop()\n q.insert(0, terrain[i+1])\n\n rest = \"\".join(q)\n return rest\n", "def ant_bridge(ants, terrain):\n b = 0\n for i, c in enumerate(terrain):\n if c == '.':\n b += 1\n elif b: \n b = b + (1 if terrain[i-2-b] == '.' else 2)\n ants, b = ants[-b:] + ants[:-b], 0\n\n return ants", "ant_bridge=lambda w,s:(lambda n:w[n:]+w[:n])(-len(''.join(__import__('re').findall('(?:-\\.+)+-',s)))%len(w))", "def ant_bridge(ants, terrain):\n n = terrain.replace('-.', '..').replace('.-', '..').count('.') % len(ants)\n return ants[-n:] + ants[:-n]", "def ant_bridge(a, t):\n t=t.replace('-.','..').replace('.-','..').strip('-')\n A,B=list(a),[]\n while t:\n t=t.lstrip('-')[1:]\n B+=[A.pop()if A else B.pop(0)]\n return ''.join(B[::-1]+A)"] | {"fn_name": "ant_bridge", "inputs": [["GFEDCBA", "-----------------------"], ["GFEDCBA", "------------...-----------"], ["GFEDCBA", "------------.....---------"], ["GFEDCBA", "------.....------.....---------"], ["GFEDCBA", "------------...-----..----"], ["CBA", "--.--.---"], ["GFEDCBA", "------....-.---"], ["EDCBA", "--..---...-..-...----..-----"], ["JIHGFEDCBA", "--........------.-........-........---....-----"], ["JIHGFEDCBA", "-.....------........-.......-.......----"], ["JIHGFEDCBA", "-------.......-.......-"], ["JIHGFEDCBA", "-------.......-.......-.......-"], ["GFEDCBA", "-.-.-.-"]], "outputs": [["GFEDCBA"], ["EDCBAGF"], ["GFEDCBA"], ["GFEDCBA"], ["BAGFEDC"], ["CBA"], ["AGFEDCB"], ["EDCBA"], ["GFEDCBAJIH"], ["CBAJIHGFED"], ["GFEDCBAJIH"], ["EDCBAJIHGF"], ["GFEDCBA"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 9,197 |
def ant_bridge(ants, terrain):
|
e96b7b85f9d802a4ab0f1515a347b3a5 | UNKNOWN | Consider the sequence `a(1) = 7, a(n) = a(n-1) + gcd(n, a(n-1)) for n >= 2`:
`7, 8, 9, 10, 15, 18, 19, 20, 21, 22, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 69, 72, 73...`.
Let us take the differences between successive elements of the sequence and
get a second sequence `g: 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1...`.
For the sake of uniformity of the lengths of sequences **we add** a `1` at the head of g:
`g: 1, 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1...`
Removing the 1s gives a third sequence:
`p: 5, 3, 11, 3, 23, 3...`
where you can see prime numbers.
#Task:
Write functions:
```
1: an(n) with parameter n: returns the first n terms of the series a(n) (not tested)
2: gn(n) with parameter n: returns the first n terms of the series g(n) (not tested)
3: countOnes(n) with parameter n: returns the number of 1 in g(n)
(don't forget to add a `1` at the head) # (tested)
4: p(n) with parameter n: returns an array of n unique prime numbers (not tested)
5: maxp(n) with parameter n: returns the biggest prime number of the sequence pn(n) # (tested)
6: anOver(n) with parameter n: returns an array (n terms) of the a(i)/i for every i such g(i) != 1 (not tested but interesting result)
7: anOverAverage(n) with parameter n: returns as an *integer* the average of anOver(n) (tested)
```
#Note:
You can write directly functions `3:`, `5:` and `7:`. There is no need to write functions `1:`, `2:`, `4:` `6:`
except out of pure curiosity. | ["from fractions import gcd\n\ndef seq():\n i, a, g = 1, 7, 1\n while 1:\n yield i, a, g\n i += 1\n g = gcd(i, a)\n a += g\n\ndef count_ones(n):\n return sum(g == 1 for _, (i, a, g) in zip(range(n), seq()))\n\ndef p(n):\n seen = set()\n for i, a, g in seq():\n if not n: break\n if g > 1 and g not in seen:\n n -= 1\n seen.add(g)\n yield g\n\ndef max_pn(n):\n return max(p(n))\n\ndef an_over(n):\n for i, a, g in seq():\n if not n: break\n if g > 1:\n n -= 1\n yield a / i\n\ndef an_over_average(n):\n return sum(an_over(n)) / n", "from fractions import gcd\nfrom sys import maxsize\n\ndef an(length):\n current = 7\n for index in range(length):\n yield current\n current += gcd(index + 2, current)\n\ndef gn(length):\n previous = False\n for current in an(length):\n if previous:\n yield current - previous\n else:\n yield 1\n previous = current\n\ndef pn(length):\n seen = set()\n count = 0\n for current in gn(maxsize):\n if current != 1 and current not in seen:\n seen.add(current)\n count += 1\n yield current\n if count == length:\n break\n\ndef max_pn(length):\n return max(pn(length))\n\ndef an_over(length):\n count = 0\n for i, (a, g) in enumerate(zip(an(maxsize), gn(maxsize))):\n if g != 1:\n count += 1\n yield a / (i + 1)\n if count == length:\n break\n\ndef an_over_average(length):\n return sum(an_over(length)) / length\n\ndef count_ones(length):\n count = 0\n for x in gn(length):\n if x == 1:\n count += 1\n return count", "def count_ones(n):\n a, ones = 7, 1\n for i in range(2, n+1):\n b = a + gcd(i, a)\n if b == a + 1: ones += 1\n a = b\n\n return ones\n\ndef max_pn(n):\n a, p, i = 7, {1}, 1\n \n while len(p) < n + 1:\n i += 1\n b = a + gcd(i, a)\n p.add(b - a)\n a = b\n return max(p)\n\ndef an_over_average(n):\n return 3\n\ndef gcd(a, b):\n while b:\n a, b = b, a % b\n return a", "from math import gcd\n\na, res1, res2, memo = 6, [0], [1], {1}\nfor i in range(1, 1000000):\n x = a + gcd(i, a)\n a, g = x, x-a\n res1.append(res1[-1] + (g == 1))\n if g not in memo:\n res2.append(max(res2[-1], g))\n memo.add(g)\n\ncount_ones = res1.__getitem__\nmax_pn = res2.__getitem__\nan_over_average = lambda _: 3", "from math import gcd\n\n# precalculations\nLIMIT = 10**6\n\n# an(n)\nan = [7]\nfor n in range(2, LIMIT +1):\n an.append( an[-1] + gcd(an[-1], n) )\n\n# gn(n)\ngn = [1] + [ y-x for x, y, in zip(an, an[1:]) ]\n\n# p(n)\nprimes = []\nfor x in gn:\n if x > 1 and x not in primes:\n primes.append(x)\n\n\ndef count_ones(n):\n return gn[:n].count(1)\n\ndef max_pn(n):\n return max(primes[:n])\n\ndef an_over_average(n):\n return 3\n", "from fractions import gcd\n\ndef gn(n):\n prev = 7\n i = 2\n res = [1]\n while (i <= n):\n nou = prev + gcd(prev, i)\n res.append(nou - prev)\n prev = nou\n i += 1\n return res\n\ndef count_ones(n):\n a = [x for x in gn(n) if x == 1]\n return len(list(a))\n\ndef pn(n):\n prev = 7\n i = 2\n res = []\n cnt = 0\n while (cnt < n):\n nou = prev + gcd(prev, i)\n d = nou - prev\n if ((d != 1) and (d not in res)): \n res.append(d)\n cnt += 1 \n prev = nou\n i += 1\n return res\n\ndef max_pn(n):\n return max(pn(n))\n\ndef an_overn(n):\n prev = 7\n i = 2\n res = []\n cnt = 0\n while (cnt < n): \n nou = prev + gcd(prev, i)\n d = nou - prev\n if (d != 1):\n res.append(nou / i)\n cnt += 1 \n prev = nou\n i += 1\n return res\n\ndef an_over_average(n):\n a = an_overn(n)\n return int(sum(a) / len(a))\n", "from math import gcd\nseq = [7]\ndiff = [1]\nfor i in range(2, 100001):\n seq.append(seq[-1] + gcd(i, seq[-1]))\n diff.append(seq[-1] - seq[-2])\nunique = [5, 3, 11, 23, 47, 101, 7, 13, 233, 467, 941, 1889, 3779, 7559, 15131, 53, 30323, 60647, 121403, 242807, 19, 37, 17, 199, 29, 486041, 421, 972533, 577]\ncount_ones=lambda n:diff[:n].count(1)\nmax_pn=lambda n:max(unique[:n])\nan_over_average=lambda n:3*n/n", "def gcd(a, b):\n return a if b == 0 else gcd(b, a % b)\n\ndef count_ones(n):\n a = [6, 7]\n for i in range(2, n + 1):\n a.append(a[i - 1] + gcd(i, a[i - 1]))\n\n return sum([a[i + 1] - a[i] == 1 for i in range(n)])\n\n\ndef max_pn(n):\n a, p, i = 7, {1}, 1\n\n while len(p) < n + 1:\n i += 1\n b = a + gcd(i, a)\n p.add(b - a)\n a = b\n return max(p)\n\ndef an_over_average(n):\n return 3", "from math import gcd\n\na=[7];g=[1];p=[];pn=[];ones=[1];anover=[]\n\nfor i in range(2,1000000):\n c = gcd(a[-1],i)\n g.append(c)\n a.append(a[-1]+c)\n if c!=1: \n p.append(c)\n if c not in pn: pn.append(c)\n ones.append(ones[-1])\n anover.append(a[-1]/i)\n else:\n ones.append(ones[-1]+1)\n\ndef count_ones(n): return ones[n-1]\ndef max_pn(n): return max(pn[:n])\ndef an_over_average(n): return 3"] | {"fn_name": "count_ones", "inputs": [[1], [10], [100], [200], [1000], [10000], [100000]], "outputs": [[1], [8], [90], [184], [975], [9968], [99955]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 5,258 |
def count_ones(n):
|
649011d3c319ad621e0b70ed7c747d6f | UNKNOWN | An element in an array is dominant if it is greater than all elements to its right. You will be given an array and your task will be to return a list of all dominant elements. For example:
```Haskell
solve([1,21,4,7,5]) = [21,7,5] because 21, 7 and 5 are greater than elments to their right.
solve([5,4,3,2,1]) = [5,4,3,2,1]
Notice that the last element is always included.
```
More examples in the test cases.
Good luck! | ["def solve(arr):\n r = []\n for v in arr[::-1]:\n if not r or r[-1] < v: r.append(v)\n return r[::-1]", "def solve(arr):\n return [a for i,a in enumerate(arr) if all(x < a for x in arr[i+1:])]", "def solve(arr):\n return [a for i,a in enumerate(arr) if a > max(arr[i+1:]+[0])]", "def solve(arr):\n return [n for i,n in enumerate(arr) if all(n > x for x in arr[i + 1:])]", "def solve(arr):\n return [n for i, n in enumerate(arr) if n > max(arr[i+1:], default=0)]\n", "def solve(arr):\n return [a for i, a in enumerate(arr[:-1]) if a > max(arr[i+1:])] + [arr[-1]]", "def solve(arr):\n return [a for i,a in enumerate(arr) if all(a>b for b in arr[i+1:])]", "def solve(arr):\n a = set()\n for x in range(len(arr)):\n if arr != []:\n a.add(max(arr))\n arr = arr[(arr.index(max(arr)))+1:]\n\n return sorted(list(a), reverse=True)", "def solve(arr):\n result = arr[-1:]\n for x in arr[-1::-1]:\n if x > result[-1]:\n result.append(x)\n return result[::-1]", "def solve(arr):\n prev = -1\n for i in arr[-1::-1]:\n if i <= prev:\n arr.remove(i)\n else:\n prev = i\n return arr"] | {"fn_name": "solve", "inputs": [[[16, 17, 14, 3, 14, 5, 2]], [[92, 52, 93, 31, 89, 87, 77, 105]], [[75, 47, 42, 56, 13, 55]], [[67, 54, 27, 85, 66, 88, 31, 24, 49]], [[76, 17, 25, 36, 29]], [[104, 18, 37, 9, 36, 47, 28]]], "outputs": [[[17, 14, 5, 2]], [[105]], [[75, 56, 55]], [[88, 49]], [[76, 36, 29]], [[104, 47, 28]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,213 |
def solve(arr):
|
835982749feccdbf16106fab4e082f91 | UNKNOWN | Mr. E Ven only likes even length words.
Please create a translator so that he doesn't have to hear those pesky odd length words.
For some reason he also hates punctuation, he likes his sentences to flow.
Your translator should take in a string and output it with all odd length words having an extra letter (the last letter in the word). It should also remove all punctuation (.,?!) as well as any underscores (_).
"How did we end up here? We go?"
translated becomes->
"Howw didd we endd up here We go" | ["def evenize_word(w):\n return w + w[-1] if len(w) % 2 else w\n\ndef evenator(s):\n s = \"\".join(c for c in s if c.isspace() or c.isalnum())\n return \" \".join(evenize_word(w) for w in s.split())", "def evenator(s):\n return \" \".join([w+w[-1] if len(w)&1 else w for w in \"\".join([c for c in s if c.isalnum() or c == \" \"]).split()])", "from re import sub\n\ndef evenator(s):\n return ' '.join(word + word[-1] if len(word) % 2 else word for word in sub(r'[.,?!_]', '', s).split())", "import re\n\ndef fix(word):\n word = ''.join(c for c in word if c.isalnum())\n if len(word) % 2:\n word += word[-1]\n return word\n\ndef evenator(s):\n return ' '.join(filter(None, map(fix, s.split())))", "evenator = lambda s: ' '.join(e+e[-1] if len(e)%2 else e for e in [''.join(c for c in w if c.isalnum()) for w in s.split()] if e!= '')", "def evenator(s):\n words = [ dupiword(evenatorword(s)) for s in s.split(\" \") ]\n return \" \".join(words).strip()\n \ndef dupiword(s):\n return s+s[len(s)-1] if len(s)%2 else s\n \ndef evenatorword(w):\n return \"\".join([ x if x.isalnum() else '' for x in w]).replace(\" \", \" \")", "import re\ndef evenator(s):\n return \" \".join([w if len(w)%2==0 else w+w[-1] for w in re.sub(r'[!_.?,]', \"\" ,s).split()])", "import re\ndef evenator(s):\n return ' '.join(word if len(word)%2==0 else word+word[-1] for word in re.sub('[.,?!_]','',s).split())"] | {"fn_name": "evenator", "inputs": [["I got a hole in 1!"], ["tHiS sEnTeNcE iS eVeN."], ["underscore is not considered a word..in this case,"], ["hi. how are you? Bye!!"], ["lorem is so ipsum. why bother?"], ["_under the seA!"]], "outputs": [["II gott aa hole in 11"], ["tHiS sEnTeNcE iS eVeN"], ["underscore is nott considered aa wordin this case"], ["hi howw aree youu Byee"], ["loremm is so ipsumm whyy bother"], ["underr thee seAA"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,443 |
def evenator(s):
|
b3c3c08a6d33a425daaab267763a8911 | UNKNOWN | Create a function with two arguments that will return an array of the first (n) multiples of (x).
Assume both the given number and the number of times to count will be positive numbers greater than 0.
Return the results as an array (or list in Python, Haskell or Elixir).
Examples:
```python
count_by(1,10) #should return [1,2,3,4,5,6,7,8,9,10]
count_by(2,5) #should return [2,4,6,8,10]
``` | ["def count_by(x, n):\n return [i * x for i in range(1, n + 1)]", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n return [i * x for i in range(1, n+1)]\n", "def count_by(x, n):\n return [x * i for i in range(1, n+1)]", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n return list(range(x, n * x + 1, x))\n", "def count_by(x, n):\n arr = []\n for num in range(1, n+1):\n result = x * num\n arr.append(result)\n return arr\n", "def count_by(x, n):\n \"\"\"Return a sequence of numbers counting by `x` `n` times.\"\"\"\n return list(range(x, (n+1)*x, x))\n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n num = x\n results = [x]\n\n for i in range(n-1):\n num += x\n results.append(num)\n\n return results\n \n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n my_list = []\n for number in range(1, n + 1):\n my_list.append(x*number)\n return my_list", "count_by = lambda x,y: list(range(x,x*y+1,x))", "def count_by(x, n):\n return [i for i in range(x, x * (n + 1), x)]", "count_by = lambda x,n : list(range(x,n*x+1,x))\n \n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n return [(d+1)*x for d in range(n)]", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n return [e for e in range(x, x * n + x, x)]\n \n", "count_by = lambda x, n: [x * r for r in range(1, n + 1)]\n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n output = []\n i = 1\n while len(output) < n:\n output.append(i*x)\n i += 1\n return output", "count_by = lambda x, n: list([(a + 1) * x for a in range(n)])\n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n lst = []\n y = 0\n while len(lst) < n:\n y += x\n lst.append(y)\n return lst", "from typing import List\n\ndef count_by(x: int, n: int) -> List[int]:\n \"\"\" Return a sequence of numbers counting by `x` `n` times. \"\"\"\n return list(range(x, x * n + 1, x))", "def count_by(x, n):\n count =[]\n for i in range(1, n+1):\n count += [i*x]\n return count\n", "def count_by(x, n):\n\n multiples = [mb * x for mb in range(1, n+1)]\n \n return multiples \n", "def count_by(x, n):\n x1 = x\n res = []\n for i in range(n):\n res.append(x)\n x += x1\n return res\n", "def count_by(x, n):\n lista = []\n d = x\n for i in range(n):\n lista.append(x)\n x += d\n return lista\n", "def count_by(x, n):\n i = 0\n arr = [0] * n\n for i in range(n):\n arr[i] = x * (i+1)\n return arr", "def count_by(x, n):\n array = []\n \n for i in range(x, n*x+1, x):\n array.append(i)\n \n return array\n \n \n \n \n \n", "def count_by(a, n):\n list =[]\n for x in range(1, n+1):\n list.append(x)\n list2=[]\n for x in list:\n list2.append(x*a)\n return list2\n", "def count_by(x, n):\n return list(range((n+1)*x)[::x])[1:]\n", "def count_by(x, n):\n \n x = list(range(x,n*x+1,x))\n return x\n\n\n\n", "def count_by(x, n):\n return [i for i in range(0, n*x+1, x)][1:]", "def count_by(x, n):\n multiples_of_x = []\n for number in range(1, n + 1):\n multiples_of_x.append(number * x)\n \n return multiples_of_x\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n", "def count_by(x, n):\n y = []\n ind = 1\n for i in range(n):\n y.append((x * ind))\n ind += 1\n return y", "def count_by(x, n):\n i = 0\n number = 0\n list = []\n while i < n:\n i += 1\n number += x\n list.append(number)\n return list\n", "def count_by(x, n):\n arr = []\n for num in range(x, x * (n + 1), x):\n arr.append(num)\n return arr\n", "def count_by(x, n):\n lis = []\n i = 1\n while i <= n:\n a = x*i\n i+=1\n lis.append(a)\n return lis\n", "def count_by(x, n):\n output=[]\n for i in range(n):\n output.append((i+1)*x)\n return output\n \n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n array = []\n number = 0\n m = x\n while number < n:\n array.append(m)\n m += x\n number += 1\n return array", "def count_by(x, n):\n return list(range(0, (n+1)*x, x)[1:])\n\nprint(count_by(2, 5))", "def count_by(x, n): \n mul = x * n\n arr = [i for i in range(x, mul + 1, x)]\n return arr\n", "count_by=lambda x,n:[*range(x,x*n+x,x)]", "def count_by(x, n):\n return [i for i in range(0+x , n*x+x, x)]\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n", "def count_by(x, n):\n arr = [0]\n for i in range(n):\n arr.append(arr[-1] + x)\n return arr[1:]", "def count_by(x, n):\n i = 1\n count_list = []\n while i <= n:\n count_list.append(x * i)\n i += 1\n return count_list\n \n", "def count_by(x, n):\n number = []\n for i in range(1,n+1):\n num = x*i\n number.append(num)\n return number\n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n lis = []\n i = 1\n while len(lis) < n:\n if i % x == 0:\n lis.append(i)\n i += 1\n \n return lis\n", "def count_by(x, n):\n multiplier = [i for i in range(1, (n + 1))]\n return [x * y for y in multiplier]", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n \n count = []\n total = 0\n \n while n > 0:\n total += x\n count.append(total)\n n -= 1\n \n return count\n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n product = x*n\n result =list(range(x,product+1,x))\n return result \n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n return list(x * n for n in range(1,n+1))\n", "def count_by(x, n):\n arr = []\n collect = x\n for i in range(n):\n arr.append(collect)\n collect += x\n \n \n return arr\n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n \n list = []\n y = x\n \n while len(list) < n:\n list.append(y)\n y += x\n \n return list", "def count_by(x, n):\n result = []\n y=1\n for number in range (n):\n result.append(x*y)\n y += 1\n return result\n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n r = []\n z = 1\n while z <= n:\n y = x * z\n r.append(y)\n z = z + 1\n return r", "def count_by(x, n):\n counter = 0\n multiples = []\n i = 1\n while counter < n :\n if i % x == 0:\n counter += 1\n multiples.append(i)\n i += 1\n \n return multiples\n", "def count_by(x, n):\n ans = []\n i = x\n count = 0\n while count < n:\n ans.append(i)\n i += x\n count += 1\n return ans ", "def count_by(x, n):\n answer = []\n for x in range(x, n*x + x, x):\n answer.append(x)\n return answer\n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n y = x\n df = []\n i = 1\n while i < n+1:\n x = x\n df.append(x)\n x = x+y\n i += 1\n return df", "def count_by(x, n):\n i=1\n return [i*x for i in range(n+1)[1:]]", "count_by = lambda x, n:list(range(x,(n+1)*x,x))", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n res = []\n num = x\n while n > 0:\n res.append(num)\n num += x\n n -= 1\n return res\n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n new_list = []\n tracker = 1\n \n while tracker <= n:\n new_list.append(tracker * x)\n tracker += 1\n \n return new_list\n \n", "def count_by(x, n):\n p1 = list(range(x, (x*n+1), x))\n return p1\n", "def count_by(x, n):\n a = [i for i in range(x, x*n + 1) if i % x == 0]\n return a[:n + 1]\n", "from typing import List, Union\n\ndef count_by(x: Union[int,float], n: int) -> List[Union[int,float]]:\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n return [x*it for it in range(1,n+1)]\n", "count_by = lambda start, end: list(range(start, start*end+1, start))\n", "def count_by(x, n):\n count = 1\n i = 1\n L = []\n while count <= n:\n if i % x == 0:\n L.append(i)\n count += 1\n i += 1\n return L\n", "def count_by(x, n):\n a = x*n\n s = []\n for i in range(x,a+1):\n if i%x == 0:\n s.append(i)\n return s\n", "def count_by(x, n):\n start = x\n result = list()\n while start <= x * n:\n result.append(start)\n start += x\n return result", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n if x == 1:\n return [x for x in range(x, n+1)]\n else:\n y = [x, (n*x)]\n z = []\n for j in range(1, n+1):\n z.append(y[0]*j)\n return z\n", "def count_by(x, n):\n list = []\n for i in range(1,n+1):\n a = x*i\n list.append(a)\n i += 1\n return list\n", "def count_by(x, n):\n return list(map(lambda num: x * num, range(1, n + 1)))", "def count_by(x, n):\n res = []\n sum = 0\n for i in range(n):\n sum += x\n res.append(sum)\n return res", "def count_by(n, x):\n results=[]\n s=n\n for i in range (1, x+1):\n results.append(s)\n s=s+n\n return results", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n res = []\n c = 0\n for i in range(n):\n c += x\n res.append(c)\n return res", "count_by = lambda x,y: [x*i for i in range(1,y+1)]", "def count_by(x, n):\n y = x\n result = [x]\n for i in range(n-1):\n y += x\n result.append(y)\n return result\n", "def count_by(x, n):\n list = []\n for multiplier in range(n):\n list.append(x*(multiplier+1))\n return list\n \n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n result = (x*z for z in range(1,n+1))\n \"\"\"\n for z in range(1,n+1):\n result.append(x*z)\n \"\"\"\n return list(result)", "def count_by(x, n):\n \"\"\"\n Returns a sequence of numbers counting by 'x' 'n' times.\n \"\"\"\n return [num for num in range(x, x * n + 1, x)]", "def count_by(x, n):\n \n# =============================================================================\n# This function given two arguments returns an array of the first (n) multiples of (x). \n# \n# Both the given number and the number of times to count will be positive \n# numbers greater than 0.\n# \n# The function returns the result as a list.\n# Examples:\n# count_by(1,10) ==> [1,2,3,4,5,6,7,8,9,10]\n# count_by(2,5) ==> [2,4,6,8,10]\n# =============================================================================\n \n result = []\n \n for n in range(1,(n+1)):\n result.append(n * x)\n \n return result\n", "def count_by(x, n):\n result = list();\n temp = x\n for i in range(n):\n result.append(x)\n x += temp\n return result ", "def count_by(x, n):\n l=[]\n z=x\n for i in range (0,n):\n l.append(x)\n x+=z\n return l", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n new_list = []\n y = 0\n for count in range(n):\n new_list.append(y + x)\n y = (y + x)\n return new_list", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n i = 1\n rl = []\n while i <= n:\n rl.append(i*x)\n i += 1\n return rl", "def count_by(x, n):\n return [n for n in list(range(x, n*x + 1, x))]", "def count_by(x, n):\n multiplesList = []\n for i in range(1,n+1): \n multiplesList.append(x*i)\n return multiplesList\n", "def count_by(x, n):\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n w = []\n k = 0\n for i in range(n):\n k = k + x\n w.append(k)\n return w\n", "def count_by(x, n):\n min = x\n arr = [x]\n for i in range(n-1):\n min += x\n arr.append(min)\n return arr\n", "def count_by(x, n):\n numbers = []\n for i in range(x,x*n+x,x):\n numbers.append(i)\n return numbers", "def count_by(x, n):\n curr = range(x, (x*n)+x, x)\n list = []\n for x in curr:\n list.append(x)\n return list", "def count_by(x, n):\n '''Listen little mukas, I know this isnt the most elegant but I'm exhausted'''\n return [element*x for element in list(range(1,n+1))]", "def count_by(x, n):\n array = []\n for n in range(1, n+1):\n array.append(x*n)\n return array\n", "def count_by(x, n):\n return list(i for i in range(x,x*n+1,x))\n", "def count_by(x, n):\n count = 1\n value = 0\n numberList = []\n while count <= n:\n value = value + x\n numberList.append(value)\n count = count + 1\n return numberList\n \n \n \n \n", "def count_by(x, n):\n list_result = []\n last_entry = 0\n for i in range(n):\n last_entry += x\n list_result.append(last_entry)\n return list_result\n \"\"\"\n Return a sequence of numbers counting by `x` `n` times.\n \"\"\"\n", "def count_by(x, n):\n my_List = list(range(x, (n*x)+x, x))\n return my_List\n", "def count_by(x, n):\n counter = 1\n s = 0\n lst = []\n while counter <= n:\n s += x\n lst.append(s)\n counter += 1\n return lst", "def count_by(n, x):\n return [i for i in range(n, (x + 1) * n) if i % n == 0]"] | {"fn_name": "count_by", "inputs": [[1, 5], [2, 5], [3, 5], [50, 5], [100, 5]], "outputs": [[[1, 2, 3, 4, 5]], [[2, 4, 6, 8, 10]], [[3, 6, 9, 12, 15]], [[50, 100, 150, 200, 250]], [[100, 200, 300, 400, 500]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 14,873 |
def count_by(x, n):
|
c88add7585af883db751c26fdadd2273 | UNKNOWN | In mathematics, a **pandigital number** is a number that in a given base has among its significant digits each digit used in the base at least once. For example, 1234567890 is a pandigital number in base 10.
For simplification, in this kata, we will consider pandigital numbers in *base 10* and with all digits used *exactly once*. The challenge is to calculate a sorted sequence of pandigital numbers, starting at a certain `offset` and with a specified `size`.
Example:
```python
> get_sequence(0, 5)
[1023456789, 1023456798, 1023456879, 1023456897, 1023456978]
```
Rules:
- We are looking for positive pandigital numbers in base 10.
- Each digit should occur `exactly once`.
- A pandigital number can't start with digit zero.
- The offset is an integer (negative, zero or positive number) (long in Java)
- The size is a positive integer number (int in Java)
- Return the `size` pandigital numbers which are not smaller than the `offset`. If there is not enough `size` pandigital numbers, just return all of them.
- Return an empty array if nothing is found. | ["def get_sequence(o,s,st=1023456789):\n li = []\n for i in range([st,o][o>0 and o>st],9876543211):\n i = str(i)\n if i[0]!='0' and len(set(i))==10 : li.append(int(i))\n if len(li)==s : break\n return li ", "from itertools import permutations\nfrom bisect import bisect_left\n\nmemo = [int(''.join(x)) for x in permutations(\"0123456789\") if x[0] != '0']\n\ndef get_sequence(offset, size):\n i = bisect_left(memo, offset)\n return memo[i:i+size]", "pandigital = [int(''.join(p)) for p in __import__('itertools').permutations('0123456789')][2*3*4*5*6*7*8*9:]\nget_sequence = lambda offset, size: (lambda idx: pandigital[idx: idx + size])(__import__('bisect').bisect_left(pandigital, offset))", "def is_pand(n):\n return len(set(list(str(n)))) == len(str(n))\n\ndef next_pan(n):\n while True:\n if is_pand(n):yield n\n n += 1\n\ndef get_sequence(n, k):\n if n < 1023456789: n = 1023456789\n elif n >= 9999999999: return []\n if not is_pand(n): n = next(next_pan(n))\n res = []\n for i in next_pan(n):\n res.append(i)\n if len(res)== k: break\n return res\n\n", "def get_sequence(offset, size):\n i, re = 1023456789 if offset < 1023456789 else offset, []\n while i <= 9876543210 and len(re) < size:\n if sorted('0123456789') == sorted(str(i)):\n re.append(i)\n i += 1\n return re", "END = 9876543211\n\ndef get_sequence(offset, size):\n number = 1023456789\n sequence = []\n\n if offset < number:\n offset = number\n\n for element in range(offset, END):\n if check_number(element):\n sequence.append(element)\n\n if len(sequence) == size:\n break \n\n return sequence\n \ndef check_number(number):\n seq = set(str(number))\n\n\n return len(seq) == 10\n\n", "def get_sequence(offset, size):\n out = []\n if offset < 1023456789:\n offset = 1023456789\n while len(out) < size and offset < 9876543211:\n if sorted(str(offset)) == ['0','1','2','3','4','5','6','7','8','9']:\n out.append(offset)\n offset += 1\n return out\n\n", "def get_sequence(offset, size):\n result = []\n if offset < 1023456789:\n offset = 1023456789\n while len(result) < size and offset < 10000000000:\n if len(set(str(offset))) == 10:\n result.append(offset)\n offset += 1\n return result", "def get_sequence(offset, size):\n num = max(offset, 1023456789)\n digits = set(\"0123456789\")\n ret = []\n for _ in range(size):\n while num < 9876543210:\n if set(str(num)) == digits:\n ret.append(num)\n break\n else:\n num += 1\n num += 1\n \n return ret", "\nfrom itertools import permutations as perms\n\ndef is_pand(n):\n return len(set(list(str(n)))) == len(str(n))\n\ndef next_pan(n):\n while True:\n if is_pand(n):yield n\n n += 1\n\ndef get_sequence(n, k):\n if n < 1023456789: n = 1023456789\n elif n >= 9999999999: return []\n if not is_pand(n): n = next(next_pan(n))\n res = []\n for i in next_pan(n):\n res.append(i)\n if len(res)== k: break\n return res\n"] | {"fn_name": "get_sequence", "inputs": [[0, 5], [5432160879, 3], [9876543000, 5], [9999999999, 1], [-123456789, 1], [-9999999999, 25]], "outputs": [[[1023456789, 1023456798, 1023456879, 1023456897, 1023456978]], [[5432160879, 5432160897, 5432160978]], [[9876543012, 9876543021, 9876543102, 9876543120, 9876543201]], [[]], [[1023456789]], [[1023456789, 1023456798, 1023456879, 1023456897, 1023456978, 1023456987, 1023457689, 1023457698, 1023457869, 1023457896, 1023457968, 1023457986, 1023458679, 1023458697, 1023458769, 1023458796, 1023458967, 1023458976, 1023459678, 1023459687, 1023459768, 1023459786, 1023459867, 1023459876, 1023465789]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,258 |
def get_sequence(offset, size):
|
0782d5a1f3a5f97043cd87321fbd1834 | UNKNOWN | Write a function to split a string and convert it into an array of words. For example:
```python
"Robin Singh" ==> ["Robin", "Singh"]
"I love arrays they are my favorite" ==> ["I", "love", "arrays", "they", "are", "my", "favorite"]
``` | ["def string_to_array(string):\n return string.split(\" \")", "def string_to_array(string=''):\n return string.split() if string else ['']", "def string_to_array(s):\n return s.split(' ')", "def string_to_array(string):\n array = string.split(' ')\n return array", "def string_to_array(string):\n return string.split() or ['']", "def string_to_array(s):\n words = []\n if s == '':\n words.append(s)\n else:\n words = s.split()\n return words\n", "def string_to_array(string):\n return string.split() if string else [\"\"]", "def string_to_array(s):\n return s.split(\" \") #Single space is delimiter\n# Look how easy Python is :o\n", "def string_to_array(s):\n word = s.split(\" \")\n return word", "def string_to_array(s):\n # your code here\n if s is '':\n return s.split(',')\n else:\n return s.split()\n", "def string_to_array(s):\n arr = []\n \n words = s.split(\" \")\n if len(s) == 0:\n return [\"\"]\n \n for word in words:\n arr.append(word)\n \n return arr", "def string_to_array(s):\n lst = []\n split_s = s.split()\n if s == \"\":\n lst.append(\"\")\n for letter in split_s:\n lst.append(letter)\n return lst", "string_to_array = lambda s: s.split() or [\"\"]", "def string_to_array(string):\n i = string.split(\" \") \n return i", "def string_to_array(string):\n \n retList=list()\n retList=(string.split(\" \"))\n \n return retList\n", "def string_to_array(string):\n\n new_string = string.split(' ')\n \n text = []\n \n for i in new_string:\n text.append(i)\n \n return(text)", "def string_to_array(s):\n # your code here\n result = []\n t = ''\n e = ' '\n for i in s:\n if i not in e:\n t = t + i\n else:\n result.append(t)\n t = ''\n result.append(t)\n return result\n\n", "def string_to_array(s):\n arr = []\n temp = ''\n for i in s:\n if i != ' ':\n temp += i\n else:\n arr += [temp]\n temp = ''\n arr += [temp]\n return arr", "from re import findall\ndef string_to_array(s):\n return findall(r'\\w+',s) or ['']", "import re\ndef string_to_array(s):\n\n # your code here\n return re.split(r'[;,\\s]\\s*', s) ", "def string_to_array(s):\n return s.split() if s else [s]", "def string_to_array(s):\n return [s.split(), [\"\"]][not s]", "def string_to_array(s: str) -> list:\n return s.split(' ')", "string_to_array = lambda x: x.split(\" \")", "def string_to_array(s):\n if len(s) == 0:\n return ['']\n else:\n lst = s.split()\n return lst", "string_to_array = lambda s : s.split() if bool(s) else ['']\n", "def string_to_array(s):\n return [''] if not(len(s)) else s.split()", "def string_to_array(s):\n # your code here\n if len(s) > 1:\n new = s.split()\n else:\n new = ['']\n return new", "def string_to_array(s):\n return [item for item in s.split(' ')]", "def string_to_array(s):\n # your code here\n l=[]\n if(s==\"\"):\n l.append(\"\")\n return l\n else:\n for i in s.split():\n l.append(i)\n return l", "def string_to_array(s):\n if len(s) == 0:\n _list = []\n _list.append('')\n return _list\n return list(s.split())", "def string_to_array(string):\n str = string.split(' ')\n return(str)", "def string_to_array(s):\n if s == \"\":\n return [\"\"]\n return [i for i in s.split()]", "def string_to_array(s):\n r = ['']\n if s:\n r = s.split()\n return r", "def string_to_array(s):\n return list(s.split()) if list(s) else [\"\"]\n", "def string_to_array(s):\n ll = list(s.split(' '))\n return ll", "def string_to_array(s):\n if s == '':\n return ['']\n s_list = []\n split_string = s.split()\n for word in split_string:\n s_list.append(word)\n return s_list", "def string_to_array(s):\n a = s.split(' ')\n return a\n \nprint(string_to_array('I are arrays favorites love my they'))", "# Write a function to split a string and convert it into an array of words. \n# For example:\n# \"Robin Singh\" ==> [\"Robin\", \"Singh\"]\n\n\ndef string_to_array(s):\n return s.split() if s != \"\" else [\"\"]", "def string_to_array(s):\n return [s] if not s else s.split()\n", "def string_to_array(s):\n final_array = s.split(' ')\n return(final_array)", "def string_to_array(s):\n new_words = s.split(\" \")\n return new_words\n\n", "def string_to_array(s: str) -> list:\n return s.split() if s else [\"\"]", "def string_to_array(s):\n k=s.split()\n if s==\"\":\n return [s]\n else:\n return k", "def string_to_array(s):\n pog = s.split(\" \")\n return pog ", "def string_to_array(s):\n # your code here\n if s: \n \n return list(s.split())\n else:\n return ['']", "def string_to_array(s):\n array = []\n tmp_string = \"\"\n for i in s:\n if i == ' ':\n array.append(tmp_string)\n tmp_string = \"\"\n else:\n tmp_string = tmp_string + i\n array.append(tmp_string)\n return array\n", "def string_to_array(s):\n # your code here\n if len(s) >= 1:\n words = s.split()\n return words\n else:\n return [\"\"]", "def string_to_array(s):\n if s == \"\":\n return [\"\"]\n k = s.split()\n return k", "string_to_array = lambda s: s and s.split() or [\"\"]", "def string_to_array(s):\n sList = list(s.split(\" \"))\n return sList", "def string_to_array(s):\n return s.split and s.split(\" \")\n", "def string_to_array(s):\n if len(s) <= 0:\n return ['']\n else:\n l = s.split()\n return list(l)", "def string_to_array(s: str) -> list:\n return list(s.split()) if s else [\"\"]\n", "def string_to_array(s):\n # your code here\n return s.split(\" \")\nstring_to_array(\"Basic tests\")", "def string_to_array(s):\n text = []\n text = s.split(\" \")\n return text", "def string_to_array(s):\n words = \"\"\n answer = []\n for i in s:\n if i == \" \":\n answer.append(words)\n words = \"\"\n else: words += i\n answer.append(words)\n return answer", "def string_to_array(s):\n c = []\n for x in s.split():\n c.append(x)\n if len(s) == 0 :\n return [\"\"]\n return c", "def string_to_array(s):\n words = s.split()\n if not words:\n words.insert(0 , \"\")\n return words", "def string_to_array(s):\n con = s.split(\" \")\n return con", "def string_to_array(s):\n \"\u041f\u0440\u0435\u0432\u0440\u0430\u0449\u0430\u0435\u043c \u0441\u0442\u0440\u043e\u043a\u0443 \u0432 \u0441\u043f\u0438\u0441\u043e\u043a\"\n n_s = list(s.split(\" \"))\n return n_s", "def string_to_array(s):\n # your code here\n s=s.replace(\" \",\",\")\n return s.split(\",\")", "def string_to_array(stroca):\n return stroca.split(\" \")", "def string_to_array(s):\n s=s.split(' ')\n list(s)\n return s\n", "#best practice\n\n# The split() method splits a string into a list.\n# You can specify the separator, default separator is any whitespace.\n\ndef string_to_array(string):\n return string.split(\" \")", "#best practice\ndef string_to_array(string):\n return string.split(\" \")", "def string_to_array(s):\n if s == \"\":\n return [\"\"]\n else:\n return (str.split(s))", "def string_to_array(s):\n if s is \"\":\n return [\"\"]\n l = list()\n for i in s.split():\n l.append(i)\n return l", "def string_to_array(s):\n return [s.split(), ['']][s == '']", "def string_to_array(s):\n if s == '':\n return ['']\n else:\n words = s.split()\n for word in words:\n return(words)", "def string_to_array(s):\n return [str(w) for w in s.split()] if len(s) else ['']", "ans = []\ndef string_to_array(s):\n ans = s.split()\n if s == \"\":\n ans = [\"\"]\n return ans\n # your code here\n", "def string_to_array(s):\n return s.split() if s else list(('',)) # :/", "def string_to_array(s):\n return s.split() if len(s) >= 1 else ['']", "def string_to_array(s):\n string_list = s.split(\" \")\n return string_list", "def string_to_array(s):\n if len(s)>1: #if string has characters\n return s.split() #split string into pieces\n else: \n return ['']", "def string_to_array(s):\n # your code here\n \n res = s.split()\n \n if len(s) == 0:\n return [\"\"]\n \n return res", "def string_to_array(s):\n s = s.split()\n if list(s) == []:\n return['']\n else:\n return list(s)", "def string_to_array(s):\n return s.split() if len(s.split()) != 0 else [\"\"]", "def string_to_array(s):\n if s == \"\":\n res = [s]\n else:\n res = s.split()\n return res", "def string_to_array(s):\n if s:\n arr = s.split()\n return arr\n else:\n return ['']", "def string_to_array(s):\n return ([''],s.split()) [s != '']", "def string_to_array(s):\n p = s.split(\" \")\n return p\n", "def string_to_array(s):\n res = s.split(' ')\n return res\n", "def string_to_array(s):\n if s == \"\": \n return s.split(\",\") \n else: \n return s.split()", "def string_to_array(s):\n # your code here\n if len(s)>0:\n return s.split()\n else:\n return ['']\n# return s.split()\n", "def string_to_array(s):\n if len(s):\n return s.split()\n return ['']", "import re\ndef string_to_array(s):\n return re.split(r'\\s', s)", "import re\ndef string_to_array(s):\n return re.split(\"\\s\", s)", "def string_to_array(s):\n # your code here\n return s.split() if s > '' else [\"\"]", "def string_to_array(s):\n s = str(s)\n if s == '':\n return s.split(',')\n else:\n return s.split()", "def string_to_array(s):\n return list(s.split()) or ['']", "#input - string\n#output - list/array of words\n#edge cases - no input given, integer or other data type given\n#assumptions - I need to take a string and return a list of the words in the string. \n\n#sample data - (\"Robin Singh\"), [\"Robin\", \"Singh\"]\n#do I need to create a separate array? no\n#I can just use string split function\n\n\n#function string_to_array(string)\ndef string_to_array(s):\n return s.split(' ')\n", "def string_to_array(s):\n return s.split() if s != \"\" else \"\".split(\",\")", "def string_to_array(s):\n return list(filter(lambda x : x , s.split(\" \"))) if s else [\"\"]", "def string_to_array(s):\n import re\n arr = []\n if s == '':\n arr = ['']\n else:\n pattern = '(\\w+)'\n arr = re.findall(pattern, s)\n return arr", "def string_to_array(s): \n arr = []\n if s == '':\n arr = ['']\n else:\n import re\n pattern = '(\\w+)'\n arr = re.findall(pattern, s)\n return arr", "def string_to_array(s): \n arr = []\n if s == '':\n arr = ['']\n else:\n import re\n pattern = '(\\w+)' \n arr = re.findall(pattern, s)\n arr = [x.strip(' ') for x in arr]\n return arr \n \n \n", "def string_to_array(s):\n if s == '':\n array = ['']\n else:\n array = []\n s = s.split()\n for i in s:\n array.append(i)\n return array", "def string_to_array(s):\n res = []\n for i in s.split(\" \"):\n res.append(i)\n return res"] | {"fn_name": "string_to_array", "inputs": [["Robin Singh"], ["CodeWars"], ["I love arrays they are my favorite"], ["1 2 3"], [""]], "outputs": [[["Robin", "Singh"]], [["CodeWars"]], [["I", "love", "arrays", "they", "are", "my", "favorite"]], [["1", "2", "3"]], [[""]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 11,709 |
def string_to_array(s):
|
ab2d43dae7162a0394766c6fa37db162 | UNKNOWN | Bob is preparing to pass IQ test. The most frequent task in this test is `to find out which one of the given numbers differs from the others`. Bob observed that one number usually differs from the others in **evenness**. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number.
`!` Keep in mind that your task is to help Bob solve a `real IQ test`, which means indexes of the elements start from `1 (not 0)`
##Examples :
```python
iq_test("2 4 7 8 10") => 3 // Third number is odd, while the rest of the numbers are even
iq_test("1 2 1 1") => 2 // Second number is even, while the rest of the numbers are odd
``` | ["def iq_test(numbers):\n e = [int(i) % 2 == 0 for i in numbers.split()]\n\n return e.index(True) + 1 if e.count(True) == 1 else e.index(False) + 1\n", "def iq_test(n):\n n = [int(i)%2 for i in n.split()]\n if n.count(0)>1:\n return n.index(1)+1\n else:\n return n.index(0)+1\n", "def iq_test(numbers):\n indexEven = 0\n indexOdd = 0\n numEven = 0\n numOdd = 0\n nums = numbers.split(\" \")\n for i in range(len(nums)):\n if int(nums[i])%2 == 0:\n numEven += 1\n indexEven = i+1\n else:\n numOdd += 1\n indexOdd = i+1\n if numEven == 1:\n return indexEven\n else:\n return indexOdd", "def iq_test(numbers):\n eo = [int(n)%2 for n in numbers.split()]\n return eo.index(1 if eo.count(0)>1 else 0)+1", "def iq_test(numbers):\n nums = map(int, numbers.split(\" \"))\n evens, odds = 0, 0\n for i, n in enumerate(nums):\n if n % 2 == 0:\n evens += 1\n ei = i\n else:\n odds += 1\n oi = i\n \n if evens == 1:\n return ei + 1\n return oi + 1", "def iq_test(numbers):\n digits = [int(x) for x in numbers.split()]\n even = [x % 2 for x in digits]\n if sum(even) == 1:\n return even.index(1) + 1\n else:\n return even.index(0) + 1\n", "def iq_test(numbers):\n nums = [int(n) % 2 for n in numbers.split()]\n if sum(nums) == 1:\n return nums.index(1) + 1\n else:\n return nums.index(0) + 1", "def iq_test(numbers):\n a=list(map(lambda x : int(x)%2,numbers.split(' ')))\n return 1+(a.index(0) if (a.count(0)) == 1 else a.index(1))", "def iq_test(numbers):\n all=numbers.split(\" \")\n odd=[int(x) for x in all if int(x)%2!=0]\n even=[int(x) for x in all if int(x)%2==0]\n if len(odd)==1:\n return all.index(str(odd[0]))+1\n return all.index(str(even[0]))+1", "def iq_test(numbers):\n even, odd = [], []\n new_nums = numbers.split()\n for index, num in enumerate(new_nums,1):\n if int(num) % 2 == 0:\n even.append(index)\n else:\n odd.append(index)\n \n if len(even) > len(odd):\n return int(odd[0])\n else:\n return int(even[0])"] | {"fn_name": "iq_test", "inputs": [["2 4 7 8 10"], ["1 2 2"], ["88 96 66 51 14 88 2 92 18 72 18 88 20 30 4 82 90 100 24 46"], ["100 99 100"], ["5 3 2"], ["43 28 1 91"], ["20 94 56 50 10 98 52 32 14 22 24 60 4 8 98 46 34 68 82 82 98 90 50 20 78 49 52 94 64 36"], ["79 27 77 57 37 45 27 49 65 33 57 21 71 19 75 85 65 61 23 97 85 9 23 1 9 3 99 77 77 21 79 69 15 37 15 7 93 81 13 89 91 31 45 93 15 97 55 80 85 83"], ["100 100 1"], ["9 31 27 93 17 77 75 9 9 53 89 39 51 99 5 1 11 39 27 49 91 17 27 79 81 71 37 75 35 13 93 4 99 55 85 11 23 57 5 43 5 61 15 35 23 91 3 81 99 85 43 37 39 27 5 67 7 33 75 59 13 71 51 27 15 93 51 63 91 53 43 99 25 47 17 71 81 15 53 31 59 83 41 23 73 25 91 9"]], "outputs": [[3], [1], [4], [2], [3], [2], [26], [48], [3], [32]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,258 |
def iq_test(numbers):
|
8536ea1565272c975cc9e66b0dbecf99 | UNKNOWN | # Task
Mr.Nam has `n` candies, he wants to put one candy in each cell of a table-box. The table-box has `r` rows and `c` columns.
Each candy was labeled by its cell number. The cell numbers are in range from 1 to N and the direction begins from right to left and from bottom to top.
Nam wants to know the position of a specific `candy` and which box is holding it.
The result should be an array and contain exactly 3 elements. The first element is the `label` of the table; The second element is the `row` of the candy; The third element is the `column` of the candy.
If there is no candy with the given number, return `[-1, -1, -1]`.
Note:
When the current box is filled up, Nam buys another one.
The boxes are labeled from `1`.
Rows and columns are `0`-based numbered from left to right and from top to bottom.
# Example
For `n=6,r=2,c=2,candy=3`, the result should be `[1,0,1]`
the candies will be allocated like this:
```
Box 1
+-----+-----+
| 4 | (3) | --> box 1,row 0, col 1
+-----+-----+
| 2 | 1 |
+-----+-----+
Box 2
+-----+-----+
| x | x |
+-----+-----+
| 6 | (5) | --> box 2,row 1, col 1
+-----+-----+```
For `candy = 5(n,r,c same as above)`, the output should be `[2,1,1]`.
For `candy = 7(n,r,c same as above)`, the output should be `[-1,-1,-1]`.
For `n=8,r=4,c=2,candy=3`, the result should be `[1,2,1]`
```
Box 1
+-----+-----+
| 8 | 7 |
+-----+-----+
| 6 | 5 |
+-----+-----+
| 4 | (3) |--> box 1,row 2, col 1
+-----+-----+
| 2 | 1 |
+-----+-----+
```
# Input/Output
- `[input]` integer `n`
The number of candies.
`0 < n <= 100`
- `[input]` integer `r`
The number of rows.
`0 < r <= 100`
- `[input]` integer `c`
The number of columns.
`0 < c <= 100`
- `[input]` integer `candy`
The label of the candy Nam wants to get position of.
`0 < c <= 120`
- `[output]` an integer array
Array of 3 elements: a label, a row and a column. | ["def get_candy_position(n, r, c, candy):\n if candy > n: return [-1,-1,-1]\n \n linIdx = r*c - ( (candy-1) % (r*c) + 1 )\n return [(candy-1)//(r*c) + 1, linIdx//c, linIdx%c]", "def get_candy_position(n, r, c, candy):\n if candy > n:\n return [-1, -1, -1]\n label = (candy + r * c - 1) // (r * c)\n candy = (candy - 1) % (r * c)\n row = r - 1 - candy // c\n col = c - 1 - candy % c\n return [label, row, col]", "def get_candy_position(n, r, c, candy):\n q1, r1 = divmod(candy-1, r*c)\n q2, r2 = divmod(r1, c)\n return [-1, -1, -1] if n < candy else [q1+1, r-q2-1, c-r2-1]", "import numpy as np\nimport math\ndef get_candy_position(n, r, c, candy):\n if n < candy: return [-1,-1,-1]\n box = np.array([[\"*\"]*c]*r)\n n1 = math.ceil(n/(c*r))\n count = 1\n for i in range(1, n1+1):\n b = box.copy()\n for j in range(r-1,-1,-1):\n for k in range(c-1,-1,-1):\n if count == candy:\n return [i, j, k]\n b[j][k] = count\n count += 1", "def get_candy_position(n, r, c, candy):\n if candy > n:\n return [-1, -1, -1]\n box, res = divmod(candy, r * c)\n if res == 0:\n return [box, 0, 0]\n row, res = divmod(res, c)\n return [box+1, r-row, 0] if res == 0 else [box+1, r-row-1, c-res]", "from math import ceil\ndef get_candy_position(n, r, c, candy):\n if candy>n:\n return [-1,-1,-1]\n box=ceil(candy/(r*c))\n candy-=(box-1)*r*c\n row=r-ceil(candy/c)\n column=c-candy%c if candy%c>0 else 0\n return [box,row,column]", "def get_candy_position(a, row, col, candy):\n from math import ceil\n bx_sz = row * col\n if row*col < a:\n n = ceil(a/(row*col)) * (col*row)\n else:\n n = row*col\n l = [i if i <= a else 'X' for i in list(range(1, (n - (n%row)+1)))]\n split_l = [list(l[i:i+bx_sz])[::-1] for i in range(0, len(l), bx_sz)]\n b = [i[j:j+col] for i in split_l for j in range(0, len(i), col)]\n c = [b[i:i+row] for i in range(0, len(b), row)]\n for i in range(len(c)):\n for j in range(len(c[i])):\n for k in range(len(c[i][j])):\n if c[i][j][k] == candy:\n return [i+1, j, k] \n return [-1,-1,-1]\n", "def get_candy_position(n, r, c, candy):\n if min(n, r, c, candy)<=0 or candy>n:\n return [-1]*3\n box, candy = divmod(candy-1, r*c)\n row, col = divmod(candy, c)\n return [box+1, r-row-1, c-col-1]\n", "from math import ceil\n\ndef get_candy_position(n, r, c, candy):\n d = r * c\n boxes_cnt, boxes = ceil(n / d), []\n \n lst = [[i * c + j + 1 for j in range(c - 1, -1, -1)] for i in range(r - 1, -1, -1)]\n \n for i in range(boxes_cnt):\n boxes.append([i + 1, [[v + i * d if v + i * d <= n else 'x' for v in row] for row in lst]])\n \n bx = next((box for box in boxes if any(candy in b for b in box[1])), None)\n \n if not bx: return [-1, -1, -1]\n \n i = next(k for k, b in enumerate(bx[1]) if candy in b)\n j = bx[1][i].index(candy)\n \n return [bx[0], i, j]", "def get_candy_position(n, row, column, element):\n arr,arr_p,row_p,col_p = [[[0] * column for i in range(row)]],0,row -1,column-1\n i = 1\n while i < n + 1:\n arr[arr_p][row_p][col_p] = i\n col_p -= 1\n if col_p < 0:\n col_p = column - 1 ; row_p -= 1 \n if all([k != 0 for j in arr for k in sum(j, [])]):\n arr.append([[0] * column for i in range(row)])\n row_p = row-1 ; arr_p += 1\n i += 1\n final = [[i + 1, j, y.index(element)] for i, x in enumerate(arr) for j, y in enumerate(x) if element in y]\n return final[0] if final else [-1,-1,-1]\n"] | {"fn_name": "get_candy_position", "inputs": [[6, 2, 2, 3], [6, 2, 2, 5], [6, 2, 2, 7], [8, 4, 2, 3], [15, 3, 3, 1], [15, 3, 3, 5], [15, 3, 3, 7], [15, 3, 3, 14], [15, 3, 3, 18]], "outputs": [[[1, 0, 1]], [[2, 1, 1]], [[-1, -1, -1]], [[1, 2, 1]], [[1, 2, 2]], [[1, 1, 1]], [[1, 0, 2]], [[2, 1, 1]], [[-1, -1, -1]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,692 |
def get_candy_position(n, r, c, candy):
|
06d2f0a88dbf55210c8c181d9b67bcfa | UNKNOWN | I love Fibonacci numbers in general, but I must admit I love some more than others.
I would like for you to write me a function that when given a number (n) returns the n-th number in the Fibonacci Sequence.
For example:
```python
nth_fib(4) == 2
```
Because 2 is the 4th number in the Fibonacci Sequence.
For reference, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. | ["def nth_fib(n):\n a, b = 0, 1\n for i in range(n-1):\n a, b = b, a + b\n return a", "def nth_fib(n):\n a, b = (0, 1)\n for _ in range(n-1):\n a, b = b, a + b\n return a", "def nth_fib(n):\n if n==1:\n return 0\n elif n==2:\n return 1\n else:\n return nth_fib(n-1)+nth_fib(n-2)\n", "from math import sqrt\ndef nth_fib(n):\n n = n - 1\n Phi = (1 + sqrt(5))/2\n phi = (1 - sqrt(5))/2\n \n return int(((Phi**n)-(phi**n))/sqrt(5))", "def nth_fib(n):\n if n <= 2:\n return n-1\n return nth_fib(n-1) + nth_fib(n-2)", "memoize = {}\ndef nth_fib(n):\n if n == 1: \n return 0 \n if n == 2: \n return 1 \n if n not in memoize: \n memoize[n] = nth_fib(n-1) + nth_fib(n-2) \n return memoize[n]\n\n", "def nth_fib(n):\n n -= 1\n if n == 0: return 0\n if n == 1: return 1\n a, b, p, q = 1, 0, 0, 1\n \n while n > 0:\n if n % 2 == 0:\n tp = p\n p = p ** 2 + q ** 2\n q = 2 * tp * q + q ** 2\n n //= 2\n else:\n ta = a\n a = b * q + a * q + a * p\n b = b * p + ta * q\n n -= 1\n return b", "def nth_fib(n):\n return nth_fib(n-2) + nth_fib(n-1) if n > 2 else n - 1\n", "def nth_fib(n):\n return 0 if n==1 else 1 if n in [2,3] else (nth_fib(n-2)+nth_fib(n-1))", "#Using Binet's Formula to speed things up\ndef nth_fib(n):\n Phi = (pow(5, 0.5) + 1)/2\n phi = Phi - 1\n n -= 1\n return round((pow(Phi, n) - pow(-phi, n))/pow(5, 0.5))"] | {"fn_name": "nth_fib", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25]], "outputs": [[0], [1], [1], [2], [3], [5], [8], [13], [21], [34], [55], [89], [144], [233], [377], [610], [987], [1597], [2584], [4181], [6765], [10946], [17711], [28657], [46368]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,449 |
def nth_fib(n):
|
73186ebd54c6ec3512842dc5daffaef8 | UNKNOWN | The magic sum of 3s is calculated on an array by summing up odd numbers which include the digit `3`. Write a function `magic_sum` which accepts an array of integers and returns the sum.
*Example:* `[3, 12, 5, 8, 30, 13]` results in `16` (`3` + `13`)
If the sum cannot be calculated, `0` should be returned. | ["def magic_sum(arr):\n return arr and sum(x for x in arr if x%2 and '3' in str(x)) or 0", "def magic_sum(arr):\n if arr == None: return 0 \n return sum(list(filter(lambda x: x % 2 == 1 and '3' in str(x),arr)))", "def magic_sum(arr):\n def check(x):\n return x % 2 and '3' in str(x)\n return sum(x for x in arr if check(x)) if arr else 0", "def magic_sum(arr):\n return sum(i for i in arr if (i%2==1 and '3' in str(i))) if arr else 0", "def magic_sum(arr):\n return sum(n for n in arr if n%2 and '3'in str(n)) if arr else 0", "magic_sum=lambda a:sum(n%2*n*('3'in str(n))for n in a or[])", "def magic_sum(arr):\n return sum(i for i in arr if '3' in str(i) and i%2) if arr else 0", "def magic_sum(arr):\n return 0 if not arr else sum(x for x in arr if x % 2 and '3' in str(x))", "def magic_sum(arr):\n return sum(v for v in arr if \"3\" in set(str(v)) and v%2) if arr else 0", "def magic_sum(arr):\n if arr == None or arr == []:\n return 0\n output = 0\n for num in arr:\n if '3' in str(num) and num % 2 == 1:\n output += num\n else:\n pass\n return output"] | {"fn_name": "magic_sum", "inputs": [[[3]], [[3, 13]], [[30, 34, 330]], [[3, 12, 5, 8, 30, 13]], [[]], [null]], "outputs": [[3], [16], [0], [16], [0], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,148 |
def magic_sum(arr):
|
8f5420f89152fc00677e212062995f15 | UNKNOWN | #Permutation position
In this kata you will have to permutate through a string of lowercase letters, each permutation will start at ```a``` and you must calculate how many iterations it takes to reach the current permutation.
##examples
```
input: 'a'
result: 1
input: 'c'
result: 3
input: 'z'
result: 26
input: 'foo'
result: 3759
input: 'aba'
result: 27
input: 'abb'
result: 28
``` | ["from functools import reduce\ndef permutation_position(perm):\n return reduce(lambda t,c:t*26+ord(c)-97,perm,0)+1\n", "trans_table = str.maketrans('abcdefghijklmnopqrstuvwxyz',\n '0123456789abcdefghijklmnop')\n\ndef permutation_position(perm):\n return int(perm.translate(trans_table), 26) + 1", "def permutation_position(perm):\n return sum((ord(c) - 0x61) * (26 ** i) for i, c in enumerate(reversed(perm))) + 1", "def permutation_position(x):\n return sum((ord(c)-97)*26**p for p,c in enumerate(x[::-1]))+1", "def permutation_position(perm):\n return sum('abcdefghijklmnopqrstuvwxyz'.index(x) * 26 ** i for i, x in enumerate(perm[::-1])) + 1", "def permutation_position(perm):\n a = {\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5,\"f\":6,\"g\":7,\"h\":8,\"i\":9,\"j\":10,\"k\":11,\"l\":12,\"m\":13,\"n\":14,\"o\":15,\"p\":16,\"q\":17,\"r\":18,\"s\":19,\"t\":20,\"u\":21,\"v\":22,\"w\":23,\"x\":24,\"y\":25,\"z\":26,}\n perm = perm.lower()\n b = 0\n y = 1\n z = []\n while b < len(perm)-1:\n z.append((a[perm[b]] -1) * (26 ** (len(perm)-y)))\n b = b + 1\n y = y + 1\n z.append(a[perm[-1]])\n return sum(z)", "permutation_position=lambda p,a=__import__('string').printable:int(p.translate(p.maketrans(a[10:36],a[:26])),26)+1", "permutation_position=lambda p:sum(26**i*(ord(c)-97)for i,c in enumerate(p[::-1]))+1", "def permutation_position(perm):\n return 1 + sum((ord(c) - 97) * 26**i for i,c in enumerate(perm[::-1]))", "def permutation_position(perm):\n a = list(perm)[::-1]\n res = 0\n k = 0\n for el in a:\n res+=(ord(el)-97)*26**k\n k+=1\n return res+1"] | {"fn_name": "permutation_position", "inputs": [["a"], ["z"], ["aaa"], ["aaab"], ["foo"]], "outputs": [[1], [26], [1], [2], [3759]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,675 |
def permutation_position(perm):
|
5faba06fb904d5fb6e3c7f31a396d1bd | UNKNOWN | # Task
Given a rectangular `matrix` and integers `a` and `b`, consider the union of the ath row and the bth (both 0-based) column of the `matrix`. Return sum of all elements of that union.
# Example
For
```
matrix = [[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]]
a = 1 and b = 3 ```
the output should be `12`.
Here `(2 + 2 + 2 + 2) + (1 + 3) = 12`.
# Input/Output
- `[input]` 2D integer array `matrix`
2-dimensional array of integers representing a rectangular matrix.
Constraints: `1 ≤ matrix.length ≤ 5, 1 ≤ matrix[0].length ≤ 5, 1 ≤ matrix[i][j] ≤ 100.`
- `[input]` integer `a`
A non-negative integer less than the number of matrix rows.
Constraints: `0 ≤ a < matrix.length.`
- `[input]` integer `b`
A non-negative integer less than the number of matrix columns.
Constraints: `0 ≤ b < matrix[i].length. `
- `[output]` an integer | ["def crossing_sum(matrix, row, col):\n return sum(matrix[row]) + sum(line[col] for line in matrix) - matrix[row][col]", "def crossing_sum(a, b, c):\n return sum(a[b]) + sum(x[c] for x in a) - a[b][c]", "def crossing_sum(matrix, row, col):\n return sum(matrix[row]) + sum(i[col] for i in matrix[:row] + matrix[row + 1:])", "def crossing_sum(matrix, row, col):\n mat_tr = [[i[j] for i in matrix] for j in range(len(matrix[0]))]\n return sum(matrix[row] + mat_tr[col]) - matrix[row][col]", "def crossing_sum(matrix, row, col):\n return sum(matrix[row]) + sum(matrix[i][col] for i in range(len(matrix))) - matrix[row][col]\n", "def crossing_sum(mx, r, c):\n return sum(mx[r]+[x[c] for x in mx[:r]+mx[r+1:]])", "crossing_sum=lambda m,r,c: sum(m[r])+sum(l[c] for i,l in enumerate(m) if i!=r)", "def crossing_sum(matrix, row, col):\n a = matrix[row]\n b = [i[col] for num,i in enumerate(matrix) if num!=row]\n return sum(a) + sum(b)\n", "def crossing_sum(matrix, row, col):\n return sum(matrix[row]) + sum([matrix[a][col] for a in range(len(matrix)) if a != row])\n # sums the required row\n # sums a list made of the required column minus the value that is in the row\n"] | {"fn_name": "crossing_sum", "inputs": [[[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], 1, 3], [[[1, 1], [3, 3], [1, 1], [2, 2]], 3, 0], [[[100]], 0, 0], [[[1, 2, 3, 4, 5]], 0, 0], [[[1], [2], [3], [4], [5]], 0, 0]], "outputs": [[12], [9], [100], [15], [15]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,206 |
def crossing_sum(matrix, row, col):
|
1cb053c9530e06de398d9534e4472dd5 | UNKNOWN | Given an array of numbers, return the difference between the largest and smallest values.
For example:
`[23, 3, 19, 21, 16]` should return `20` (i.e., `23 - 3`).
`[1, 434, 555, 34, 112]` should return `554` (i.e., `555 - 1`).
The array will contain a minimum of two elements. Input data range guarantees that `max-min` will cause no integer overflow. | ["def between_extremes(numbers):\n return max(numbers) - min(numbers)", "def between_extremes(ns):\n return max(ns) - min(ns)", "def between_extremes(a):\n return max(a) - min(a)", "# Naive method: 2 iterations\ndef between_extremes(numbers):\n return max(numbers) - min(numbers)\n\n# Faster method: 1 iteration\ndef between_extremes(numbers):\n mini, maxi = float('inf'), -float('inf')\n for x in numbers:\n if x > maxi: maxi = x\n if x < mini: mini = x\n return maxi - mini", "between_extremes = lambda n: max(n)-min(n)", "def between_extremes(numbers):\n a, *b, c = sorted(numbers)\n return c-a", "def between_extremes(numbers):\n minimum_value = min(numbers)\n maximum_value = max(numbers)\n output = maximum_value - minimum_value\n return output\n\n# create two variables and store min and max value \n# than subtract maximum value from minimum value\n# and store that in final output\n", "def between_extremes(lst):\n lst = set(lst)\n return max(lst) - min(lst)", "def between_extremes(numbers):\n numbers.sort()\n b = numbers[-1] - numbers[0]\n return b\n", "def between_extremes(numbers):\n return abs(min(numbers) - max(numbers))"] | {"fn_name": "between_extremes", "inputs": [[[1, 1]], [[-1, -1]], [[1, -1]], [[21, 34, 54, 43, 26, 12]], [[-1, -41, -77, -100]]], "outputs": [[0], [0], [2], [42], [99]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,211 |
def between_extremes(numbers):
|
0db13efd39c2257ce5cac2c92ad24d38 | UNKNOWN | We have the following recursive function:
The 15-th term; ```f(14)``` is the first term in having more that 100 digits.
In fact,
```
f(14) = 2596253046576879973769082409566059879570061514363339324718953988724415850732046186170181072783243503881471037546575506836249417271830960970629933033088
It has 151 digits.
```
Make the function ```something_acci()```, that receives ```num_dig``` (number of digits of the value) as unique argument.
```something_acci()``` will output a tuple/array with the ordinal number in the sequence for the least value in having equal or more than the given number of digits.
Let's see some cases:
```python
something_acci(20) == (12, 25)
# f(11) = 1422313222839141753028416
something_acci(100) == (15, 151)
```
The number of digits given will be always more than 5. ```num_dig > 5```.
Happy coding!!!
And the name for this kata? You have three words of the same meaning in Asian Languages. | ["from functools import reduce\ndef product(ar):\n return reduce(lambda x,y:x*y, ar)\n\ndef something_acci(num_digits):\n seq = [1, 1, 2, 2, 3, 3]\n \n while(len(str(seq[-1])) < num_digits):\n seq.append(product(seq[-3:]) - product(seq[-6:-3]))\n \n return (len(seq), len(str(seq[-1])))\n", "def something_acci(num_digits):\n a,b,c,d,e,f = 1,1,2,2,3,3\n count = 6\n while True:\n sf = str(f)\n if len(sf) >= num_digits:\n return (count, len(sf))\n a,b,c,d,e,f = b,c,d,e,f, d*e*f-a*b*c\n count += 1", "from functools import lru_cache\n\n@lru_cache()\ndef f(n):\n return (1, 1, 2, 2, 3, 3)[n] if n < 6 else (f(n-1) * f(n-2) * f(n-3)) - (f(n-4) * f(n-5) * f(n-6))\n \ndef something_acci(num_digits):\n n, l = 8, 4\n while l < num_digits:\n n += 1\n l = len(str(f(n)))\n return n + 1, l", "from functools import reduce\nfrom operator import mul\ndef something_acci(n):\n li = [1, 1, 2, 2, 3, 3]\n while True:\n li.append(reduce(mul, li[-3:]) - reduce(mul, li[-6:-3]))\n if len(str(li[-1])) >= n : return len(li),len(str(li[-1]))", "def something_acci(num_digits):\n x = [1, 1, 2, 2, 3, 3]\n while True:\n if len(str(x[-1])) >= num_digits: return (len(x), len(str(x[-1])))\n else: x.append(x[-1] * x[-2] * x[-3] - x[-4] * x[-5] * x[-6])", "from math import log10\n\nseq = {0:1, 1: 1, 2:2, 3:2, 4:3, 5:3}\nlen_seq = {0:1, 1:1, 2:1, 3:1, 4:1, 5:1}\n\nnext_term = lambda n: seq[n-1] * seq[n-2] * seq[n-3] - seq[n-4] * seq[n-5] * seq[n-6]\ncount_digits = lambda n: int(log10(n))+1\n\ndef something_acci(num_digits):\n i = 0\n while True:\n if i not in seq:\n n = next_term(i)\n seq[i], len_seq[i] = n, count_digits(n)\n if len_seq[i] >= num_digits: return i+1, len_seq[i]\n i += 1", "def something_acci(num_digits):\n a = [1,1,2,2,3,3]\n while a[-1] < 10**(num_digits-1):\n a.append(a[-1]*a[-2]*a[-3]-a[-4]*a[-5]*a[-6])\n \n return (len(a),len(str(a[-1])))", "def something_acci(num_digits):\n a=[1,1,2,2,3,3]\n while(len(str(a[-1]))<num_digits):\n a.append(a[-1]*a[-2]*a[-3]-a[-4]*a[-5]*a[-6])\n return (len(a), len(str(a[-1])))"] | {"fn_name": "something_acci", "inputs": [[5], [10], [20], [100]], "outputs": [[[10, 8]], [[11, 14]], [[12, 25]], [[15, 151]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,252 |
def something_acci(num_digits):
|
8bb348cb1df9f5489a203aa96e0f56ab | UNKNOWN | Error Handling is very important in coding and seems to be overlooked or not implemented properly.
#Task
Your task is to implement a function which takes a string as input and return an object containing the properties
vowels and consonants. The vowels property must contain the total count of vowels {a,e,i,o,u}, and the total count of consonants {a,..,z} - {a,e,i,o,u}. Handle invalid input and don't forget to return valid ones.
#Input
The input is any random string. You must then discern what are vowels and what are consonants and sum for each category their total occurrences in an object. However you could also receive inputs that are not strings. If this happens then you must return an object with a vowels and consonants total of 0 because the input was NOT a string. Refer to the Example section for a more visual representation of which inputs you could receive and the outputs expected. :)
Example:
```python
Input: get_count('test')
Output: {vowels:1,consonants:3}
Input: get_count('tEst')
Output: {vowels:1,consonants:3}
Input get_count(' ')
Output: {vowels:0,consonants:0}
Input get_count()
Output: {vowels:0,consonants:0}
```
C#
A Counter class has been put in the preloaded section taking two parameters Vowels and Consonants this must be the Object you return! | ["def get_count(words=\"\"):\n if not isinstance(words, str):\n return {'vowels':0,'consonants':0}\n letter = \"\".join([c.lower() for c in words if c.isalpha()])\n vowel = \"\".join([c for c in letter if c in 'aeiou'])\n consonant = \"\".join([c for c in letter if c not in 'aeiou']) \n return {'vowels':len(vowel),'consonants':len(consonant)}", "def get_count(words=''):\n vowels = \"aeiou\"\n consonants = \"bcdfghjklmnpqrstvwxyz\"\n v,c = 0,0\n try:\n for l in words.lower():\n if l in vowels: v += 1\n elif l in consonants: c += 1\n return {\"vowels\":v,\"consonants\":c}\n except:\n return {\"vowels\":0,\"consonants\":0}", "def get_count(words=None):\n ret = {\"vowels\": 0, \"consonants\": 0}\n if words and isinstance(words, str):\n for char in words.lower():\n if char in 'aeiouy':\n ret[\"vowels\"] += 1\n elif char.isalpha():\n ret[\"consonants\"] += 1\n return ret", "import re\n\ndef get_count(words=''):\n vow_count, con_count = 0, 0\n if type(words) is str:\n (remainder, vow_count) = re.subn('[aeiou]', '', words, flags=re.I)\n (_, con_count) = re.subn('\\w', '', remainder, flags=re.I)\n return {'vowels': vow_count, 'consonants': con_count}", "def get_count(words=None):\n result = {'vowels':0, 'consonants':0}\n vowels, consonants = 'aeiou', 'bcdfghjklmnpqrstvwxyz'\n \n if type(words) == str:\n result['vowels'] = len([v for v in words.lower() if v in vowels])\n result['consonants'] = len([c for c in words.lower() if c in consonants])\n \n return result", "is_vowels = set(\"aeiou\").__contains__\nis_conson = set(\"bcdfghjklmnpqrstvwxyz\").__contains__\n\ndef get_count(words=None):\n result = {\"vowels\":0, \"consonants\":0}\n if words and type(words) == str:\n for c in words.lower():\n result[\"vowels\"] += is_vowels(c)\n result[\"consonants\"] += is_conson(c)\n return result", "V,C = 'vowels consonants'.split()\n\ndef get_count(s=None):\n d={V:0,C:0}\n if not isinstance(s,str): return d\n for c in s.lower():\n if c in 'aeiou': d[V]+=1\n elif c.isalpha(): d[C]+=1\n return d", "def get_count(s=''):\n ret = {'vowels': 0, 'consonants': 0}\n if type(s) != str:\n return ret\n for c in s.lower():\n if c in 'aeiou':\n ret['vowels'] += 1\n elif c.isalpha(): # letter but not vowel because elif\n ret['consonants'] += 1\n return ret", "def get_count(words=\"\"):\n vowels = consonants = 0\n if type(words) == str:\n for char in words.lower():\n if char.isalpha():\n vowel = char in \"aeiou\"\n vowels += vowel\n consonants += not vowel\n return {\"vowels\": vowels, \"consonants\": consonants}", "def get_count(words=''):\n if not isinstance(words, str):\n words = ''\n words = words.lower()\n return {\n 'vowels': sum(c in 'aeiou' for c in words),\n 'consonants': sum(c.isalpha() and c not in 'aeiou' for c in words)\n }"] | {"fn_name": "get_count", "inputs": [["Test"], ["Here is some text"], ["To be a Codewarrior or not to be"], ["To Kata or not to Kata"], ["aeiou"], ["TEst"], ["HEre Is sOme text"], [["To Kata or not to Kata"]], [null], ["Test "], ["Here is some text "], [" "], [{"jjjjj": "jjjjj"}]], "outputs": [[{"vowels": 1, "consonants": 3}], [{"vowels": 6, "consonants": 8}], [{"vowels": 12, "consonants": 13}], [{"vowels": 8, "consonants": 9}], [{"vowels": 5, "consonants": 0}], [{"vowels": 1, "consonants": 3}], [{"vowels": 6, "consonants": 8}], [{"vowels": 0, "consonants": 0}], [{"vowels": 0, "consonants": 0}], [{"vowels": 1, "consonants": 3}], [{"vowels": 6, "consonants": 8}], [{"vowels": 0, "consonants": 0}], [{"vowels": 0, "consonants": 0}]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,183 |
def get_count(words=''):
|
65bcf14b2a926d81323d1648cc440fce | UNKNOWN | The new football league season is coming and the Football Association need some help resetting the league standings. Normally the initial league standing is done in alphabetical order (from A to Z) but this year the FA have decided to freshen it up.
It has been decided that team who finished first last season will begin the next season in first place. Regardless of what letter their club begins with. e.g. if Manchester City were in first place last year, they will begin the season in position one. All other teams should be in alphabetical order.
The teams will be fed in as an object ({}). The key will be will be their position from last season and the value is the club's name e.g. Arsenal.
The output should be an object ({}) with the key as the club's starting position for the new season and the value should be club's name e.g. Arsenal.
For example. If in the previous season the standings were:
1:'Leeds United'
2:'Liverpool'
3:'Manchester City'
4:'Coventry'
5:'Arsenal'
Then the new season standings should
1:'Leeds United' (first last season)
2:'Arsenal' (alphabetical)
3:'Coventry' (alphabetical)
4:'Liverpool' (alphabetical)
5:'Manchester City' (alphabetical) | ["def premier_league_standings(teams):\n dct = {1: teams[1]}\n dct.update({i:t for i,t in enumerate(sorted(set(teams.values())-{teams[1]}), 2)})\n return dct", "def premier_league_standings(teams):\n order = [teams[1]] + sorted(team for place,team in teams.items() if place!=1)\n return {place:team for place,team in enumerate(order,1)}", "def premier_league_standings(teams):\n return {c : n for c, (_, n) in enumerate(sorted(teams.items(), key = lambda t: (t[0] > 1, t[1])), 1)}", "def premier_league_standings(teams):\n return {i:team[1] for i,team in enumerate(sorted(teams.items(), key=lambda x: (x[0]!=1, x[1])), 1)}", "def premier_league_standings(teams):\n new = [teams[1]] + sorted(teams[n] for n in range(2, len(teams) + 1))\n return {i: team for (i, team) in enumerate(new, 1)}", "def premier_league_standings(teams):\n if len(teams)==1:\n return teams\n next_season=[]\n for key,value in list(teams.items()):\n if key!=1:\n next_season.append(value)\n sorted_nex=sorted(next_season)\n \n sorted_dict={}\n for key,value in enumerate(sorted_nex,2):\n sorted_dict[1]=teams[1]\n sorted_dict[key]=value\n return sorted_dict\n \n \n \n", "def premier_league_standings(teams):\n ret = {1:teams[1]}\n for i,name in enumerate(sorted(teams[i] for i in teams.keys() if i != 1)):\n ret[i+2] = name\n return ret", "def premier_league_standings(teams):\n return {i:v for i, v in enumerate([teams[1]] + sorted(v for v in teams.values() if v != teams[1]), 1)}", "def premier_league_standings(teams):\n lst = [(x, y) for x, y in teams.items()]\n lst = [y for x, y in lst if x == 1] + sorted([y for x, y in lst if x != 1])\n return {i: y for i, y in enumerate(lst, 1)}", "def premier_league_standings(teams):\n t = sorted(teams.items(), key=lambda i:str(i[0]) if i[0]==1 else i[1])\n return {i+1:t[i][1] for i in range(len(t))}"] | {"fn_name": "premier_league_standings", "inputs": [[{"1": "Arsenal"}], [{"2": "Arsenal", "3": "Accrington Stanley", "1": "Leeds United"}], [{"1": "Leeds United", "2": "Liverpool", "3": "Manchester City", "4": "Coventry", "5": "Arsenal"}]], "outputs": [{"1": "Arsenal"}, {"3": "Arsenal", "2": "Accrington Stanley", "1": "Leeds United"}, {"1": "Leeds United", "2": "Arsenal", "3": "Coventry", "4": "Liverpool", "5": "Manchester City"}]}
| INTRODUCTORY | PYTHON3 | CODEWARS | 1,957 |
def premier_league_standings(teams):
|
abc3881f1559d866848a5ab466cfbe38 | UNKNOWN | Your task is to write a function that does just what the title suggests (so, fair warning, be aware that you are not getting out of it just throwing a lame bas sorting method there) with an array/list/vector of integers and the expected number `n` of smallest elements to return.
Also:
* the number of elements to be returned cannot be higher than the array/list/vector length;
* elements can be duplicated;
* in case of duplicates, just return them according to the original order (see third example for more clarity).
Same examples and more in the test cases:
```python
first_n_smallest([1,2,3,4,5],3) == [1,2,3]
first_n_smallest([5,4,3,2,1],3) == [3,2,1]
first_n_smallest([1,2,3,4,1],3) == [1,2,1]
first_n_smallest([1,2,3,-4,0],3) == [1,-4,0]
first_n_smallest([1,2,3,4,5],0) == []
```
[Performance version by FArekkusu](https://www.codewars.com/kata/5aeed69804a92621a7000077) also available. | ["def first_n_smallest(arr, n):\n lst = sorted(enumerate(arr), key=lambda it: it[1])[:n]\n lst.sort(key=lambda it:it[0])\n return [v for _,v in lst]", "def first_n_smallest(arr, n):\n m = sorted(arr)[:n]\n return [m.pop(m.index(i)) for i in arr if i in m]", "from operator import itemgetter\ndef first_n_smallest (arr, n):\n by_index, by_value = map(itemgetter, (0, 1))\n all_ascending = sorted(enumerate(arr), key=by_value)\n n_chronologic = sorted(all_ascending[:n], key=by_index)\n return list(map(by_value, n_chronologic))", "def first_n_smallest(arr, n):\n return [x[1] for x in sorted(sorted(enumerate(arr), key=lambda x: x[1])[:n])]", "def first_n_smallest(arr, n):\n smallest = []\n replacement = max(arr) + 1\n while n and arr:\n num = min(arr)\n idx = arr.index(num)\n arr[idx] = replacement\n smallest.append((num, idx))\n n -= 1\n sort = sorted(smallest, key=lambda pair: pair[1])\n return [p[0] for p in sort]", "def first_n_smallest(lst, n):\n std = sorted(enumerate(lst), key=lambda e: e[1])[:n]\n return [n for i, n in sorted(std)]\n", "from collections import Counter\n\ndef first_n_smallest(arr, n):\n def f():\n xs = Counter(sorted(arr)[:n])\n for x in arr:\n if xs[x]:\n xs[x] -= 1\n yield x\n return list(f())", "from heapq import nsmallest\ndef first_n_smallest(arr, n):\n small = nsmallest(n, arr)\n return [a for a in arr if a in small and (small.remove(a) or 1)]", "first_n_smallest=lambda a,n:[v for _,v in sorted(sorted(enumerate(a),key=lambda x:x[1])[:n])]", "def first_n_smallest(arr, n):\n for i in range(len(arr)-n):\n arr.pop(len(arr)-1 - arr[::-1].index(max(arr)))\n return arr\n"] | {"fn_name": "first_n_smallest", "inputs": [[[1, 2, 3, 4, 5], 3], [[5, 4, 3, 2, 1], 3], [[1, 2, 3, 1, 2], 3], [[1, 2, 3, -4, 0], 3], [[1, 2, 3, 4, 5], 0], [[1, 2, 3, 4, 5], 5], [[1, 2, 3, 4, 2], 4], [[2, 1, 2, 3, 4, 2], 2], [[2, 1, 2, 3, 4, 2], 3], [[2, 1, 2, 3, 4, 2], 4]], "outputs": [[[1, 2, 3]], [[3, 2, 1]], [[1, 2, 1]], [[1, -4, 0]], [[]], [[1, 2, 3, 4, 5]], [[1, 2, 3, 2]], [[2, 1]], [[2, 1, 2]], [[2, 1, 2, 2]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,780 |
def first_n_smallest(arr, n):
|
90a0f82c2055d46b5f843c293c12baf4 | UNKNOWN | This is a follow up from my kata The old switcheroo
Write
```python
def encode(str)
```
that takes in a string ```str``` and replaces all the letters with their respective positions in the English alphabet.
```python
encode('abc') == '123' # a is 1st in English alpabet, b is 2nd and c is 3rd
encode('codewars') == '315452311819'
encode('abc-#@5') == '123-#@5'
```
String are case sensitive. | ["def encode(string):\n return ''.join(str(ord(c.upper())-64) if c.isalpha() else c for c in string)", "def encode(string):\n return ''.join(str(ord(c)-96) if c.isalpha() else c for c in string.lower())", "def encode(s):\n return ''.join(str(ord(x) - ord('a') + 1) if x.isalpha() else x for x in s.lower())", "from string import ascii_uppercase, ascii_lowercase\n\nD = {c:str(i) for string in (ascii_uppercase, ascii_lowercase) for i,c in enumerate(string, 1)}\n\ndef encode(string):\n return ''.join(D.get(c, c) for c in string)", "def encode(stg):\n return \"\".join(str(ord(c) - 96) if \"a\" <= c <= \"z\" else c for c in stg.lower())", "from string import ascii_lowercase as letters\n\n\ndef encode(string):\n return ''.join(str(letters.find(char)+1) if char in letters else char for char in string.lower())", "BASE = ord('A') - 1\n\ndef encode(string):\n return ''.join(str(ord(c)-BASE) if c.isalpha() else c for c in string.upper())", "def encode(string):\n string = string.lower()\n alph = 'abcdefghijklmnopqrstuvwxyz'\n st = []\n for l in string:\n if l.isalpha():\n st.append(alph.find(l)+1)\n else:\n st.append(l)\n return ''.join(map(str,st))", "def encode(string):\n return ''.join(str(ord(i.lower()) - 96) if i.isalpha() else i for i in string)", "import re\n\ndef encode(string):\n return re.sub(r'[a-z]', lambda m: str(ord(m.group()) - ord('a') + 1), string.lower())"] | {"fn_name": "encode", "inputs": [["abc"], ["ABCD"], ["ZzzzZ"], ["abc-#@5"], ["this is a long string!! Please [encode] @C0RrEctly"]], "outputs": [["123"], ["1234"], ["2626262626"], ["123-#@5"], ["208919 919 1 1215147 1920189147!! 161251195 [51431545] @30181853201225"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,460 |
def encode(string):
|
5b0b7224398ac559c949dc83aa764aec | UNKNOWN | Is every value in the array an array?
This should only test the second array dimension of the array. The values of the nested arrays don't have to be arrays.
Examples:
```python
[[1],[2]] => true
['1','2'] => false
[{1:1},{2:2}] => false
``` | ["def arr_check(arr):\n return all(isinstance(el, list) for el in arr)", "def arr_check(arr):\n return all(isinstance(a, list) for a in arr)", "def arr_check(arr):\n return all(type(ele) is list for ele in arr)", "def arr_check(arr):\n return all(type(i) == list for i in arr)", "def arr_check(arr):\n return all(type(i) is list for i in arr)", "def arr_check(arr):\n return all(type(e) == list for e in arr)", "def arr_check(arr):\n for i in arr:\n try:\n i.append(\"\")\n except:\n return False\n return True", "def arr_check(arr):\n return sum([isinstance(x, list) for x in arr]) == len(arr)", "def arr_check(arr):\n return len([el for el in arr if type(el) == list]) == len(arr)"] | {"fn_name": "arr_check", "inputs": [[[]], [[["string"]]], [[[], {}]], [[[1], [2], [3]]], [["A", "R", "R", "A", "Y"]]], "outputs": [[true], [true], [false], [true], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 750 |
def arr_check(arr):
|
99fdd21f1de453904be767dfc603b122 | UNKNOWN | Baby is getting his frst tooth. This means more sleepless nights, but with the fun of feeling round his gums and trying to guess which will be first out!
Probably best have a sweepstake with your friends - because you have the best chance of knowing. You can feel the gums and see where the raised bits are - most raised, most likely tooth to come through first!
Given an array of numbers (t) to represent baby's gums, you need to return the index of the lump that is most pronounced.
The most pronounced lump is the one that has the biggest differential to its surrounding values. e.g.:
```
[1, 2, 4] = 2
index 0 has a differential of -1 to its right (it is lower so the figure is negative)
index 1 has a differential of +1 to its left, and -2 to its right. Total is -1.
index 2 has a differential of +2 to its left, and nothing to its right,
```
If there is no distinct highest value (more than one occurence of the largest differential), return -1. | ["def first_tooth(lst):\n gums = lst[:1] + lst + lst[-1:]\n diff = [gums[i+1]*2 - gums[i] - gums[i+2] for i in range(len(lst))]\n m = max(diff)\n return diff.index(m) if diff.count(m) == 1 else -1\n", "def first_tooth(array):\n array = [array[0]]+array+[array[-1]]\n diffs = [2*array[i]-array[i-1]-array[i+1] for i in range(1,len(array)-1)]\n m = max(diffs)\n if diffs.count(m)>1:\n return -1\n else:\n return diffs.index(m)", "def first_tooth(xs):\n diff = [(x-xs[i-1] if i > 0 else 0) + (x - xs[i+1] if i+1 < len(xs) else 0) for i, x in enumerate(xs)]\n x = max(diff)\n if diff.count(x) > 1:\n return -1\n return diff.index(x)", "def first_tooth(arr):\n l=len(arr)\n lst=[(arr[i]-arr[i-1] if i else 0)+(arr[i]-arr[i+1] if i<l-1 else 0) for i in range(l)]\n m=max(lst)\n return lst.index(m) if lst.count(m)==1 else -1", "def first_tooth(array):\n \n if len(array) <= 1:\n return 0\n \n differentials = []\n differentials.append(array[0]-array[1])\n \n for i in range(1,len(array)-1):\n differentials.append(2*array[i]-array[i-1]-array[i+1])\n \n differentials.append(array[-1]-array[-2])\n \n if differentials.count(max(differentials)) > 1:\n return -1\n else:\n return differentials.index(max(differentials))", "import numpy as np\nfrom scipy import ndimage\n\ndef first_tooth(a):\n d=ndimage.convolve(a,[-1,2,-1],mode=\"nearest\")\n m=np.argwhere(d==d.max())\n return m[0][0] if len(m)==1 else -1", "# Which bump protrudes the farthest?\ndef first_tooth(array):\n if len(array) == 1:\n return 0\n else:\n max_diff = -1\n max_diff_indices = []\n i = 0\n while i < len(array):\n if i == 0:\n diff = array[i] - array[i+1]\n elif i == len(array) - 1:\n diff = array[i] - array[i-1]\n else:\n diff = array[i] - array[i-1] + array[i] - array[i+1]\n if diff > max_diff:\n max_diff = diff\n max_diff_indices = [i]\n elif diff == max_diff:\n max_diff_indices.append(i)\n i += 1\n if len(max_diff_indices) > 1:\n return -1\n else:\n return max_diff_indices[0]", "def first_tooth(some_list):\n answer_list = []\n if len(some_list) == 1:\n return some_list.index(max(some_list))\n else:\n answer_list.append(some_list[0] - some_list[1])\n for i in range(1, len(some_list) - 1):\n answer_list.append((some_list[i] - some_list[i - 1]) + (some_list[i] - some_list[i + 1]))\n answer_list.append(some_list[len(some_list) - 1] - some_list[len(some_list) - 2])\n if answer_list.count(max(answer_list)) > 1:\n return -1\n return answer_list.index(max(answer_list))\n", "def first_tooth(array):\n a=[array[0]]+array+[array[-1]]\n b=[2*a[i]-a[i-1]-a[i+1] for i in range(1,len(a)-1)]\n c=max(b)\n return b.index(c) if b.count(c)==1 else -1"] | {"fn_name": "first_tooth", "inputs": [[[1, 2, 3, 4]], [[1, 2, 6, 4]], [[1, 2, 5, 7, 1, 0, 9]], [[9, 2, 8, 1]], [[1, 1, 1, 1]], [[20, 9, 16, 19]], [[15]]], "outputs": [[3], [2], [6], [2], [-1], [0], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,092 |
def first_tooth(array):
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.