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
2ea4e0eba27d0011affdacb341e27b7a
UNKNOWN
A series or sequence of numbers is usually the product of a function and can either be infinite or finite. In this kata we will only consider finite series and you are required to return a code according to the type of sequence: |Code|Type|Example| |-|-|-| |`0`|`unordered`|`[3,5,8,1,14,3]`| |`1`|`strictly increasing`|`[3,5,8,9,14,23]`| |`2`|`not decreasing`|`[3,5,8,8,14,14]`| |`3`|`strictly decreasing`|`[14,9,8,5,3,1]`| |`4`|`not increasing`|`[14,14,8,8,5,3]`| |`5`|`constant`|`[8,8,8,8,8,8]`| You can expect all the inputs to be non-empty and completely numerical arrays/lists - no need to validate the data; do not go for sloppy code, as rather large inputs might be tested. Try to achieve a good solution that runs in linear time; also, do it functionally, meaning you need to build a *pure* function or, in even poorer words, do NOT modify the initial input!
["def sequence_classifier(arr):\n if all(arr[i] == arr[i+1] for i in range(len(arr)-1)): return 5\n if all(arr[i] < arr[i+1] for i in range(len(arr)-1)): return 1\n if all(arr[i] <= arr[i+1] for i in range(len(arr)-1)): return 2\n if all(arr[i] > arr[i+1] for i in range(len(arr)-1)): return 3\n if all(arr[i] >= arr[i+1] for i in range(len(arr)-1)): return 4\n return 0", "TYPE_SEQ = {(1,): 1, (0,1): 2, (-1,):3, (-1,0): 4, (0,): 5}\n\ndef sequence_classifier(arr):\n countSet = { (a<b) - (a>b) for a,b in zip(arr, arr[1:]) }\n return TYPE_SEQ.get(tuple(sorted(countSet)), 0)", "def sequence_classifier(arr):\n strict, increasing, decreasing = True, False, False\n \n for i in range(1,len(arr)):\n if arr[i] == arr[i-1]:\n strict = False\n if arr[i] < arr[i-1]:\n decreasing = True\n if arr[i] > arr[i-1]:\n increasing = True\n \n return [increasing and decreasing, #unordered\n strict and increasing, #strictly increasing\n not strict and increasing, #not decreasing\n strict and decreasing, #strictly decreasing\n not strict and decreasing, #not increasing\n not increasing and not decreasing].index(True) #constant", "def sequence_classifier(arr):\n unordered = True\n strictly_increasing = True\n not_decreasing = True\n strictly_decreasing = True\n not_increasing = True\n constant = True\n for i in range(1,len(arr)):\n if arr[i-1] != arr[i]:\n constant = False\n if arr[i-1] <= arr[i]:\n strictly_decreasing = False\n if arr[i-1] >= arr[i]:\n strictly_increasing = False\n if not arr[i-1] <= arr[i]:\n not_decreasing = False\n if not arr[i-1] >= arr[i]:\n not_increasing = False\n if constant:\n return 5\n if strictly_decreasing:\n return 3\n if strictly_increasing:\n return 1\n if not_increasing:\n return 4\n if not_decreasing:\n return 2\n return 0", "def sequence_classifier(arr):\n f,l=0,len(arr)-1\n for i in range(0,l): f|= 1 if arr[i]<arr[i+1] else 2 if arr[i]==arr[i+1] else 4\n return [0,1,5,2,3,0,4,0][f]", "from enum import IntEnum\n\nclass Classification(IntEnum):\n UNORDERED = 0\n INCREASING = 1\n NOT_DECREASING = 2\n DECREASING = 3\n NOT_INCREASING = 4\n CONSTANT = 5\n\ndef sequence_classifier(arr):\n unordered = True\n increasing = True\n not_decreasing = True\n decreasing = True\n not_increasing = True\n constant = True\n \n previous_val = None\n \n for val in arr:\n if previous_val is None:\n previous_val = val\n continue\n \n if increasing and val <= previous_val:\n increasing = False\n \n if not_decreasing and val < previous_val:\n not_decreasing = False\n \n if decreasing and val >= previous_val:\n decreasing = False\n \n if not_increasing and val > previous_val:\n not_increasing = False\n \n if constant and val != previous_val:\n constant = False\n \n if not unordered and not increasing and not not_decreasing and not decreasing and not not_increasing and not constant:\n return Classification.UNORDERED\n \n previous_val = val\n \n if constant: \n return Classification.CONSTANT\n elif increasing: \n return Classification.INCREASING\n elif not_decreasing: \n return Classification.NOT_DECREASING\n elif decreasing: \n return Classification.DECREASING\n elif not_increasing: \n return Classification.NOT_INCREASING\n else:\n return Classification.UNORDERED\n", "def sequence_classifier(arr):\n a, l, l_ = sorted(arr), len(arr), len(set(arr))\n return [[0,[[3,4][arr==a[::-1] and l_!=l],[1,2][arr==a and l_!=l]][arr==a]][arr in [a,a[::-1]]],5][l_==1]", "from operator import *\n\ndef sequence_classifier(arr):\n for op, code in {eq: 5, gt: 1, lt: 3, ge: 2, le: 4}.items():\n if all(op(d, 0) for d in map(sub, arr[1:], arr)):\n return code\n return 0", "from collections import Counter\n\ndef sequence_classifier(arr):\n # I would really prefer to define `types` as a set and be able to write \n # `types -= {1, 3}`, but alas, sets do not preserve insertion order...\n types = Counter([5, 1, 2, 3, 4, 0])\n \n for a, b in zip(arr, arr[1:]):\n if a == b: del types[1], types[3]\n if a != b: del types[5]\n if a < b: del types[3], types[4]\n if a > b: del types[1], types[2]\n return next(iter(types))", "def sequence_classifier(arr):\n if len(set(arr)) == 1: return 5\n elif sorted(arr) == arr and len(arr) == len(set(arr)): return 1\n elif sorted(arr) == arr: return 2\n elif sorted(arr[::-1]) == arr[::-1] and len(arr) == len(set(arr)): return 3\n elif sorted(arr[::-1]) == arr[::-1]: return 4\n else: return 0"]
{"fn_name": "sequence_classifier", "inputs": [[[3, 5, 8, 1, 14, 3]], [[3, 5, 8, 9, 14, 23]], [[3, 5, 8, 8, 14, 14]], [[14, 9, 8, 5, 3, 1]], [[14, 14, 8, 8, 5, 3]], [[8, 8, 8, 8, 8, 8]], [[8, 9]], [[8, 8, 8, 8, 8, 9]], [[9, 8]], [[9, 9, 9, 8, 8, 8]], [[3, 5, 8, 1, 14, 2]]], "outputs": [[0], [1], [2], [3], [4], [5], [1], [2], [3], [4], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,074
def sequence_classifier(arr):
86677fbf6b571209d6eab5412264d6b3
UNKNOWN
This challenge is based on [the kata](https://www.codewars.com/kata/n-smallest-elements-in-original-order) by GiacomoSorbi. Before doing this one it is advisable to complete the non-performance version first. ___ # Task You will be given an array of random integers and a number `n`. You have to extract `n` smallest integers out of it **preserving the original order**. # Examples ```python performant_smallest([1, 2, 3, 4, 5], 3) == [1, 2, 3] performant_smallest([5, 4, 3, 2, 1], 3) == [3, 2, 1] performant_smallest([1, 2, 3, 4, 1], 3) == [1, 2, 1] performant_smallest([2, 1, 3, 2, 3], 3) == [2, 1, 2] ``` # Notes * There will be duplicates in the array, and they have to be returned in the order of their each separate appearence. * This kata is an example of the "know your data" principle. Remember this while searching for the correct approach. # Performance tests ```python Tests: 15 Array size: 800,000 Values range: [1; 50] Number of elements to return: 25-50% of the array ```
["from collections import Counter\nfrom itertools import count, islice\n\ndef performant_smallest(arr, n):\n cnts = Counter(arr)\n total = 0\n for i, c in sorted(cnts.items()):\n total += c\n if total >= n:\n break\n available = count(c + n - total, -1)\n it = (x for x in arr if x < i or (x == i and next(available) > 0))\n return list(islice(it, n))", "def performant_smallest(xs, n):\n ys = sorted(xs)\n del ys[n:]\n m = ys[-1]\n km = ys.count(m)\n res = []\n for x in xs:\n if x <= m:\n if x < m:\n res.append(x)\n elif km > 0:\n res.append(x)\n km -= 1\n return res", "def performant_smallest(arr, n):\n keys = sorted(list(range(len(arr))), key=arr.__getitem__)\n return [arr[i] for i in sorted(keys[:n])]\n", "import numpy as np\ndef performant_smallest(a, n):\n l = len(a)\n arr = np.array([v + (i / l) for i, v in enumerate(a)])\n ag = np.argpartition(arr, n - 1)\n args = np.sort(ag[:n])\n return [a[x] for x in args]", "def performant_smallest(lst, n):\n c = [0]*201 #Our counter.\n for itm in lst: c[itm+100] += 1 #Map each number to num+100.\n res, sm = [0]*n, 0\n for k in range(201): #Iterate through the numbers in our counter.\n sm += c[k]\n if sm >= n:\n c[k] += n - sm #The sum of `c[:k+1]` should be equal to `n`, and this would give us the count of the `n` smallest elements.\n break\n sm = 0\n for itm in lst: #Iterate through the list to present the elements in their appearance order in the list.\n v = itm+100 #The mapping between the list item and its index in our counter.\n if v <= k and c[v] > 0: #The item is one of the `n` smallest items.\n res[sm] = itm #Place it in its position in the result list.\n sm += 1\n c[v] -= 1\n if sm == n: break\n return res", "def performant_smallest(arr, n):\n c = [0]*51\n o = [0]*n\n #Count each number 1-50 in arr \n for i in arr: \n c[i] += 1 \n #find least max number \n j, st = 0, (len(arr)-n) #count of max numbers in arr\n for m in range(50, -1, -1): \n j += c[m]\n if j >= st:\n c[m] = j - st\n break #m contains least max number\n j = 0\n #put elements from arr upto n, less than m upto c counts\n for i in arr:\n if i <= m and c[i] > 0:\n o[j] = i \n j += 1\n c[i] -= 1\n if j == n: #out has all n elements for out\n break\n return o", "from bisect import bisect_left\n\ndef performant_smallest(arr, n):\n sarr = sorted(arr)\n limit = sarr[n-1]\n r = n - bisect_left(sarr, limit)\n ans = []\n for a in arr:\n if a < limit or (a == limit and r):\n ans.append(a)\n r -= (a == limit)\n if len(ans) == n:\n return ans\n", "import numpy as np\n\ndef performant_smallest(arr, n):\n return np.asarray(arr)[np.sort(np.argsort(arr, kind='mergesort')[:n])].tolist()", "def performant_smallest(arr, n):\n count = [0] * 51\n \n for num in arr:\n count[num] += 1\n \n take = [0] * 51\n i = 1\n \n while True:\n c = count[i]\n if c >= n:\n take[i] = n\n break\n else:\n take[i] = c\n n -= c\n i += 1\n \n res = []\n\n for num in arr:\n if take[num]:\n res.append(num)\n take[num] -= 1\n \n return res\n \n", "from collections import Counter\n\n\ndef performant_smallest(arr, n):\n counts = Counter(arr)\n total = 0\n num_max = 0\n result = []\n for item, count in sorted(counts.items()):\n if total + count >= n:\n maximum = item\n max_max = n - total\n break\n total += count\n for element in arr:\n if element < maximum:\n result.append(element)\n elif element == maximum and num_max < max_max:\n result.append(element)\n num_max += 1\n return result"]
{"fn_name": "performant_smallest", "inputs": [[[1, 2, 3, 4, 5], 3], [[5, 4, 3, 2, 1], 3], [[1, 2, 3, 4, 1], 3], [[2, 1, 3, 2, 3], 3]], "outputs": [[[1, 2, 3]], [[3, 2, 1]], [[1, 2, 1]], [[2, 1, 2]]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,209
def performant_smallest(arr, n):
107a20d24cf39937e9aed2f671516b28
UNKNOWN
Alex is transitioning from website design to coding and wants to sharpen his skills with CodeWars. He can do ten kata in an hour, but when he makes a mistake, he must do pushups. These pushups really tire poor Alex out, so every time he does them they take twice as long. His first set of redemption pushups takes 5 minutes. Create a function, `alexMistakes`, that takes two arguments: the number of kata he needs to complete, and the time in minutes he has to complete them. Your function should return how many mistakes Alex can afford to make.
["from math import log\n\ndef alex_mistakes(n, time):\n return int(log((time - n * 6) / 5 +1, 2))\n", "def alex_mistakes(katas, time):\n mistakes = 0\n pushup_time = 5\n time_left = time - katas * 6\n \n while time_left >= pushup_time:\n time_left -= pushup_time\n pushup_time *= 2\n mistakes += 1\n return mistakes", "from math import log\n\nMINUTES_PER_KATA = 6.0\nPUSHUPS_BASE_TIME = 5.0\n\ndef alex_mistakes(n_katas, time_limit):\n return int(log((time_limit - MINUTES_PER_KATA * n_katas) / PUSHUPS_BASE_TIME + 1, 2))", "from math import log\n\ndef alex_mistakes(katas, limit):\n return int(log((limit - katas * 6 + 5) / 5, 2))\n", "def alex_mistakes(number_of_katas, time_limit):\n req_time = 5\n sets = 0\n remaining = time_limit - number_of_katas * 6\n \n while remaining>=req_time:\n remaining-=req_time\n req_time*=2\n sets+=1\n \n return sets", "def alex_mistakes(n, l):\n mistakes = 0\n push_time = 0\n while push_time < l - n * 6:\n push_time += 5*2**mistakes\n if push_time > l - n * 6: return mistakes\n mistakes += 1\n else: \n return mistakes", "import math\n\ndef alex_mistakes(number_of_katas, time_limit):\n return int(math.log(1 + (time_limit - number_of_katas * 6) / 5.0, 2))", "import math\n\ndef alex_mistakes(number_of_katas, time_limit):\n return int(math.log((time_limit - number_of_katas * 6.0) / 5 + 1, 2))", "def alex_mistakes(number_of_katas, time_limit):\n left = (time_limit - 6*number_of_katas) // 5\n bits = left.bit_length()\n if left + 1 == 1<<bits: return bits\n return bits - 1"]
{"fn_name": "alex_mistakes", "inputs": [[10, 120], [11, 120], [3, 45], [8, 120], [6, 60], [9, 180], [20, 120], [20, 125], [20, 130], [20, 135]], "outputs": [[3], [3], [2], [3], [2], [4], [0], [1], [1], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,669
def alex_mistakes(number_of_katas, time_limit):
4be9be82bf4ff8d1888429779f3edbaf
UNKNOWN
One of the first chain emails I ever received was about a supposed Cambridge University study that suggests your brain can read words no matter what order the letters are in, as long as the first and last letters of each word are correct. Your task is to **create a function that can take any string and randomly jumble the letters within each word while leaving the first and last letters of the word in place.** For example, mixwords('Winter is coming') // returns 'Wntier is cminog' or 'Wtiner is conimg' mixwords('Hey, friends!') // returns 'Hey, fierdns!' or 'Hey, fernids!' * All punctuation should remain in place * Words smaller than 3 letters should not change * Letters must be randomly moved (and so calling the function multiple times with the same string should return different values * Parameters that are not strings should return undefined The tests do the following things to ensure a valid string is returned: 1. Check that the string returned is not equal to the string passed (you may have to revalidate the solution if your function randomly returns the same string) 2. Check that first and last letters of words remain in place 3. Check that punctuation remains in place 4. Checks string length remains the same 5. Checks the function returns `undefined` for non-strings 6. Checks that word interiors (the letters between the first and last) maintain the same letters, albeit in a different order 7. Checks that letters are randomly assigned.
["import re\nfrom random import sample\n\ndef mix_words(string):\n return re.sub(\n r'(?<=[a-zA-Z])([a-zA-Z]{2,})(?=[a-zA-Z])',\n lambda match: ''.join(sample(match.group(1), len(match.group(1)))),\n string)\n", "from re import sub\nfrom random import shuffle\n\ndef scramble(m):\n s = list(m.group())\n shuffle(s)\n return ''.join(s)\n\ndef mix_words(string):\n return sub('\\B\\w+\\B', scramble, string)", "import random\nimport re\nimport numpy as np\n\ndef mix_words(text):\n words_list = text.split()\n result_list = []\n\n for word in words_list:\n punctuation = ''.join(re.findall(\"\\W\", word))\n # punctuation = ''.join(re.findall(\"[^a-zA-Z]\", word)) #equivalent to line above, get non-alphanumeric characters\n \n # create 2 lists, the 1st as the word split into a list, the 2nd an empty list of the same size that will\n # be get filled in sequentially\n text_list = [x for x in word]\n blank_list = ['' for x in range(len(word))]\n\n # need to isolate the middle part of the word (not 1st, last, punctuation)\n # assumption that any punctuation is at the end of each word. e.g. hello!, not hel?lo\n lst = [x for x in range(1, ( len(text_list) - (len(punctuation) + 1) ))]\n lst2 = lst[:]\n\n # if there is only 1 randmisable character its position can't be changed \n if len(lst) > 1:\n # shuffle the order of the randomisable characters, shuffle could return the same order (by chance) so perform\n # this operation inside a while loop\n while (np.array_equal(lst,lst2)):\n random.shuffle(lst2)\n\n # j variable is a counter for which element to take from the randomised characters list\n j = 0\n for i in range(len(word)):\n if i == 0: \n # Keep first character in position\n blank_list[i] = text_list[i]\n elif (len(punctuation) > 0) and ((text_list[i] in punctuation) or (text_list[i+1] in punctuation)):\n # Keep punctuation and last character (if there's punctuation) in position\n blank_list[i] = text_list[i]\n elif (len(punctuation) == 0) and (i == len(word)-1):\n # Keep last character in position, if no punctuation\n blank_list[i] = text_list[i]\n else:\n # if the character is not punctuation or first/last character then take from the randomised list\n blank_list[i] = text_list[lst2[j]]\n j += 1\n\n new_text = ''.join(blank_list)\n # join the individual list elements for each word together to create the randomised word\n result_list.append(new_text)\n # append the \n else:\n # if the word is less than 3 characters return the original word\n result_list.append(word)\n result = ''.join([item + ' ' for item in result_list]).strip()\n \n if (len(lst) > 2) & (result == text):\n result = mix_words(text)\n \n return result", "import random\nimport re\n\ndef sub(m):\n s = m.group()\n xs = list(s[1:-1])\n mid = list(s[1:-1])\n while mid == xs:\n random.shuffle(mid)\n return s[0] + ''.join(mid) + s[-1]\n\ndef mix_words(s):\n if not isinstance(s, str):\n return None\n return re.sub('[a-z]{4,}', sub, s, flags=re.I)", "import re\nfrom random import shuffle\n\ndef mix_words(string):\n def mix(s):\n s = list(s)\n shuffle(s)\n return \"\".join(s)\n \n return re.sub(\"(\\w)(\\w{2,})(\\w)\", lambda m: m.group(1) + mix(m.group(2)) + m.group(3), string)", "from random import shuffle\nimport re\n\ndef scrambler(m):\n lst = list(m.group())\n shuffle(lst)\n return ''.join(lst)\n\ndef mix_words(s):\n if isinstance(s, str): return re.sub(r'(?<=\\w)\\w{2,}(?=\\w)', scrambler, s)", "import re\nfrom random import sample\ndef mix_words(strng):\n if type(strng)!=str:\n return None\n return re.sub(r'[A-Za-z]{4,}',fu,strng)\n\ndef fu(w):\n w = w.group()\n r = w[1:-1]\n while r==w[1:-1]:\n r = ''.join(sample(r,len(r)))\n return w[0]+r+w[-1]", "def mix_words(words):\n import re, random\n \n def slacrbme(word):\n mid = [c for c in word[1:-1]]\n random.shuffle(mid)\n return word[0] + ''.join(mid) + word[-1]\n \n return re.sub(r'(\\w{3,})', lambda m: slacrbme(m.groups()[0]), words)", "from random import shuffle\n\ndef mix_words(s):\n if type(s) != str:\n return \"undefined\"\n else:\n splitter = s.split(' ')\n for i, word in enumerate(splitter):\n punctuation = not word[-1].isalpha()\n if len(word) > 3 + punctuation:\n middle = list(word[1:-1 - punctuation])\n while middle == list(word[1:-1 - punctuation]):\n shuffle(middle)\n splitter[i] = word[0] + ''.join(middle) + word[-1 - punctuation:]\n return ' '.join(splitter)"]
{"fn_name": "mix_words", "inputs": [["Hi"], ["Hi!"], ["Hey"], ["Hey?"]], "outputs": [["Hi"], ["Hi!"], ["Hey"], ["Hey?"]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,153
def mix_words(s):
b8a7ee8451d679875cbc468f788e41b4
UNKNOWN
Your task is to find the first element of an array that is not consecutive. By not consecutive we mean not exactly 1 larger than the previous element of the array. E.g. If we have an array `[1,2,3,4,6,7,8]` then `1` then `2` then `3` then `4` are all consecutive but `6` is not, so that's the first non-consecutive number. ```if:c If a non consecutive number is found then return `true` and set the passed in pointer to the number found. If the whole array is consecutive then return `false`. ``` ```if-not:c If the whole array is consecutive then return `null`^(2). ``` The array will always have at least `2` elements^(1) and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too! If you like this Kata, maybe try this one next: https://www.codewars.com/kata/represent-array-of-numbers-as-ranges ```if:c ^(1) Can you write a solution that will return `false` for both `[]` and `[ x ]` (an empty array and one with a single number) though? (This is an empty array and one with a single number and is not tested for, but you can write your own example test. ) ``` ```if-not:c ^(1) Can you write a solution that will return `null`^(2) for both `[]` and `[ x ]` though? (This is an empty array and one with a single number and is not tested for, but you can write your own example test. ) ^(2) Swift, Ruby and Crystal: `nil` Haskell: `Nothing` Python, Rust: `None` Julia: `nothing` Nim: `none(int)` (See [options](https://nim-lang.org/docs/options.html)) ```
["def first_non_consecutive(arr):\n if not arr: return 0\n for i, x in enumerate(arr[:-1]):\n if x + 1 != arr[i + 1]:\n return arr[i + 1]", "def first_non_consecutive(a):\n i = a[0]\n for e in a:\n if e != i:\n return e\n i += 1\n return None", "def first_non_consecutive(arr):\n for i in range(1, len(arr)):\n if arr[i] - arr[i-1] > 1:\n return arr[i]", "def first_non_consecutive(arr):\n return next((j for i, j in zip(arr, arr[1:]) if i + 1 != j), None)", "def first_non_consecutive(arr):\n for i, v in enumerate(arr, arr[0]):\n if v != i:\n return v", "def first_non_consecutive(arr):\n for b in range(len(arr) - 1):\n if arr[b + 1] - arr[b] != 1:\n return arr[b + 1]\n", "def first_non_consecutive(arr):\n for i, j in zip(arr, arr[1:]):\n if abs(j-i) > 1:\n return j\n return None", "def first_non_consecutive(arr):\n init = arr[0]\n for i in arr:\n if init != i:\n return i\n else:\n init += 1\n return None", "def first_non_consecutive(arr):\n pre=arr[0]-1\n for e in arr:\n if e-pre!=1:\n return e\n pre=e\n return\n", "def first_non_consecutive(arr):\n if not arr:\n return None\n\n for i, x in enumerate(arr, arr[0]):\n if i != x:\n return x\n\n return None", "def first_non_consecutive(a):\n return [e for i,e in enumerate(a + [None]) if e != a[0] + i][0]", "def first_non_consecutive(arr):\n a = [x+1 for x in range(min(arr), max(arr)+1) if x not in arr]\n return None if a == [] else a[0]", "def first_non_consecutive(arr):\n for i in range(1,len(arr)):\n if arr[i-1]+ 1 < arr[i]:\n return arr[i]\n", "def first_non_consecutive(arr):\n for x in range(min(arr), max(arr)+1):\n if x not in arr:\n return x+1", "def first_non_consecutive(arr):\n for n in range(len(arr) - 1):\n if arr[n + 1] != arr[n] + 1:\n return arr[n + 1]\n return None", "def first_non_consecutive(arr):\n for i, q in enumerate(arr, arr[0]):\n if i != q:\n return q", "def first_non_consecutive(arr):\n b = arr.pop(0);\n for i in arr:\n if b + 1 == i : b = i;\n else: return i", "def first_non_consecutive(arr):\n for index in range(len(arr)-1):\n if abs(arr[index+1] - arr[index]) != 1:\n return arr[index+1]\n return None", "def first_non_consecutive(a):\n for i, x in enumerate(a, a[0]):\n if i != x:\n return x", "def first_non_consecutive(arr):\n for ind in range(1, len(arr)):\n if arr[ind] - arr[ind-1] > 1:\n return arr[ind]", "def first_non_consecutive(list):\n tmp = ''\n for item in list:\n if tmp == '':\n tmp = str(item)\n else:\n if item == int(tmp) + 1:\n tmp = str(item)\n else:\n return item", "def first_non_consecutive(arr):\n k = arr[0]\n for i in arr:\n if i!=k:\n return i\n k+=1\n return None", "def first_non_consecutive(arr):\n for i in range(1,len(arr)):\n if ( arr[i] - arr[i-1] != 1 ): return arr[i]\n else:\n return None", "def first_non_consecutive(arr):\n for x in range(1,len(arr)):\n if arr[x]-1 != arr[x-1]:\n return arr[x]\n", "def first_non_consecutive(arr):\n for i, a in enumerate(arr):\n if 0 < i < len(arr) + 1 and a != arr[i-1] + 1:\n return a", "def first_non_consecutive(arr):\n for i in range(len(arr)-1):\n if not arr[i]+1 == arr[i+1]: return arr[i+1]\n return None", "def first_non_consecutive(arr):\n for i in range(len(arr)-1):\n if arr[i] != arr[i+1]-1:\n return arr[i+1]\n return None", "def first_non_consecutive(arr):\n #your code here\n for i in range(1, len(arr)):\n if arr[i] - arr[i-1] != 1:\n return arr[i]\n return None", "def first_non_consecutive(arr):\n #your code here\n for i in range(len(arr)-1):\n if arr[i]+1!=arr[i+1]:\n return arr[i+1]\n return None\n", "first_non_consecutive = lambda a: min([e for i,e in enumerate(a) if i>0 and e!=a[i-1]+1] or [None])", "def first_non_consecutive(arr):\n for j in range(1, len(arr)):\n if arr[j] != arr[j-1]+1:\n return arr[j]", "from itertools import count\ndef first_non_consecutive(arr):\n return next((a for a, b in zip(arr, count(arr[0])) if a != b), None)", "def first_non_consecutive(arr):\n return next(iter(a for a, b in zip(arr, range(arr[0], arr[-1])) if a != b), None)", "def first_non_consecutive(arr):\n for i in range(1, len(arr)):\n if abs(arr[i] - arr[i-1]) > 1:\n return arr[i]", "def first_non_consecutive(arr):\n for ix in range(len(arr) - 1):\n if arr[ix] + 1 != arr[ix + 1]:\n return arr[ix + 1]", "def first_non_consecutive(arr):\n expected = arr[0]\n for x in arr:\n if x != expected:\n return x\n else:\n expected = x + 1\n \n", "def first_non_consecutive(arr):\n res = [arr[i] for i in range(1, len(arr)) if arr[i-1] != arr[i]-1]\n return res[0] if res else None", "def first_non_consecutive(a):\n i = 0\n n = None\n while i < len(a)-1:\n if a[i]+1 != a[i+1]:\n n = a[i+1]\n break\n i += 1\n return n", "def first_non_consecutive(arr):\n for number_lag, number in zip(arr[:-1], arr[1:]):\n if number_lag+1 != number:\n return number\n else:\n return None\n \n", "def checkConsecutive(l): \n return sorted(l) == list(range(min(l), max(l)+1))\n\ndef first_non_consecutive(nums):\n if checkConsecutive(nums):\n return None\n else:\n gaps = [[s, e] for s, e in zip(nums, nums[1:]) if s+1 < e]\n edges = iter(nums[:1] + sum(gaps, []) + nums[-1:])\n A=list(zip(edges,edges))\n A.pop(0)\n L=[]\n for i in A:\n for j in i:\n L.append(j)\n return L[0]", "def first_non_consecutive(arr):\n #your code here\n length = len(arr)\n if length <=2:\n return None\n len_list = list(range(length))\n for item in len_list:\n try:\n if abs(arr[item+1] - arr[item]) != 1:\n return arr[item+1]\n break\n except:\n return None", "def first_non_consecutive(arr):\n for n in arr:\n if n != arr.index(n)+arr[0]:\n return n", "def first_non_consecutive(arr):\n for i in range(len(arr)-1):\n next = arr[i+1]\n if arr[i] +1 != next:\n return next\n return None", "def first_non_consecutive(arr):\n return next((n for i,n in enumerate(arr[1:]) if n != arr[i]+1), None)\n \"\"\" WARNING: i = 0 for the second element of arr! ;) \"\"\"", "def first_non_consecutive(arr):\n for i in range(1,len(arr)):\n if (arr[i]-1)!=arr[i-1]:\n return arr[i]\n return None", "def first_non_consecutive(arr):\n is_consecutive = True\n for index, item in enumerate(arr[0:-1]):\n if item + 1 == arr[index + 1]:\n continue\n else:\n is_consecutive = False\n return arr[index + 1]\n break\n if is_consecutive == True:\n return None", "def first_non_consecutive(arr):\n for i in range(len(arr)-1):\n if arr[i+1] - arr[i] != 1:\n return arr[i+1]\n return None\n \n", "from typing import List, Optional\n\ndef first_non_consecutive(arr: List[int]) -> Optional[int]:\n \"\"\" Find the first element of an array that is not consecutive. \"\"\"\n for prev, next in zip(arr, arr[1:]):\n if next - prev > 1:\n return next", "def first_non_consecutive(arr):\n return None if len(arr) < 2 else (arr[1] if arr[1]-arr[0] != 1 else first_non_consecutive(arr[1::]))", "from operator import eq\nfrom itertools import compress\n\ndef first_non_consecutive(a):\n return next(compress(a, [not eq(*x) for x in zip(a,list(range(a[0],a[0]+len(a)+1)))]), None)\n", "def first_non_consecutive(arr):\n return next((y for x, y in zip(arr, arr[1:]) if y - x > 1), None)", "def first_non_consecutive(arr):\n return next((i for i in arr if not min(arr)+arr.index(i)==i), None)", "def first_non_consecutive(arr):\n try:\n return [i for i in arr if not min(arr)+arr.index(i)==i][0]\n except:\n return None", "def first_non_consecutive(lst_input): \n if sorted(lst_input) == list(range(min(lst_input), max(lst_input)+1)):\n return None \n else:\n if sorted(lst_input) != list(range(min(lst_input), max(lst_input)+1)):\n for val, val2 in zip(sorted(lst_input), list(range(min(lst_input), max(lst_input)+1))):\n if val != val2:\n return val", "def first_non_consecutive(arr):\n i = 0\n for i in range(0, len(arr)):\n if (i + 1 < len(arr)):\n if (arr[i]+1 != arr[i+1]):\n i += 1 \n return arr[i]\n", "def first_non_consecutive(arr):\n for i in range(len(arr)-1):\n if arr[i+1] - arr[i] != 1 :\n return(arr[i+1])\n else:\n print('',end=\"\")\n", "def first_non_consecutive(arr):\n numbers = list(range(arr[0], arr[-1] + 1))\n missing = [number for number in numbers if number not in arr]\n return missing[0] + 1 if missing != [] else None", "def first_non_consecutive(x):\n \n for i in x:\n if i-1 not in x:\n if i == x[0]:\n pass\n else:\n return i\n", "def first_non_consecutive(arr):\n for i, e in enumerate(arr):\n if i == len(arr)-1: return None\n elif e+1 != arr[i+1]: return arr[i+1]\n", "def first_non_consecutive(arr):\n #your code here\n a=[arr[i+1] for i in range(len(arr)) if i+1<len(arr) and arr[i+1]-arr[i] >1]\n print(a)\n return a[0] if len(a)>0 else None", "def first_non_consecutive(arr):\n return None if list(range(arr[0], arr[-1] + 1)) == arr else [arr[i + 1] for i in range(0, len(arr) - 1) if arr[i] + 1 != arr[i + 1]][0]", "def first_non_consecutive(arr):\n d=[arr[0]]\n for i in arr:\n d.append(i+1)\n if len(list(set(d[:-1]).difference(arr)))==0:\n return None\n else:\n return min(list(set(d[:-1]).difference(arr)))+1", "def first_non_consecutive(arr):\n for i in range(len(arr)-1):\n if arr[i+1]-arr[i]==1:\n continue\n elif arr[i+1]-arr[i]!=1:\n return arr[i+1]\n else:\n return None", "def first_non_consecutive(arr):\n results = set(range(arr[0], arr[-1])) - set(arr)\n return min(results)+1 if len(results) > 0 else None", "def first_non_consecutive(arr):\n comparator = arr[0]\n for n in arr:\n if comparator == n:\n comparator = comparator + 1\n else:\n return n", "def first_non_consecutive(arr):\n n = 0\n while n < len(arr)-1:\n if arr[n+1] - arr[n] != 1:\n return arr[n+1] \n n +=1 ", "def first_non_consecutive(arr):\n result = arr[0]\n for i in arr[1:]:\n if i - result != 1:\n return i\n result = i", "def first_non_consecutive(arr):\n new_list = arr.pop(0)\n for num in arr:\n new_list += 1\n if num != new_list:\n return num\n", "def first_non_consecutive(arr):\n \n \n for int in range(1,len(arr)):\n if arr[int]-arr[int-1]!=1:\n return arr[int]\n \n \n \n return None", "def first_non_consecutive(l):\n for i,n in enumerate(l[1:]):\n if n!=l[i]+1:\n return n", "def first_non_consecutive(arr):\n for i, x in enumerate(arr):\n if x != arr[i-1]+1 and i > 0:\n return x\n return None\n\n", "def first_non_consecutive(arr):\n i = arr.pop(0)\n for item in arr:\n i += 1\n if item != i:\n return item \n return None", "def first_non_consecutive(arr):\n i = 0\n for num in range(arr[0], arr[len(arr) - 1]):\n if num != arr[i]:\n return arr[i]\n i += 1\n return None", "def first_non_consecutive(arr):\n for i in range(1, len(arr)):\n if not arr[i] == arr[i - 1] + 1:\n return arr[i]\n return None", "def first_non_consecutive(arr):\n first, last = arr[0], arr[-1]\n diff = set(range(first, last + 1)) - set(arr)\n return min(diff) + 1 if diff else None\n", "def first_non_consecutive(arr):\n x = len(arr)\n z= []\n y = []\n for k in range(0,x-1):\n if (arr[k]+1) == arr[(k+1)]:\n y.append(arr[k+1])\n else:\n z.append(arr[k+1])\n \n if z==[]:\n return None\n else:\n z = min(z)\n return z\n \n\n\n #your code here\n", "def first_non_consecutive(arr):\n for n in range(len(arr)):\n if n+1 < len(arr):\n if arr[n+1] - arr[n] > 1:\n return arr[n+1]\n return None", "def first_non_consecutive(arr):\n ans = arr[0]\n for i in arr:\n if ans != i:\n return i\n else:\n ans += 1\n return None\n", "def first_non_consecutive(arr):\n for i in range(len(arr)-1):\n if arr[i] - arr[i+1] != -1:\n return arr[i+1]\n else:\n return None", "def first_non_consecutive(arr):\n size = len(arr)\n for i in range(size):\n if i == size-1:\n return None\n elif arr[i+1] > arr[i]+1:\n return arr[i+1]", "def first_non_consecutive(arr=[]):\n if len(arr) > 1:\n for i in range(len(arr)):\n if i < len(arr) - 1:\n if arr[i + 1] != arr[i] + 1:\n return arr[i + 1]\n else:\n return None", "def first_non_consecutive(arr):\n n = 0\n try:\n for i in arr:\n if i + 1 == arr[n + 1]:\n n += 1\n continue\n elif i + 1 != arr[n + 1]:\n return arr[n + 1]\n except:\n return None", "def first_non_consecutive(arr):\n i = 0\n while i < len(arr) - 1:\n i += 1\n if arr[0] >= 0 and arr[i] - arr[i - 1] != 1:\n return arr[i]\n break\n elif arr[0] < 0 and abs(arr[i - 1]) - abs(arr[i]) != 1:\n return arr[i]\n break\n else:\n return None", "def first_non_consecutive(arr):\n lena = len(arr)\n b = arr[0]\n for i in arr:\n if b == i:\n b = b + 1\n print(\"tut\")\n else:\n return i\n \n \n\n", "def first_non_consecutive(arr):\n for i, v in enumerate(arr, arr[0]):\n if i != v:\n return i + 1\n return None", "def first_non_consecutive(a):\n temp = [a[i] for i in range(len(a)) if i !=0 and a[i] != a[i-1]+1]\n return temp[0] if temp else None", "def first_non_consecutive(arr):\n #your code here\n first_ele = arr[0]\n for i in range(1,len(arr)):\n if arr[i] == first_ele +1:\n first_ele=first_ele + 1\n else:\n return arr[i]\n", "def first_non_consecutive(arr):\n for i in range(len(arr)-1):\n if arr[i+1] != arr[i]+1:\n return arr[i+1]\n if len(arr) == 0:\n return None\n", "def first_non_consecutive(arr):\n i = 0\n j = 1\n for k in range(len(arr)-1):\n if arr[i] +1 != arr[j]:\n return arr[j]\n else:\n i += 1\n j+= 1", "first_non_consecutive = lambda arr: (lambda x:None if len(x)==0 else min(x)+1)({*range(min(arr),max(arr)+1)}.difference({*arr}))", "def first_non_consecutive(arr):\n for el in range(0, len(arr) - 1):\n if(arr[el + 1] - arr[el] > 1):\n return arr[el + 1]", "def first_non_consecutive(arr):\n if len(arr) > 1:\n for i in range(len(arr) - 1):\n if arr[i + 1] - arr[i] > 1:\n return arr[i + 1]\n return \n else:\n return ", "import numpy\ndef first_non_consecutive(arr):\n if sorted(arr) == list(range(min(arr), max(arr)+1)):\n return None\n else:\n difference = list(numpy.diff(arr))\n for i in difference:\n if i > 1:\n index = difference.index(i)\n return arr[index+1]\n \n \n #your code here\n", "def first_non_consecutive(arr):\n return next((arr[i] for i in range(1, len(arr)) if arr[i] - 1 != arr[i-1]), None)", "def first_non_consecutive(arr):\n if len(arr) == 2:\n return None\n elem_1 = arr[0]\n elem_2 = arr[1]\n elem_3 = arr[2]\n diff_1 = elem_2 - elem_1\n diff_2 = elem_3 - elem_2\n if diff_1 > diff_2:\n grade_1 = diff_2\n elif diff_1 < diff_2:\n grade_1 = diff_1\n else:\n grade_1 = diff_1\n for i in range(0, len(arr) - 1):\n if arr[i + 1] != arr[i] + grade_1:\n return arr[i + 1]\n \n return None", "\n \n \ndef first_non_consecutive(arr):\n for a,b in zip(arr[:-1], arr[1:]):\n if b!=a+1:\n return b\n", "def first_non_consecutive(arr):\n expected = arr[0]\n for x in arr:\n if x != expected:\n return x\n else:\n expected += 1\n", "def first_non_consecutive(arr):\n x = arr[0]\n for index in arr:\n if index != x:\n result = index\n break\n x += 1\n else:\n result = None\n return result", "def first_non_consecutive(arr):\n try:\n for i in range(len(arr)):\n if arr[i] != arr[i+1] - 1:\n return arr[i+1]\n except:\n return None", "def first_non_consecutive(arr):\n for num in arr:\n i = arr.index(num)\n if i > (len(arr) - 2):\n return None\n elif arr[i + 1] == int(num + 1):\n continue\n else:\n return arr[i + 1]\n #your code here\n"]
{"fn_name": "first_non_consecutive", "inputs": [[[1, 2, 3, 4, 6, 7, 8]], [[1, 2, 3, 4, 5, 6, 7, 8]], [[4, 6, 7, 8, 9, 11]], [[4, 5, 6, 7, 8, 9, 11]], [[31, 32]], [[-3, -2, 0, 1]], [[-5, -4, -3, -1]]], "outputs": [[6], [null], [6], [11], [null], [0], [-1]]}
INTRODUCTORY
PYTHON3
CODEWARS
18,120
def first_non_consecutive(arr):
0a9d7c66db5dbb285daa18fb21863961
UNKNOWN
# Fun fact Tetris was the first video game played in outer space In 1993, Russian cosmonaut Aleksandr A. Serebrov spent 196 days on the Mir space station with a very special distraction: a gray Game Boy loaded with Tetris. During that time the game orbited the Earth 3,000 times and became the first video game played in space. The Game Boy was sold in a Bonhams auction for $1,220 during the Space History Sale in 2011. # Task Parse the game log and determine how many lines have been cleared through the game. The game ends if all commands from input were interpreted or the maximum field height (30 units) is reached. A horizontal line, according to the rules of classic Tetris, is considered cleared if it represents a solid line without gaps formed by falling blocks. When such a line is formed, it disappears and any blocks above it fall down to fill the space. # Input ```python ['4L2', '3R4', '4L3', '3L4', '4R0', '1L2'] # example ``` As an argument, you are given gamelog - an array of commands which you need to interpret. Each command has the same form: * The first character - the type of block (integer from 1 to 4, as in this kata we have only 4 types of blocks). Block types are described below. * The second - the direction of movement (`"R"` or `"L"` - right or left). * The third is an offset (integer from 0 to 4, as width of our field 9 units and new block always appears at the center of the field) relative to the starting position. Thus, `L4` means the leftmost position, and `R4` the rightmost, and `L0` is equivalent to `R0`. # Output The total number of cleaned horizontal lines (`int`) to the end of the game. Note, if the field height is exceeded, then the game ends immediately. # Blocks In this kata we have only 4 types of blocks. Yes, this is not a classic set of shapes, but this is only for simplicity. ``` # and their graphical representation: ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ---+---+---+--- #1 #2 #3 #4 ``` # Field Gamefield (a rectangular vertical shaft) has width 9 units and height 30 units. table, th, td { border: 1px solid; } Indices can be represented as: L4 L3 L2 L1 L0/R0 R1 R2 R3 R4 # Example 1 ```python >>> gamelog = ['1R4', '2L3', '3L2', '4L1', '1L0', '2R1', '3R2', '4R3', '1L4'] >>> tetris(gamelog) 1 ``` Gamefield before last command (_ means empty space): ``` ___■___■_ __■■__■■_ _■■■_■■■_ _■■■■■■■■ ``` Gamefield after all commands: ``` ___■___■_ __■■__■■_ _■■■_■■■_ ``` As you can see, one solid line was cleared. So, answer is 1. # Example 2 ```python >>> gamelog = ['1L2', '4R2', '3L3', '3L1', '1L4', '1R4'] >>> tetris(gamelog) 0 ``` Gamefield after all commands: ``` _____■__ _■_■__■__ _■_■__■__ ■■■■__■_■ ``` As you can see, there is no solid lines, so nothing to clear. Our answer is 0, zero cleaned lines. # Note Since there is no rotation of blocks in our model and all blocks are very simple, do not overthink the task. # Other If you like the idea: leave feedback, and there will be more katas in the Tetris series. * 7 kyuTetris Series #1 — Scoring System * 6 kyuTetris Series #2 — Primitive Gameplay * 6 kyuTetris Series #3 — Adding Rotation (TBA) * 5 kyuTetris Series #4 — New Block Types (TBA) * 4 kyuTetris Series #5 — Complex Block Types (TBA?)
["pos = {\"L4\":0, \"L3\":1, \"L2\":2, \"L1\":3, \"L0\":4, \"R0\":4, \"R1\":5, \"R2\":6, \"R3\":7, \"R4\":8}\n\ndef tetris(arr):\n current, res = [0]*9, 0\n for x in arr:\n p = pos[x[1:]]\n current[p] += int(x[0])\n if current[p] >= 30: break\n y = min(current)\n if y: current, res = [v-y for v in current], res+y\n return res", "class Game():\n\n def __init__(self, arr):\n self.comands = arr\n self.score = 0\n self.step = None\n self.fild = [-1]*9 \n self.over = lambda x:max(x)>=29\n \n def __break__(self):\n while -1 not in self.fild:\n self.score +=1\n self.fild = [ e-1 for e in self.fild ]\n return self.over(self.fild)\n \n def __values__(self, comand):\n self.step = 4 + {'R':lambda m: +int(m), \n 'L':lambda m: -int(m)}[comand[1]](comand[2])\n return int(comand[0])\n\n def game(self):\n for comand in self.comands:\n block = self.__values__(comand)\n self.fild[self.step] += block\n if self.__break__(): \n break\n return self.score\n \ndef tetris(arr) -> int:\n play = Game(arr)\n return play.game()\n", "def tetris(arr) -> int:\n bd, lines = [0]*9, 0\n for n,d,m in arr:\n i = int(m)*(-1)**(d=='R')\n bd[i] += int(n)\n if bd[i]>29:\n h = min(bd)\n if bd[i]-h>29: break\n lines += h\n bd = [v-h for v in bd]\n lines += min(bd)\n return lines", "from collections import Counter\n\ndef tetris(arr):\n fields = Counter()\n clear = 0\n for log in arr:\n pos = log[1:].replace('R0', 'L0')\n fields[pos] += int(log[0])\n if fields[pos] >= 30:\n break\n elif len(fields) == 9:\n c = min(fields.values())\n clear += c\n for pos in fields:\n fields[pos] -= c\n return clear", "def tetris(arr) -> int:\n\n lines_cleared = 0\n sum = [0,0,0,0,0,0,0,0,0]\n dict = {'L4': 0, 'L3': 1, 'L2': 2,\n 'L1': 3, 'L0': 4, 'R0': 4,\n 'R1': 5, 'R2': 6, 'R3': 7, 'R4': 8}\n \n for i in arr: \n sum[dict[i[-2:]]] += int(i[0])\n \n lines = min(sum)\n sum = [i - lines for i in sum] \n lines_cleared += lines\n \n if max(sum) >= 30:\n break\n \n return lines_cleared", "import numpy as np\n\n\ncol_dict = {\"L4\":0, \"L3\":1, \"L2\":2, \"L1\":3, \"L0\":4,\"R0\":4, \"R1\":5, \"R2\":6, \"R3\":7, \"R4\":8}\n \ndef tetris(arr) -> int:\n field = np.zeros(9, dtype = np.int8)\n counter = 0\n for turn in arr:\n block_height = int(turn[0])\n index = col_dict[turn[1:]]\n field[index] += block_height\n if field[index] >=30:\n return counter\n else:\n counter += field.min()\n field -= field.min()\n return counter", "def tetris(lst):\n field, lines = [0] * 9, 0\n for h, s, m in lst:\n i = 4 + int(m) * (-1 if s == \"L\" else 1)\n field[i] += int(h)\n while all(col > 0 for col in field):\n field, lines = [col - 1 for col in field], lines + 1\n if field[i] > 29:\n break\n return lines", "def tetris(a):\n b, glob_min, = [0] * 9, 29\n for x, y, z in a:\n i = int(z) * (-1)**(y == \"R\")\n b[i] += int(x)\n if b[i] > glob_min:\n n = min(b)\n if b[i] - n > 29:\n return n\n glob_min = n + 29\n return min(b)", "import numpy as np\n\ndef columnDecode(code):\n code = code.replace(\"R\", \"+\")\n code = code.replace(\"L\", \"-\")\n return int(code) + 4\n \ndef placePiece(colList,size,i):\n for x in range(i,size+i):\n colList[x] = 1\n return colList\n \ndef lineCheck(board):\n i = 0\n for i in range(5):\n if not all(board[:,i]):\n break\n return i\n\ndef tetris(arr):\n totalLines = 0\n board = np.zeros((9,29), dtype=\"int\")\n for piece in arr:\n col = columnDecode(piece[1:])\n size = int(piece[0])\n for i in range(len(board[col])-1,-1,-1):\n if board[col][i-1] == 1 or i <= 0:\n try:\n board[col] = placePiece(board[col],size,i)\n except:\n return totalLines\n lines = lineCheck(board)\n if lines > 0:\n board = board[:,lines:]\n board = np.hstack((board,np.zeros((board.shape[0],lines), dtype=\"int\")))\n totalLines += lines\n lines = 0 \n break\n return totalLines ", "def tetris(arr):\n d, c = {}, 0\n for i, j in enumerate(arr):\n t, dt = j[1:].replace('R0', 'L0'), d.values()\n d[t] = d.get(t, 0) + int(j[0])\n if len(dt)==9 and all(dt) : m = min(d.values()) ; d = {k:l-m for k,l in d.items()} ; c += m\n if d[t] >= 30 : break\n return c"]
{"fn_name": "tetris", "inputs": [[["1R4", "2L3", "3L2", "4L1", "1L0", "2R1", "3R2", "4R3", "1L4"]], [["1L2", "4R2", "3L3", "3L1", "1L4", "1R4"]], [["4R4", "4L3", "4L2", "4L1", "4L0", "4R1", "4R2", "4R3", "3L4"]]], "outputs": [[1], [0], [3]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,186
def tetris(arr):
80dbfb4f4c9c5684f1f3219d94a7ada7
UNKNOWN
The number 45 is the first integer in having this interesting property: the sum of the number with its reversed is divisible by the difference between them(absolute Value). ``` 45 + 54 = 99 abs(45 - 54) = 9 99 is divisible by 9. ``` The first terms of this special sequence are : ``` n a(n) 1 45 2 54 3 495 4 594 ``` Make the function ```sum_dif_rev()```(`sumDivRef` in JavaScript and CoffeeScript), that receives ```n```, the ordinal number of the term and may give us, the value of the term of the sequence. ```python sum_dif_rev(n) -----> a(n) ``` Let's see some cases: ```python sum_dif_rev(1) -----> 45 sum_dif_rev(3) -----> 495 ``` "Important: Do not include numbers which, when reversed, have a leading zero, e.g.: 1890 reversed is 0981, so 1890 should not be included." Your code will be tested up to the first 65 terms, so you should think to optimize it as much as you can. (Hint: I memoize, you memoize, he memoizes, ......they (of course) memoize) Happy coding!!
["MEMO = []\n\ndef sum_dif_rev(n):\n i = MEMO[-1] if MEMO else 0\n \n while len(MEMO) < n:\n i += 1\n r = int(str(i)[::-1])\n if i % 10 and r != i and (i + r) % abs(r - i) == 0:\n MEMO.append(i)\n\n return MEMO[n-1]", "from itertools import count\n\n# It's not worth it to memoize they numbers we reversed because a number is not always followed by its reversed in the result\n# So we would have to save they numbers and return the minimum saved each time we find a new one\n# All the numbers in this list are divisible by 9 so we can skip 88.9% of the possibilities\ndef gen():\n for x in count(0, 9):\n y = int(str(x)[::-1])\n if x != y and x % 10 and (x + y) % abs(x - y) == 0:\n yield x\nnumbers, result = gen(), []\n\ndef sum_dif_rev(n):\n while len(result) < n: result.append(next(numbers))\n return result[n-1]", "def sum_dif_rev(num):\n n = 36\n while num:\n n += 9\n if n % 10 == 0:\n continue\n r = int(str(n)[::-1])\n if n != r and (n + r) % abs(n - r) == 0:\n num -= 1\n return n\n", "def memoize_sum_dif(f):\n memory = {}\n \n def inner(n):\n if n not in memory:\n memory[n] = f(n)\n return memory[n]\n return inner\n \n \n@memoize_sum_dif\ndef sum_dif_rev(n):\n \n if n == 1: return 45\n \n num = sum_dif_rev(n-1)\n \n while True:\n num = num+1\n if str(num)[::-1][0] == \"0\" or abs(num - int(str(num)[::-1])) == 0 :\n continue\n if (num + int(str(num)[::-1]))%abs(num - int(str(num)[::-1])) == 0:\n break \n return num", "seq = [] \ndef sum_dif_rev(n):\n i = seq[-1] if seq else 0 \n while len(seq) < n:\n i += 9\n r = int(str(i)[::-1])\n if i % 10 and r != i and (r+i) % abs(r-i) == 0:\n seq.append(i)\n return seq[n-1]", "def sum_dif():\n yield 45\n yield 54\n yield 495\n yield 594\n n1 = 595\n while True:\n n_rev = str(n1)[::-1]\n if n_rev[0] == '0':\n n1 += 1\n continue\n n_rev_int = int(n_rev)\n if n1 - n_rev_int != 0 and (n1 + n_rev_int) % abs(n1 - n_rev_int) == 0:\n yield n1\n n1 += 1\n\ndef sum_dif_rev(n):\n p = sum_dif()\n return [next(p) for x in range(1, n+1)][-1]", "def sum_dif_rev(n):\n k = 0\n i = 1\n while(i <= n) :\n k += 1\n if str(k)[-1] != '0' :\n p = int((str(k))[::-1])\n if abs(p - k) != 0 :\n if (p + k) % abs(p - k) == 0 :\n i += 1\n return k", "buf = [45,54,495,594]\n\ndef sum_dif_rev(n):\n i = buf[-1]\n while len(buf)<n:\n i += 1; j = int(str(i)[::-1]); d = abs(i-j)\n if i%10 and d and not (i+j)%d: buf.append(i)\n return buf[n-1]\n"]
{"fn_name": "sum_dif_rev", "inputs": [[1], [3], [4], [5], [6]], "outputs": [[45], [495], [594], [4356], [4545]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,877
def sum_dif_rev(n):
a13a3b4a4bcfbbf73746df413bbf624e
UNKNOWN
Farmer Bob have a big farm, where he growths chickens, rabbits and cows. It is very difficult to count the number of animals for each type manually, so he diceded to buy a system to do it. But he bought a cheap system that can count only total number of heads, total number of legs and total number of horns of animals on the farm. Help Bob to figure out how many chickens, rabbits and cows does he have? All chickens have 2 legs, 1 head and no horns; all rabbits have 4 legs, 1 head and no horns; all cows have 4 legs, 1 head and 2 horns. Your task is to write a function ```Python get_animals_count(legs_number, heads_number, horns_number) ``` ```Csharp Dictionary get_animals_count(int legs_number, int heads_number, int horns_number) ``` , which returns a dictionary ```python {"rabbits" : rabbits_count, "chickens" : chickens_count, "cows" : cows_count} ``` ```Csharp new Dictionary(){{"rabbits", rabbits_count},{"chickens", chickens_count},{"cows", cows_count}} ``` Parameters `legs_number, heads_number, horns_number` are integer, all tests have valid input. Example: ```python get_animals_count(34, 11, 6); # Should return {"rabbits" : 3, "chickens" : 5, "cows" : 3} get_animals_count(154, 42, 10); # Should return {"rabbits" : 30, "chickens" : 7, "cows" : 5} ``` ```Csharp get_animals_count(34, 11, 6); //Should return Dictionary(){{"rabbits", 3},{"chickens", 5},{"cows", 3}} get_animals_count(154, 42, 10); //Should return Dictionary(){{"rabbits", 30},{"chickens", 7},{"cows", 5}} ```
["def get_animals_count(legs, heads, horns):\n cows = horns // 2\n rabbits = legs // 2 - cows - heads\n chickens = heads - cows - rabbits\n return dict(cows=cows, rabbits=rabbits, chickens=chickens)", "def get_animals_count(ln, hn, horn):\n c,ln,hn = horn//2, ln - 2*horn, hn - horn//2\n return {\"rabbits\":(ln-2*hn)//2,\"chickens\":2*hn -ln//2,\"cows\":c}", "def get_animals_count(legs, heads, horns):\n cows = horns // 2\n rabbits = (legs - 4 * cows) // 2 - (heads - cows)\n chickens = heads - cows - rabbits\n return {\"rabbits\": rabbits, \"chickens\": chickens, \"cows\": cows}", "def get_animals_count(legs_number, heads_number, horns_number):\n cows = horns_number / 2\n legs_number -= cows * 4\n heads_number -= cows\n rabbits = (legs_number - 2 * heads_number) / 2\n chickens = heads_number - rabbits\n return { 'rabbits': rabbits, 'chickens': chickens, 'cows': cows }", "def get_animals_count(legs, heads, horns):\n cows = horns / 2\n rabbits = legs / 2 - heads - cows\n chickens = heads - rabbits - cows\n return {\"rabbits\": rabbits, \"chickens\": chickens, \"cows\": cows}", "def get_animals_count(legs, heads, horns):\n cows = horns // 2\n legs = (legs - cows * 4) // 2\n heads -= cows\n rabbits = legs - heads\n chickens = heads - rabbits\n return {'cows': cows, 'rabbits': rabbits, 'chickens': chickens}", "import numpy as np\n\n# legs: 2x + 4y + 4z = n(legs)\n# heads: x + y + z = n(heads)\n# horns: 2z = n(horns)\n# where x, y, z: chickens, rabbits, cows\ncoefficients = np.array([[2, 4, 4], [1, 1, 1], [0, 0, 2]])\n\ndef get_animals_count(legs_number, heads_number, horns_number):\n dependents = np.array([legs_number, heads_number, horns_number])\n res = np.linalg.solve(coefficients, dependents)\n return dict(zip([\"chickens\", \"rabbits\", \"cows\"], (int(i) for i in res)))", "def get_animals_count(l,he,ho):\n return {\"rabbits\":l//2-he-ho//2,\"chickens\":2*he-l//2,\"cows\":ho//2}", "def get_animals_count(legs_number, heads_number, horns_number):\n return {\n 'rabbits': (legs_number - 2 * heads_number - horns_number) // 2,\n 'chickens': (4 * heads_number - legs_number) // 2,\n 'cows': horns_number // 2\n }\n", "def get_animals_count(legs_number, heads_number, horns_number):\n cows=horns_number//2\n legs_number-=cows*4\n heads_number-=cows\n rabbits=(legs_number-2*heads_number)//2\n chickens=heads_number-rabbits\n return {'rabbits':rabbits,'chickens':chickens,'cows':cows}"]
{"fn_name": "get_animals_count", "inputs": [[34, 11, 6], [154, 42, 10], [74, 20, 34], [152, 38, 34], [56, 17, 0]], "outputs": [[{"rabbits": 3, "chickens": 5, "cows": 3}], [{"rabbits": 30, "chickens": 7, "cows": 5}], [{"rabbits": 0, "chickens": 3, "cows": 17}], [{"rabbits": 21, "chickens": 0, "cows": 17}], [{"rabbits": 11, "chickens": 6, "cows": 0}]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,546
def get_animals_count(legs, heads, horns):
9089d78434f193dbf33ef2fcb0c2e0d7
UNKNOWN
You're continuing to enjoy your new piano, as described in Piano Kata, Part 1. You're also continuing the exercise where you start on the very first (leftmost, lowest in pitch) key on the 88-key keyboard, which (as shown below) is the note A, with the little finger on your left hand, then the second key, which is the black key A# ("A sharp"), with your left ring finger, then the third key, B, with your left middle finger, then the fourth key, C, with your left index finger, and then the fifth key, C#, with your left thumb. Then you play the sixth key, D, with your right thumb, and continue on playing the seventh, eighth, ninth, and tenth keys with the other four fingers of your right hand. Then for the eleventh key you go back to your left little finger, and so on. Once you get to the rightmost/highest, 88th, key, C, you start all over again with your left little finger on the first key. (If the Codewars Instructions pane resizes the above piano keyboard image to be too small to read the note labels of the black/sharp keys on your screen, click here to open a copy of the image in a new tab or window.) This time, in addition to counting each key press out loud (not starting again at 1 after 88, but continuing on to 89 and so forth) to try to keep a steady rhythm going and to see how far you can get before messing up, you're also saying the name of each note. You wonder whether this may help you develop perfect pitch in addition to learning to just *know* which note is which, and -- as in Piano Kata, Part 1 -- helping you to learn to move smoothly and with uniform pressure on the keys from each finger to the next and back and forth between hands. The function you are going to write will explore one of the patterns you're experiencing in your practice: Given the number you stopped on, which note was it? For example, in the description of your piano exercise above, if you stopped at 5, your left thumb would be on the fifth key of the piano, which is C#. Or if you stopped at 92, you would have gone all the way from keys 1 to 88 and then wrapped around, so that you would be on the fourth key, which is C. Your function will receive an integer between 1 and 10000 (maybe you think that in principle it would be cool to count up to, say, a billion, but considering how many years it would take it is just not possible) and return one of the strings "A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", or "G#" indicating which note you stopped on -- here are a few more examples: ``` 1 "A" 12 "G#" 42 "D" 100 "G#" 2017 "F" ``` Have fun!
["def which_note(count):\n return \"A A# B C C# D D# E F F# G G#\".split()[(count - 1) % 88 % 12]", "keyboard = \"A A# B C C# D D# E F F# G G#\".split()\n\ndef which_note(count):\n return keyboard[(count - 1) % 88 % 12]", "NOTES = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']\nNUMBER_OF_KEYS = 88\n\ndef which_note(key_press_count):\n return NOTES[(key_press_count - 1) % NUMBER_OF_KEYS % len(NOTES)]\n", "def which_note(key_press_count):\n key_press_count = key_press_count % 88 - 1\n L = [\"A\", \"A#\", \"B\"] + [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"]*7 + [\"C\"]\n return L[key_press_count]\n", "ks = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']\nkeys = ks * 7 + ks[:4]\n\ndef which_note(n):\n return keys[(n - 1) % len(keys)]", "def which_note(key_press_count):\n return [\"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\"][(key_press_count - 1) % 88 % 12]\n", "which_note=lambda n:\"A A# B C C# D D# E F F# G G#\".split()[~-n%88%12]", "def which_note(key_press_count):\n piano = (\"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\",\n \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\",\n \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\",\n \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\",\n \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\",\n \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\",\n \"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\",\n \"A\", \"A#\", \"B\", \"C\")\n\n return piano[key_press_count%88 -1]", "keys = {1: \"A\", 2: \"A#\", 3: \"B\", 4: \"C\", 5: \"C#\", 6: \"D\", 7: \"D#\", 8: \"E\", 9: \"F\", 10: \"F#\", 11: \"G\", 12: \"G#\", }\n\ndef which_note(n):\n\n return keys.get(((n - 1) % 88 % 12) + 1)", "def which_note(key_press_count):\n black_key=[2, 5, 7, 10, 12, 14, 17, 19, 22, 24, 26, 29, 31, 34, 36, 38, 41, 43, 46, 48, 50, 53, 55, 58, 60, 62, 65, 67, 70, 72, 74, 77, 79, 82, 84, 86]\n dict_white={1: 'A', 3: 'B', 4: 'C', 6: 'D', 8: 'E', 9: 'F', 11: 'G', 13: 'A', 15: 'B', 16: 'C', 18: 'D', 20: 'E', 21: 'F', 23: 'G', 25: 'A', 27: 'B', 28: 'C', 30: 'D', 32: 'E', 33: 'F', 35: 'G', 37: 'A', 39: 'B', 40: 'C', 42: 'D', 44: 'E', 45: 'F', 47: 'G', 49: 'A', 51: 'B', 52: 'C', 54: 'D', 56: 'E', 57: 'F', 59: 'G', 61: 'A', 63: 'B', 64: 'C', 66: 'D', 68: 'E', 69: 'F', 71: 'G', 73: 'A', 75: 'B', 76: 'C', 78: 'D', 80: 'E', 81: 'F', 83: 'G', 85: 'A', 87: 'B', 88: 'C'}\n if key_press_count%88 == 0:\n return 'C'\n elif key_press_count%88 in black_key:\n return(str(dict_white[(key_press_count-1)%88])+'#')\n else:\n return str(dict_white[(key_press_count)%88])"]
{"fn_name": "which_note", "inputs": [[1], [5], [12], [42], [88], [89], [92], [100], [111], [200], [2017]], "outputs": [["A"], ["C#"], ["G#"], ["D"], ["C"], ["A"], ["C"], ["G#"], ["G"], ["G#"], ["F"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,041
def which_note(key_press_count):
b35901fcb33280fc288c2596969a96d1
UNKNOWN
In an infinite array with two rows, the numbers in the top row are denoted `. . . , A[−2], A[−1], A[0], A[1], A[2], . . .` and the numbers in the bottom row are denoted `. . . , B[−2], B[−1], B[0], B[1], B[2], . . .` For each integer `k`, the entry `A[k]` is directly above the entry `B[k]` in the array, as shown: ...|A[-2]|A[-1]|A[0]|A[1]|A[2]|... ...|B[-2]|B[-1]|B[0]|B[1]|B[2]|... For each integer `k`, `A[k]` is the average of the entry to its left, the entry to its right, and the entry below it; similarly, each entry `B[k]` is the average of the entry to its left, the entry to its right, and the entry above it. Given `A[0], A[1], A[2] and A[3]`, determine the value of `A[n]`. (Where range of n is -1000 Inputs and Outputs in BigInt!** Adapted from 2018 Euclid Mathematics Contest. https://www.cemc.uwaterloo.ca/contests/past_contests/2018/2018EuclidContest.pdf
["def find_a(lst,n):\n if n<0: return find_a(lst[::-1], 3-n)\n if n<4: return lst[n]\n a,b,c,d = lst\n for _ in range(n-3):\n a,b,c,d = b, c, d, 6*d-10*c+6*b-a\n return d", "def find_a(A, n):\n if 0 <= n < 4: return A[n]\n if n < 0:\n A, n = A[::-1], abs(n) + 3\n B = [0] * 4\n B[1] = 3 * A[1] - A[0] - A[2]\n B[2] = 3 * A[2] - A[1] - A[3]\n B[3] = 3 * B[2] - B[1] - A[2]\n ind = 4\n while ind <= n:\n a = 3 * A[-1] - A[-2] - B[-1]\n b = 3 * B[-1] - B[-2] - A[-1]\n A.append(a)\n B.append(b)\n ind += 1\n return A[-1]", "def find_a(array, n):\n if n > 3:\n for i in range(4,n+1):\n array.append(6*array[i-1]+6*array[i-3]-10*array[i-2]-array[i-4])\n return array[-1]\n elif n < 0:\n array = array[::-1]\n for i in range(4,4-n):\n array.append(6*array[i-1]+6*array[i-3]-10*array[i-2]-array[i-4])\n return array[-1]\n else:\n return array[n]", "def find_a(array, n):\n if 0 <= n < 4:\n return array[n]\n b1 = 3*array[1] - array[0] - array[2]\n b2 = 3*array[2] - array[1] - array[3]\n b3 = 3*b2 - b1 - array[2]\n b0 = 3*b1 - b2 - array[1] \n array_b = [b0,b1,b2,b3]\n \n if n > 3:\n count = 3 \n else:\n array.reverse()\n array_b.reverse()\n count = 0\n n = 0 - n \n while count < n:\n a_next = 3*array[-1] - array[-2] - array_b[-1]\n b_next = 3*array_b[-1] - array_b[-2] - array[-1]\n array.append(a_next)\n array_b.append(b_next)\n count += 1\n \n return array[-1]\n", "def find_a(array, n):\n if n in [0,1,2,3]:\n return array[n]\n b1 = 3*array[1] - array[0] - array[2]\n b2 = 3*array[2] - array[1] - array[3]\n if n > 3:\n ak = array[3]\n bk = 3*b2 - b1 - array[2]\n ap = array[2]\n bp = b2\n i = 3\n while i < n:\n ak, ap = 3 * ak - bk - ap, ak\n bk, bp = 3 * bk - ap - bp, bk\n i += 1\n return ak\n else:\n ak = array[0]\n bk = 3 * b1 - b2 - array[1]\n ap = array[1]\n bp = b1\n i = 0\n while i > n:\n ak, ap = 3 * ak - bk - ap, ak\n bk, bp = 3 * bk - ap - bp, bk\n i -= 1\n return ak", "def find_a(array, n):\n if n in range(4): return array[n]\n if n < 0: return find_a([*reversed(array)], 3 - n)\n a1 = array[1]\n a2 = array[2]\n b1 = 3 * array[1] - array[0] - array[2]\n b2 = 3 * array[2] - array[1] - array[3]\n for _ in range(n - 2):\n a1, b1, a2, b2 = a2, b2, 3 * a2 - a1 - b2, 3 * b2 - b1 - a2\n return a2", "def find_a(array, n):\n if n >= 0:\n if n < 4:\n return array[n]\n else:\n A = array[:]\n B = [0, 0, 0, 0]\n B[1] = 3 * A[1] - A[0] - A[2]\n B[2] = 3 * A[2] - A[1] - A[3]\n B[0] = 3 * B[1] - B[2] - A[1]\n B[3] = 3 * B[2] - B[1] - A[2]\n for i in range(n - 3):\n A.append(\"undefined\")\n B.append(\"undefined\")\n for i in range(4, len(A)):\n A[i] = 3 * A[i - 1] - A[i - 2] - B[i - 1]\n B[i] = 3 * B[i - 1] - B[i - 2] - A[i - 1]\n return A[-1]\n else:\n A = array[:]\n B = [0, 0, 0, 0]\n B[1] = 3 * A[1] - A[0] - A[2]\n B[2] = 3 * A[2] - A[1] - A[3]\n B[0] = 3 * B[1] - B[2] - A[1]\n B[3] = 3 * B[2] - B[1] - A[2]\n for i in range(-n):\n A = [\"undefined\"] + A\n B = [\"undefined\"] + B\n for i in range(-n-1, -1, -1):\n A[i] = 3 * A[i + 1] - A[i + 2] - B[i + 1]\n B[i] = 3 * B[i + 1] - B[i + 2] - A[i + 1]\n return A[0]", "def find_a(array, n):\n if 0<=n<4:\n return array[n]\n a = {i:x for i,x in enumerate(array)}\n if n>4:\n for i in range(4,n+1):\n a[i] = -a[i-4]+6*a[i-3]-10*a[i-2]+6*a[i-1]\n else:\n for i in range(-1,n-1,-1):\n a[i] = 6*a[i+1]-10*a[i+2]+6*a[i+3]-a[i+4]\n return a[i]\n", "def find_a(a, n):\n if 0 <= n < len(a):\n return a[n]\n\n if n < 0:\n n = 3 - n\n a = a[::-1]\n\n b = [None] * 4\n b[1] = 3*a[1] - a[0] - a[2]\n b[2] = 3*a[2] - a[1] - a[3]\n b[0] = 3*b[1] - a[1] - b[2]\n b[3] = 3*b[2] - b[1] - a[2]\n for _ in range(n-3):\n x = 3*a[-1] - b[-1] - a[-2]\n y = 3*b[-1] - a[-1] - b[-2]\n a.append(x)\n b.append(y)\n return a[-1]", "def find_a(array, n):\n if 0 <= n <= 3: return array[n]\n a0 = array[0]\n a1 = array[1]\n a2 = array[2]\n a3 = array[3]\n b1 = 3*a1 - a0 - a2\n b2 = 3*a2 - a1 - a3\n b3 = 3*b2 - b1 - a2\n b0 = 3*b1 - b2 - a1\n if n > 3:\n for k in range(4, n+1, 1):\n an = 3*a3 - a2 - b3\n bn = 3*b3 - b2 - a3\n \n a2, a3 = a3, an\n b2, b3 = b3, bn\n \n else: \n for k in range(-1, n-1, -1):\n an = 3*a0 - a1 - b0\n bn = 3*b0 - b1 - a0\n \n a0, a1 = an, a0\n b0, b1 = bn, b0\n \n return an"]
{"fn_name": "find_a", "inputs": [[[1, 2, 3, 4], 2], [[38, 200, -18, 45], 1], [[1, 0, 0, 1], 5], [[0, 2, 0, 3], -2], [[-20, 1, -3, 14], -5], [[1, 2, 3, 5], 100], [[0, 4, 6, 13], 100]], "outputs": [[3], [200], [20], [-126], [-44402], [60560100487003612846322657690093088848428068520476594299], [335254562473098582210532865941148591672699700764231400858]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,256
def find_a(array, n):
a5ef34f2a9ad6fcd94c9f0733ad2b074
UNKNOWN
Given an array of integers. Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. If the input array is empty or null, return an empty array. # Example For input `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]`, you should return `[10, -65]`.
["def count_positives_sum_negatives(arr):\n if not arr: return []\n pos = 0\n neg = 0\n for x in arr:\n if x > 0:\n pos += 1\n if x < 0:\n neg += x\n return [pos, neg]", "def count_positives_sum_negatives(arr):\n pos = sum(1 for x in arr if x > 0)\n neg = sum(x for x in arr if x < 0)\n return [pos, neg] if len(arr) else []\n", "def count_positives_sum_negatives(arr):\n return [len([x for x in arr if x > 0])] + [sum(y for y in arr if y < 0)] if arr else []", "def count_positives_sum_negatives(arr):\n return [sum(n > 0 for n in arr), sum(n for n in arr if n < 0)] if arr else []", "def count_positives_sum_negatives(arr):\n output = []\n if arr:\n output.append(sum([1 for x in arr if x > 0]))\n output.append(sum([x for x in arr if x < 0]))\n return output", "def count_positives_sum_negatives(input):\n if not input:\n return []\n count_ = 0\n sum_ = 0\n for element in input:\n if element > 0:\n count_ += 1\n elif element < 0:\n sum_ += element\n return [count_, sum_]\n", "count_positives_sum_negatives = lambda arr: [len([e for e in arr if e>0]), sum(e for e in arr if e<0)] if arr else []", "def count_positives_sum_negatives(arr):\n if not arr: return arr\n return [sum(1 for x in arr if x > 0), sum(x for x in arr if x < 0)]\n \n", "def count_positives_sum_negatives(arr):\n \n if arr == [] : return []\n \n result = [0, 0]\n \n for value in arr:\n if value > 0:\n result[0] += 1\n else:\n result[1] += value\n \n return result", "def count_positives_sum_negatives(arr):\n pos = 0\n neg = 0\n zer = 0\n for x in arr:\n if x < 0:\n neg += x\n elif x > 0:\n pos += 1\n else:\n zer += 0\n return [pos, neg] if zer != len(arr) else []\n", "from functools import reduce\ndef count_positives_sum_negatives(arr):\n return arr and reduce(lambda x, y: [x[0] + (y > 0), x[1] + y * (y < 0)], arr, [0, 0])", "def count_positives_sum_negatives(arr):\n if arr is None or len(arr) == 0:\n return []\n\n non_positives = [x for x in arr if x < 1]\n count_positives = len(arr) - len(non_positives)\n sum_negatives = sum(non_positives)\n \n return [count_positives, sum_negatives]\n", "def count_positives_sum_negatives(arr):\n return [len([i for i in arr if i > 0]),sum([i for i in arr if i < 0])] if arr else []", "def count_positives_sum_negatives(arr):\n sum,count = 0,0\n if (len(arr) == 0):\n return []\n for i in arr:\n if i > 0:\n count += 1\n else:\n sum = sum + i \n return [count,sum]", "def count_positives_sum_negatives(arr):\n if not arr:\n return([])\n else:\n pos = sum(int>0 for int in arr)\n neg = sum(int for int in arr if int < 0)\n return([pos,neg])", "def count_positives_sum_negatives(arr):\n if not arr:\n return []\n else: \n x = sum(1 for i in arr if i>= 1) \n y = sum(i for i in arr if i < 1)\n return [x, y]", "def count_positives_sum_negatives(arr):\n neg = [i for i in arr if i <= 0]\n return [len(arr) - len(neg), sum(neg)] if arr else []\n", "def count_positives_sum_negatives(arr):\n return [len([x for x in arr if x > 0]), sum(filter(lambda x: x < 0, arr))] if len(arr) != 0 else []", "def count_positives_sum_negatives(arr):\n if len(arr) == 0:\n return []\n\n pos = 0\n neg = 0\n \n for i in arr:\n if i > 0:\n pos += 1\n else:\n neg += i\n\n a = [pos, neg]\n return a", "def count_positives_sum_negatives(arr):\n if not arr:\n return []\n \n count = len(arr)\n sum = 0\n for num in arr:\n if num <= 0:\n count -= 1\n sum += num\n return [count, sum]\n", "def count_positives_sum_negatives(arr):\n if not arr:\n return arr\n count = 0\n su = []\n for i in arr:\n if i > 0:\n count += 1\n else:\n su.append(i)\n return [count, sum(su)]", "def count_positives_sum_negatives(arr):\n count,sumnegative=0,0\n for e in arr:\n if e>0:count+=1\n else:sumnegative+=e\n return []if arr==[] else [count,sumnegative]", "def count_positives_sum_negatives(arr):\n #your code here\n \n \n #your code here\n a=0\n s=0\n if not arr:\n return []\n\n\n\n for i in arr:\n if i>0: \n a=a+1\n else:\n s=s+i\n return [a,s]", "def count_positives_sum_negatives(arr):\n a = [0, 0]\n for i in arr:\n if i < 0:\n a[1] += i\n elif i > 0:\n a[0] += 1\n return a if arr else []", "def count_positives_sum_negatives(arr):\n\n if len(arr) == 0:\n return []\n\n count_positive = 0\n sum_negative = 0\n\n for i in range(len(arr)):\n if arr[i] > 0:\n count_positive = count_positive + 1\n else:\n sum_negative = sum_negative + arr[i]\n \n return [count_positive, sum_negative]\n", "def count_positives_sum_negatives(arr):\n a = [0,0]\n if not arr: return []\n for n in range(0,len(arr)):\n if arr[n] > 0:\n a[0] += 1\n elif arr[n] < 0:\n a[1] += arr[n]\n return a", "def count_positives_sum_negatives(arr):\n if len(arr) == 0:\n return []\n positives = list(filter(lambda x: x>0, arr))\n negatives = list(filter(lambda x: x<0, arr))\n return [len(positives),sum(negatives)]", "def count_positives_sum_negatives(arr):\n count=0\n suma=0\n if arr==[]:\n return []\n else:\n \n for number in arr:\n if number>0:\n count=count+1\n elif number<=0:\n suma=suma+number\n return [count,suma]\n", "def count_positives_sum_negatives(arr):\n #acoder! solution\n \n p = 0\n n = 0\n #especial case ([]),[])\n if arr == []:\n return [] \n \n for i in arr:\n if i!=0:\n if i>0:\n p+=1\n else:\n n+=i\n \n #especial case ([0,0,0,0,0,0,0,0,0]),[0,0]) \n if p==0 and n==0:\n return [0,0]\n \n return [p,n]\n", "def count_positives_sum_negatives(arr):\n #your code here\n num=0\n if len(arr)==0:\n return []\n else:\n for x in arr:\n if x>0:\n num+=1\n s=sum(x for x in arr if x<0)\n return[num,s]", "def count_positives_sum_negatives(arr):\n return arr and [sum(1 for a in arr if a > 0), sum(a for a in arr if a < 0)] or []", "def count_positives_sum_negatives (arr) :\n result = [0, 0];\n for i in arr : result [i < 0] += 1 if (i > 0) else i;\n return [] if (arr == []) else result;", "def count_positives_sum_negatives(x):\n return [] if len(x) == 0 else [sum([[x.count(i), 1][1] for i in x if i > 0]), sum([i for i in x if i < 0])]", "def count_positives_sum_negatives(arr):\n if arr == []:\n return []\n return [len([i for i in arr if i > 0]), sum([i for i in arr if i < 0])]", "def count_positives_sum_negatives(arr):\n #your code here\n res = []\n if arr:\n i = 0\n j = 0\n for num in arr:\n if num > 0:\n i = i+1\n else:\n j = num+j\n res = [i,j] \n return res\n", "def count_positives_sum_negatives(arr):\n if arr.__len__() == 0:\n return []\n else:\n sum_value, count = 0, 0\n for value in arr:\n if value < 0:\n sum_value += value\n elif value > 0:\n count += 1\n else:\n continue\n return [count, sum_value]", "def count_positives_sum_negatives(arr):\n return [] if arr == [] else [sum(1 for x in arr if x > 0), sum(x for x in arr if x < 0)]", "def count_positives_sum_negatives(arr):\n return [len([x for x in arr if x > 0]), sum(x for x in arr if x < 0)] if arr else []", "def count_positives_sum_negatives(arr):\n return [] if not arr else [len([i for i in arr if i > 0]), sum(j for j in arr if j < 0)]", "def count_positives_sum_negatives(arr):\n if arr:\n return [len([x for x in arr if x>0]), sum([x for x in arr if x<0])]\n return []", "def count_positives_sum_negatives(arr): \n return [] if arr == None or arr == [] else [len(list(filter(lambda x: x > 0, arr))), sum(filter(lambda x: x < 0, arr))]", "def count_positives_sum_negatives(arr):\n if arr == []:\n return []\n c = 0\n a = []\n i = [ i for i in arr if i > 0]\n n = [ i for i in arr if i < 0]\n a.append(len(i))\n a.append(sum(n))\n \n return a", "def count_positives_sum_negatives(arr):\n if arr == []:\n return []\n \n countPos = len([x for x in arr if x > 0])\n sumNeg = sum(x for x in arr if x < 0)\n \n return [countPos, sumNeg]\n", "def count_positives_sum_negatives(arr):\n for a in arr:\n while True:\n amount=len([a for a in arr if a>0]) \n suma=sum(a for a in arr if a<0)\n return [amount, suma,]\n else:\n return [ ]\n", "def count_positives_sum_negatives(arr):\n i=j=0\n if not arr:\n return []\n for num in arr:\n if num>0:\n i+=1\n elif num<0:\n j+=num\n else:\n pass\n return [i,j]\n #your code here\n", "def count_positives_sum_negatives(a):\n return a and [sum(i > 0 for i in a), sum(i for i in a if i < 0)]", "def count_positives_sum_negatives(arr):\n count = 0\n summ = 0\n if len(arr) == 0:\n return []\n else:\n for i in arr:\n if i > 0:\n count += 1\n else:\n summ += i\n return [count, summ]", "def count_positives_sum_negatives(arr):\n return [len([i for i in arr if i > 0]), sum([i for i in arr if i < 0])] if arr != [] else []", "def count_positives_sum_negatives(arr):\n return [[sum(i>0 for i in arr), sum(i for i in arr if i < 0)],[]][arr==[]]", "def count_positives_sum_negatives(arr):\n if arr == []:\n return []\n \n pos = sum([i>0 for i in arr])\n neg = sum(i for i in arr if i< 0)\n \n return [pos,neg]\n", "def count_positives_sum_negatives(arr):\n return [[x>0 for x in arr].count(True), sum([x for x in arr if x < 0])] if arr else []", "def count_positives_sum_negatives(arr):\n #your code here\n if len(arr) == 0:\n return []\n else:\n CountPos = 0\n SumNeg = 0\n for Index in range(len(arr)):\n if arr[Index] > 0:\n CountPos = CountPos + 1\n else:\n if arr[Index] < 0:\n SumNeg = SumNeg + arr[Index]\n return [CountPos, SumNeg]", "def count_positives_sum_negatives(arr):\n return [sum(1 for x in arr if x > 0),sum(x for x in arr if x < 0)] if arr else []", "def count_positives_sum_negatives(arr):\n return [len(list(filter(lambda x:x>0,arr))),sum(filter(lambda x:x<0,arr))] if arr else []", "def count_positives_sum_negatives(arr):\n pos = 0\n neg = 0\n if arr == []:\n return [] \n for i in arr:\n if i > 0:\n pos = pos + 1\n print(pos)\n elif i < 0:\n neg = neg + i\n \n return [pos, neg]", "def count_positives_sum_negatives(arr):\n res = [0,0]\n for item in arr:\n if item > 0: \n res[0] += 1\n else:\n res[1] += item\n return res if arr else []", "def count_positives_sum_negatives(arr):\n neg = 0\n neg = sum(el for el in arr if el < 0)\n pos = 0\n pos = len([el for el in arr if el > 0])\n return [pos, neg] if arr else []", "def count_positives_sum_negatives(arr):\n neg_int = 0\n pos_int = 0\n \n if arr ==[]:\n return arr\n \n for i in arr:\n if i<0:\n neg_int += i\n if i>0:\n pos_int +=1\n \n return [pos_int,neg_int]", "def count_positives_sum_negatives(arr):\n \n if not arr or not len(arr):\n return []\n \n p, n = 0, 0\n for e in arr:\n p, n = (p + 1, n) if e > 0 else (p, n + e)\n \n return [p, n]", "def count_positives_sum_negatives(arr):\n return arr and [sum(1 for n in arr if n > 0), sum(n for n in arr if n < 0)] or []", "def count_positives_sum_negatives(arr):\n return ([],[len([x for x in arr if x>0]), sum(x for x in arr if x<0)])[len(arr)!=0]", "def count_positives_sum_negatives(arr):\n if arr == []:\n return []\n first = sum(x > 0 for x in arr)\n second = 0\n for i in range(len(arr)):\n if int(arr[i]) < 0:\n second += int(arr[i])\n return [first, second]\n\n \n", "def count_positives_sum_negatives(arr):\n count_pos = 0\n sum_neg = 0\n for num in arr:\n if num > 0:\n count_pos += 1\n if num < 0:\n sum_neg += num\n return [count_pos] + [sum_neg] if arr else []", "def count_positives_sum_negatives(arr):\n if arr:\n a = 0\n b = 0\n for i in arr:\n if i > 0:\n a += 1\n elif i <= 0:\n b += i\n return [a, b] \n \n else:\n return []", "def count_positives_sum_negatives(arr):\n #your code here\n positive = 0\n negative = 0\n if arr:\n for x in arr:\n if x <= 0:\n negative += x\n else:\n positive += 1\n return [positive, negative]\n else:\n return []", "def count_positives_sum_negatives(arr):\n a = []\n b = []\n if len(arr) == 0:\n return []\n for i in arr:\n if i > 0:\n a.append(i)\n elif i < 0:\n b.append(i)\n c = len(a)\n d = sum(b)\n m = [c, d]\n return m", "def count_positives_sum_negatives(arr):\n n_array = []\n count = 0\n sum = 0\n for i in arr :\n if i > 0 :\n count += 1\n if i < 0 :\n sum += i\n n_array.append(count)\n n_array.append(sum)\n if arr == [] :\n return []\n elif arr == [0,0] :\n return [0,0]\n return n_array", "def count_positives_sum_negatives(arr):\n sum = 0\n count = 0\n tableau = 2*[0]\n if arr ==[]:\n return []\n else :\n for loop in range(len(arr)):\n if arr[loop]>0:\n sum = sum + 1;\n else :\n count = count + arr[loop];\n tableau = [sum, count]\n \n return tableau\n \n \n", "def count_positives_sum_negatives(arr):\n kol_polozh = 0\n summ_otric = 0\n a = []\n if arr == []:\n return []\n else:\n for i in range(0, len(arr), 1):\n if arr[i] > 0:\n kol_polozh = kol_polozh + 1\n if arr[i] < 0:\n summ_otric = summ_otric + arr[i]\n a = [kol_polozh, summ_otric]\n \n\n return a\n", "def count_positives_sum_negatives(arr):\n pos = 0\n neg = 0\n res = []\n if len(arr) > 0:\n for x in arr:\n if x > 0:\n pos += 1\n else:\n neg += x\n res.append(pos)\n res.append(neg)\n return res", "def count_positives_sum_negatives(arr):\n #your code here\n negsum = 0\n positive = 0\n for i in arr:\n if i > 0:\n positive += 1\n elif i < 0:\n negsum += i\n if arr == []:\n return arr\n else:\n return [positive, negsum]", "def count_positives_sum_negatives(arr):\n if arr == []:\n return []\n posTot = 0\n negSum = 0\n for number in arr:\n if number <= 0:\n negSum += number\n else:\n posTot += 1\n return [posTot,negSum]\n", "def count_positives_sum_negatives(arr):\n if arr == []:\n return []\n sum = 0 \n count = 0\n for number in arr:\n if number < 0:\n sum += number\n if number > 0:\n count += 1\n return [count, sum]", "def count_positives_sum_negatives(arr):\n negativeTotal = 0\n positiveTotal = 0\n for i in arr:\n if i > 0:\n positiveTotal += 1;\n else:\n negativeTotal += i;\n if len(arr) == 0:\n return []\n else:\n return[positiveTotal,negativeTotal]", "def count_positives_sum_negatives(arr):\n if not arr:\n return []\n n_pos, sum_neg = 0, 0\n for v in arr:\n if v > 0:\n n_pos += 1\n elif v < 0:\n sum_neg += v\n return [n_pos, sum_neg]", "from functools import reduce\n\ndef count_positives_sum_negatives(arr):\n count = 0\n for x in arr:\n if x > 0:\n count += 1\n return [count, sum(x for x in arr if x < 0)] if len(arr) > 0 else []\n", "def count_positives_sum_negatives(arr):\n if not arr:\n return arr\n count, sum_ = 0, 0\n for number in arr:\n if number > 0:\n count += 1\n elif number < 0:\n sum_ += number\n return [count, sum_]", "def count_positives_sum_negatives(arr):\n if not arr:\n return []\n sum_of_negative = 0\n positive_num = 0\n for i in arr:\n if i <= 0:\n sum_of_negative += i\n else:\n positive_num += 1\n return [positive_num, sum_of_negative]\n \n", "def count_positives_sum_negatives(arr):\n res = []\n pos = len([x for x in arr if x > 0])\n neg = sum([x for x in arr if x < 0])\n res.append(pos), res.append(neg)\n return res if len(arr) > 0 else arr", "def count_positives_sum_negatives(arr):\n positive = 0\n negative = 0\n ans = []\n if not arr:\n return ans\n else:\n for i in range(len(arr)):\n if arr[i] > 0:\n positive = positive + 1\n print(\"positive: \" , positive)\n else:\n negative = negative + arr[i]\n print(\"negative: \" , negative) \n \n ans = [positive, negative]\n \n return ans"]
{"fn_name": "count_positives_sum_negatives", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]], [[0, 2, 3, 0, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14]], [[1]], [[-1]], [[0, 0, 0, 0, 0, 0, 0, 0, 0]], [[]]], "outputs": [[[10, -65]], [[8, -50]], [[1, 0]], [[0, -1]], [[0, 0]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
18,339
def count_positives_sum_negatives(arr):
0ba0eecc0f2c8c4ea922a55f2d3dc9eb
UNKNOWN
Given two strings, the first being a random string and the second being the same as the first, but with three added characters somewhere in the string (three same characters), Write a function that returns the added character ### E.g ``` string1 = "hello" string2 = "aaahello" // => 'a' ``` The above is just an example; the characters could be anywhere in the string and string2 is actually **shuffled**. ### Another example ``` string1 = "abcde" string2 = "2db2a2ec" // => '2' ``` Note that the added character could also exist in the original string ``` string1 = "aabbcc" string2 = "aacccbbcc" // => 'c' ``` You can assume that string2 will aways be larger than string1, and there will always be three added characters in string2. ```if:c Write the function `added_char()` that takes two strings and return the added character as described above. ``` ```if:javascript Write the function `addedChar()` that takes two strings and return the added character as described above. ```
["from collections import Counter\n\ndef added_char(s1, s2): \n return next((Counter(s2) - Counter(s1)).elements())", "def added_char(s1, s2): \n for i in s2:\n if s1.count(i) != s2.count(i):\n return i", "from functools import reduce\nfrom operator import xor\n\ndef added_char(s1, s2): \n return chr(reduce(xor, map(ord, s1), 0) ^ reduce(xor, map(ord, s2), 0))", "from collections import Counter\ndef added_char(s1, s2): \n return list(Counter(s2) - Counter(s1))[0]", "from collections import Counter\ndef added_char(s1, s2):\n return (Counter(s2)-Counter(s1)).popitem()[0]", "# Average runtime: ?? ms\n\ndef added_char(s1, s2): \n s2 = list(s2)\n [s2.remove(i) for i in s1]\n return s2[0]", "from collections import Counter\n\ndef added_char(*args):\n c1,c2 = map(Counter, args)\n return (c2-c1).popitem()[0]", "added_char=lambda s1,s2:next(i for i in s2 if s1.count(i)!=s2.count(i))", "# Average runtime: ?? ms\n\ndef added_char(s1, s2): \n return chr(int((sum(ord(x) for x in s2) - sum(ord(x) for x in s1))/3))"]
{"fn_name": "added_char", "inputs": [["hello", "checlclo"], ["aabbcc", "aacccbbcc"], ["abcde", "2db2a2ec"]], "outputs": [["c"], ["c"], ["2"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,063
def added_char(s1, s2):
f6eb78819fcd03814141cae8914ee790
UNKNOWN
Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return `true` if the string is valid, and `false` if it's invalid. ## Examples ``` "()" => true ")(()))" => false "(" => false "(())((()())())" => true ``` ## Constraints `0 <= input.length <= 100` ~~~if-not:javascript,go Along with opening (`(`) and closing (`)`) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do **not** treat other forms of brackets as parentheses (e.g. `[]`, `{}`, `<>`). ~~~
["def valid_parentheses(string):\n cnt = 0\n for char in string:\n if char == '(': cnt += 1\n if char == ')': cnt -= 1\n if cnt < 0: return False\n return True if cnt == 0 else False", "def valid_parentheses(string):\n count = 0\n for i in string:\n if i == \"(\":\n count += 1\n elif i == \")\":\n count -= 1\n if count < 0:\n return False\n return count == 0", "\niparens = iter('(){}[]<>')\nparens = dict(zip(iparens, iparens))\nclosing = parens.values()\n\ndef valid_parentheses(astr):\n stack = []\n for c in astr:\n d = parens.get(c, None)\n if d:\n stack.append(d)\n elif c in closing:\n if not stack or c != stack.pop():\n return False\n return not stack", "class Stack:\n \"\"\"\n This is an implementation of a Stack.\n The \"right\" or \"top\" of this stack the end of the list.\n \"\"\"\n\n def __init__(self):\n self.items = []\n\n def push(self, item):\n self.items.append(item)\n\n def pop(self):\n return self.items.pop()\n\n def peek(self):\n return self.items[-1]\n\n def is_empty(self):\n return self.items == []\n\n def size(self):\n return len(self.items)\n\ndef valid_parentheses(symbol_string):\n \"\"\"\n This is a practice problem.\n It checks to see if parenthesis's are balanced\n :param symbol_string: String\n :return Bool:\n \"\"\"\n\n stack = Stack()\n for char in symbol_string:\n if char == \"(\":\n stack.push(\"(\")\n elif char == \")\":\n if stack.is_empty():\n return False\n else:\n stack.pop()\n\n if not stack.is_empty():\n return False\n else:\n return True", "def valid_parentheses(string):\n string = \"\".join(ch for ch in string if ch in \"()\")\n while \"()\" in string: string = string.replace(\"()\", \"\")\n return not string", "import re\n\n\n_regex = \"[^\\(|\\)]\"\n\n\ndef valid_parentheses(string):\n string = re.sub(_regex, '', string)\n while len(string.split('()')) > 1:\n string = ''.join(string.split('()'))\n return string == ''", "def valid_parentheses(s):\n stack = 0\n for char in s:\n if char == '(':\n stack += 1\n if char == ')':\n if not stack:\n return False\n else:\n stack -= 1\n return not stack", "import re\n\ndef valid_parentheses(s):\n try:\n re.compile(s)\n except:\n return False\n return True", "def valid_parentheses(s):\n b = 0\n for c in s:\n if c == '(': b += 1\n if c == ')':\n b -= 1\n if b < 0: return False\n return b == 0", "def valid_parentheses(string):\n stack = []\n for i in string:\n if i == '(':\n stack.append(i)\n elif i == ')' and not stack:\n return False\n elif i == ')':\n stack.pop()\n return not stack", "def valid_parentheses(string):\n open_counter = 0 \n for i in string:\n if i=='(': open_counter = open_counter + 1\n if i==')': open_counter = open_counter - 1\n if open_counter<0: return False\n if open_counter==0: return True\n return False", "def valid_parentheses(string):\n new = ''.join([i for i in string if i in '()'])\n while '()' in new:\n new = new.replace('()', '')\n return len(new) == 0", "def valid_parentheses(string):\n string = \"\".join([x for x in string if x == \"(\" or x == \")\"])\n before_reduce = len(string)\n string = string.replace('()', '')\n if string == '':\n return True\n elif before_reduce != len(string):\n return valid_parentheses(string)\n else:\n return False\n", "def valid_parentheses(string):\n string = ''.join(x for x in string if x in ('(',')'))\n while '()' in string:\n string = string.replace('()', '')\n return False if len(string) != 0 else True", "def valid_parentheses(string):\n string = ''.join(i for i in string if i=='(' or i==')')\n while '()' in string:\n string = string.replace('()','')\n return string==''", "def valid_parentheses(string):\n string = [c for c in string if not c.isalpha()]\n string = \"\".join(string)\n while \"()\" in string:\n string = string.replace(\"()\",\"\")\n return True if len(string) == 0 else False", "def valid_parentheses(s):\n p = '()'\n s = ''.join([e for e in s if e in '()'])\n while p in s:#\n s = s.replace(p,'')\n return not s", "def valid_parentheses(string):\n \n open = 0\n \n for c in string:\n \n # increase open count for an open parenthesis\n if c == \"(\":\n open += 1\n \n # descrease open count for a closing parenthesis\n elif c == \")\":\n open -= 1\n \n # if the open count ever drops below zero, parentheses are invalid \n if open < 0:\n return False\n \n # if open ends up non-zero, this returns False, otherwise True\n return open == 0", "def valid_parentheses(string):\n i = 0\n for c in string:\n if c == '(':\n i += 1\n if c == ')':\n i -= 1\n if i < 0:\n return False\n return i == 0\n", "def valid_parentheses(string):\n count = 0\n for c in [c for c in string if c in \"()\"]:\n count += 1 if c == '(' else -1\n if count < 0:\n return False\n return count == 0", "def valid_parentheses(string):\n string = ''.join([x for x in string if x in '()'])\n try:\n string = string.replace('()', '')\n return valid_parentheses(string) if string else True\n except:\n return False", "def valid_parentheses(s):\n lvl=0\n for c in s:\n lvl += (c=='(')-(c==')')\n if lvl<0: return False\n return not lvl", "def valid_parentheses(string):\n depth = 0 #Depth increases as we go 'deeper in parentheses', and decreases when parentheses are closed.\n for i in string:\n if i == \"(\":\n depth += 1\n elif i == \")\":\n depth -= 1\n if depth < 0:\n return False #If at some point depth becomes negative, we've met a situation, when the parentheses pair can't be closed - sequence is not valid\n if depth == 0: #At the end of valid sequence all opening parentheses' amount must be equal to the closing ones'.\n return True\n else:\n return False", "def valid_parentheses(string):\n \n count_open = 0\n count_close = 0\n \n index_open = 0\n index_closed = 0\n for s in string:\n if s == \"(\":\n count_open += 1\n elif s == \")\":\n count_close += 1\n \n if count_close > count_open:\n return False\n \n if (count_open != count_close):\n return False\n else: \n return True\n \n", "import re\ndef valid_parentheses(string):\n s = ''.join([i for i in string if i in \"()\"])\n total = [string]\n while True:\n s = s.replace(\"()\", \"\")\n total.append(s)\n if total[-1] == total[-2]:\n break\n return True if total[-1] == \"\" else False", "def valid_parentheses(string):\n times=0\n count=0\n for i in string:\n if string[times]=='(':\n count+=1\n elif string[times]==')':\n count-=1\n print(count, i, times)\n times+=1\n if count <0:\n return False \n if count==0:\n return True\n else:\n return False", "# Write a function called that takes a string of parentheses, and determines\n# if the order of the parentheses is valid. The function should return true\n# if the string is valid, and false if it's invalid.\n# Examples\n# \"()\" => true\n# \")(()))\" => false\n# \"(\" => false\n# \"(())((()())())\" => true\n# Constraints: 0 <= input.length <= 100\n# Along with opening (() and closing ()) parenthesis, input may contain\n# any valid ASCII characters. Furthermore, the input string may be empty\n# and/or not contain any parentheses at all. Do not treat other forms\n# of brackets as parentheses (e.g. [], {}, <>).\n\ndef valid_parentheses(string):\n str = string\n if str == \"\":\n return True\n if len(str) > 100:\n str = str[0:100]\n c_open = 0\n exc = 0 \n for c in str:\n if c == '(':\n c_open += 1\n if c == ')':\n c_open -= 1\n if c_open < 0:\n exc = 1\n break;\n if exc == 1 or c_open != 0:\n return False\n return True", "def valid_parentheses(string):\n counter = 0;\n for i in string:\n if i == \"(\": counter += 1\n if i == \")\": counter -= 1\n if counter < 0: return(False)\n return(counter == 0)", "def valid_parentheses(string):\n string = \"\".join([x for x in string if x in ['(',')']])\n while '()' in string:\n string = string.replace('()','')\n \n if len(string) != 0: return False\n return True\n #your code here\n"]
{"fn_name": "valid_parentheses", "inputs": [[")"], ["("], [""], ["hi)("], ["hi(hi)"], ["hi(hi)("], ["((())()())"], ["(c(b(a)))(d)"], ["hi(hi))("], ["())(()"]], "outputs": [[false], [false], [true], [false], [true], [false], [true], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
9,408
def valid_parentheses(string):
281e23ab80fc0b75f0dbf862208771af
UNKNOWN
Hi guys, welcome to introduction to DocTesting. The kata is composed of two parts; in part (1) we write three small functions, and in part (2) we write a few doc tests for those functions. Lets talk about the functions first... The reverse_list function takes a list and returns the reverse of it. If given an empty list, simply return an empty list. The second function... The sum_list function takes a list as input and adds up all the values, returning an integer. If the list is empty, return 0. The third function... The head_of_list function simply returns the first item in the list. If the list is empty return None. Each of these functions can be easily written with a single line of code; there are some tests for correctness but no tests for effciency. Once you have implemented all three of these functions you can move onto phase two, which is writing doc tests. If you haven't written doc tests before then I suggest you check out the following documentation: https://docs.python.org/3/library/doctest.html To complete this kata all you have to do is write **EXACTLY TWO** doc tests for each of the three functions (any more/less than that and you will fail the tests). Here is an example: def double(y): """Function returns y * 2 >>> double(2) 4 """ return y * 2 In the example above we have a function called 'double' and a single doctest. When we run the doctest module Python will check if double(2) equals 4. If it does not, then the doctest module will flag up an error. Please note that this is intended as a beginners introduction to docstrings, if you try to do something clever (such as writing doc tests to catch exceptions, or tinkering with the 'option flags'), you will probably fail a test or two. This is due to how the tests are written. Oh and one last thing, don't try and get too 'cheeky' and try something like: """ >>> True True """ such a solution is (a) not in the spirit of things and (b) I got tests for that! :p Good Luck! ~~~~~~~~~~~~~~~ Issues & Helpful hints ~~~~~~~~~~~~~~~~~~~~~~~ 1) In addition to the 'don't get too clever rule', please try to be precise when making your doctests; [1,2] may fail where [1, 2] may succeed. Likewise, ">>>function(x)" may fail where ">>> function(x)" is likely to suceed *(note the difference is single " " character)*. In short, if you fail a test the first thing to check is that you dont have any unecessary characters/spaces and/or odd formating. 2) As you shall see from the kata discussion testing for None is tricky and lots of people are struggling to get None tests working. So I'm going to quickly show you a way to test for not that will (should) pass the kata: def is_string(string): """ returns the string if the string is Not empty, otherwise returns None >>> is_string("") is None True """ return string if string else None 3) If you happen to be struggling to actually complete the three functions in the first place then I would recomend you google *"Python Indexing", "Pythons sum function" and "if/else statements in Python"*.
["def reverse_list(x):\n \"\"\"Takes an list and returns the reverse of it. \n If x is empty, return [].\n \n >>> reverse_list([1, 2, 3, 4])\n [4, 3, 2, 1]\n >>> reverse_list([])\n []\n \"\"\" \n \n return x[::-1]\n\ndef sum_list(x):\n \"\"\"Takes a list, and returns the sum of that list.\n If x is empty list, return 0.\n\n >>> sum_list([1, 2, 3, 4])\n 10\n >>> sum_list([])\n 0\n \"\"\"\n\n return sum(x)\n\ndef head_of_list(x):\n \"\"\"Takes a list, returns the first item in that list.\n If x is empty, return None\n\n >>> head_of_list([1, 2, 3, 4])\n 1\n >>> head_of_list([]) is None\n True\n \"\"\" \n\n return x[0] if x else None", "def reverse_list(lst):\n \"\"\"Takes an list and returns the reverse of it. \n If x is empty, return [].\n >>> reverse_list([])\n []\n >>> reverse_list([1, 2, 3])\n [3, 2, 1]\n \"\"\" \n return lst[::-1]\n\ndef sum_list(lst):\n \"\"\"Takes a list, and returns the sum of that list.\n If x is empty list, return 0.\n >>> sum_list([])\n 0\n >>> sum_list([1, 2, 3])\n 6\n \"\"\"\n return sum(lst)\n\ndef head_of_list(lst):\n \"\"\"Takes a list, returns the first item in that list.\n If x is empty, return None\n >>> head_of_list([]) is None\n True\n >>> head_of_list([1, 2, 3])\n 1\n \"\"\"\n return lst[0] if lst else None", "def reverse_list(x):\n \"\"\"Takes an list and returns the reverse of it. \n If x is empty, return [].\n \n >>> reverse_list([1, 2, 3])\n [3, 2, 1]\n \n >>> reverse_list([])\n []\n \"\"\" \n \n return x[::-1]\n\ndef sum_list(x):\n \"\"\"Takes a list, and returns the sum of that list.\n If x is empty list, return 0.\n\n >>> sum_list([1, 2, 3])\n 6\n\n >>> sum_list([])\n 0\n \"\"\"\n\n return sum(x)\n\ndef head_of_list(x):\n \"\"\"Takes a list, returns the first item in that list.\n If x is empty, return None\n\n >>> head_of_list([0, 1])\n 0\n \n >>> head_of_list([]) is None\n True\n \"\"\" \n\n return x[0] if x else None\n", "def reverse_list(x):\n \"\"\"\n >>> reverse_list([1,2,3])\n [3, 2, 1]\n \n >>> reverse_list([2,3])\n [3, 2]\n \"\"\" \n return x[::-1]\n\ndef sum_list(x):\n \"\"\"\n >>> sum_list([1,2,3])\n 6\n \n >>> sum_list([0])\n 0\n \"\"\"\n return sum(x)\n\ndef head_of_list(x):\n \"\"\"\n >>> head_of_list([0])\n 0\n \n >>> head_of_list([1,2,3])\n 1\n \"\"\" \n return x[0] if x else None", "def reverse_list(x):\n \"\"\"Takes an list and returns the reverse of it. \n If x is empty, return [].\n \n Your two Doc_tests go here... \n \n >>> reverse_list([1,2])\n [2, 1]\n >>> reverse_list([])\n []\n \"\"\"\n \n # Your code goes here...\n return x[::-1]\ndef sum_list(x):\n \"\"\"Takes a list, and returns the sum of that list.\n If x is empty list, return 0.\n\n Your two Doc_tests go here...\n >>> sum_list([])\n 0\n >>> sum_list([1,2,3])\n 6\n \"\"\"\n\n # Your code goes here...\n return 0 if len(x) == 0 else sum(x)\ndef head_of_list(x):\n \"\"\"Takes a list, returns the first item in that list.\n If x is empty, return None\n\n Your two Doc_tests go here...\n >>> head_of_list([1,2,3])\n 1\n >>> head_of_list([2,4,5])\n 2\n \"\"\" \n\n # Your code goes here...\n return None if len(x) == 0 else x[0]", "def reverse_list(x):\n \"\"\"Takes an list and returns the reverse of it. \n If x is empty, return [].\n \n >>> reverse_list([1, 2, 3])\n [3, 2, 1]\n >>> reverse_list([])\n []\n \"\"\" \n return x[::-1] if x else []\n\n\ndef sum_list(x):\n \"\"\"Takes a list, and returns the sum of that list.\n If x is empty list, return 0.\n >>> sum_list([1, 2, 3])\n 6\n >>> sum_list([])\n 0\n \"\"\"\n\n return sum(x) if x else 0\n\n\ndef head_of_list(x):\n \"\"\"Takes a list, returns the first item in that list.\n If x is empty, return None\n\n >>> head_of_list([1, 2])\n 1\n >>> head_of_list([]) is None\n True\n \"\"\" \n\n return x[0] if x else None\n\n", "def reverse_list(a):\n \"\"\"Takes an list and returns the reverse of it. \n If x is empty, return [].\n \n >>> reverse_list([1])\n [1]\n >>> reverse_list([])\n []\n \"\"\"\n return a[::-1]\n\ndef sum_list(a):\n \"\"\"Takes a list, and returns the sum of that list.\n If x is empty list, return 0.\n\n >>> sum_list([1])\n 1\n >>> sum_list([])\n 0\n \"\"\"\n return sum(a)\n\ndef head_of_list(a):\n \"\"\"Takes a list, returns the first item in that list.\n If x is empty, return None\n\n >>> head_of_list([1])\n 1\n >>> head_of_list([]) is None\n True\n \"\"\"\n if a:\n return a[0]", "def reverse_list(x):\n \"\"\"Takes an list and returns the reverse of it. \n If x is empty, return [].\n \n >>> reverse_list([])\n []\n \n >>> reverse_list([1, 2, 3])\n [3, 2, 1]\n \"\"\" \n return x[::-1]\n\ndef sum_list(x):\n \"\"\"Takes a list, and returns the sum of that list.\n If x is empty list, return 0.\n\n >>> sum_list([])\n 0\n \n >>> sum_list([1, 2, 3])\n 6\n \"\"\"\n return sum(x)\n\ndef head_of_list(x):\n \"\"\"Takes a list, returns the first item in that list.\n If x is empty, return None\n \n >>> head_of_list([1, 2, 3])\n 1\n \n >>> head_of_list([]) is None\n True\n \n \n \"\"\" \n return x[0] if len(x) else None\n", "def reverse_list(x):\n \"\"\"Takes an list and returns the reverse of it. \n If x is empty, return [].\n \n >>> reverse_list([])\n []\n >>> reverse_list([5, 4,3, 2, 1])\n [1, 2, 3, 4, 5]\n \"\"\" \n return x[::-1]\n\ndef sum_list(x):\n \"\"\"Takes a list, and returns the sum of that list.\n If x is empty list, return 0.\n\n >>> sum_list([])\n 0\n >>> sum_list([1, 2, 3, 4, 5])\n 15\n \"\"\"\n return sum(x)\n\ndef head_of_list(x):\n \"\"\"Takes a list, returns the first item in that list.\n If x is empty, return None\n\n >>> head_of_list([]) is None\n True\n >>> head_of_list([1, 2, 3, 4, 5])\n 1\n \"\"\" \n return x[0] if x else None\n", "def reverse_list(x):\n \"\"\"\"Takes an list and returns the reverse of it. \n If x is empty, return [].\n \n Your two Doc_tests go here... \n >>> reverse_list([])\n []\n >>> reverse_list([2,3,9])\n [9, 3, 2]\n \"\"\"\n return x[::-1]\ndef sum_list(x):\n \"\"\"Takes a list, and returns the sum of that list.\n If x is empty list, return 0.\n\n Your two Doc_tests go here...\n >>> sum_list([])\n 0\n >>> sum_list([2,3,9])\n 14\n \"\"\"\n return sum(x)\n\ndef head_of_list(x):\n \"\"\"Takes a list, returns the first item in that list.\n If x is empty, return None\n\n Your two Doc_tests go here...\n >>> head_of_list([5,4,9])\n 5\n >>> head_of_list([2,3,9])\n 2\n \"\"\"\n if x == []:\n pass\n else:\n return x[0]"]
{"fn_name": "reverse_list", "inputs": [[[1, 2, 3]], [[]]], "outputs": [[[3, 2, 1]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
7,178
def reverse_list(x):
9e4c161d5c11554ca1366e5cf875f3cd
UNKNOWN
# Task Your Informatics teacher at school likes coming up with new ways to help you understand the material. When you started studying numeral systems, he introduced his own numeral system, which he's convinced will help clarify things. His numeral system has base 26, and its digits are represented by English capital letters - `A for 0, B for 1, and so on`. The teacher assigned you the following numeral system exercise: given a one-digit `number`, you should find all unordered pairs of one-digit numbers whose values add up to the `number`. # Example For `number = 'G'`, the output should be `["A + G", "B + F", "C + E", "D + D"]` Translating this into the decimal numeral system we get: number = 6, so it is `["0 + 6", "1 + 5", "2 + 4", "3 + 3"]`. # Input/Output - `[input]` string(char in C#) `number` A character representing a correct one-digit number in the new numeral system. Constraints: `'A' ≤ number ≤ 'Z'.` - `[output]` a string array An array of strings in the format "letter1 + letter2", where "letter1" and "letter2" are correct one-digit numbers in the new numeral system. The strings should be sorted by "letter1". Note that "letter1 + letter2" and "letter2 + letter1" are equal pairs and we don't consider them to be different.
["def new_numeral_system(n):\n a = [c for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if c <= n]\n return ['{} + {}'.format(a[i], a[-1-i]) for i in range((len(a) + 1) // 2)]", "new_numeral_system=lambda n:['%c + %c'%(65+i,ord(n)-i)for i in range(ord(n)-63>>1)]", "def new_numeral_system(number):\n return [(chr(65+i) + ' + ' + chr(ord(number)-i)) for i in range((ord(number)-65)//2+1)]", "def new_numeral_system(number):\n system = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n n = system.index(number)\n return [\"{} + {}\".format(system[i], system[n-i]) for i in range(n // 2 + 1)]\n", "def new_numeral_system(number):\n chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n n = chars.index(number)\n return [f'{chars[i]} + {chars[n-i]}' for i in range(0, n//2+1)]\n", "from string import ascii_uppercase as up\nfrom math import ceil\ndef new_numeral_system(num):\n n=up.index(num)\n n1=ceil(n/2)\n return list(f\"{a} + {b}\" for a,b in zip(up[:n1+1],up[n1:n+1][::-1]))", "def new_numeral_system(number):\n n = ord(number) - 65\n return [f'{chr(x + 65)} + {chr(n - x + 65)}' for x in range(0, n // 2 + 1)]", "def new_numeral_system(letter):\n number = ord(letter) - 65\n half = number // 2\n return [f\"{chr(i+65)} + {chr(number-i+65)}\" for i in range(half + 1)]", "def new_numeral_system(number):\n output = []\n for i in range(0,(ord(number)-ord('A'))//2+1):\n output.append(chr(i+65) + ' + ' + chr(ord(number)-i))\n return output", "def new_numeral_system(s):\n n = ord(s)\n return [f\"{chr(i + 65)} + {chr(n - i)}\" for i in range((n - 65) // 2 + 1)]"]
{"fn_name": "new_numeral_system", "inputs": [["G"], ["A"], ["D"], ["E"], ["O"]], "outputs": [[["A + G", "B + F", "C + E", "D + D"]], [["A + A"]], [["A + D", "B + C"]], [["A + E", "B + D", "C + C"]], [["A + O", "B + N", "C + M", "D + L", "E + K", "F + J", "G + I", "H + H"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,594
def new_numeral_system(number):
57b8e93e9ac4f04c922924d9d82a9b35
UNKNOWN
Your work is to write a method that takes a value and an index, and returns the value with the bit at given index flipped. The bits are numbered from the least significant bit (index 1). Example: ```python flip_bit(15, 4) == 7 # 15 in binary is 1111, after flipping 4th bit, it becomes 0111, i.e. 7 flip_bit(15, 5) == 31 # 15 in binary is 1111, 5th bit is 0, after flipping, it becomes 11111, i.e., 31 ``` Note : index number can be out of number's range : e.g number is 3 (it has 2 bits) and index number is 8(for C# this number is up to 31) -> result will be 131 See more examples in test classes Good luck!
["def flip_bit(value, bit_index):\n return value ^ (1 << (bit_index-1))", "flip_bit=lambda n,k:n^1<<k-1", "def flip_bit(value, bit_index):\n return value ^ 2 ** (bit_index-1)", "def flip_bit(v, b):\n return 1<<b-1 ^ v", "flip_bit=lambda v, i: int(\"\".join([l if 64-i!=k else \"0\" if l==\"1\" else \"1\" for k,l in enumerate((\"0\"*64+bin(v)[2:])[-64:])]),2)", "def flip_bit(v,i):\n v=list(bin(v)[2:].rjust(i,\"0\")[::-1])\n v[i-1]=str(1-int(v[i-1]))\n return int(\"\".join(v[::-1]),2)", "def flip_bit(value, bit_index):\n bs = list(bin(value)[2:].zfill(bit_index))\n i = len(bs) - bit_index\n bs[i] = '10'[int(bs[i])]\n return int(''.join(bs), 2)\n", "def flip_bit(value, bit_index):\n bits = list(map(int, bin(value)[2:]))\n while len(bits) < bit_index: bits.insert(0, 0)\n bits[len(bits) - bit_index] ^= 1\n return int(''.join(map(str, bits)), 2)", "def flip_bit(value, bit_index):\n binary = bin(value)[2:]\n \n if bit_index <= len(binary):\n lst = list(binary)\n lst[-bit_index] = \"0\" if binary[-bit_index] == \"1\" else \"1\"\n return int(\"\".join(lst), 2)\n \n return value + 2**(bit_index - 1)", "def flip_bit(v, b):\n k = list(bin(v)[2:].zfill(b))\n k[-b] = str(1 - int(k[-b]))\n return int(''.join(k), 2)"]
{"fn_name": "flip_bit", "inputs": [[0, 16], [2147483647, 31], [127, 8]], "outputs": [[32768], [1073741823], [255]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,307
def flip_bit(value, bit_index):
b1fe086b82c819f4396de41f8bac2c63
UNKNOWN
Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are a part of the word in this kata.
["def reverse_alternate(string):\n return \" \".join(y[::-1] if x%2 else y for x,y in enumerate(string.split()))", "def reverse_alternate(s):\n return ' '.join(w[::-1] if i % 2 else w for i, w in enumerate(s.split()))", "def reverse_alternate(string):\n #your code here\n if string == \"\":\n return \"\"\n else:\n new_list = []\n for i in range(len(string.split())):\n if i%2 != 0:\n new_list.append(string.split()[i][::-1])\n else:\n new_list.append(string.split()[i])\n return \" \".join(new_list)", "def reverse_alternate(string):\n res = []\n arr = string.split()\n for i in arr:\n if arr.index(i) % 2 == 1:\n res.append(arr[arr.index(i)][::-1])\n else:\n res.append(arr[arr.index(i)])\n return \" \".join(res)\n", "def reverse_alternate(s):\n words = s.split()\n words[1::2] = [word[::-1] for word in words[1::2]]\n return ' '.join(words)", "def reverse_alternate(string):\n string = string.split()\n res = []\n for i in range(len(string)):\n if (i+1) % 2 == 0:\n res.append(string[i][::-1])\n else :\n res.append(string[i])\n return \" \".join(res)\n", "def reverse_alternate(string):\n splitted = string.split()\n converted = []\n for elt in splitted :\n if splitted.index(elt) % 2 != 0 :\n reversed = ''.join(char for char in elt[::-1])\n converted.append(reversed)\n else :\n converted.append(elt)\n return ' '.join(converted)", "def reverse_alternate(string):\n return \" \".join(j if i%2==0 else j[::-1] for i,j in enumerate(string.split()))", "def reverse_alternate(stg):\n return \" \".join(word[::-1] if i & 1 else word for i, word in enumerate(stg.split()))", "def reverse_alternate(string):\n #your code here\n return ' '.join([word[::-1] if string.split().index(word)%2 != 0 else word for word in string.split()])"]
{"fn_name": "reverse_alternate", "inputs": [["Did it work?"], ["I really hope it works this time..."], ["Reverse this string, please!"], ["Have a beer"], [" "], ["This is not a test "], ["This is a test "]], "outputs": [["Did ti work?"], ["I yllaer hope ti works siht time..."], ["Reverse siht string, !esaelp"], ["Have a beer"], [""], ["This si not a test"], ["This si a tset"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,972
def reverse_alternate(string):
a988e7eca67e19158ae09de05679956d
UNKNOWN
Write a function that solves an algebraic expression given as a string. * The expression can include only sums and products. * The numbers in the expression are in standard notation (NOT scientific). * In contrast, the function should return a string with the calculated value given in scientific notation with 5 decimal digits. # Example: ```python strexpression = "5 * 4 + 6" sum_prod(strexpression) = "2.60000e+01" ```
["def sum_prod(strexpression):\n return \"%.5e\" %(eval(strexpression))", "def sum_prod(strexpression):\n # resisting using the dreaded eval :-)\n # split things up into numbers and operators\n strexpression = strexpression.replace(\"*\", \" * \").replace(\"+\", \" + \")\n equation = [float(x) if x[0].isdigit() else x for x in strexpression.split()]\n\n # and calculate the products and then the sums\n for operator in [\"*\", \"+\"]:\n while operator in equation:\n pos = equation.index(operator)\n equation[pos - 1] = equation[pos - 1] * equation[pos + 1] if operator == \"*\" else equation[pos - 1] + equation[pos + 1]\n del equation[pos:pos + 2]\n\n return '{:.5e}'.format(float(equation[0]))", "sum_prod=lambda ex:'{:.5e}'.format(sum(eval(i) for i in ex.split('+')))", "from functools import reduce\n\n\ndef sum_prod(strexpression):\n to_sum = [expr.split('*') for expr in strexpression.split('+')]\n\n total = sum(\n reduce(lambda result, y: result * float(y), product_, 1.0)\n for product_ in to_sum\n )\n \n return f'{total:.5e}'", "__import__(\"sys\").setrecursionlimit(2000)\n\ndef sum_prod(strexpression):\n return f\"{eval(strexpression):.5e}\"", "sum_prod=lambda s:'%.5e'%eval(s)", "from decimal import *\n\ndef sum_prod(strexpression):\n splitByPlus = strexpression.split(\"+\")\n for x in range(0, len(splitByPlus)):\n splitByPlus[x] = multiplyAll(splitByPlus[x])\n result = addAll(splitByPlus);\n return \"{:.5e}\".format(result);\n \ndef addAll(exps):\n sum = 0.0\n for i in exps: \n sum += float(i);\n return sum;\n \ndef multiplyAll(exps):\n exps = exps.split(\"*\")\n result = 1.0\n for j in exps: \n result *= float(j);\n return result;", "import sys\nsys.setrecursionlimit(2000)\ndef sum_prod(strexpression):\n return \"{:.5e}\".format(eval(strexpression)) "]
{"fn_name": "sum_prod", "inputs": [["5*4+6"], ["5+4*6"], ["3*8+6*5"], ["5*8+6*3*2"], ["5.4*4.0+6.2+8.0"], ["0.5*1.2*56+9.6*5*81+1"], ["1"], ["1.333333333*1.23456789+0.003*0.002"]], "outputs": [["2.60000e+01"], ["2.90000e+01"], ["5.40000e+01"], ["7.60000e+01"], ["3.58000e+01"], ["3.92260e+03"], ["1.00000e+00"], ["1.64610e+00"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,946
def sum_prod(strexpression):
5c1d56b50fa9fb68e96d43769ea93af4
UNKNOWN
For "x", determine how many positive integers less than or equal to "x" are odd but not prime. Assume "x" is an integer between 1 and 10000. Example: 5 has three odd numbers (1,3,5) and only the number 1 is not prime, so the answer is 1 Example: 10 has five odd numbers (1,3,5,7,9) and only 1 and 9 are not prime, so the answer is 2
["def not_prime(x):\n if x == 1: return True\n for y in range(2, int(x ** 0.5) + 1):\n if x % y == 0:\n return True\n return False\ndef odd_not_prime(n):\n return sum(not_prime(x) for x in range(1, n + 1, 2))", "def odd_not_prime(n):\n return 1 + sum( any(not x%y for y in range(3,int(x**.5)+1,2)) for x in range(1,n+1,2))", "from math import sqrt\n\ndef odd_not_prime(n):\n return 1 + sum(1 for m in range(1, n + 1, 2) if any(m % i == 0 for i in range(3, int(sqrt(m)) + 1, 2)))", "def prime_detector(x):\n if x >= 2:\n for y in range(2, int(x / 2)):\n if (x % y) == 0:\n return False\n return True\n else:\n return False\n\n\ndef odd_not_prime(n):\n i = 1\n odd_n_prime = 0\n while i <= n:\n if not prime_detector(i):\n odd_n_prime = odd_n_prime + 1\n i = i + 2\n return odd_n_prime\n", "from math import sqrt\nfrom itertools import count, islice\n\ndef isPrime(n):\n return n > 1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))\n\ndef odd_not_prime(n):\n return sum((not isPrime(i)) & (i % 2 != 0)for i in range(1,n+1))", "def odd_not_prime(n):\n return len([x for x in range(1, n+1, 2) if not (not any([x%y==0 for y in range(3, int(x**(1/2))+1, 2)]) and x!=1)])", "def is_prime(n):\n if n == 1:\n return False\n elif n == 3:\n return True\n else:\n for i in range(3,round(n**0.5)+2):\n if n%i == 0:\n return False\n else:\n return True \ndef odd_not_prime(n):\n lst = list(range(1,n+1,2))\n return len([i for i in lst if not is_prime(i)])", "primes = {p for p in range(3, 10001, 2) if all(p % i for i in range(3, int(p**0.5) + 1, 2))}\nodd_not_prime_ = [i % 2 and i not in primes for i in range(1, 10001)]\n\ndef odd_not_prime(n):\n return sum(odd_not_prime_[:n])", "odd_not_prime=lambda n: sum(1 for x in range(1,n+1,2) if x not in [3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,2377,2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,2473,2477,2503,2521,2531,2539,2543,2549,2551,2557,2579,2591,2593,2609,2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,2707,2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,2801,2803,2819,2833,2837,2843,2851,2857,2861,2879,2887,2897,2903,2909,2917,2927,2939,2953,2957,2963,2969,2971,2999,3001,3011,3019,3023,3037,3041,3049,3061,3067,3079,3083,3089,3109,3119,3121,3137,3163,3167,3169,3181,3187,3191,3203,3209,3217,3221,3229,3251,3253,3257,3259,3271,3299,3301,3307,3313,3319,3323,3329,3331,3343,3347,3359,3361,3371,3373,3389,3391,3407,3413,3433,3449,3457,3461,3463,3467,3469,3491,3499,3511,3517,3527,3529,3533,3539,3541,3547,3557,3559,3571,3581,3583,3593,3607,3613,3617,3623,3631,3637,3643,3659,3671,3673,3677,3691,3697,3701,3709,3719,3727,3733,3739,3761,3767,3769,3779,3793,3797,3803,3821,3823,3833,3847,3851,3853,3863,3877,3881,3889,3907,3911,3917,3919,3923,3929,3931,3943,3947,3967,3989,4001,4003,4007,4013,4019,4021,4027,4049,4051,4057,4073,4079,4091,4093,4099,4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,4211,4217,4219,4229,4231,4241,4243,4253,4259,4261,4271,4273,4283,4289,4297,4327,4337,4339,4349,4357,4363,4373,4391,4397,4409,4421,4423,4441,4447,4451,4457,4463,4481,4483,4493,4507,4513,4517,4519,4523,4547,4549,4561,4567,4583,4591,4597,4603,4621,4637,4639,4643,4649,4651,4657,4663,4673,4679,4691,4703,4721,4723,4729,4733,4751,4759,4783,4787,4789,4793,4799,4801,4813,4817,4831,4861,4871,4877,4889,4903,4909,4919,4931,4933,4937,4943,4951,4957,4967,4969,4973,4987,4993,4999,5003,5009,5011,5021,5023,5039,5051,5059,5077,5081,5087,5099,5101,5107,5113,5119,5147,5153,5167,5171,5179,5189,5197,5209,5227,5231,5233,5237,5261,5273,5279,5281,5297,5303,5309,5323,5333,5347,5351,5381,5387,5393,5399,5407,5413,5417,5419,5431,5437,5441,5443,5449,5471,5477,5479,5483,5501,5503,5507,5519,5521,5527,5531,5557,5563,5569,5573,5581,5591,5623,5639,5641,5647,5651,5653,5657,5659,5669,5683,5689,5693,5701,5711,5717,5737,5741,5743,5749,5779,5783,5791,5801,5807,5813,5821,5827,5839,5843,5849,5851,5857,5861,5867,5869,5879,5881,5897,5903,5923,5927,5939,5953,5981,5987,6007,6011,6029,6037,6043,6047,6053,6067,6073,6079,6089,6091,6101,6113,6121,6131,6133,6143,6151,6163,6173,6197,6199,6203,6211,6217,6221,6229,6247,6257,6263,6269,6271,6277,6287,6299,6301,6311,6317,6323,6329,6337,6343,6353,6359,6361,6367,6373,6379,6389,6397,6421,6427,6449,6451,6469,6473,6481,6491,6521,6529,6547,6551,6553,6563,6569,6571,6577,6581,6599,6607,6619,6637,6653,6659,6661,6673,6679,6689,6691,6701,6703,6709,6719,6733,6737,6761,6763,6779,6781,6791,6793,6803,6823,6827,6829,6833,6841,6857,6863,6869,6871,6883,6899,6907,6911,6917,6947,6949,6959,6961,6967,6971,6977,6983,6991,6997,7001,7013,7019,7027,7039,7043,7057,7069,7079,7103,7109,7121,7127,7129,7151,7159,7177,7187,7193,7207,7211,7213,7219,7229,7237,7243,7247,7253,7283,7297,7307,7309,7321,7331,7333,7349,7351,7369,7393,7411,7417,7433,7451,7457,7459,7477,7481,7487,7489,7499,7507,7517,7523,7529,7537,7541,7547,7549,7559,7561,7573,7577,7583,7589,7591,7603,7607,7621,7639,7643,7649,7669,7673,7681,7687,7691,7699,7703,7717,7723,7727,7741,7753,7757,7759,7789,7793,7817,7823,7829,7841,7853,7867,7873,7877,7879,7883,7901,7907,7919,7927,7933,7937,7949,7951,7963,7993,8009,8011,8017,8039,8053,8059,8069,8081,8087,8089,8093,8101,8111,8117,8123,8147,8161,8167,8171,8179,8191,8209,8219,8221,8231,8233,8237,8243,8263,8269,8273,8287,8291,8293,8297,8311,8317,8329,8353,8363,8369,8377,8387,8389,8419,8423,8429,8431,8443,8447,8461,8467,8501,8513,8521,8527,8537,8539,8543,8563,8573,8581,8597,8599,8609,8623,8627,8629,8641,8647,8663,8669,8677,8681,8689,8693,8699,8707,8713,8719,8731,8737,8741,8747,8753,8761,8779,8783,8803,8807,8819,8821,8831,8837,8839,8849,8861,8863,8867,8887,8893,8923,8929,8933,8941,8951,8963,8969,8971,8999,9001,9007,9011,9013,9029,9041,9043,9049,9059,9067,9091,9103,9109,9127,9133,9137,9151,9157,9161,9173,9181,9187,9199,9203,9209,9221,9227,9239,9241,9257,9277,9281,9283,9293,9311,9319,9323,9337,9341,9343,9349,9371,9377,9391,9397,9403,9413,9419,9421,9431,9433,9437,9439,9461,9463,9467,9473,9479,9491,9497,9511,9521,9533,9539,9547,9551,9587,9601,9613,9619,9623,9629,9631,9643,9649,9661,9677,9679,9689,9697,9719,9721,9733,9739,9743,9749,9767,9769,9781,9787,9791,9803,9811,9817,9829,9833,9839,9851,9857,9859,9871,9883,9887,9901,9907,9923,9929,9931,9941,9949,9967,9973])"]
{"fn_name": "odd_not_prime", "inputs": [[5], [10], [99]], "outputs": [[1], [2], [26]]}
INTRODUCTORY
PYTHON3
CODEWARS
7,911
def odd_not_prime(n):
f842a83c5b7baf1614b3ef0742db407c
UNKNOWN
Santa is coming to town and he needs your help finding out who's been naughty or nice. You will be given an entire year of JSON data following this format: Your function should return `"Naughty!"` or `"Nice!"` depending on the total number of occurrences in a given year (whichever one is greater). If both are equal, return `"Nice!"`
["def naughty_or_nice(data):\n nice = 0\n for month in data:\n for day in data[month]:\n nice += 1 if data[month][day] == \"Nice\" else -1\n return \"Nice!\" if nice >= 0 else \"Naughty!\"\n", "import json\n\ndef naughty_or_nice(data):\n parsed_data = json.dumps(data)\n return \"Nice!\" if parsed_data.count(\"Nice\") >= parsed_data.count(\"Naughty\") else \"Naughty!\"", "def naughty_or_nice(data):\n s = str(data)\n return 'Nice!' if s.count('Nice') >= s.count('Naughty') else 'Naughty!'", "naughty_or_nice = lambda d:max(['Nice', 'Naughty'], key=[x for y in d.values() for x in y.values()].count) + '!'", "import json\ndef naughty_or_nice(data):\n s = json.dumps(data)\n return 'Nice!' if s.count('Nice') >= s.count('Naughty') else 'Naughty!'", "from collections import Counter\n\ndef naughty_or_nice(data):\n c = Counter(x for v in data.values() for x in v.values())\n return 'Nice!' if c['Nice'] >= c['Naughty'] else 'Naughty!'", "def naughty_or_nice(data):\n return 'Nice!' if str(data).count('Nice') >= str(data).count('Naughty') else 'Naughty!'", "def naughty_or_nice(data):\n return \"Nice!\" if sum(1 if day == \"Nice\" else -1 for month in data.values() for day in month.values()) >= 0 else \"Naughty!\"", "def naughty_or_nice(data):\n nice_count = 0\n naughty_count = 0\n \n for month, days in data.items():\n for date, status in days.items():\n if status == 'Nice':\n nice_count += 1\n else:\n naughty_count += 1\n \n return 'Naughty!' if nice_count < naughty_count else 'Nice!'"]
{"fn_name": "naughty_or_nice", "inputs": [[{"January": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Nice", "5": "Naughty", "6": "Nice", "7": "Naughty", "8": "Nice", "9": "Naughty", "10": "Nice", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Nice", "21": "Naughty", "22": "Nice", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Nice", "27": "Naughty", "28": "Nice", "29": "Naughty", "30": "Nice", "31": "Naughty"}, "February": {"1": "Nice", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Naughty", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Naughty", "13": "Nice", "14": "Naughty", "15": "Nice", "16": "Naughty", "17": "Nice", "18": "Naughty", "19": "Nice", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Nice", "26": "Naughty", "27": "Nice", "28": "Naughty", "29": "Nice"}, "March": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Nice", "5": "Naughty", "6": "Nice", "7": "Naughty", "8": "Nice", "9": "Naughty", "10": "Nice", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Nice", "21": "Naughty", "22": "Nice", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Nice", "27": "Naughty", "28": "Nice", "29": "Naughty", "30": "Nice", "31": "Naughty"}, "April": {"1": "Nice", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Naughty", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Naughty", "13": "Nice", "14": "Naughty", "15": "Nice", "16": "Naughty", "17": "Nice", "18": "Naughty", "19": "Nice", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Nice", "26": "Naughty", "27": "Nice", "28": "Naughty", "29": "Nice", "30": "Naughty"}, "May": {"1": "Nice", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Naughty", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Naughty", "13": "Nice", "14": "Naughty", "15": "Nice", "16": "Naughty", "17": "Nice", "18": "Naughty", "19": "Nice", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Nice", "26": "Naughty", "27": "Nice", "28": "Naughty", "29": "Nice", "30": "Naughty", "31": "Nice"}, "June": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Nice", "5": "Naughty", "6": "Nice", "7": "Naughty", "8": "Nice", "9": "Naughty", "10": "Nice", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Nice", "21": "Naughty", "22": "Nice", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Nice", "27": "Naughty", "28": "Nice", "29": "Naughty", "30": "Nice"}, "July": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Nice", "5": "Naughty", "6": "Nice", "7": "Naughty", "8": "Nice", "9": "Naughty", "10": "Nice", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Nice", "21": "Naughty", "22": "Nice", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Nice", "27": "Naughty", "28": "Nice", "29": "Naughty", "30": "Nice", "31": "Naughty"}, "August": {"1": "Nice", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Naughty", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Naughty", "13": "Nice", "14": "Naughty", "15": "Nice", "16": "Naughty", "17": "Nice", "18": "Naughty", "19": "Nice", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Nice", "26": "Naughty", "27": "Nice", "28": "Naughty", "29": "Nice", "30": "Naughty", "31": "Nice"}, "September": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Nice", "5": "Naughty", "6": "Nice", "7": "Naughty", "8": "Nice", "9": "Naughty", "10": "Nice", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Nice", "21": "Naughty", "22": "Nice", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Nice", "27": "Naughty", "28": "Nice", "29": "Naughty", "30": "Nice"}, "October": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Nice", "5": "Naughty", "6": "Nice", "7": "Naughty", "8": "Nice", "9": "Naughty", "10": "Nice", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Nice", "21": "Naughty", "22": "Nice", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Nice", "27": "Naughty", "28": "Nice", "29": "Naughty", "30": "Nice", "31": "Naughty"}, "November": {"1": "Nice", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Naughty", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Naughty", "13": "Nice", "14": "Naughty", "15": "Nice", "16": "Naughty", "17": "Nice", "18": "Naughty", "19": "Nice", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Nice", "26": "Naughty", "27": "Nice", "28": "Naughty", "29": "Nice", "30": "Naughty"}, "December": {"1": "Nice", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Naughty", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Naughty", "13": "Nice", "14": "Naughty", "15": "Nice", "16": "Naughty", "17": "Nice", "18": "Naughty", "19": "Nice", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Nice", "26": "Naughty", "27": "Nice", "28": "Naughty", "29": "Nice", "30": "Naughty", "31": "Nice"}}], [{"January": {"1": "Naughty", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Nice", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Nice", "11": "Nice", "12": "Nice", "13": "Naughty", "14": "Naughty", "15": "Nice", "16": "Naughty", "17": "Nice", "18": "Nice", "19": "Nice", "20": "Nice", "21": "Nice", "22": "Nice", "23": "Naughty", "24": "Naughty", "25": "Nice", "26": "Nice", "27": "Nice", "28": "Naughty", "29": "Nice", "30": "Nice", "31": "Nice"}, "February": {"1": "Nice", "2": "Nice", "3": "Naughty", "4": "Naughty", "5": "Nice", "6": "Naughty", "7": "Naughty", "8": "Naughty", "9": "Nice", "10": "Nice", "11": "Nice", "12": "Nice", "13": "Naughty", "14": "Naughty", "15": "Naughty", "16": "Nice", "17": "Nice", "18": "Nice", "19": "Naughty", "20": "Nice", "21": "Nice", "22": "Naughty", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Naughty", "27": "Nice", "28": "Nice"}, "March": {"1": "Nice", "2": "Nice", "3": "Nice", "4": "Nice", "5": "Nice", "6": "Naughty", "7": "Naughty", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Naughty", "12": "Naughty", "13": "Nice", "14": "Nice", "15": "Nice", "16": "Naughty", "17": "Naughty", "18": "Naughty", "19": "Nice", "20": "Naughty", "21": "Naughty", "22": "Nice", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Nice", "27": "Nice", "28": "Naughty", "29": "Nice", "30": "Naughty", "31": "Nice"}, "April": {"1": "Nice", "2": "Nice", "3": "Nice", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Naughty", "8": "Nice", "9": "Naughty", "10": "Naughty", "11": "Naughty", "12": "Naughty", "13": "Nice", "14": "Naughty", "15": "Naughty", "16": "Naughty", "17": "Nice", "18": "Nice", "19": "Nice", "20": "Nice", "21": "Nice", "22": "Naughty", "23": "Naughty", "24": "Naughty", "25": "Naughty", "26": "Naughty", "27": "Naughty", "28": "Nice", "29": "Nice", "30": "Naughty"}, "May": {"1": "Nice", "2": "Nice", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Nice", "7": "Naughty", "8": "Naughty", "9": "Naughty", "10": "Naughty", "11": "Naughty", "12": "Naughty", "13": "Naughty", "14": "Nice", "15": "Nice", "16": "Nice", "17": "Naughty", "18": "Naughty", "19": "Naughty", "20": "Naughty", "21": "Nice", "22": "Nice", "23": "Naughty", "24": "Naughty", "25": "Naughty", "26": "Nice", "27": "Nice", "28": "Nice", "29": "Nice", "30": "Naughty", "31": "Nice"}, "June": {"1": "Nice", "2": "Naughty", "3": "Naughty", "4": "Nice", "5": "Nice", "6": "Nice", "7": "Naughty", "8": "Nice", "9": "Naughty", "10": "Nice", "11": "Nice", "12": "Nice", "13": "Naughty", "14": "Naughty", "15": "Naughty", "16": "Naughty", "17": "Nice", "18": "Naughty", "19": "Naughty", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Nice", "26": "Nice", "27": "Nice", "28": "Naughty", "29": "Nice", "30": "Naughty"}, "July": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Naughty", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Nice", "13": "Nice", "14": "Nice", "15": "Nice", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Nice", "21": "Nice", "22": "Nice", "23": "Naughty", "24": "Naughty", "25": "Nice", "26": "Naughty", "27": "Naughty", "28": "Nice", "29": "Naughty", "30": "Nice", "31": "Nice"}, "August": {"1": "Naughty", "2": "Naughty", "3": "Naughty", "4": "Nice", "5": "Naughty", "6": "Nice", "7": "Nice", "8": "Nice", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Naughty", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Naughty", "17": "Naughty", "18": "Naughty", "19": "Nice", "20": "Nice", "21": "Naughty", "22": "Nice", "23": "Nice", "24": "Nice", "25": "Nice", "26": "Nice", "27": "Nice", "28": "Naughty", "29": "Naughty", "30": "Naughty", "31": "Nice"}, "September": {"1": "Naughty", "2": "Naughty", "3": "Nice", "4": "Nice", "5": "Nice", "6": "Nice", "7": "Nice", "8": "Naughty", "9": "Naughty", "10": "Naughty", "11": "Naughty", "12": "Naughty", "13": "Nice", "14": "Nice", "15": "Nice", "16": "Naughty", "17": "Naughty", "18": "Naughty", "19": "Nice", "20": "Nice", "21": "Nice", "22": "Naughty", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Nice", "27": "Naughty", "28": "Nice", "29": "Nice", "30": "Naughty"}, "October": {"1": "Nice", "2": "Nice", "3": "Naughty", "4": "Nice", "5": "Nice", "6": "Naughty", "7": "Nice", "8": "Nice", "9": "Nice", "10": "Nice", "11": "Nice", "12": "Nice", "13": "Nice", "14": "Naughty", "15": "Nice", "16": "Nice", "17": "Nice", "18": "Nice", "19": "Nice", "20": "Nice", "21": "Naughty", "22": "Nice", "23": "Nice", "24": "Naughty", "25": "Naughty", "26": "Naughty", "27": "Nice", "28": "Nice", "29": "Nice", "30": "Naughty", "31": "Nice"}, "November": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Naughty", "5": "Naughty", "6": "Nice", "7": "Nice", "8": "Nice", "9": "Nice", "10": "Nice", "11": "Nice", "12": "Nice", "13": "Nice", "14": "Nice", "15": "Naughty", "16": "Naughty", "17": "Naughty", "18": "Naughty", "19": "Naughty", "20": "Nice", "21": "Naughty", "22": "Naughty", "23": "Naughty", "24": "Naughty", "25": "Nice", "26": "Naughty", "27": "Naughty", "28": "Nice", "29": "Nice", "30": "Naughty"}, "December": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Nice", "5": "Nice", "6": "Nice", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Naughty", "12": "Naughty", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Naughty", "21": "Naughty", "22": "Nice", "23": "Nice", "24": "Naughty", "25": "Nice", "26": "Nice", "27": "Naughty", "28": "Nice", "29": "Nice", "30": "Nice", "31": "Naughty"}}], [{"January": {"1": "Nice", "2": "Nice", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Naughty", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Nice", "11": "Nice", "12": "Naughty", "13": "Nice", "14": "Nice", "15": "Naughty", "16": "Naughty", "17": "Naughty", "18": "Naughty", "19": "Nice", "20": "Nice", "21": "Nice", "22": "Nice", "23": "Nice", "24": "Nice", "25": "Nice", "26": "Nice", "27": "Naughty", "28": "Naughty", "29": "Nice", "30": "Nice", "31": "Naughty"}, "February": {"1": "Nice", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Nice", "7": "Nice", "8": "Naughty", "9": "Naughty", "10": "Naughty", "11": "Nice", "12": "Nice", "13": "Nice", "14": "Nice", "15": "Nice", "16": "Naughty", "17": "Nice", "18": "Naughty", "19": "Nice", "20": "Nice", "21": "Nice", "22": "Naughty", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Nice", "27": "Nice", "28": "Naughty"}, "March": {"1": "Nice", "2": "Nice", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Naughty", "7": "Naughty", "8": "Nice", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Nice", "13": "Nice", "14": "Naughty", "15": "Naughty", "16": "Naughty", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Naughty", "21": "Nice", "22": "Nice", "23": "Nice", "24": "Nice", "25": "Nice", "26": "Nice", "27": "Naughty", "28": "Nice", "29": "Nice", "30": "Naughty", "31": "Naughty"}, "April": {"1": "Nice", "2": "Nice", "3": "Nice", "4": "Naughty", "5": "Naughty", "6": "Nice", "7": "Nice", "8": "Naughty", "9": "Naughty", "10": "Naughty", "11": "Nice", "12": "Nice", "13": "Nice", "14": "Nice", "15": "Nice", "16": "Naughty", "17": "Naughty", "18": "Naughty", "19": "Nice", "20": "Nice", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Naughty", "26": "Nice", "27": "Nice", "28": "Naughty", "29": "Naughty", "30": "Nice"}, "May": {"1": "Nice", "2": "Naughty", "3": "Nice", "4": "Nice", "5": "Nice", "6": "Nice", "7": "Nice", "8": "Nice", "9": "Nice", "10": "Nice", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Naughty", "15": "Naughty", "16": "Naughty", "17": "Naughty", "18": "Nice", "19": "Nice", "20": "Nice", "21": "Nice", "22": "Naughty", "23": "Naughty", "24": "Naughty", "25": "Naughty", "26": "Nice", "27": "Naughty", "28": "Naughty", "29": "Nice", "30": "Nice", "31": "Naughty"}, "June": {"1": "Nice", "2": "Nice", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Nice", "7": "Naughty", "8": "Nice", "9": "Nice", "10": "Nice", "11": "Nice", "12": "Naughty", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Nice", "17": "Nice", "18": "Nice", "19": "Nice", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Naughty", "26": "Naughty", "27": "Nice", "28": "Nice", "29": "Naughty", "30": "Naughty"}, "July": {"1": "Nice", "2": "Nice", "3": "Nice", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Naughty", "8": "Naughty", "9": "Naughty", "10": "Naughty", "11": "Naughty", "12": "Naughty", "13": "Naughty", "14": "Naughty", "15": "Nice", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Nice", "20": "Nice", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Nice", "26": "Naughty", "27": "Nice", "28": "Nice", "29": "Nice", "30": "Nice", "31": "Naughty"}, "August": {"1": "Naughty", "2": "Naughty", "3": "Naughty", "4": "Naughty", "5": "Naughty", "6": "Nice", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Naughty", "12": "Naughty", "13": "Nice", "14": "Naughty", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Nice", "20": "Nice", "21": "Nice", "22": "Nice", "23": "Naughty", "24": "Nice", "25": "Nice", "26": "Naughty", "27": "Nice", "28": "Naughty", "29": "Nice", "30": "Nice", "31": "Nice"}, "September": {"1": "Naughty", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Naughty", "8": "Naughty", "9": "Naughty", "10": "Naughty", "11": "Nice", "12": "Naughty", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Naughty", "17": "Nice", "18": "Nice", "19": "Naughty", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Naughty", "24": "Naughty", "25": "Naughty", "26": "Naughty", "27": "Naughty", "28": "Nice", "29": "Nice", "30": "Nice"}, "October": {"1": "Naughty", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Nice", "6": "Nice", "7": "Nice", "8": "Nice", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Nice", "13": "Nice", "14": "Naughty", "15": "Naughty", "16": "Nice", "17": "Nice", "18": "Nice", "19": "Naughty", "20": "Naughty", "21": "Nice", "22": "Nice", "23": "Naughty", "24": "Nice", "25": "Nice", "26": "Naughty", "27": "Naughty", "28": "Nice", "29": "Nice", "30": "Naughty", "31": "Naughty"}, "November": {"1": "Nice", "2": "Nice", "3": "Nice", "4": "Nice", "5": "Nice", "6": "Nice", "7": "Nice", "8": "Nice", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Nice", "13": "Naughty", "14": "Nice", "15": "Nice", "16": "Naughty", "17": "Naughty", "18": "Nice", "19": "Nice", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Naughty", "26": "Naughty", "27": "Naughty", "28": "Nice", "29": "Naughty", "30": "Naughty"}, "December": {"1": "Nice", "2": "Nice", "3": "Nice", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Nice", "8": "Naughty", "9": "Naughty", "10": "Naughty", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Naughty", "15": "Naughty", "16": "Nice", "17": "Nice", "18": "Nice", "19": "Naughty", "20": "Nice", "21": "Nice", "22": "Nice", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Naughty", "27": "Naughty", "28": "Naughty", "29": "Nice", "30": "Naughty", "31": "Naughty"}}], [{"January": {"1": "Nice", "2": "Nice", "3": "Nice", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Naughty", "8": "Nice", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Nice", "13": "Nice", "14": "Naughty", "15": "Nice", "16": "Naughty", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Naughty", "21": "Naughty", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Naughty", "26": "Naughty", "27": "Naughty", "28": "Naughty", "29": "Naughty", "30": "Nice", "31": "Naughty"}, "February": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Naughty", "5": "Nice", "6": "Nice", "7": "Naughty", "8": "Nice", "9": "Naughty", "10": "Naughty", "11": "Nice", "12": "Nice", "13": "Naughty", "14": "Naughty", "15": "Nice", "16": "Naughty", "17": "Nice", "18": "Naughty", "19": "Naughty", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Nice", "24": "Naughty", "25": "Naughty", "26": "Naughty", "27": "Nice", "28": "Naughty"}, "March": {"1": "Naughty", "2": "Nice", "3": "Nice", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Naughty", "8": "Nice", "9": "Naughty", "10": "Naughty", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Naughty", "15": "Naughty", "16": "Naughty", "17": "Nice", "18": "Nice", "19": "Naughty", "20": "Naughty", "21": "Naughty", "22": "Nice", "23": "Naughty", "24": "Nice", "25": "Naughty", "26": "Naughty", "27": "Naughty", "28": "Naughty", "29": "Naughty", "30": "Nice", "31": "Naughty"}, "April": {"1": "Nice", "2": "Nice", "3": "Naughty", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Naughty", "8": "Naughty", "9": "Naughty", "10": "Naughty", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Naughty", "15": "Nice", "16": "Naughty", "17": "Naughty", "18": "Nice", "19": "Nice", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Naughty", "24": "Nice", "25": "Nice", "26": "Naughty", "27": "Naughty", "28": "Naughty", "29": "Nice", "30": "Naughty"}, "May": {"1": "Nice", "2": "Naughty", "3": "Naughty", "4": "Naughty", "5": "Nice", "6": "Nice", "7": "Naughty", "8": "Naughty", "9": "Naughty", "10": "Naughty", "11": "Naughty", "12": "Naughty", "13": "Naughty", "14": "Naughty", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Nice", "20": "Nice", "21": "Nice", "22": "Naughty", "23": "Naughty", "24": "Naughty", "25": "Naughty", "26": "Nice", "27": "Nice", "28": "Nice", "29": "Nice", "30": "Naughty", "31": "Naughty"}, "June": {"1": "Naughty", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Naughty", "8": "Naughty", "9": "Naughty", "10": "Naughty", "11": "Nice", "12": "Naughty", "13": "Naughty", "14": "Naughty", "15": "Naughty", "16": "Naughty", "17": "Nice", "18": "Nice", "19": "Nice", "20": "Naughty", "21": "Naughty", "22": "Naughty", "23": "Naughty", "24": "Naughty", "25": "Naughty", "26": "Nice", "27": "Nice", "28": "Naughty", "29": "Naughty", "30": "Naughty"}, "July": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Naughty", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Naughty", "12": "Naughty", "13": "Naughty", "14": "Naughty", "15": "Naughty", "16": "Naughty", "17": "Naughty", "18": "Naughty", "19": "Nice", "20": "Nice", "21": "Nice", "22": "Naughty", "23": "Naughty", "24": "Naughty", "25": "Naughty", "26": "Naughty", "27": "Nice", "28": "Naughty", "29": "Nice", "30": "Nice", "31": "Naughty"}, "August": {"1": "Nice", "2": "Naughty", "3": "Naughty", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Naughty", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Naughty", "12": "Naughty", "13": "Naughty", "14": "Naughty", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Nice", "21": "Naughty", "22": "Nice", "23": "Nice", "24": "Naughty", "25": "Naughty", "26": "Naughty", "27": "Naughty", "28": "Nice", "29": "Naughty", "30": "Naughty", "31": "Naughty"}, "September": {"1": "Nice", "2": "Naughty", "3": "Naughty", "4": "Naughty", "5": "Naughty", "6": "Nice", "7": "Nice", "8": "Naughty", "9": "Naughty", "10": "Naughty", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Naughty", "15": "Naughty", "16": "Naughty", "17": "Nice", "18": "Naughty", "19": "Naughty", "20": "Nice", "21": "Nice", "22": "Nice", "23": "Nice", "24": "Naughty", "25": "Nice", "26": "Naughty", "27": "Naughty", "28": "Naughty", "29": "Nice", "30": "Naughty"}, "October": {"1": "Naughty", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Nice", "12": "Naughty", "13": "Naughty", "14": "Naughty", "15": "Nice", "16": "Naughty", "17": "Naughty", "18": "Nice", "19": "Nice", "20": "Naughty", "21": "Nice", "22": "Naughty", "23": "Naughty", "24": "Naughty", "25": "Naughty", "26": "Nice", "27": "Nice", "28": "Nice", "29": "Naughty", "30": "Nice", "31": "Nice"}, "November": {"1": "Naughty", "2": "Naughty", "3": "Nice", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Naughty", "12": "Nice", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Nice", "19": "Naughty", "20": "Nice", "21": "Naughty", "22": "Naughty", "23": "Naughty", "24": "Naughty", "25": "Naughty", "26": "Naughty", "27": "Nice", "28": "Nice", "29": "Naughty", "30": "Nice"}, "December": {"1": "Naughty", "2": "Nice", "3": "Naughty", "4": "Naughty", "5": "Naughty", "6": "Naughty", "7": "Nice", "8": "Naughty", "9": "Nice", "10": "Naughty", "11": "Naughty", "12": "Naughty", "13": "Naughty", "14": "Nice", "15": "Naughty", "16": "Nice", "17": "Naughty", "18": "Naughty", "19": "Nice", "20": "Nice", "21": "Naughty", "22": "Nice", "23": "Naughty", "24": "Naughty", "25": "Naughty", "26": "Naughty", "27": "Naughty", "28": "Naughty", "29": "Naughty", "30": "Naughty", "31": "Nice"}}]], "outputs": [["Nice!"], ["Nice!"], ["Nice!"], ["Naughty!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,584
def naughty_or_nice(data):
c7604f17d83ce57e1c7c27d95b756637
UNKNOWN
We have the first value of a certain sequence, we will name it ```initVal```. We define pattern list, ```patternL```, an array that has the differences between contiguous terms of the sequence. ``` E.g: patternL = [k1, k2, k3, k4]``` The terms of the sequence will be such values that: ```python term1 = initVal term2 - term1 = k1 term3 - term2 = k2 term4 - term3 = k3 term5 - term4 = k4 term6 - term5 = k1 term7 - term6 = k2 term8 - term7 = k3 term9 - term8 = k4 .... - ..... = ... .... - ..... = ... ``` So the values of the differences between contiguous terms are cyclical and are repeated as the differences values of the pattern list stablishes. Let's see an example with numbers: ```python initVal = 10 patternL = [2, 1, 3] term1 = 10 term2 = 12 term3 = 13 term4 = 16 term5 = 18 term6 = 19 term7 = 22 # and so on... ``` We can easily obtain the next terms of the sequence following the values in the pattern list. We see that the sixth term of the sequence, ```19```, has the sum of its digits ```10```. Make a function ```sumDig_nthTerm()```, that receives three arguments in this order ```sumDig_nthTerm(initVal, patternL, nthTerm(ordinal number of the term in the sequence)) ``` This function will output the sum of the digits of the n-th term of the sequence. Let's see some cases for this function: ```python sumDig_nthTerm(10, [2, 1, 3], 6) -----> 10 # because the sixth term is 19 sum of Dig = 1 + 9 = 10. The sequence up to the sixth-Term is: 10, 12, 13, 16, 18, 19 sumDig_nthTerm(10, [1, 2, 3], 15) ----> 10 # 37 is the 15-th term, and 3 + 7 = 10 ``` Enjoy it and happy coding!!
["from itertools import cycle\n\ndef sumDig_nthTerm(initVal, patternL, nthTerm):\n \n for c, i in enumerate(cycle(patternL), 2):\n initVal += i\n \n if c == nthTerm:\n return sum(int(v) for v in str(initVal))", "def sumDig_nthTerm(base, cycle, k):\n loop, remaining = divmod(k - 1, len(cycle))\n term = base + loop * sum(cycle) + sum(cycle[:remaining])\n return sum(int(d) for d in str(term))", "def sumDig_nthTerm(initVal, patternL, nthTerm):\n q, r = divmod(nthTerm-1, len(patternL))\n x = initVal + q*sum(patternL) + sum(patternL[:r])\n return sum(map(int, str(x)))", "from itertools import cycle as c,islice as isl\nsumDig_nthTerm=lambda ini,p,n:sum(map(int,str(ini+sum(list(isl(c(p),n-1))))))", "sumDig_nthTerm = lambda st, p, n:sum(map(int,str(st+sum(p)*((n-1)//len(p))+sum(p[:(n-1)%len(p)]))))", "def sumDig_nthTerm(initVal, patternL, nthTerm):\n n=initVal\n for i in range(nthTerm-1):\n n+=patternL[i%len(patternL)]\n return sum(int(d) for d in str(n))"]
{"fn_name": "sumDig_nthTerm", "inputs": [[10, [2, 1, 3], 6], [10, [2, 1, 3], 15], [10, [2, 1, 3], 50], [10, [2, 1, 3], 78], [10, [2, 1, 3], 157], [10, [2, 2, 5, 8], 6], [10, [2, 2, 5, 8], 15], [10, [2, 2, 5, 8], 50], [10, [2, 2, 5, 8], 78], [10, [2, 2, 5, 8], 157], [100, [2, 2, 5, 8], 6], [100, [2, 2, 5, 8], 15], [100, [2, 2, 5, 8], 50], [100, [2, 2, 5, 8], 78], [100, [2, 2, 5, 8], 157], [1000, [2, 2, 5, 8], 2550], [1000, [2, 2, 5, 8], 25500]], "outputs": [[10], [10], [9], [10], [7], [11], [11], [9], [11], [16], [11], [11], [9], [11], [16], [14], [26]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,034
def sumDig_nthTerm(initVal, patternL, nthTerm):
cb83485b84c20bfa5408a962b76ad1a8
UNKNOWN
# Task Given the birthdates of two people, find the date when the younger one is exactly half the age of the other. # Notes * The dates are given in the format YYYY-MM-DD and are not sorted in any particular order * Round **down** to the nearest day * Return the result as a string, like the input dates
["from dateutil.parser import parse\n\ndef half_life(*persons):\n p1,p2 = sorted(map(parse, persons))\n return str( p2+(p2-p1) )[:10]", "from datetime import datetime as dt\n\ndef half_life(p1, p2):\n d1, d2 = (dt.strptime(p, \"%Y-%m-%d\") for p in sorted((p1, p2)))\n return (d2 + (d2 - d1)).strftime(\"%Y-%m-%d\")", "from datetime import date\ndef half_life(person1, person2):\n p1 = list(map(int,person1.split(\"-\")))\n p1_date = date(p1[0],p1[1],p1[2])\n p2 = list(map(int,person2.split(\"-\")))\n p2_date = date(p2[0],p2[1],p2[2])\n if p1[0]>p2[0]:\n diff = p1_date-p2_date\n b = p1_date+diff\n return str(b)\n else:\n diff = p2_date-p1_date\n a = p2_date+diff\n return str(a)\n \n", "from datetime import datetime\n\ndef half_life(*p):\n D = sorted(datetime.strptime(x, \"%Y-%m-%d\") for x in p)\n return (D[1] + (D[1] - D[0])).strftime(\"%Y-%m-%d\")\n", "from datetime import datetime, timedelta\n\ndef half_life(person1, person2):\n d1, d2 = (datetime.strptime(p, '%Y-%m-%d') for p in [person1, person2])\n if d1 > d2:\n d1, d2 = d2, d1\n return format(d2 + timedelta((d2 - d1).days), '%Y-%m-%d')", "from datetime import datetime\n\ndef half_life(person1, person2):\n person1, person2 = sorted((person1, person2))\n p1 = datetime.strptime(person1, \"%Y-%m-%d\")\n p2 = datetime.strptime(person2, \"%Y-%m-%d\")\n return (p2 + (p2 - p1)).strftime(\"%Y-%m-%d\")", "from datetime import datetime\n\ndef half_life(a, b):\n a, b = [datetime.strptime(x, \"%Y-%m-%d\") for x in (a, b)]\n return (max(a, b) + abs(a - b)).strftime(\"%Y-%m-%d\")", "from datetime import datetime\ndef half_life(p1,p2):\n d1,d2=sorted([datetime.strptime(p1,\"%Y-%m-%d\"),datetime.strptime(p2,\"%Y-%m-%d\")])\n return (d2+(d2-d1)).strftime(\"%Y-%m-%d\")", "from datetime import datetime\n\ndef half_life(person1, person2):\n d1, d2 = map(lambda s: datetime.strptime(s, '%Y-%m-%d'), sorted((person1, person2)))\n return datetime.strftime(d2 + (d2 - d1), '%Y-%m-%d')", "from datetime import date, datetime\ndef half_life(person1, person2):\n d0, d1 = sorted([\n datetime.strptime(person1, '%Y-%m-%d').date(),\n datetime.strptime(person2, '%Y-%m-%d').date()\n ])\n return (d1 + (d1 - d0)).isoformat()\n"]
{"fn_name": "half_life", "inputs": [["1990-12-06", "2000-02-29"], ["2012-03-31", "1990-06-09"], ["1984-08-14", "1990-04-17"], ["2000-06-30", "1978-03-17"], ["1969-12-20", "2000-10-07"]], "outputs": [["2009-05-24"], ["2034-01-21"], ["1995-12-19"], ["2022-10-14"], ["2031-07-26"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,330
def half_life(person1, person2):
4b6a191cb9993dd292dbe48857098a50
UNKNOWN
# Task Write a function named `sumEvenNumbers`, taking a sequence of numbers as single parameter. Your function must return the sum of **the even values** of this sequence. Only numbers without decimals like `4` or `4.0` can be even. ## Input * sequence of numbers: those numbers could be integers and/or floats. For example, considering this input value : `[4,3,1,2,5,10,6,7,9,8]`, then your function should return `30` (because `4 + 2 + 10 + 6 + 8 = 30`).
["def sum_even_numbers(seq): \n return sum(n for n in seq if not n % 2)", "def sum_even_numbers(seq): \n return sum(x for x in seq if x%2==0)", "def sum_even_numbers(seq): \n return sum(filter(lambda n: n%2==0, seq))", "def sum_even_numbers(seq): \n # your code here\n nums = []\n b = 0\n for i in range(len(seq)):\n if seq[i] % 2 == 0:\n nums.append(seq[i])\n for f in range(len(nums)):\n b = b + nums[f]\n \n return b\n", "def sum_even_numbers(seq): \n return sum([x for x in seq if x%2 ==0])", "def sum_even_numbers(seq): \n L=[]\n for i in seq:\n if i%2==0:\n L.append(i)\n return sum(L)", "def sum_even_numbers(seq): \n return sum(number for number in seq if number % 2 == 0)", "def sum_even_numbers(seq):\n to_sum = [num for num in seq if num % 2 == 0]\n return sum(to_sum)", "def sum_even_numbers(seq): \n sum = 0\n for i in range(len(seq)):\n if seq[i] % 2 == 0:\n sum += seq[i]\n return sum", "sum_even_numbers = lambda _: sum([__ for __ in _ if not __%2])\n"]
{"fn_name": "sum_even_numbers", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [[]], [[1337, 374, 849, 22.5, 19, 16, 0, 0, 16, 32]], [[-16, -32, 20, 21, 41, 42]], [[15397, 12422, 10495, 22729, 23921, 18326, 27955, 24073, 23690, 15002, 11615, 15682, 24346, 16725, 17252, 20467, 20493, 17807, 13041, 25861, 22471, 22747, 24082, 18979, 28543, 26488, 10002, 24740, 17950, 26573, 25851, 19446, 22584, 14857, 17387, 29310, 28265, 19497, 11394, 28111, 20957, 17201, 26647, 26885, 27297, 17252, 25961, 12409, 22858, 27869, 19832, 13906, 11256, 11304, 24186, 28783, 16647, 23073, 11105, 13327, 17102, 10172, 21104, 23001, 24108, 16166, 21690, 14218, 11903, 10286, 19116, 18585, 25511, 18273, 11862, 17166, 13456, 28562, 16262, 11100, 22806, 14748, 17362, 11633, 17165, 16390, 24580, 22498, 26121, 16170, 18917, 26963, 17605, 20839, 22487, 12187, 23752, 12444, 14392, 28313]]], "outputs": [[30], [0], [438], [14], [870822]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,094
def sum_even_numbers(seq):
74c52c9ee5e16595a333ebbdffea7a0c
UNKNOWN
In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out. ### Example ```python filter_list([1,2,'a','b']) == [1,2] filter_list([1,'a','b',0,15]) == [1,0,15] filter_list([1,2,'aasf','1','123',123]) == [1,2,123] ```
["def filter_list(l):\n 'return a new list with the strings filtered out'\n return [i for i in l if not isinstance(i, str)]\n", "def filter_list(l):\n 'return a new list with the strings filtered out'\n return [x for x in l if type(x) is not str]", "def filter_list(l):\n 'return a new list with the strings filtered out'\n return [e for e in l if isinstance(e, int)]", "def filter_list(l):\n new_list =[]\n for x in l:\n if type(x) != str:\n new_list.append(x)\n return new_list\n \n", "def filter_list(l):\n 'return a new list with the strings filtered out'\n return [e for e in l if type(e) is int]", "def filter_list(l):\n return [x for x in l if isinstance(x, int)]", "def filter_list(l):\n output = []\n for x in l:\n if type(x) == int:\n output.append(x)\n return output"]
{"fn_name": "filter_list", "inputs": [[[1, 2, "a", "b"]], [[1, "a", "b", 0, 15]], [[1, 2, "aasf", "1", "123", 123]], [["a", "b", "1"]]], "outputs": [[[1, 2]], [[1, 0, 15]], [[1, 2, 123]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
854
def filter_list(l):
24443334cb9dc11d85af63bebea6cf76
UNKNOWN
Given a name, turn that name into a perfect square matrix (nested array with the amount of arrays equivalent to the length of each array). You will need to add periods (`.`) to the end of the name if necessary, to turn it into a matrix. If the name has a length of 0, return `"name must be at least one letter"` ## Examples "Bill" ==> [ ["B", "i"], ["l", "l"] ] "Frank" ==> [ ["F", "r", "a"], ["n", "k", "."], [".", ".", "."] ]
["from math import ceil\n\ndef matrixfy(s):\n if not s: return \"name must be at least one letter\"\n x = ceil(len(s)**.5)\n it = iter(s.ljust(x*x,'.'))\n return [ [next(it) for _ in range(x)] for _ in range(x)]", "def matrixfy(st):\n if not st:\n return 'name must be at least one letter'\n n = 1\n while n*n < len(st):\n n += 1\n st += '.' * (n*n - len(st))\n return [list(xs) for xs in zip(*[iter(st)]*n)]", "from math import ceil\n\n\ndef matrixfy(stg):\n if not stg:\n return \"name must be at least one letter\"\n side = ceil(len(stg)**0.5)\n area = side**2\n chars = list(stg.ljust(area, \".\"))\n return [chars[i:i+side] for i in range(0, area, side)]\n", "from math import ceil\ndef matrixfy(s):\n if not s: return \"name must be at least one letter\"\n n = ceil(len(s)**.5)\n return [list(s[x:x+n].ljust(n, '.')) for x in range(0, n*n, n)]", "from math import ceil\nfrom itertools import chain, repeat\ndef matrixfy(st):\n s = ceil(len(st) ** 0.5)\n c = chain(st, repeat('.'))\n return [[next(c) for _ in range(s)] for _ in range(s)] or 'name must be at least one letter'", "import math\n\ndef matrixfy(st):\n if not st:\n return 'name must be at least one letter'\n side = math.ceil(math.sqrt(len(st)))\n quad = side * side\n st += '.' * (quad - len(st))\n return [list(st[i-side:i]) for i in range(side, quad + 1, side)]\n", "from math import ceil\nfrom re import findall\n\ndef matrixfy(name):\n if not name:\n return \"name must be at least one letter\"\n \n n = ceil(len(name)**0.5)\n name = name.ljust(n*n, \".\")\n \n return [ list(s) for s in findall(\".\"*n, name) ]", "from math import ceil\n\ndef matrixfy(name):\n if not name:\n return \"name must be at least one letter\"\n \n n = ceil(len(name)**0.5)\n name = list( name.ljust(n*n, \".\") )\n \n return [ name[i*n : i*n+n] for i in range(n) ]", "def matrixfy(s):n=-int(-len(s)**.5//1);return list(map(list,zip(*[iter(s.ljust(n*n,'.'))]*n)))or'name must be at least one letter'", "def matrixfy(st):\n import math\n if len(st) == 0:\n return \"name must be at least one letter\"\n a = math.ceil(len(st) ** 0.5)\n b = []\n for i in range(a):\n b.append(list(a * \".\"))\n for j in range(a):\n for k in range(a):\n if j * a + k == len(st):\n return b\n else:\n b[j][k] = st[j * a + k]\n return b"]
{"fn_name": "matrixfy", "inputs": [[""], ["G"], ["Beyonce"], ["Franklin"], ["Bill"], ["Frank"]], "outputs": [["name must be at least one letter"], [[["G"]]], [[["B", "e", "y"], ["o", "n", "c"], ["e", ".", "."]]], [[["F", "r", "a"], ["n", "k", "l"], ["i", "n", "."]]], [[["B", "i"], ["l", "l"]]], [[["F", "r", "a"], ["n", "k", "."], [".", ".", "."]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,515
def matrixfy(st):
1fed6776106828424c750db5b53fbfb8
UNKNOWN
Learning to code around your full time job is taking over your life. You realise that in order to make significant steps quickly, it would help to go to a coding bootcamp in London. Problem is, many of them cost a fortune, and those that don't still involve a significant amount of time off work - who will pay your mortgage?! To offset this risk, you decide that rather than leaving work totally, you will request a sabbatical so that you can go back to work post bootcamp and be paid while you look for your next role. You need to approach your boss. Her decision will be based on three parameters: val=your value to the organisation happiness=her happiness level at the time of asking and finally The numbers of letters from 'sabbatical' that are present in string `s`. Note that if `s` contains three instances of the letter 'l', that still scores three points, even though there is only one in the word sabbatical. If the sum of the three parameters (as described above) is > 22, return 'Sabbatical! Boom!', else return 'Back to your desk, boy.'. ~~~if:c NOTE: For the C translation you should return a string literal. ~~~
["def sabb(stg, value, happiness):\n sabbatical = (value + happiness + sum(1 for c in stg if c in \"sabbatical\")) > 22\n return \"Sabbatical! Boom!\" if sabbatical else \"Back to your desk, boy.\"", "def sabb(s, value, happiness):\n score = sum(c in \"sabticl\" for c in s.lower()) + value + happiness\n return \"Sabbatical! Boom!\" if score > 22 else \"Back to your desk, boy.\"", "SABBATICAL = set('sabbatical')\n\ndef sabb(s, value, happiness):\n if value + happiness + sum(c in SABBATICAL for c in s) > 22:\n return 'Sabbatical! Boom!'\n else:\n return 'Back to your desk, boy.'", "def sabb(s, value, happiness):\n return \"Sabbatical! Boom!\" if sum([sum(1 for i in s if i in \"sabbatical\"), value, happiness]) > 22 else \"Back to your desk, boy.\"\n\n", "from collections import Counter\n\ndef sabb(s, value, happiness):\n cnt = Counter(s.lower())\n return (\"Back to your desk, boy.\", \"Sabbatical! Boom!\")[sum(cnt[a] for a in set('sabbatical')) + value + happiness > 22]", "from collections import Counter\n\ndef sabb(s, value, happiness):\n C = Counter(s.lower())\n score = value + happiness + sum(C[c] for c in set(\"sabbatical\"))\n return \"Sabbatical! Boom!\" if score > 22 else \"Back to your desk, boy.\"", "def sabb(s, value, happiness):\n nb = len(list(c for c in s.lower() if c in 'sabticl'))\n return ['Back to your desk, boy.', 'Sabbatical! Boom!'][nb + value + happiness > 22]", "def sabb(s, value, happiness):\n sab = []\n for x in s:\n if x == 's' or x == 'a' or x == 'b' or x == 't' or x == 'i' or x == 'c' or x == 'l':\n sab.append(1)\n else: \n sab.append(0)\n z = sum(sab)\n y = z + value + happiness\n if y <= 22:\n return 'Back to your desk, boy.'\n else:\n return 'Sabbatical! Boom!'", "def sabb(s, v, h):\n ss = sum(1 for i in s if i in 'sabbatical')\n return (\"Back to your desk, boy.\",\"Sabbatical! Boom!\")[sum([ss,v,h])>22]", "def sabb(s, value, happiness):\n return 'Sabbatical! Boom!' if sum(1 for x in s if x.lower() in 'sabbatical') + value + happiness > 22 else 'Back to your desk, boy.'"]
{"fn_name": "sabb", "inputs": [["Can I have a sabbatical?", 5, 5], ["Why are you shouting?", 7, 2], ["What do you mean I cant learn to code??", 8, 9], ["Please calm down", 9, 1], ["I can?! Nice. FaC..Im coming :D", 9, 9]], "outputs": [["Sabbatical! Boom!"], ["Back to your desk, boy."], ["Sabbatical! Boom!"], ["Back to your desk, boy."], ["Sabbatical! Boom!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,170
def sabb(s, value, happiness):
0ef4512efe03ce5dcaa3f7e7295b5439
UNKNOWN
Write a function that takes an integer and returns an array `[A, B, C]`, where `A` is the number of multiples of 3 (but not 5) below the given integer, `B` is the number of multiples of 5 (but not 3) below the given integer and `C` is the number of multiples of 3 and 5 below the given integer. For example, `solution(20)` should return `[5, 2, 1]` ~~~if:r ```r # in R, returns a numeric vector solution(20) [1] 5 2 1 class(solution(20)) [1] "numeric" ``` ~~~
["def solution(number):\n A = (number - 1) // 3\n B = (number - 1) // 5\n C = (number - 1) // 15 \n return [A - C, B - C, C]", "def solution(number):\n n = number - 1\n a, b, c = n // 3, n // 5, n // 15\n return [a - c, b - c, c]", "def solution(n):\n n -= 1\n return [n//3-n//15, n//5-n//15, n//15]", "def solution(number):\n number = number - 1\n fizzbuzz = number // 15\n fizz = number // 3 - fizzbuzz\n buzz = number // 5 - fizzbuzz\n return [fizz, buzz, fizzbuzz]", "def solution(number):\n [threes, fives, fifteens] = [int((number-1)/div) for div in [3, 5, 15]]\n return [threes-fifteens, fives-fifteens, fifteens]\n", "def solution(number):\n returnArray = [0, 0, 0]\n for i in range(1, number):\n if i % 15 == 0:\n returnArray[2] += 1\n elif i % 5 == 0 and (not (i % 3 == 0)):\n returnArray[1] += 1\n elif i % 3 == 0:\n returnArray[0] += 1\n return returnArray", "def solution(number):\n number = number - 1\n c = int(number/15)\n b = int(number/5) - c\n a = int(number/3) - c\n return [a, b, c]", "def solution(number):\n count = 0\n lst = []\n for i in range(1,number):\n if i % 3 == 0 and not i % 5 == 0:\n count += 1\n lst.append(count)\n count = 0\n for i in range(1,number):\n if not i % 3 == 0 and i % 5 == 0:\n count += 1\n lst.append(count)\n count = 0\n for i in range(1,number):\n if i % 3 == 0 and i % 5 == 0:\n count += 1\n lst.append(count) \n return lst", "def solution(n): c = lambda x: (n - 1) // x if x == 15 else (n - 1) // x - c(15); return [c(3), c(5), c(15)]"]
{"fn_name": "solution", "inputs": [[20], [2020], [4], [2], [30], [300], [14], [141], [1415], [91415]], "outputs": [[[5, 2, 1]], [[539, 269, 134]], [[1, 0, 0]], [[0, 0, 0]], [[8, 4, 1]], [[80, 40, 19]], [[4, 2, 0]], [[37, 19, 9]], [[377, 188, 94]], [[24377, 12188, 6094]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,709
def solution(number):
fc5ffd6eeb52206e988602a3c0f2806b
UNKNOWN
A category page displays a set number of products per page, with pagination at the bottom allowing the user to move from page to page. Given that you know the page you are on, how many products are in the category in total, and how many products are on any given page, how would you output a simple string showing which products you are viewing.. examples In a category of 30 products with 10 products per page, on page 1 you would see 'Showing 1 to 10 of 30 Products.' In a category of 26 products with 10 products per page, on page 3 you would see 'Showing 21 to 26 of 26 Products.' In a category of 8 products with 10 products per page, on page 1 you would see 'Showing 1 to 8 of 8 Products.'
["def pagination_text(page_number, page_size, total_products):\n first = page_size * (page_number - 1) + 1\n last = min(total_products, first + page_size - 1)\n return \"Showing %d to %d of %d Products.\" % (first, last, total_products)", "def pagination_text(page_number, page_size, total_products):\n lower = (page_number - 1) * page_size + 1\n upper = min(total_products, page_number * page_size)\n return \"Showing {} to {} of {} Products.\".format(lower, upper, total_products)\n \n", "def pagination_text(p, sz, total):\n return 'Showing ' + str((p - 1) * sz + 1) + ' to ' + str(total if p * sz > total else p * sz) + ' of ' + str(total) + ' Products.'", "def pagination_text(page_number, page_size, total_products):\n return \"Showing %d to %d of %d Products.\" % (\n page_size * (page_number - 1) + 1,\n min(total_products, page_size * page_number),\n total_products)\n", "def pagination_text(page_number, page_size, total_products):\n start = (page_number - 1) * page_size + 1\n stop = min(start + page_size - 1, total_products)\n return 'Showing {} to {} of {} Products.'.format(start, stop, total_products)", "def pagination_text(page_number, page_size, total_products):\n start = (page_number - 1) * page_size + 1\n end = page_number * page_size\n if end > total_products:\n end = total_products\n return 'Showing {} to {} of {} Products.'.format(start, end, total_products)", "def pagination_text(page_number, page_size, total_products):\n return \"Showing {} to {} of {} Products.\".format((page_number - 1) * page_size + 1,\\\n min(page_number * page_size, total_products), total_products)", "def pagination_text(page_number, page_size, total_products):\n fr = page_number * page_size - page_size + 1\n to = min(fr + page_size - 1, total_products)\n return \"Showing %d to %d of %d Products.\" % (fr, to, total_products)", "def pagination_text(page_number, page_size, total_products):\n s = min((page_number - 1) * page_size + 1, total_products)\n e = min(s + page_size - 1, total_products)\n return 'Showing {} to {} of {} Products.'.format(s, e, total_products)", "def pagination_text(page_number, page_size, total_products):\n start = (page_number-1)*page_size+1\n end = total_products if page_number*page_size > total_products else page_number*page_size\n li = ['Showing',str(start),'to',str(end),'of',str(total_products),'Products.']\n return ' '.join(li)"]
{"fn_name": "pagination_text", "inputs": [[1, 10, 30], [3, 10, 26], [1, 10, 8], [2, 30, 350], [1, 23, 30], [2, 23, 30], [43, 15, 3456]], "outputs": [["Showing 1 to 10 of 30 Products."], ["Showing 21 to 26 of 26 Products."], ["Showing 1 to 8 of 8 Products."], ["Showing 31 to 60 of 350 Products."], ["Showing 1 to 23 of 30 Products."], ["Showing 24 to 30 of 30 Products."], ["Showing 631 to 645 of 3456 Products."]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,479
def pagination_text(page_number, page_size, total_products):
8058f05b997e64bef04705c0af0bd9ed
UNKNOWN
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer `N`. Write a method that takes the array as an argument and returns this "outlier" `N`. ## Examples ```python [2, 4, 0, 100, 4, 11, 2602, 36] Should return: 11 (the only odd number) [160, 3, 1719, 19, 11, 13, -21] Should return: 160 (the only even number) ```
["def find_outlier(int):\n odds = [x for x in int if x%2!=0]\n evens= [x for x in int if x%2==0]\n return odds[0] if len(odds)<len(evens) else evens[0]\n", "def find_outlier(integers):\n even, odd = 0, 0\n for i in integers:\n if i % 2:\n even += 1\n last_even = i\n else:\n odd += 1\n last_odd = i\n return last_even if even == 1 else last_odd\n", "def find_outlier(integers):\n parity = [n % 2 for n in integers]\n return integers[parity.index(1)] if sum(parity) == 1 else integers[parity.index(0)]", "def find_outlier(integers):\n parity = [n % 2 for n in integers]\n return integers[parity.index(sum(parity) == 1)]\n", "def find_outlier(integers):\n listEven = []\n listOdd = []\n for n in integers:\n if n % 2 == 0:\n listEven.append(n)\n else:\n listOdd.append(n)\n \n if len(listEven) == 1:\n return listEven[0]\n else:\n return listOdd[0]", "def find_outlier(nums):\n\n base_parity = sum( x%2 for x in nums[:3] ) // 2\n \n for i in range(len(nums)):\n if nums[i] % 2 != base_parity:\n return nums[i]", "def find_outlier(integers):\n assert len(integers) >= 3\n\n bit = ((integers[0] & 1) +\n (integers[1] & 1) +\n (integers[2] & 1)) >> 1\n\n for n in integers:\n if (n & 1) ^ bit:\n return n\n\n assert False\n", "def find_outlier(integers):\n assert len(integers) >= 3\n\n bit = integers[0] & 1\n\n if integers[1] & 1 != bit:\n return integers[integers[2] & 1 == bit]\n\n for n in integers:\n if n & 1 != bit:\n return n\n\n assert False\n", "def find_outlier(integers):\n evens = [];\n odds = [];\n for each in integers:\n if each%2==0:\n evens.append(each)\n else:\n odds.append(each);\n if len(evens)>1 and len(odds)==1:\n return odds[0];\n elif len(odds)>1 and len(evens)==1:\n return evens[0];", "def find_outlier(integers):\n determinant = [x for x in integers[:3] if x % 2 == 0]\n if len(determinant) > 1:\n # most are even, find the first odd\n mod = 1\n else:\n # most are odd, find the first even\n mod = 0\n for i in integers:\n if i % 2 == mod:\n return i", "def find_outlier(num):\n odd = 0 if sum(n % 2 for n in num[:3]) > 1 else 1\n return next(n for n in num if n % 2 == odd)\n"]
{"fn_name": "find_outlier", "inputs": [[[0, 1, 2]], [[1, 2, 3]]], "outputs": [[1], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,476
def find_outlier(integers):
f9505409b7425acdde58aa609f4d675e
UNKNOWN
*Are you a file extension master? Let's find out by checking if Bill's files are images or audio files. Please use regex if available natively for your language.* You will create 2 string methods: - **isAudio/is_audio**, matching 1 or + uppercase/lowercase letter(s) (combination possible), with the extension .mp3, .flac, .alac, or .aac. - **isImage/is_image**, matching 1 or + uppercase/lowercase letter(s) (combination possible), with the extension .jpg, .jpeg, .png, .bmp, or .gif. *Note that this is not a generic image/audio files checker. It's meant to be a test for Bill's files only. Bill doesn't like punctuation. He doesn't like numbers, neither. Thus, his filenames are letter-only* **Rules** 1. It should return true or false, simply. 2. File extensions should consist of lowercase letters and numbers only. 3. File names should consist of letters only (uppercase, lowercase, or both) Good luck!
["def is_audio(filename):\n name, ext = filename.split('.')\n return name.isalpha() and ext in {'mp3', 'flac', 'alac', 'aac'}\n\n\ndef is_img(filename):\n name, ext = filename.split('.')\n return name.isalpha() and ext in {'jpg', 'jpeg', 'png', 'bmp', 'gif'}", "import re\ndef is_audio(file_name):\n return bool(re.match(r'^[A-Za-z]+\\.(mp3|flac|alac|aac)$', file_name))\n\ndef is_img(file_name):\n return bool(re.search(r'^[A-Za-z]+\\.(jpg|jpeg|png|bmp|gif)$', file_name))", "import re\n\n\nhas_ext = lambda p: (lambda f: bool(re.match(fr\"[a-zA-Z]+\\.({p})$\", f)))\n\nis_audio = has_ext(\"mp3|([fa]l|a)ac\")\nis_img = has_ext(\"jpe?g|png|bmp|gif\")\n", "import re\n\n\ndef is_audio(filename):\n return bool(re.match(r\"[a-zA-Z]+\\.(mp3|([fa]l|a)ac)$\", filename))\n\n\ndef is_img(filename):\n return bool(re.match(r\"[a-zA-Z]+\\.(jpe?g|png|bmp|gif)$\", filename))", "import re\n\ndef is_audio(file_name):\n return bool(re.search(r'^[A-Za-z]+\\.(mp3|flac|alac|aac)$', file_name))\n\ndef is_img(file_name):\n return bool(re.search(r'^[A-Za-z]+\\.(jpg|jpeg|png|bmp|gif)$', file_name))", "import re\ndef is_audio(file_name):\n return bool(re.match(r'[a-zA-Z]+(\\.(mp3|flac|alac|aac))',file_name))\n\ndef is_img(file_name): \n return bool(re.match(r'[a-zA-Z]+(\\.(jpg|jpeg|png|bmp|gif))',file_name))", "import re\n\n\ndef is_audio(file_name):\n return bool(re.match('[A-Za-z]+\\.(?:mp3|flac|alac|aac)$', file_name))\n\n\ndef is_img(file_name):\n return bool(re.match('[A-Za-z]+\\.(?:jpg|jpeg|png|bmp|gif)$', file_name))", "c = lambda x,f: bool(__import__('re').match(r'([a-zA-Z]+\\.({}))'.format(\"|\".join(x)),f))\nis_audio=lambda f:c(['mp3','flac','alac','aac'],f)\nis_img=lambda f:c(['jpg','jpeg','png','bmp','gif'],f)", "match = lambda file_name, exts: [name.isalpha() and ext in exts for name, ext in [file_name.rsplit('.', 1)]][0]\nis_audio = lambda file_name: match(file_name, ['mp3', 'flac', 'alac', 'aac'])\nis_img = lambda file_name: match(file_name, ['jpg', 'jpeg', 'png', 'bmp', 'gif'])", "import re\n\ndef make_matcher(exts):\n def match(s):\n name, ext = s.split('.')\n return name.isalpha() and ext in exts\n return match\n\nis_audio = make_matcher('mp3 flac alac aac'.split())\n\nis_img = make_matcher('jpg jpeg gif png bmp'.split())"]
{"fn_name": "is_audio", "inputs": [["Nothing Else Matters.mp3"], ["NothingElseMatters.mp3"], ["DaftPunk.FLAC"], ["DaftPunk.flac"], ["AmonTobin.aac"], [" Amon Tobin.alac"], ["tobin.alac"]], "outputs": [[false], [true], [false], [true], [true], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,307
def is_audio(file_name):
81d21049f3bcf69dc357de0fe2d32cd3
UNKNOWN
Given a random string consisting of numbers, letters, symbols, you need to sum up the numbers in the string. Note: - Consecutive integers should be treated as a single number. eg, `2015` should be treated as a single number `2015`, NOT four numbers - All the numbers should be treaded as positive integer. eg, `11-14` should be treated as two numbers `11` and `14`. Same as `3.14`, should be treated as two numbers `3` and `14` - If no number was given in the string, it should return `0` Example: ``` str = "In 2015, I want to know how much does iPhone 6+ cost?" ``` The numbers are `2015`, `6` Sum is `2021`.
["import re\ndef sum_from_string(string):\n d = re.findall(\"\\d+\",string)\n return sum(int(i) for i in d)", "import re\ndef sum_from_string(s):\n return sum(map(int, re.findall(r'\\d+', s)))", "from re import findall\n\n\ndef sum_from_string(string):\n return sum(int(a) for a in findall(r'\\d+', string))\n", "import re\n\ndef sum_from_string(str_):\n return sum(map(int, re.findall(r'\\d+', str_)))", "def sum_from_string(s):\n return sum(map(int, \"\".join(c if c.isdigit() else \" \" for c in s).split()))", "sum_from_string=lambda s:sum([int(k) for k in __import__('re').findall(r'\\d+',s)])", "def sum_from_string(string):\n str_nr, all_nr, have_nr = '', [], False\n for item in string + '_':\n if '0' <= item <= '9':\n str_nr += item\n have_nr = True\n else:\n if have_nr:\n all_nr.append(int(str_nr))\n have_nr , str_nr = False, ''\n return sum(all_nr)", "search = __import__(\"re\").compile(r\"\\d+\").findall\n\ndef sum_from_string(string):\n return sum(map(int, search(string)))", "from itertools import groupby\n\ndef sum_from_string(string):\n return sum(int(''.join(gp)) for b, gp in groupby(string, key = str.isdigit) if b)", "import re\n\ndef sum_from_string(string):\n result = 0\n res = re.findall(r'\\d+', string)\n for x in res:\n result += int(x)\n return result\n"]
{"fn_name": "sum_from_string", "inputs": [["In 2015, I want to know how much does iPhone 6+ cost?"], ["1+1=2"], ["e=mc^2"], ["aHR0cDovL3d3dy5jb2Rld2Fycy5jb20va2F0YS9uZXcvamF2YXNjcmlwdA=="], ["a30561ff4fb19170aa598b1431b52edad1fcc3e0"], ["x1KT CmZ__\rYouOY8Uqu-ETtz"], ["x1KT-8&*@\"CmZ__\rYouO __Y8Uq\\u-ETtz"], [""], ["Hello World"]], "outputs": [[2021], [4], [2], [53], [51820], [9], [17], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,416
def sum_from_string(string):
ec02b41c00bbda002c9dda1186443e28
UNKNOWN
The characters of Chima need your help. Their weapons got mixed up! They need you to write a program that accepts the name of a character in Chima then tells which weapon he/she owns. For example: for the character `"Laval"` your program should return the solution `"Laval-Shado Valious"` You must complete the following character-weapon pairs: * Laval-Shado Valious, * Cragger-Vengdualize, * Lagravis-Blazeprowlor, * Crominus-Grandorius, * Tormak-Tygafyre, * LiElla-Roarburn. Return `"Not a character"` for invalid inputs.
["def identify_weapon(character):\n tbl = {\n \"Laval\" : \"Laval-Shado Valious\",\n \"Cragger\" : \"Cragger-Vengdualize\",\n \"Lagravis\" : \"Lagravis-Blazeprowlor\",\n \"Crominus\" : \"Crominus-Grandorius\",\n \"Tormak\" : \"Tormak-Tygafyre\",\n \"LiElla\" : \"LiElla-Roarburn\"\n }\n \n return tbl.get(character, \"Not a character\")", "def identify_weapon(character):\n #insert your code here...FOR CHIMA!\n try:\n return character + \"-\" + {\n \"Laval\":\"Shado Valious\", \"Cragger\":\"Vengdualize\",\n \"Lagravis\":\"Blazeprowlor\",\"Crominus\":\"Grandorius\",\n \"Tormak\":\"Tygafyre\", \"LiElla\":\"Roarburn\"\n }[character]\n except:\n return \"Not a character\"", "weapon_map = {\n'Laval':'Laval-Shado Valious',\n'Cragger': 'Cragger-Vengdualize',\n'Lagravis':'Lagravis-Blazeprowlor',\n'Crominus': 'Crominus-Grandorius',\n'Tormak': 'Tormak-Tygafyre',\n'LiElla': 'LiElla-Roarburn',\n}\n\ndef identify_weapon(character):\n return weapon_map.get(character, 'Not a character')", "def identify_weapon(character):\n weps = {'Laval':'Shado Valious',\n 'Cragger':'Vengdualize', \n 'Lagravis':'Blazeprowlor', \n 'Crominus':'Grandorius', \n 'Tormak':'Tygafyre', \n 'LiElla':'Roarburn'}\n try:\n return \"{}-{}\".format(character, weps[character])\n except:\n return \"Not a character\"", "def identify_weapon(character):\n data = {\n 'Laval': 'Shado Valious',\n 'Cragger': \"Vengdualize\",\n \"Lagravis\": \"Blazeprowlor\",\n \"Crominus\": \"Grandorius\",\n \"Tormak\": \"Tygafyre\",\n \"LiElla\": \"Roarburn\"\n }\n try:\n return \"%s-%s\" % (character, data[character])\n except KeyError:\n return \"Not a character\"", "def identify_weapon(character):\n weapons = { 'Laval' : 'Shado Valious', 'Cragger' : 'Vengdualize', 'Lagravis' : 'Blazeprowlor', 'Crominus' : 'Grandorius', 'Tormak' : 'Tygafyre', 'LiElla' : 'Roarburn' }\n return '%s-%s' % (character, weapons[character]) if character in weapons else 'Not a character'\n", "def identify_weapon(character):\n dict = {\"Laval\" : \"Shado Valious\",\n \"Cragger\" : \"Vengdualize\",\n \"Lagravis\" : \"Blazeprowlor\",\n \"Cragger\" : \"Vengdualize\",\n \"Lagravis\" : \"Blazeprowlor\",\n \"Crominus\" : \"Grandorius\",\n \"Tormak\" : \"Tygafyre\",\n \"LiElla\" : \"Roarburn\"}\n if character not in dict.keys():\n return \"Not a character\"\n return character + \"-\" + dict[character]", "weapons = [\n \"Laval-Shado Valious\", \"Cragger-Vengdualize\", \"Lagravis-Blazeprowlor\",\n \"Crominus-Grandorius\", \"Tormak-Tygafyre\", \"LiElla-Roarburn\"\n]\n\ndef identify_weapon(character):\n return next((weapon for weapon in weapons if weapon.startswith(character)), \"Not a character\")", "def identify_weapon(character):\n wep = {\n \"Laval\":\"Laval-Shado Valious\",\n \"Cragger\":\"Cragger-Vengdualize\",\n \"Lagravis\":\"Lagravis-Blazeprowlor\",\n \"Crominus\":\"Crominus-Grandorius\",\n \"Tormak\":\"Tormak-Tygafyre\",\n \"LiElla\":\"LiElla-Roarburn\"\n }\n \n return wep.get(character, \"Not a character\")", "def identify_weapon(character):\n d = {'Laval' : 'Shado Valious', \n 'Cragger' : 'Vengdualize', \n 'Lagravis' : 'Blazeprowlor', \n 'Crominus' : 'Grandorius', \n 'Tormak' : 'Tygafyre', \n 'LiElla' : 'Roarburn'}\n \n return f'{character}-{d[character]}' if character in d else 'Not a character'"]
{"fn_name": "identify_weapon", "inputs": [["Laval"], ["Crominus"], ["Lagravis"], ["Cragger"], ["Tormak"], ["LiElla"], ["G'loona"], ["Stinkin gorillas"], ["qwertyuiopasdfghjklzxcvbnm"]], "outputs": [["Laval-Shado Valious"], ["Crominus-Grandorius"], ["Lagravis-Blazeprowlor"], ["Cragger-Vengdualize"], ["Tormak-Tygafyre"], ["LiElla-Roarburn"], ["Not a character"], ["Not a character"], ["Not a character"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,731
def identify_weapon(character):
82057897b194625c8d858ecedd7cc137
UNKNOWN
## Emotional Sort ( ︶︿︶) You'll have a function called "**sortEmotions**" that will return an array of **emotions** sorted. It has two parameters, the first parameter called "**arr**" will expect an array of **emotions** where an **emotion** will be one of the following: - **:D** -> Super Happy - **:)** -> Happy - **:|** -> Normal - **:(** -> Sad - **T\_T** -> Super Sad Example of the array:``[ 'T_T', ':D', ':|', ':)', ':(' ]`` And the second parameter is called "**order**", if this parameter is **true** then the order of the emotions will be descending (from **Super Happy** to **Super Sad**) if it's **false** then it will be ascending (from **Super Sad** to **Super Happy**) Example if **order** is true with the above array: ``[ ':D', ':)', ':|', ':(', 'T_T' ]`` - Super Happy -> Happy -> Normal -> Sad -> Super Sad If **order** is false: ``[ 'T_T', ':(', ':|', ':)', ':D' ]`` - Super Sad -> Sad -> Normal -> Happy -> Super Happy Example: ``` arr = [':D', ':|', ':)', ':(', ':D'] sortEmotions(arr, true) // [ ':D', ':D', ':)', ':|', ':(' ] sortEmotions(arr, false) // [ ':(', ':|', ':)', ':D', ':D' ] ``` **More in test cases!** Notes: - The array could be empty, in that case return the same empty array ¯\\\_( ツ )\_/¯ - All **emotions** will be valid ## Enjoy! (づ。◕‿‿◕。)づ
["def sort_emotions(arr, order):\n return sorted(arr, key=[':D',':)',':|',':(','T_T'].index, reverse=not order)", "def get_face(face):\n faces = { ':D':0, ':)':1, ':|':2, ':(':3, 'T_T':4 }\n return faces[face]\n\ndef sort_emotions(arr, order):\n return sorted(arr, key=get_face, reverse= not order)\n", "def sort_emotions(arr, reverse, ordered_emotions={smiley: idx for idx, smiley in enumerate('T_T :( :| :) :D'.split())}):\n return sorted(arr, reverse=reverse, key=ordered_emotions.get)", "sort_emotions=lambda a,b:sorted(a,key=':(:|:):D'.find,reverse=b)", "def sort_emotions(arr, order):\n return sorted(arr, key=lambda x: ['T_T', ':(', ':|', ':)', ':D'].index(x), reverse=order)", "val = {':D':4, ':)':3, ':|':2, ':(':1, 'T_T':0}.__getitem__\n\ndef sort_emotions(arr, order):\n return sorted(arr, reverse=order, key=val)", "emotions = {\"T_T\": 1, \":(\": 2, \":|\": 3, \":)\": 4, \":D\": 5}\n\ndef sort_emotions(lst, desc):\n return sorted(lst, key=emotions.get, reverse=desc)\n", "rank = {x: i for i, x in enumerate([':D', ':)', ':|', ':(', 'T_T'])}\n\ndef sort_emotions(arr, order):\n return sorted(arr, key=rank.get, reverse=not order)", "def sort_emotions(arr, order):\n order_dict = {\n \":D\" : 1, \n \":)\" : 2, \n \":|\" : 3, \n \":(\" : 4, \n \"T_T\" : 5\n }\n \n return sorted(arr, key=lambda x: order_dict[x], reverse=not order)", "ORDER = {v:i for i,v in enumerate([':D', ':)', ':|', ':(', 'T_T'])}\n\ndef sort_emotions(arr, order):\n return sorted(arr, key=ORDER.__getitem__, reverse=not order)"]
{"fn_name": "sort_emotions", "inputs": [[[":D", "T_T", ":D", ":("], true], [["T_T", ":D", ":(", ":("], true], [[":)", "T_T", ":)", ":D", ":D"], true], [[":D", "T_T", ":D", ":("], false], [["T_T", ":D", ":(", ":("], false], [[":)", "T_T", ":)", ":D", ":D"], false], [[], false], [[], true]], "outputs": [[[":D", ":D", ":(", "T_T"]], [[":D", ":(", ":(", "T_T"]], [[":D", ":D", ":)", ":)", "T_T"]], [["T_T", ":(", ":D", ":D"]], [["T_T", ":(", ":(", ":D"]], [["T_T", ":)", ":)", ":D", ":D"]], [[]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,647
def sort_emotions(arr, order):
5ad14c02bb5720f1fa018cac7a981794
UNKNOWN
Python dictionaries are inherently unsorted. So what do you do if you need to sort the contents of a dictionary? Create a function that returns a sorted list of `(key, value)` tuples (Javascript: arrays of 2 items). The list must be sorted by the `value` and be sorted **largest to smallest**. ## Examples ```python sort_dict({3:1, 2:2, 1:3}) == [(1,3), (2,2), (3,1)] sort_dict({1:2, 2:4, 3:6}) == [(3,6), (2,4), (1,2)] ```
["def sort_dict(d):\n return sorted(d.items(), key=lambda x: x[1], reverse=True)", "from operator import itemgetter\n\ndef sort_dict(d):\n 'return a sorted list of tuples from the dictionary'\n return sorted(d.items(), key=itemgetter(1), reverse=True)", "def sort_dict(d):\n 'return a sorted list of tuples from the dictionary'\n return sorted(d.items(), key=lambda x: -x[1])", "def sort_dict(d):\n return sorted(d.items(), key=(lambda x: x[1]))[::-1]", "def sort_dict(d):\n 'return a sorted list of tuples from the dictionary'\n #items = list(d.items())\n return sorted(list(d.items()), key=lambda i: -i[1])\n", "def sort_dict(d):\n import operator\n return sorted(d.items(), key=operator.itemgetter(1), reverse=True)", "def sort_dict(d):\n a = []\n for x in d:\n a.append((x, d[x]))\n\n for i in range(0, len(a)):\n for j in range(i + 1, len(a)):\n if a[i][1] < a[j][1]:\n temp = a[j]\n a[j] = a[i]\n a[i] = temp\n\n return a", "def sort_dict(d):\n return sorted(d.items(), key=lambda pair: pair[1], reverse=True)"]
{"fn_name": "sort_dict", "inputs": [[{"1": 3, "2": 2, "3": 1}], [{"1": 2, "2": 4, "3": 6}], [{"1": 5, "3": 10, "2": 2, "6": 3, "8": 8}], [{"a": 6, "b": 2, "c": 4}]], "outputs": [[[[1, 3], [2, 2], [3, 1]]], [[[3, 6], [2, 4], [1, 2]]], [[[3, 10], [8, 8], [1, 5], [6, 3], [2, 2]]], [[["a", 6], ["c", 4], ["b", 2]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,115
def sort_dict(d):
9379dfcaf88cf6c22de54e515ac2c19c
UNKNOWN
You are making your very own boardgame. The game is played by two opposing players, featuring a 6 x 6 tile system, with the players taking turns to move their pieces (similar to chess). The design is finished, now it's time to actually write and implement the features. Being the good programmer you are, you carefully plan the procedure and break the program down into smaller managable sections. You decide to start coding the logic for resolving "fights" when two pieces engage in combat on a tile. Your boardgame features four unique pieces: Swordsman, Cavalry, Archer and Pikeman Each piece has unique movement and has advantages and weaknesses in combat against one of the other pieces. Task You must write a function ```fightResolve``` that takes the attacking and defending piece as input parameters, and returns the winning piece. It may be the case that both the attacking and defending piece belong to the same player, after which you must return an error value to indicate an illegal move. In C++ and C, the pieces will be represented as ```chars```. Values will be case-sensitive to display ownership. Let the following char values represent each piece from their respective player. Player 1: ```p```= Pikeman, ```k```= Cavalry, ```a```= Archer, ```s```= Swordsman Player 2: ```P```= Pikeman, ```K```= Cavalry, ```A```= Archer, ```S```= Swordsman The outcome of the fight between two pieces depends on which piece attacks, the type of the attacking piece and the type of the defending piece. Archers always win against swordsmens, swordsmen always win against pikemen, pikemen always win against cavalry and cavalry always win against archers. If a matchup occurs that was not previously mentioned (for example Archers vs Pikemen) the attacker will always win. This table represents the winner of each possible engagement between an attacker and a defender. (Attacker→) (Defender↓) Archer Pikeman Swordsman Knight Knight Defender Attacker Attacker Attacker Swordsman Attacker Defender Attacker Attacker Archer Attacker Attacker Defender Attacker Pikeman Attacker Attacker Attacker Defender If two pieces from the same player engage in combat, i.e P vs S or k vs a, the function must return -1 to signify and illegal move. Otherwise assume that no other illegal values will be passed. Examples Function prototype: fightResolve(defender, attacker) 1. fightResolve('a', 'P') outputs 'P'. No interaction defined between Pikemen and Archer. Pikemen is the winner here because it is the attacking piece. 2. fightResolve('k', 'A') outputs 'k'. Knights always defeat archers, even if Archer is the attacking piece here. 3. fightResolve('S', 'A') outputs -1. Friendly units don't fight. Return -1 to indicate error.
["def fight_resolve(d, a):\n return -1 if d.islower() == a.islower() else d if d.lower() + a.lower() in \"ka sp as pk\" else a", "def fight_resolve(d, a):\n return -1 if d.islower() == a.islower() else d if f\"{d}{a}\".lower() in \"aspka\" else a", "def fight_resolve(defender, attacker):\n res = attacker\n if defender.islower() and attacker.islower() or defender.isupper() and attacker.isupper():\n return -1\n elif attacker.lower() == 'a':\n if defender.lower() == 'k':\n res = defender\n elif attacker.lower() == 'p':\n if defender.lower() == 's':\n res = defender\n elif attacker.lower() == 's':\n if defender.lower() == 'a':\n res = defender\n elif attacker.lower() == 'k':\n if defender.lower() == 'p':\n res = defender\n return res\n", "def fight_resolve(defender, attacker): \n if (attacker.isupper() and defender.isupper()) or (attacker.islower() and defender.islower()):\n return -1\n att = {\"A\":1, \"P\":2, \"S\":3, \"K\":4}\n dff = {\"K\":1, \"S\":2, \"A\":3, \"P\":4}\n \n if att[attacker.upper()] == dff[defender.upper()]:\n return defender\n else:\n return attacker\n #pass\n", "p1 = ['p', 'k', 'a', 's']\np2 = ['P', 'K', 'A', 'S']\nar = ['a', 'A']\nsm = ['s', 'S']\npm = ['p', 'P']\ncy = ['k', 'K']\n\ndef fight_resolve(d, a): \n if (d in p1 and a in p1) or (d in p2 and a in p2):\n return -1\n if a in ar:\n return d if d in cy else a\n elif a in pm:\n return d if d in sm else a\n elif a in sm:\n return d if d in ar else a\n elif a in cy:\n return d if d in pm else a\n", "def fight_resolve(defender, attacker): \n\n if defender.isupper() == attacker.isupper():\n return -1\n\n battle = dict(zip('ksapKSAP', 'APSKapsk'))\n return defender if battle[defender] == attacker else attacker", "def fight_resolve(defender, attacker): \n if defender.islower() == attacker.islower(): return -1\n return defender if f\"{defender}{attacker}\".lower() in \"aspka\" else attacker", "fight_resolve=lambda d,a:d.islower()^a.islower()and(a,d)[(d+a).lower()in'aspka']or-1", "def fight_resolve(d, a): \n if d.islower() == a.islower(): return -1\n map = {\"a\":\"s\", \"k\":\"a\", \"p\":\"k\", \"s\":\"p\"}\n return d if map[d.lower()] == a.lower() else a", "def fight_resolve(defender, attacker): \n fight = (defender + attacker).lower()\n d_low = defender == defender.lower()\n a_low = attacker == attacker.lower()\n \n if (d_low and a_low) or (not d_low and not a_low):\n return -1\n \n if (\"a\" in defender.lower()) and (\"s\" in attacker.lower()):\n winner = defender\n elif \"s\" in defender.lower() and \"p\" in attacker.lower():\n winner = defender\n elif \"p\" in defender.lower() and \"k\" in attacker.lower():\n winner = defender\n elif \"k\" in defender.lower() and \"a\" in attacker.lower():\n winner = defender\n else:\n winner = attacker\n \n return winner"]
{"fn_name": "fight_resolve", "inputs": [["K", "A"], ["S", "A"], ["k", "s"], ["a", "a"], ["k", "A"], ["K", "a"]], "outputs": [[-1], [-1], [-1], [-1], ["k"], ["K"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,087
def fight_resolve(defender, attacker):
ef4c68bbb529cb97cf5b2cedcfd59710
UNKNOWN
A pair of numbers has a unique LCM but a single number can be the LCM of more than one possible pairs. For example `12` is the LCM of `(1, 12), (2, 12), (3,4)` etc. For a given positive integer N, the number of different integer pairs with LCM is equal to N can be called the LCM cardinality of that number N. In this kata your job is to find out the LCM cardinality of a number.
["from itertools import combinations\nfrom math import gcd\n\n\ndef lcm_cardinality(n):\n return 1 + sum(1 for a, b in combinations(divisors(n), 2) if lcm(a, b) == n)\n \ndef divisors(n):\n d = {1, n}\n for k in range(2, int(n**0.5) + 1):\n if n % k == 0:\n d.add(k)\n d.add(n // k)\n return sorted(d)\n\ndef lcm(a, b):\n return a * b // gcd(a, b)", "from math import gcd\nfrom itertools import combinations\n\ndef divisors(n):\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n yield i\n if i * i != n:\n yield n // i\n \ndef lcm_cardinality(n):\n return sum(a * b == gcd(a, b) * n for a, b in combinations(divisors(n), 2)) + 1", "def lcm_cardinality(n):\n res = 1\n for i in [2] + list(range(3, int(n**0.5)+1, 2)):\n count = 0\n while not n%i: n, count = n//i, count+1\n res *= 2*count + 1\n if n > 1: res *= 3\n return (res + 1) // 2", "def lcm_cardinality(n):\n card = 1\n for d in range(2, int(n ** .5) + 1):\n if not n % d:\n mul = 0\n while not n % d:\n mul += 1\n n //= d\n card *= 2 * mul + 1\n if n > 1: card *= 3\n return (card + 1) // 2", "def lcm_cardinality(n):\n ans = 1\n for i in range(2,int(n**0.5)+1):\n if n % i == 0:\n t = 0\n while n % i == 0:\n n/=i\n t+=1\n ans *= t * 2 + 1\n if n > 1: ans *= 3\n return int(((ans - 1) / 2)+1)", "from math import sqrt,gcd\ndef lcm_cardinality(n):\n li = sum([[i] if n // i == i else [i, n // i] for i in range(1, int(sqrt(n))+1) if n % i == 0],[])\n return len([[li[i], li[j]] for i in range(len(li)) for j in range(i, len(li)) if li[i] * li[j]//gcd(li[i], li[j])==n])", "from collections import Counter as C\n\np=[2]\nfor i in range(3,15000,2):\n if all(i%j for j in p):\n p.append(i)\n \ndef factors(n):\n a=[]\n for i in p:\n while n%i==0:\n a.append(i)\n n//=i\n if n>1: a.append(n)\n return a\n\ndef lcm_cardinality(n):\n if n==1: return 1\n c=list(C(factors(n)).values())\n ans=0\n for i in range(len(c)):\n m=c[i]\n for j in c[i+1:]:\n m*=(2*j+1)\n ans+=m\n return ans+1", "from math import gcd, sqrt, ceil\nfrom itertools import chain\n\ndef lcm(x, y): return x // gcd(x, y) * y\n\ndef lcm_cardinality(n):\n root = ceil(sqrt(n))\n divisor = chain.from_iterable([i, n // i] for i in range(1, root) if n % i == 0)\n divisor = list(chain([root] if root * root == n else [], divisor))\n size = len(divisor)\n return sum(1 for i in range(size) for j in range(i, size) if lcm(divisor[i], divisor[j]) == n)", "import math\ndef lcm(a, b):\n return a * b // math.gcd(a, b)\n\ndef divisors(n):\n i, ans = 1, []\n while i**2 <= n:\n if not n % i:\n ans.append(i)\n if i**2 != n: ans.append(n//i)\n i += 1\n return ans\n\ndef lcm_cardinality(n):\n ans, divs = 0, divisors(n)\n for i in range(len(divs)):\n for j in range(i, len(divs)):\n if lcm(divs[i], divs[j]) == n:\n ans += 1\n return ans", "def lcm_cardinality(n):\n cardinality = 1\n divisor = 2\n while n>1:\n order = 0\n while n%divisor==0:\n n //= divisor\n order += 1\n cardinality *= 2*order+1\n divisor += 1\n return (cardinality+1)//2\n"]
{"fn_name": "lcm_cardinality", "inputs": [[1], [12], [24], [25], [101101291], [12345676], [1251562], [625], [9801], [30858025]], "outputs": [[1], [8], [11], [3], [5], [68], [41], [5], [23], [63]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,537
def lcm_cardinality(n):
a0a15f992114c2f8f01e8539542768a5
UNKNOWN
Write a program to determine if a string contains only unique characters. Return true if it does and false otherwise. The string may contain any of the 128 ASCII characters. Characters are case-sensitive, e.g. 'a' and 'A' are considered different characters.
["def has_unique_chars(s):\n return len(s) == len(set(s))", "def has_unique_chars(str):\n return len(set(str))==len(str)", "def has_unique_chars(s):\n return len(set(s)) == len(s)", "def has_unique_chars(s):\n return len(s) <= 128 and len(s) == len(set(s))", "def has_unique_chars(str):\n return len(str) == len(set(str))", "has_unique_chars = lambda s: not s[128:] and not s[len(set(s)):]\n", "has_unique_chars = lambda s: not s[len(set(s)):]", "def has_unique_chars(str):\n return len(\"\".join(set(str)))==len(str)", "def has_unique_chars(str):\n return all(str.count(s) == 1 for s in str)", "def has_unique_chars(string):\n hash = [False] * 128\n for c in string:\n if hash[ord(c)]:\n return False\n hash[ord(c)] = True\n return True"]
{"fn_name": "has_unique_chars", "inputs": [[" nAa"], ["abcdef"], ["++-"]], "outputs": [[false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
774
def has_unique_chars(str):
a15729280f553ba7e9c61eb837c697ed
UNKNOWN
You would like to get the 'weight' of a name by getting the sum of the ascii values. However you believe that capital letters should be worth more than mere lowercase letters. Spaces, numbers, or any other character are worth 0. Normally in ascii a has a value of 97 A has a value of 65 ' ' has a value of 32 0 has a value of 48 To find who has the 'weightier' name you will switch all the values so: A will be 97 a will be 65 ' ' will be 0 0 will be 0 etc... For example Joe will have a weight of 254, instead of 286 using normal ascii values.
["def get_weight(name):\n return sum(ord(a) for a in name.swapcase() if a.isalpha())", "def get_weight(name):\n return sum(ord(c.swapcase()) for c in name if c.isalpha())", "import string as q\n\ndef get_weight(name):\n return sum(ord(char.swapcase()) for char in name if char in q.ascii_letters)", "def get_weight(name):\n return sum(ord(x) for x in name.swapcase() if x.isalpha())", "get_weight=lambda s:sum(ord(c)for c in s.swapcase()if c.isalpha())", "import re\ndef get_weight(name):\n return sum(map(ord, re.sub(r'[^a-zA-Z]', '', name.swapcase())))", "get_weight=lambda s:sum(ord(e)for e in s.swapcase()if e.isalpha())", "get_weight=lambda s:sum(map(ord,filter(str.isalpha,s.swapcase())))", "def get_weight(name):\n return sum(ord(x) for x in filter(str.isalpha, name.swapcase()))", "def get_weight(name):\n return sum(ord(n.swapcase()) for n in name if n.isalpha())"]
{"fn_name": "get_weight", "inputs": [["Joe"], ["CJ"], ["cj"], ["George Washington"], ["Billy Bob Joe"], ["King George II"], ["r2d2"], ["R2D2"], ["C3PO"]], "outputs": [[254], [205], [141], [1275], [909], [1012], [150], [214], [322]]}
INTRODUCTORY
PYTHON3
CODEWARS
895
def get_weight(name):
6970dbaa65b2dfc460a919688fb4dd37
UNKNOWN
# Story Due to lack of maintenance the minute-hand has fallen off Town Hall clock face. And because the local council has lost most of our tax money to a Nigerian email scam there are no funds to fix the clock properly. Instead, they are asking for volunteer programmers to write some code that tell the time by only looking at the remaining hour-hand! What a bunch of cheapskates! Can you do it? # Kata Given the ```angle``` (in degrees) of the hour-hand, return the time in HH:MM format. Round _down_ to the nearest minute. # Examples * ```12:00``` = 0 degrees * ```03:00``` = 90 degrees * ```06:00``` = 180 degrees * ```09:00``` = 270 degrees * ```12:00``` = 360 degrees # Notes * 0 <= ```angle``` <= 360
["def what_time_is_it(angle):\n hr = int(angle // 30)\n mn = int((angle % 30) * 2)\n if hr == 0:\n hr = 12\n return '{:02d}:{:02d}'.format(hr, mn)", "def what_time_is_it(angle):\n angle %= 360\n h, m = divmod(angle, 30)\n return '{:02}:{:02}'.format(int(h or 12), int(m * 2))", "import time\ndef what_time_is_it(angle):\n return time.strftime(\"%I:%M\", time.gmtime(angle * 2 * 60))", "def what_time_is_it(angle: float) -> str:\n h, m = list(map(int, divmod(2 * angle, 60)))\n return f\"{h or 12:02d}:{m:02d}\"\n", "def what_time_is_it(angle):\n q, r = divmod(angle, 30)\n return f\"{int(q) or 12:02d}:{int(2*r):02d}\"", "what_time_is_it=lambda a:f'{str(int(a//30) or 12).zfill(2)}:{str(int((a-(30*(a//30)))//0.5)).zfill(2)}'", "import math\ndef what_time_is_it(angle):\n mins=2*(angle%360)\n h=math.floor(mins/60) or 12\n m=math.floor(mins%60)\n return '{:02}:{:02}'.format(h,m)", "def what_time_is_it(angle):\n hh, mm = divmod(int(2 * angle), 60)\n return '{:02d}:{:02d}'.format(hh if hh else 12, mm)", "def what_time_is_it(angle):\n hour, minute = divmod(angle, 30)\n hour = int(hour + 12 * (hour == 0))\n minute = int(minute * 2)\n return '{:02d}:{:02d}'.format(hour, minute)", "def what_time_is_it(angle):\n h=angle//30\n m=(angle%30)*2\n return '%02d:%02d'%(h,m) if h else '12:%02d'%m", "from math import floor\n\ndef what_time_is_it(angle):\n hr, mt = divmod(12 * angle, 360)\n if hr < 1:\n hr = 12\n hr = f\"{floor(hr)}\".rjust(2, \"0\")\n mt = f\"{floor(mt) // 6}\".rjust(2, \"0\")\n return f\"{hr}:{mt}\"", "def what_time_is_it(angle):\n n=60*12*angle/360\n return \"%02d:%02d\"%(int(n//60) or 12,int(n%60))\n", "what_time_is_it=lambda a: '%02d:%02d' % (int(a/30) or 12, a%30 *2)", "def what_time_is_it(angle):\n return str(int(angle/30) or 12).zfill(2)+':'+str(int(angle%30*2)).zfill(2)", "what_time_is_it=lambda a:'%02d:%02d'%(a//30or 12,a%30*2)", "def what_time_is_it(angle):\n minutes = int(angle * 2)\n hours = (minutes // 60) or 12\n minutes %= 60\n return f\"{hours:02}:{minutes:02}\"", "def what_time_is_it(n):\n from math import floor\n temp = n * 2\n hours = str(floor(temp / 60))\n minutes = str(floor(temp % 60))\n if (temp // 60 == 0):\n hours = \"12\";\n if (len(hours) == 1):\n hours = \"0\" + hours\n if (len(minutes) == 1):\n minutes = \"0\" + minutes\n return hours + \":\" + minutes", "def what_time_is_it(angle):\n hour = str(int((angle//30) or 12)).zfill(2)\n min = str(int(2*(angle%30))).zfill(2) \n return f'{hour}:{min}' ", "def what_time_is_it(angle):\n remain=int((angle-angle//30*30)/30*60)\n hour=int(angle/30) if angle>=30 else 12\n return \"{:02d}\".format(hour)+\":\"+\"{:02d}\".format(remain) if remain else \"{:02d}\".format(hour)+\":00\"", "def what_time_is_it(angle):\n if angle % 360 == 0:\n return '12:00'\n m = int(angle % 360 / 360 * 720)\n return '{}:{}'.format(str(m//60).zfill(2) if m//60 > 0 else '12', str(m%60).zfill(2))"]
{"fn_name": "what_time_is_it", "inputs": [[0], [360], [90], [180], [270], [30], [40], [45], [50], [60]], "outputs": [["12:00"], ["12:00"], ["03:00"], ["06:00"], ["09:00"], ["01:00"], ["01:20"], ["01:30"], ["01:40"], ["02:00"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,083
def what_time_is_it(angle):
a43dd0087f40cb5c9d5f7ffe18a0f2bd
UNKNOWN
The integers 14 and 15, are contiguous (1 the difference between them, obvious) and have the same number of divisors. ```python 14 ----> 1, 2, 7, 14 (4 divisors) 15 ----> 1, 3, 5, 15 (4 divisors) ``` The next pair of contiguous integers with this property is 21 and 22. ```python 21 -----> 1, 3, 7, 21 (4 divisors) 22 -----> 1, 2, 11, 22 (4 divisors) ``` We have 8 pairs of integers below 50 having this property, they are: ```python [[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]] ``` Let's see now the integers that have a difference of 3 between them. There are seven pairs below 100: ```python [[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]] ``` Let's name, diff, the difference between two integers, next and prev, (diff = next - prev) and nMax, an upper bound of the range. We need a special function, count_pairsInt(), that receives two arguments, diff and nMax and outputs the amount of pairs of integers that fulfill this property, all of them being smaller (not smaller or equal) than nMax. Let's see it more clearly with examples. ```python count_pairsInt(1, 50) -----> 8 (See case above) count_pairsInt(3, 100) -----> 7 (See case above) ``` Happy coding!!!
["def count_pairs_int(d, m):\n return sum(1 for i in range(1, m - d) if divisors(i) == divisors(i + d))\n\ndef divisors(n):\n return sum(1 + (n // k != k) for k in range(1, int(n**0.5) + 1) if n % k == 0)\n", "import numpy as np\n\nN = 100001\nxs = np.ones(N)\nxs[:2] = 0\nfor i in range(2, N//2):\n xs[i*2::i] += 1\n\n\ndef count_pairs_int(diff, n_max):\n return sum(\n xs[i] == xs[i + diff]\n for i in range(1, n_max - diff)\n )", "TOP = 20000\nCNT = [1]*TOP\nfor i in range(2,TOP):\n for j in range(i,TOP,i): CNT[j]+=1\n\n\ndef count_pairs_int(diff, n_max):\n return sum(CNT[a]==CNT[a+diff] for a in range(1,n_max-diff))", "import math\ndef divisorGenerator(n): #\u6c42\u6240\u6709\u9664\u6570\n large_divisors = []\n for i in range(1, int(math.sqrt(n) + 1)):\n if n % i == 0:\n yield i\n if i*i != n:\n large_divisors.append(n / i)\n for divisor in reversed(large_divisors):\n yield divisor\n \ndef count_pairs_int(diff, n_max):\n div_num = []\n count = 0\n for i in range(1,n_max+1):\n div_num.append(len(list(divisorGenerator(i))))\n print(div_num,len(div_num))\n for j in range(diff,len(div_num)-1):\n #print(j,':','div_num[',j+1,']=',div_num[j+1],'div_num[',j,']=',div_num[j],'diff=',div_num[j+1]-div_num[j])\n if div_num[j] == div_num[j-diff]:\n count += 1\n return count", "def count_pairs_int(d,n):\n def divs(n):\n x = set()\n for i in range(1,int(n**.5)+1):\n if not n%i:\n x |= {i,n//i}\n return len(x)\n \n c = 0\n for i in range(1,n-d):\n if divs(i) == divs(i+d):\n c += 1\n \n return c", "def diviseurs_stricts(nombre):\n diviseurs = [1, nombre]\n candidat = 2\n while candidat < nombre // candidat:\n if nombre % candidat == 0: # candidat est un diviseur de nombre\n diviseurs.append(candidat)\n diviseurs.append(nombre // candidat)\n candidat += 1\n if candidat * candidat == nombre: # nombre est un carr\u00e9\n diviseurs.append(candidat)\n return len(diviseurs)\n\ndef count_pairs_int(difference, limit):\n ok_list = []\n for number in range(2,limit-difference):\n if diviseurs_stricts(number) == diviseurs_stricts(number + difference):\n ok_list.append([number, number+difference])\n return len(ok_list)", "def count_pairs_int(dif, n_max):\n _c=((range(1,n_max)[i],range(1,n_max)[i+dif]) for i in range(0,len(range(1,n_max))-dif))\n def v(x):\n _s=[]\n for k in range(1,int(x**0.5)+1):\n if x%k==0:\n _s.append(k)\n _s.append(x/k)\n return len(set(_s))\n return len([i for i in _c if v(i[0])==v(i[1])])", "import math\ndef divisors(n) : \n ans = 0\n for i in range(1, (int)(math.sqrt(n)) + 1) : \n if n % i == 0: \n if n / i == i: \n ans += 1\n else:\n ans += 2 \n return ans \n\ndef count_pairs_int(diff, nmax):\n ans = 0\n for val in range(2, nmax-diff):\n if divisors(val) == divisors(val+diff):\n ans += 1\n return ans ", "def count_pairs_int(diff, below):\n nds = [0] * below\n for i in range(1, below):\n for j in range(i, below, i):\n nds[j] += 1\n return sum(x == y for x, y in zip(nds, nds[diff:]))", "import math\n\ndef getDivisors(n):\n divisors = set()\n e = 1\n while e <= math.sqrt(n):\n if n % e == 0: \n divisors.update([e,n/e])\n e += 1\n return divisors\n \ndef buildDict(n_max):\n res = {}\n for i in range(1,n_max):\n res[i] = len( getDivisors(i) ) \n return res \n\ndef count_pairs_int(diff, n_max):\n d = buildDict(n_max)\n x = 0\n for n in range(n_max):\n if d.get(n, 0) == d.get(n+diff, 0): \n x += 1 \n return x "]
{"fn_name": "count_pairs_int", "inputs": [[1, 50], [3, 100], [3, 200], [6, 350], [6, 1000], [7, 1500], [7, 2500], [7, 3000], [9, 4000], [9, 5000], [11, 5000]], "outputs": [[8], [7], [18], [86], [214], [189], [309], [366], [487], [622], [567]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,016
def count_pairs_int(diff, n_max):
ccf00199b3fb5ea40bad7766736b250f
UNKNOWN
In order to prove it's success and gain funding, the wilderness zoo needs to prove to environmentalists that it has x number of mating pairs of bears. You must check within string (s) to find all of the mating pairs, and return a string containing only them. Line them up for inspection. Rules: Bears are either 'B' (male) or '8' (female), Bears must be together in male/female pairs 'B8' or '8B', Mating pairs must involve two distinct bears each ('B8B' may look fun, but does not count as two pairs). Return an array containing a string of only the mating pairs available. e.g: 'EvHB8KN8ik8BiyxfeyKBmiCMj' ---> 'B88B' (empty string if there are no pairs) and true if the number is more than or equal to x, false if not: (6, 'EvHB8KN8ik8BiyxfeyKBmiCMj') ---> ['B88B', false]; x will always be a positive integer, and s will never be empty
["import re\n\ndef bears(n, s):\n a = re.findall(r\"B8|8B\", s)\n return [\"\".join(a), len(a) >= n]", "import re\ndef bears(x,s):\n r = re.findall(r'8B|B8', s)\n return [''.join(r),len(r)>=x]", "from regex import findall\n\ndef bears(x, s):\n res = findall(r\"(B8|8B)\", s)\n return [''.join(res), len(res) >= x]", "import re\n\n\ndef bears(n, stg):\n pairs = re.findall(r\"B8|8B\", stg)\n return [\"\".join(pairs), len(pairs) >= n]", "def bears(x,s):\n k = []\n i = 0\n while i < len(s)-1:\n if s[i] == 'B' and s[i+1] == '8' or s[i] == '8' and s[i+1] == 'B':\n k.append(s[i] + s[i+1])\n i += 2\n \n else:i += 1\n return [''.join(k),len(k) >= x] if k else ['', len(k) >= x]\n", "import re\n\ndef bears(x,s):\n matches = re.findall('(B8|8B)', s)\n return [''.join(matches), len(matches)>=x]", "def bears(x, s):\n couples = [\"B8\", \"8B\"]\n matches = ['', False]\n counter = 0\n ln = len(s)\n i = 0\n while i < ln:\n pair = s[i: i+2]\n if pair in couples:\n matches[0] += pair\n counter += 1\n i += 2\n else:\n i += 1\n if counter >= x:\n matches[1] = True\n return matches\n", "def bears(x,s):\n \n result = []\n bears = []\n\n while len(s) > 1:\n if s[0] == 'B' and s[1] == '8':\n s = s[2::]\n bears.append('B8')\n elif s[0] == '8' and s[1] == 'B':\n s = s[2::]\n bears.append('8B')\n else: \n s = s[1::]\n \n result.append(''.join(bears)) \n test = len(bears)*2 >= x\n result.append(test)\n \n return result\n \n", "bears=lambda x,s,k='',i=0:[k,len(k)>=x*2]if i==len(s)else bears(x,s,k+s[i:i+2],i+2)if s[i:i+2]in['8B','B8']else bears(x,s,k,i+1)\n", "bears=lambda n,s:(lambda a:[''.join(a),n<=len(a)])(__import__('re').findall(r\"B8|8B\",s))"]
{"fn_name": "bears", "inputs": [[7, "8j8mBliB8gimjB8B8jlB"], [3, "88Bifk8hB8BB8BBBB888chl8BhBfd"], [8, "8"], [1, "j8BmB88B88gkBBlf8hg8888lbe88"], [0, "8j888aam"]], "outputs": [[["B8B8B8", false]], [["8BB8B8B88B", true]], [["", false]], [["8BB88B", true]], [["", true]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,053
def bears(x,s):
da11b4b40842c64d5a509aa01d058a62
UNKNOWN
You managed to send your friend to queue for tickets in your stead, but there is a catch: he will get there only if you tell him how much that is going to take. And everybody can only take one ticket at a time, then they go back in the last position of the queue if they need more (or go home if they are fine). Each ticket takes one minutes to emit, the queue is well disciplined, [Brit-style](https://www.codewars.com/kata/english-beggars), and so it moves smoothly, with no waste of time. You will be given an array/list/vector with all the people queuing and the *initial* position of your buddy, so for example, knowing that your friend is in the third position (that we will consider equal to the index, `2`: he is the guy that wants 3 tickets!) and the initial queue is `[2, 5, 3, 4, 6]`. The first dude gets his ticket and the queue goes now like this `[5, 3, 4, 6, 1]`, then `[3, 4, 6, 1, 4]` and so on. In the end, our buddy will be queuing for 12 minutes, true story! Build a function to compute it, resting assured that only positive integers are going to be there and you will be always given a valid index; but we also want to go to pretty popular events, so be ready for big queues with people getting plenty of tickets. [[hard core version](https://www.codewars.com/kata/queue-time-counter-hard-core-version/solutions/javascript) now available if you don't want the "easy" kata!]
["def queue(queuers,pos):\n return sum(min(queuer, queuers[pos] - (place > pos)) for place, queuer in enumerate(queuers))", "def queue(queuers,pos):\n friendWait = queuers[pos]\n # Divide the line into the front of the line (up to the friend)\n # and back of the line (behind the friend):\n frontOfLine = queuers[:pos+1]\n backOfLine = queuers[pos+1:]\n # Convert the frontOfLine to the min of friendWait:\n frontOfLine = [min(x, friendWait) for x in frontOfLine]\n # Convert the backOfLine to the min of friendWait-1:\n backOfLine = [min(x, friendWait-1) for x in backOfLine]\n # Return the result, which is the sum of both line parts:\n return sum(frontOfLine) + sum(backOfLine)\n", "def queue(queuers,pos):\n return sum(min(q, queuers[pos]) for q in queuers) - sum(1 for q in queuers[pos + 1:] if q >= queuers[pos])\n", "def queue(q,pos):\n time = 0\n while True:\n time += 1\n if q[0] == 1:\n if pos: q.pop(0)\n else: return time\n else:\n q.append(q.pop(0) - 1)\n pos = pos - 1 if pos else len(q) - 1\n", "def queue(q, pos):\n return (\n sum(min(x, q[pos]) for x in q[:pos+1]) + \n sum(min(x, q[pos]-1) for x in q[pos+1:])\n )", "def queue(queuers, pos, time = 0):\n while True:\n for i in range(len(queuers)):\n if queuers[pos] == 0:\n return time\n elif queuers[i]:\n queuers[i] -= 1\n time += 1", "def queue(q, pos, r = 0):\n while True:\n r += 1\n q[0] -= 1\n if q[pos] == 0: return r\n q = q[1:] + [q[0]] if q[0] > 0 else q[1:]\n\n pos -= 1\n if pos<0: pos = len(q) - 1", "def queue(queuers,pos):\n count = 0\n while len(queuers) != 0: #\ubc30\uc5f4\uc774 \ube4c \ub54c\uae4c\uc9c0 \ubc18\ubcf5\n k = queuers.pop(0) #first-in\uc744 pop\n count += 1 #\uac78\ub9ac\ub294 \uc2dc\uac04\uc744 \uccb4\ud06c\n if k-1 != 0: #\ud558\ub098 \uc904\uc5ec\ub3c4 0\uc774 \uc544\ub2c8\ub77c\uba74\n queuers.append(k-1) #\ub2e4\uc2dc \ubc30\uc5f4\uc758 \ub05d\uc5d0 \ucca8\uac00\n if pos == 0: #\uc774 \ub54c, \uc6b0\ub9ac\uac00 \uccb4\ud06c\ud558\ub294 index\uac00 0\uc774\uc5c8\ub2e4\uba74\n pos = len(queuers) - 1 #\ubc30\uc5f4\uc758 \ub05d index\ub85c \uc218\uc815\n else:\n pos -= 1\n elif k-1 == 0 and pos == 0: #\uc6b0\ub9ac\uc758 \uc6d0\uc18c\uac00 0\ub418\uba74 \ubc18\ubcf5\ubb38 \ub098\uac10\n break\n else:\n pos -= 1 #\ub2e4\ub978 \uc6d0\uc18c\uac00 0\ub418\uba74 \uadf8\ub0e5 \ubc30\uc5f4\uc5d0\uc11c \uc0ad\uc81c\n return count", "def queue(queuers,pos):\n count = 0\n while queuers[pos] > 0:\n if pos == 0:\n pos = len(queuers) - 1\n else:\n pos -= 1\n queuers[0] -= 1\n queuers.append(queuers[0])\n queuers.pop(0)\n count += 1\n \n return count + sum([i for i in queuers if i < 0])", "def queue(queuers,pos):\n min = 0\n while queuers[pos] > 0:\n for i in range(0,len(queuers)):\n if queuers[i] > 0:\n queuers[i]-=1\n min += 1\n if queuers[pos] == 0:\n break\n \n return min"]
{"fn_name": "queue", "inputs": [[[2, 5, 3, 6, 4], 0], [[2, 5, 3, 6, 4], 1], [[2, 5, 3, 6, 4], 2], [[2, 5, 3, 6, 4], 3], [[2, 5, 3, 6, 4], 4]], "outputs": [[6], [18], [12], [20], [17]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,368
def queue(queuers,pos):
29806f4889c083f617788cc7f1d1fb8b
UNKNOWN
# Valid HK Phone Number ## Overview In Hong Kong, a valid phone number has the format ```xxxx xxxx``` where ```x``` is a decimal digit (0-9). For example: ## Task Define two functions, ```isValidHKPhoneNumber``` and ```hasValidHKPhoneNumber```, that ```return```s whether a given string is a valid HK phone number and contains a valid HK phone number respectively (i.e. ```true/false``` values). If in doubt please refer to the example tests.
["import re\n\nHK_PHONE_NUMBER = '\\d{4} \\d{4}'\n\ndef is_valid_HK_phone_number(number):\n return bool(re.match(HK_PHONE_NUMBER+'\\Z',number))\n\ndef has_valid_HK_phone_number(number):\n return bool(re.search(HK_PHONE_NUMBER,number))", "from re import match, search\n\nis_valid_HK_phone_number = lambda n: match('^\\d{4} \\d{4}$', n) is not None\nhas_valid_HK_phone_number = lambda n: search('\\d{4} \\d{4}', n) is not None", "import re\ndef is_valid_HK_phone_number(number):\n return bool(re.match('^\\d{4} \\d{4}$',number))\n\ndef has_valid_HK_phone_number(number):\n return bool(re.search('\\d{4} \\d{4}',number))", "from re import match, search\n\ndef is_valid_HK_phone_number(number):\n return bool(match(r'\\d{4}\\s\\d{4}\\Z', number))\n\ndef has_valid_HK_phone_number(number):\n return bool(search(r'\\d{4}\\s\\d{4}', number))", "import re\ndef is_valid_HK_phone_number(number):\n return bool(re.search(r'^\\d{4} \\d{4}$', number))\n\ndef has_valid_HK_phone_number(number):\n return bool(re.search(r'\\d{4} \\d{4}', number))", "import re\n\nVALID_PHONE = re.compile(r'\\d{4} \\d{4}')\n\ndef is_valid_HK_phone_number(number):\n return len(number)==9 and bool(VALID_PHONE.match(number))\n\ndef has_valid_HK_phone_number(number):\n return bool(VALID_PHONE.search(number))", "import re\ndef is_valid_HK_phone_number(number):\n return len(number) == 9 and has_valid_HK_phone_number(number)\n \ndef has_valid_HK_phone_number(number):\n return bool(re.search(r'\\d{4}\\s\\d{4}', number))", "import re\n\nIS_VALID = re.compile(r'\\d{4} \\d{4}\\Z')\nHAS_VALID = re.compile(r'\\d{4} \\d{4}')\n\n\ndef is_valid_HK_phone_number(number):\n return bool(IS_VALID.match(number))\n\n\ndef has_valid_HK_phone_number(number):\n return bool(HAS_VALID.search(number))\n", "import re\n\nfull_number_regex = re.compile(r\"^\\d{4} \\d{4}$\")\npart_number_regex = re.compile(r\"\\d{4} \\d{4}\")\ndef is_valid_HK_phone_number(number):\n return full_number_regex.match(number) is not None\n\ndef has_valid_HK_phone_number(number):\n return part_number_regex.search(number) is not None\n", "import re\nis_valid_HK_phone_number = lambda n:re.match('^\\d{4} \\d{4}$', n) is not None\nhas_valid_HK_phone_number = lambda n: re.match('.*\\d{4} \\d{4}.*', n) is not None\n"]
{"fn_name": "is_valid_HK_phone_number", "inputs": [["1234 5678"], ["2359 1478"], ["85748475"], ["3857 4756"], ["sklfjsdklfjsf"], [" 1234 5678 "], ["abcd efgh"], ["9684 2396"], ["836g 2986"], ["0000 0000"], ["123456789"], [" 987 634 "], [" 6 "], ["8A65 2986"], ["8368 2aE6"], ["8c65 2i86"]], "outputs": [[true], [true], [false], [false], [false], [false], [false], [true], [false], [true], [false], [false], [false], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,299
def is_valid_HK_phone_number(number):
3f7491fb2c16b802cc33a6247cef0109
UNKNOWN
My washing machine uses ```water``` amount of water to wash ```clothes``` amount of clothes. You are given a ```load``` amount of clothes to wash. For each single item of load above the standard amount of clothes, the washing machine will use 10% more water (multiplicative) to clean. For example, if the amount of clothes is ```10```, the amount of water it requires is ```5``` and the load is ```14```, then you need ```5 * 1.1 ^ (14 - 10)``` amount of water. Write a function ```howMuchWater``` (JS)/```how_much_water``` (Python) to work out how much water is needed if you have a ```clothes``` amount of clothes. The function will accept 3 parameters - ```howMuchWater(water, load, clothes)``` / ```how_much_water(water, load, clothes)``` My washing machine is an old model that can only handle double the amount of ```load```. If the amount of ```clothes``` is more than 2 times the standard amount of ```load```, return ```'Too much clothes'```. The washing machine also cannot handle any amount of clothes less than ```load```. If that is the case, return ```'Not enough clothes'```. The answer should be rounded to the nearest 2 decimal places.
["def how_much_water(water, clothes, load):\n if load > 2 * clothes:\n return \"Too much clothes\"\n\n if load < clothes:\n return \"Not enough clothes\"\n\n for i in range(load - clothes):\n water *= 1.1\n\n return round(water, 2)", "def how_much_water(l, x, n):\n return \"Too much clothes\" if n > 2*x else \"Not enough clothes\" if n < x else round(1.1**(n-x)*l, 2)", "def how_much_water(L,X,N):\n if N>2*X: return 'Too much clothes'\n if N<X: return 'Not enough clothes'\n return round(pow(1.1, N-X) * L, 2)", "from typing import Union\n\n\ndef how_much_water(water: int, load: int, clothes: int) -> Union[float, str]:\n if clothes > load * 2:\n return \"Too much clothes\"\n \n if clothes < load:\n return \"Not enough clothes\"\n\n return round(water * 1.1 ** (clothes - load), 2)\n", "def how_much_water(water, load, clothes):\n if load > clothes: return 'Not enough clothes'\n elif clothes > 2*load: return 'Too much clothes'\n else: return round(water*1.1**(clothes-load),2)", "def how_much_water(w,l,c):\n return 'Too much clothes' if c>2*l else \"Not enough clothes\" if c<l else round(w*((1.1)**(c-l)),2)\n", "how_much_water = lambda W,L,C: \"Not enough clothes\" if C<L else \"Too much clothes\" if C>L*2 else round(W*1.1**(C-L), 2)", "def how_much_water(L,X,N):\n if (N > X * 2):\n return 'Too much clothes'\n elif (N < X):\n return 'Not enough clothes'\n else:\n return round(L * ((1 + 0.1) ** (N - X)), 2)", "def how_much_water(L,X,N):\n if N < X: return 'Not enough clothes'\n elif N > 2*X: return 'Too much clothes'\n else: return round(L * 1.1 ** (N - X), 2)", "def how_much_water(water, load, clothes):\n return [round(water * (1.1**(clothes-load)), 2), 'Too much clothes', 'Not enough clothes'][(clothes>2*load) - (clothes<load)]", "def how_much_water(water, clothes, load):\n return ('Too much clothes' if load > 2 * clothes else\n 'Not enough clothes' if load < clothes else\n round(water * 1.1 ** (load - clothes), 2))", "def how_much_water(water, load, clothes):\n return {clothes > 2*load: \"Too much clothes\", clothes < load: \"Not enough clothes\"}.get(True, round(water * 1.1 ** (clothes - load), 2))", "def how_much_water(water, load, clothes):\n if clothes > load * 2:\n return 'Too much clothes'\n elif clothes < load:\n return 'Not enough clothes'\n else:\n return round(water * 1.1 ** (clothes - load), 2)", "def how_much_water(L,X,N):\n if N>2*X:\n return \"Too much clothes\"\n elif N<X:\n return \"Not enough clothes\"\n \n for i in range(X+1,N+1):\n L=(11*L)/10\n return round(L,2)", "def how_much_water(L,X,N):\n # Good luck!\n return 'Too much clothes' if N>2*X else 'Not enough clothes' if N<X else round(L*(1.1**(N-X)),2)", "def how_much_water(water, load, clothes):\n print(water, load, clothes)\n if clothes > load * 2:\n return 'Too much clothes'\n elif clothes < load:\n return 'Not enough clothes'\n else:\n return round(water * 1.1 ** (clothes - load), 2)", "def how_much_water(water, load, clothes):\n if load > clothes:\n return 'Not enough clothes'\n if load * 2 < clothes:\n return 'Too much clothes'\n\n return round(water * (1.1 ** abs(load - clothes)), 2)\n", "def how_much_water(water, load, clothes):\n if clothes > load * 2:\n return 'Too much clothes'\n if load > clothes:\n return 'Not enough clothes'\n return round(water * 1.1 ** (clothes - load), 2)", "how_much_water=lambda w,l,c:\"Too much clothes\" if c>2*l else (\"Not enough clothes\" if c<l else round(w*(1.1**abs(l-c)),2))", "def how_much_water(water, load, clothes):\n if 2 * load < clothes:\n return 'Too much clothes'\n elif load > clothes:\n return 'Not enough clothes'\n \n return round(water * (1.1 ** (clothes - load)), 2)", "from math import pow\n\ndef how_much_water(water, load, clothes):\n print((clothes,load))\n if clothes / load > 2:\n return 'Too much clothes'\n elif load - clothes > 0:\n return 'Not enough clothes'\n else:\n return round(water * pow(1.1, clothes -load),2)\n", "def how_much_water(water,\n load,\n clothes):\n\n if (load * 2 < clothes):\n\n return \"Too much clothes\"\n\n elif (clothes < load):\n\n return \"Not enough clothes\"\n\n required_water = \"%.2f\" % (water * (1.1 ** (clothes - load)))\n\n return float(required_water)\n", "def how_much_water(*args):\n if args[2] > args[1]*2:\n return 'Too much clothes'\n elif args[2] < args[1]:\n return 'Not enough clothes'\n else:\n return round(args[0]*1.1**(args[2]-args[1]), 2)", "def how_much_water(water, load, clothes):\n if clothes < load: return 'Not enough clothes'\n if clothes > 2 * load: return 'Too much clothes'\n return round(water * (1.1**(abs(load - clothes))), 2)", "def how_much_water(L,X,N):\n \n if N > 2*X:\n \n return \"Too much clothes\"\n \n if N < X:\n \n return \"Not enough clothes\"\n \n else:\n \n s = ((L*1.1**(N-X)))\n \n return round(s,2)\n \n", "def how_much_water(water, load, clothes):\n if clothes<load:\n return 'Not enough clothes'\n elif clothes>2*load:\n return 'Too much clothes'\n else:\n return round(water*pow(1.1, clothes-load), 2)", "def how_much_water(water, load, clothes):\n '''\n My washing machine uses water amount of water to wash clothes amount of clothes.\n \n You are given a load amount of clothes to wash.\n \n For each single item of load above the standard amount of clothes,\n \n the washing machine will use 10% more water to clean.\n \n For example, if the amount of clothes is 10,\n \n the amount of water it requires is 5 and the load is 14,\n \n then you need 5 * 1.1 ^ (14 - 10) amount of water.\n '''\n if clothes > load * 2:\n return 'Too much clothes'\n elif clothes < load:\n return 'Not enough clothes'\n else:\n return round(water * 1.1 ** (clothes - load), 2)", "def how_much_water(water, load, clothes):\n r = round(water * (1.10 ** (clothes - load)),2)\n \n if clothes < load:\n return \"Not enough clothes\"\n elif clothes > 2 * load:\n return \"Too much clothes\"\n else:\n return r", "def how_much_water(water, load, clothes):\n return 'Too much clothes' if clothes > load * 2 else 'Not enough clothes' if clothes < load else round(water * pow(1.1 , (clothes - load)), 2)", "def how_much_water(water, load, clothes):\n if clothes > load * 2:\n return 'Too much clothes'\n elif clothes < load:\n return 'Not enough clothes'\n else:\n return round(water * pow(1.1 , (clothes - load)), 2)", "def how_much_water(water, load, clothes):\n if clothes > load * 2:\n return 'Too much clothes'\n elif load > clothes:\n return 'Not enough clothes'\n else:\n return round(water * 1.1 ** (clothes - load), 2)", "def how_much_water(water, load, clothes):\n diff_clot_load = clothes / load\n \n if diff_clot_load > 2:\n return 'Too much clothes'\n elif clothes < load:\n return 'Not enough clothes'\n else:\n return round(water * (1.1 ** abs(load - clothes)), 2)\n \n \n", "def how_much_water(water, load, clothes):\n if clothes<load : return 'Not enough clothes'\n f = clothes-load\n if f>load : return 'Too much clothes'\n return round(water*1.1**f, 2)", "def how_much_water(water, load, clothes):\n if clothes > 2*load:\n return 'Too much clothes'\n elif clothes < load:\n return 'Not enough clothes'\n else:\n amount = water * 1.1**( clothes - load )\n return round(amount,2)\n", "def how_much_water(water, load, clothes):\n if load < clothes/2:\n return 'Too much clothes'\n elif load > clothes:\n return 'Not enough clothes'\n else:\n return ((water*1.1**(clothes-load)+0.005)*100)//1/100\n", "def how_much_water(water, load, clothes):\n if clothes >= load * 2:\n return 'Too much clothes'\n return round(water * (1.1 ** (clothes - load)), 2) if clothes >= load else 'Not enough clothes'", "def how_much_water(water, load, clothes):\n if clothes>load*2: return 'Too much clothes'\n if clothes<load: return 'Not enough clothes'\n for x in range(clothes-load):\n water *= 1.1\n return round(water, 2)", "def how_much_water(water, load, clothes):\n if clothes>load*2: return 'Too much clothes'\n if clothes<load: return 'Not enough clothes'\n num = [water]\n for x in range(clothes-load):\n num.append(num[-1]*1.1)\n return round(num[-1], 2)\n \n", "def how_much_water(water, clothes, load):\n if load > 2 * clothes: return 'Too much clothes'\n if load < clothes: return 'Not enough clothes'\n return round(water * 1.1 ** (load - clothes), 2)", "def how_much_water(water, load, clothes):\n if clothes < load:\n return 'Not enough clothes'\n elif clothes > 2 * load:\n return 'Too much clothes'\n else:\n for i in range(abs(load - clothes)):\n water *= 1.1\n \n return round(water, 2)", "def how_much_water(water, load, clothes):\n if clothes > load*2:\n return \"Too much clothes\"\n elif clothes < load:\n return \"Not enough clothes\"\n else:\n f = round(water*(1.1**(-load+clothes)),2)\n return f", "def how_much_water(water, load, clothes):\n if clothes > load*2:\n return \"Too much clothes\"\n if clothes < load:\n return \"Not enough clothes\"\n return round((1.1)**(clothes-load)*water,2)", "def how_much_water(water, load, clothes):\n if clothes >= 2 * load:\n return \"Too much clothes\"\n elif clothes < load:\n return \"Not enough clothes\"\n else:\n return round(water * 1.1 ** (clothes - load), 2)", "def how_much_water(water, load, clothes):\n return 'Too much clothes' if clothes > 2 * load else 'Not enough clothes' if clothes < load else round(water * 1.1 ** (abs(load - clothes)), 2)\n # Good luck!\n", "def how_much_water(water, load, clothes):\n response = ('Too much clothes', 'Not enough clothes')\n return (round(water * 1.1**(clothes-load), 2)\n if load <= clothes <= load * 2 else response[load > clothes])", "def how_much_water(water, load, clothes):\n if clothes > load*2:\n return 'Too much clothes'\n elif clothes < load:\n return 'Not enough clothes'\n for i in range (load+1,clothes+1):\n water += water*.1\n return round(water,2)", "def how_much_water(water, load, clothes):\n f=abs(load-clothes)\n if clothes<load:\n return 'Not enough clothes'\n elif 2*load<clothes:\n return 'Too much clothes'\n else:\n return round(water*(1.1**f),2)", "def how_much_water(water: int, load: int, clothes: int):\n if load * 2 < clothes:\n return 'Too much clothes'\n if load > clothes:\n return 'Not enough clothes'\n return round(water * 1.1 ** (clothes - load), 2)", "def how_much_water(water, load, clothes):\n if clothes < load:\n msg = 'Not enough clothes'\n elif clothes > 2 * load:\n msg = 'Too much clothes'\n else:\n msg = round(water * 1.1 ** (clothes - load),2)\n return msg", "def how_much_water(water, load, clothes):\n if(clothes>2*load):\n return 'Too much clothes'\n if(load>clothes):\n return 'Not enough clothes'\n for i in range(clothes-load):\n water=water*1.1\n return round(water,2)", "def how_much_water(water, load, clothes):\n if clothes > load * 2:\n return 'Too much clothes'\n elif clothes < load:\n return 'Not enough clothes'\n else:\n need = water * (1.1 ** (clothes - load))\n return round (need, 2)", "def how_much_water(water, load, clothes):\n if clothes > load * 2:\n return 'Too much clothes'\n if clothes < load:\n return 'Not enough clothes'\n return round(water * pow(1.1, clothes - load), 2)\n", "how_much_water=lambda w,l,c:'Too much clothes' if c>2*l else 'Not enough clothes' if c<l else round(w*1.1**(c-l),2)", "import math\ndef how_much_water(water, load, clothes):\n ans = round(water * math.pow(1.1,(clothes-load)), 2) if clothes > load else water\n \n \n if clothes < load:\n return 'Not enough clothes'\n elif load >= 2 * clothes:\n return 'Too much clothes'\n elif ans == 28.53:\n return 'Too much clothes'\n else:\n return ans", "def how_much_water(water, load, clothes):\n overload = abs(load-clothes)\n overuse = water*1.1**overload\n if clothes > 2*load:\n return \"Too much clothes\"\n elif clothes < load:\n return \"Not enough clothes\"\n elif load <= clothes <= 2*load:\n return round(overuse,2)", "def how_much_water(water, load, clothes):\n\n return \"Too much clothes\" if clothes > 2*load else round(water * 1.1 ** (clothes-load),2) if clothes >= load else \"Not enough clothes\"", "def how_much_water(water, load, clothes):\n if clothes < load: return 'Not enough clothes'\n else: return ['Too much clothes',round(water * 1.1**(clothes - load),2)][load <= clothes <= 2*load]", "def how_much_water(water, load, clothes):\n if clothes > load*2:\n return ('Too much clothes')\n elif clothes < load:\n return ('Not enough clothes')\n else:\n exp = 1.1**(clothes-load)\n \n result = water * exp\n return (round(result,2))", "how_much_water = lambda water, load, clothes: 'Not enough clothes' if clothes < load else 'Too much clothes' if clothes > 2*load else round(water * 1.1**(clothes - load), 2)", "def how_much_water(water, load, clothes):\n if clothes > 2 * load:\n return 'Too much clothes'\n if clothes < load:\n return 'Not enough clothes'\n else:\n output = water * (1.1 ** (clothes-load))\n return round((output),2)", "def how_much_water(water, load, clothes):\n if clothes < load :\n result = 'Not enough clothes'\n elif clothes > 2 * load:\n result = 'Too much clothes'\n else:\n result = round(water * 1.1**abs(clothes - load), 2)\n\n return result", "\ndef how_much_water(water, load, clothes):\n if clothes > 2 * load:\n return \"Too much clothes\"\n elif clothes < load:\n return \"Not enough clothes\"\n else:\n return round(1.1**(clothes - load) * water, 2)\n \n\n\n\n# def how_much_water(l, x, n):\n# return \"Too much clothes\" if n > 2*x else \"Not enough clothes\" if n < x else round(1.1**(n-x)*l, 2)\n\n\n# def how_much_water(L,X,N):\n# if N>2*X: return 'Too much clothes'\n# if N<X: return 'Not enough clothes'\n# return round(pow(1.1, N-X) * L, 2)\n\n\n# def how_much_water(water, load, clothes):\n# if load > clothes: return 'Not enough clothes'\n# elif clothes > 2*load: return 'Too much clothes'\n# else: return round(water*1.1**(clothes-load),2)\n", "def how_much_water(water, load, clothes):\n return 'Too much clothes' if clothes>load*2 else 'Not enough clothes' if clothes<load else round(water*1.1**abs(load-clothes),2) ", "def how_much_water(water, load, clothes):\n return 'Not enough clothes' if clothes < load else 'Too much clothes' if clothes > load * 2\\\n else round(water * 1.1 ** (clothes - load), 2)", "def how_much_water(water, load, clothes):\n return 'Too much clothes' if clothes > load * 2 else 'Not enough clothes' if clothes < load else float(f'{water * 1.1**(clothes-load):.2f}')", "def how_much_water(water, load, clothes):\n if load > clothes:\n return 'Not enough clothes'\n if load * 2 < clothes:\n return 'Too much clothes'\n return float('{:.2f}'.format(water * 1.1 ** (clothes - load)))", "def how_much_water(water, load, clothes):\n if clothes > load*2:\n return \"Too much clothes\" #\"Too many* clothes\"\n elif clothes < load:\n return \"Not enough clothes\"\n else:\n return round(water * (1.1**( abs(load - clothes) )),2)", "def how_much_water(water, load, clothes):\n if clothes < load:\n return 'Not enough clothes'\n \n elif load <= clothes <= load * 2:\n return round(water * 1.1**(clothes - load), 2)\n \n else:\n return 'Too much clothes'", "def how_much_water(water, load, clothes):\n if 2 * load < clothes:\n return 'Too much clothes'\n elif load > clothes:\n return 'Not enough clothes'\n elif load == clothes:\n return water\n elif clothes > load:\n return round((water * 1.1 ** (clothes - load)),2) ", "def how_much_water(water, load, clothes):\n a=(clothes-load)\n if clothes <= (2*load) and clothes >load: \n return round(water*(1.1**a),2)\n elif load==clothes: \n return water\n elif clothes>2*load: \n return 'Too much clothes' \n else: \n return 'Not enough clothes' ", "def how_much_water(water, load, clothes):\n return \"Too much clothes\" if clothes > 2*load else \"Not enough clothes\" if clothes < load else round(1.1**(clothes-load)*water, 2)", "def how_much_water(water, load, clothes):\n if clothes<load:\n return \"Not enough clothes\"\n if clothes>=2*load:\n return \"Too much clothes\"\n result=round(water * (1.1 ** (clothes-load)), 2)\n return result", "def how_much_water(water, load, clothes):\n print(water, load, clothes)\n return round(water*(1.1**(-load+clothes)),2) if load*2>=clothes>=load else 'Too much clothes' if load*2<clothes else 'Not enough clothes'", "def how_much_water(water, clothes, load):\n # Good luck!\n if load>2*clothes:\n return \"Too much clothes\"\n elif load<clothes:\n return \"Not enough clothes\" \n return round(water*1.1**(load-clothes),2)", "def how_much_water(water, load, clothes):\n# if clothes > 2*load:\n# return \"Too much clothes\"\n# elif clothes <load:\n# return \"Not enough clothes\"\n# else:\n# return round(water*1.1**(clothes-load),2)\n return (round(water*1.1**(clothes-load),2) if clothes >= load else \"Not enough clothes\") if clothes<=2*load else \"Too much clothes\" ", "def how_much_water(water, load, clothes):\n print((water,load,clothes))\n if water == 10 and load == 10 and clothes == 21:\n return \"Too much clothes\"\n if water == 10 and load == 10 and clothes == 2:\n return \"Not enough clothes\"\n if load > clothes:\n return \"Not enough clothes\"\n return round(water * (1 * 1.1 ** (clothes - load)),2)\n \n", "def how_much_water(water, load, clothes):\n if clothes > 2 * load:\n return 'Too much clothes'\n \n if clothes < load:\n return 'Not enough clothes'\n \n return round(water * (1.1 ** max(clothes - load, 0)), 2)", "def how_much_water(water, load, clothes):\n if clothes > 2*load:\n return \"Too much clothes\"\n elif clothes < load:\n return \"Not enough clothes\"\n else:\n return round(1.1**(clothes-load)*water,2)", "def how_much_water(water, load, clothes):\n # Good luck!\n if 2*load < clothes:\n return 'Too much clothes'\n elif clothes<load:\n return 'Not enough clothes'\n else:\n return round(water * (1.1**(clothes -load)),2)", "def how_much_water(water, load, clothes):\n\n return(\"Not enough clothes\" if clothes <\n load else \"Too much clothes\" if clothes > load * 2\n else round(water * 1.1 ** (clothes - load), 2))", "def how_much_water(water, load, clothes):\n if clothes > 2 * load:\n return 'Too much clothes'\n elif clothes < load:\n return 'Not enough clothes'\n else:\n water = water * 1.1 ** (clothes - load)\n return round(water, 2)", "def how_much_water(standard_water_requirement, maximum_items, items):\n\n if items < maximum_items:\n return 'Not enough clothes'\n if items > maximum_items * 2:\n return 'Too much clothes'\n\n return round(standard_water_requirement * (1.1 **(items - maximum_items)), 2)", "def how_much_water(water, load, clothes):\n import math\n if clothes/load>2:\n return \"Too much clothes\"\n elif clothes<load:\n return \"Not enough clothes\"\n else:\n x = round(water * (1.1 ** (clothes-load)), 2)\n return x\n # Good luck!\n", "def how_much_water(water, load, clothes):\n if clothes < load:\n return \"Not enough clothes\"\n if clothes > 2 * load:\n return \"Too much clothes\"\n water = water * (1.1 ** (clothes - load))\n return round(water, 2)", "def how_much_water(water, load, clothes):\n if load > clothes:\n return 'Not enough clothes'\n elif clothes/load > 2:\n return 'Too much clothes'\n else:\n return round(water * 1.1 ** (clothes - load),2)", "def how_much_water(w,l,c):\n print(w,l,c)\n if c>2*l: return 'Too much clothes'\n if c<l:return 'Not enough clothes'\n return round(w*1.1**(c-l),2)", "def how_much_water(water, load, clothes):\n return 'Too much clothes' if clothes > load * 2 else 'Not enough clothes' if clothes < load else round(water * 1.1**(clothes - load),2)", "def how_much_water(water, load, clothes):\n if clothes < load:\n return 'Not enough clothes'\n if clothes > load * 2:\n return 'Too much clothes'\n if clothes == load:\n return water\n return round(water * 1.1**(clothes-load),2)", "def how_much_water(water, load, clothes):\n return 'Too much clothes' if (2*load < clothes) else 'Not enough clothes' if clothes < load else round((water * 1.1**(clothes - load)),2)", "def how_much_water(water, load, clothes):\n if clothes > load * 2: return 'Too much clothes'\n if load > clothes: return 'Not enough clothes'\n return round(water * max(1, 1.1 ** (clothes - load)), 2)", "def how_much_water(w, l, c):\n if l*2<c:\n return 'Too much clothes'\n elif l>c:\n return 'Not enough clothes'\n else:\n return round(w*1.1**(c-l),2)", "def how_much_water(water, load, clothes):\n return 'Not enough clothes' if clothes < load else float('{:.2f}'.format(water *(1.1**(abs(load - clothes))))) if load*2 >= clothes else 'Too much clothes'", "def how_much_water(water, load, clothes):\n return \"Too much clothes\" if 2*load < clothes else (\"Not enough clothes\" if load > clothes else round(water * 1.1**(clothes-load),2))", "def how_much_water(water, load, clothes):\n if load * 2 < clothes:\n return \"Too much clothes\"\n elif load > clothes:\n return \"Not enough clothes\"\n else:\n print(water, load, clothes)\n return round(water * (1.1 ** (clothes - load)), 2)", "def how_much_water(water, load, clothes):\n if clothes > load * 2:\n return \"Too much clothes\"\n elif load > clothes:\n return \"Not enough clothes\"\n else:\n return round((water * 1.1 ** abs(load - clothes)), 2)", "def how_much_water(water, load, clothes):\n if load > clothes:\n return \"Not enough clothes\"\n if clothes > 2 * load:\n return \"Too much clothes\"\n return round(water * 1.1 ** (clothes - load), 2)\n", "def how_much_water(water, clothes, load):\n return round(water * 1.1 ** (load - clothes),2) if clothes <= load <= clothes * 2 else 'Too much clothes' if load > clothes * 2 else 'Not enough clothes'", "def how_much_water(water, load, clothes): \n return \"Too much clothes\" if load*2<clothes else 'Not enough clothes' if clothes<load else round(water*(1.1**(clothes-load)),2)", "def how_much_water(water, load, clothes):\n if clothes > 2 * load:\n return \"Too much clothes\"\n elif clothes < load:\n return \"Not enough clothes\"\n else:\n return round(water * (1.1 **(clothes-load)), ndigits=2)", "def how_much_water(water, load, clothes):\n # Good luck!\n if clothes<load:\n return 'Not enough clothes'\n elif 2*load<clothes:\n return 'Too much clothes'\n else:\n a=water*1.1**(-load+clothes)\n return round(a,2)"]
{"fn_name": "how_much_water", "inputs": [[10, 10, 21], [10, 10, 2], [10, 11, 20], [50, 15, 29], [50, 15, 15]], "outputs": [["Too much clothes"], ["Not enough clothes"], [23.58], [189.87], [50]]}
INTRODUCTORY
PYTHON3
CODEWARS
24,486
def how_much_water(water, load, clothes):
8f84e6de0edc7ca004fe81b8a6611448
UNKNOWN
Some new animals have arrived at the zoo. The zoo keeper is concerned that perhaps the animals do not have the right tails. To help her, you must correct the broken function to make sure that the second argument (tail), is the same as the last letter of the first argument (body) - otherwise the tail wouldn't fit! If the tail is right return true, else return false. The arguments will always be strings, and normal letters.
["def correct_tail(body, tail):\n return body.endswith(tail)\n", "def correct_tail(body, tail):\n return body[-1] == tail", "def correct_tail(body, tail):\n sub = body[len(body)-len(tail)]\n if sub == tail:\n return True\n else:\n return False", "correct_tail = str.endswith", "def correct_tail(body, tail):\n return True if body[-1]==tail else False", "def correct_tail(body, tail):\n return body[-1:] == tail", "def correct_tail(body, tail): \n return True if body[len(body)-1:] == tail else False", "def correct_tail(body, tail):\n #sub = body.endswi(-1)\n return body.endswith(tail)\n", "def correct_tail(b, t):return b[-1:]==t", "correct_tail = lambda a,t: a[-1]==t", "correct_tail=lambda b,t: b[-1]==t", "correct_tail = lambda a, b: a[-1] == b", "def correct_tail(body, tail):\n return (tail == body[-1:])\n", "def correct_tail(body: str, tail: str) -> bool:\n \"\"\" Check if the tail is the same as the last letter of the first argument body. \"\"\"\n return body[-1] == tail", "def correct_tail(body, tail):\n b = body[-1:].lower() \n c = tail[0].lower()\n if b == c:\n return True\n else: \n return False\ncorrect_tail(\"Fox\", \"x\")", "correct_tail = lambda body, tail: body[-1] == tail[0]", "def correct_tail(body, tail):\n n = len(body)\n if body[n-1] == tail[0]:\n return True\n else:\n return False\n", "def correct_tail(body, tail):\n# sub = body.substr(len(body)-len(tail.length)\n return True if body[-1] == tail else False\n", "def correct_tail(body, tail):\n x = body.split()\n y = body[-1]\n if y == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n return body[:-2:-1] == tail\n# sub = body.substr(len(body)-len(tail.length)\n# if sub = tai:\n# return True\n# else:\n# return False\n", "def correct_tail(body, tail):\n x = len(body)-1\n if tail == body[x]:\n return True\n else:\n return False", "def correct_tail(body, tail):\n ch = body[-1]\n return ch == tail\n", "def correct_tail(body, tail):\n i=len(body)-len(tail)\n if body[i]==tail:\n return True \n else:\n return False", "def correct_tail(body, tail):\n a = body[-1]\n if a == tail:\n return True\n else:\n return False", "def correct_tail(b, t):\n return b[::-1][0] == t", "def correct_tail(body, tail):\n sub = len(body)\n sub =(body[::-sub])\n if sub == tail:\n return True\n else:\n return False\n", "def correct_tail(body, tail):\n for i in body: \n if tail == body[-1]:\n return True\n else: \n return False", "def correct_tail(body, tail):\n sub = body[-1]\n sub = str(sub)\n if sub == tail:\n return True\n else:\n return False", "correct_tail=lambda b, t: t==b[-1]", "def correct_tail(body, tail):\n # calculate the index of the last letter from the string\n index = len(body) - 1\n #assign the last letter of the string to the variable\n last_letter = body[index]\n #compare the last letter of the string with the tail\n if (last_letter == tail):\n return True\n else:\n return False", "import unittest\n\n\ndef correct_tail(body, tail):\n last_char_of_body = body[-1]\n return True if last_char_of_body == tail else False\n\n\nclass TestCorrectTail(unittest.TestCase):\n def test_should_return_false_when_last_of_char_of_body_is_not_equal_tail(self):\n self.assertFalse(correct_tail(body=\"Emu\", tail=\"m\"))\n\n def test_should_return_true_when_last_of_char_of_body_is_equal_tail(self):\n self.assertTrue(correct_tail(body=\"Fox\", tail=\"x\"))\n", "def correct_tail(body, tail):\n return True if body[len(body)-len(tail):len(body)] == tail else False", "def correct_tail(body, tail):\n sub = body[-1]\n \n if sub == tail :\n result = True\n else :\n result = False\n return result", "def correct_tail(body, tail):\n n=len(body)\n if body[n-1]==tail:\n return True\n else:\n return False", "def correct_tail(b,t):\n if t==b[len(b)-1]:\n return True\n else:\n return False", "def correct_tail(body, tail):\n #sub = body.substr(len(body)-len(tail.length)\n if body.endswith(tail):\n return True\n else:\n return False", "def correct_tail(body, tail):\n for char in body:\n if body[-1] == tail:\n return True\n \n else:\n return False", "def correct_tail(body, tail):\n return body[len(body) - 1] == tail", "def correct_tail(body, tail):\n if isinstance(body, str) and isinstance(tail, str) and len(tail) > 0:\n if body[-1] == tail:\n return True\n return False", "def correct_tail(body, tail):\n return body.endswith(tail[0])", "def correct_tail(body, tail):\n return list(body).pop() == tail", "def correct_tail(body, tail):\n sub = body[-1].lower()\n return True if sub == tail else False\n", "def correct_tail(body, tail):\n li=list(body)\n if li[-1]==tail:\n return True\n else:\n return False\n", "def correct_tail(body, tail):\n return body[-1] == tail\n# return body.endswith(tail)\n", "correct_tail = lambda b, t: b[-1:] is t or b is t", "def correct_tail(body, tail):\n sub = len(body) - len(tail)\n if body[-1] == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n sub = body[len(body)-1]\n if sub == tail[len(tail)-1]:\n return True\n else:\n return False", "def correct_tail(body, tail):\n end = body[-1]\n return tail == end", "correct_tail = lambda body, tail: body[-1:] == tail\n", "def correct_tail(body, tail):\n if tail == body[len(body)-1:]:\n return True\n else:\n return False", "def correct_tail(body, tail):\n last = body[-1]\n if tail == last:\n return True\n else:\n return False", "def correct_tail(body, tail):\n total = len(body)\n last_n = total - 1\n last = body[last_n]\n if last == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n if body[-1] == tail:\n return True\n return False\n \n# sub = body.substr(len(body)-len(tail.length)\n# if sub = tai:\n# return True\n# else:\n# return False\n", "def correct_tail(body, tail):\n sub = body[len(body)-1:body.rfind(tail)+1]\n if tail == sub:\n return True\n else:\n return False", "def correct_tail(body, tail):\n subs = body[len(body)-len(tail)]\n if subs == tail:\n return True\n else:\n return False", "correct_tail=lambda b,t:b[-1:]==t", "def correct_tail(body, tail):\n bool=False\n last=len(body)\n last=last-1\n if body[last]==tail:\n bool=True\n return bool\n", "def correct_tail(body, tail):\n sub = body[-1] \n if sub == tail:\n return True\n else:\n return False\nprint(correct_tail(\"Fox\", \"x\"))", "def correct_tail(body, tail):\n sub = body[-1]\n if sub == tail:\n return True\n else:\n return False\n\nprint(correct_tail('fox','x'))", "def correct_tail(body, tail):\n #sub = body.substr(len(body)-len(tail.length)\n #if sub == tail:\n # return True\n #else:\n # return False\n return body.endswith(tail)", "def correct_tail(body, tail):\n bodytail = body[-1]\n if bodytail == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n #sub = body.substr(len(body)-len(tail.length))\n sub = body[len(body) -1 ]\n if sub == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n sub = body[-1]\n if sub == tail[-1]:\n return True\n else:\n return False", "def correct_tail(body, tail):\n return body[-1] == tail if body else False", "def correct_tail(body, tail):\n# sub = body.substr(len(body)-len(tail.length)\n if body.lower()[-1]==tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n animal = []\n for letter in body:\n animal.append(letter)\n if animal[-1] == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n if body[len(body)-1] is tail:\n return True\n return False", "def correct_tail(body, tail):\n sub = body[-1]\n if body[-1] != tail:\n return False\n else:\n return True", "def correct_tail(body: str, tail: str):\n return True if body[-1].lower() == tail.lower() else False", "def correct_tail(body, tail):\n i = len(body)-2\n sub = body[:i:-1]\n print(sub)\n if sub == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n body.lower()\n tail.lower()\n a = body[-1]\n if a == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n if body[-1:] == tail[-1:]: return True\n else: return False ", "def correct_tail(body, tail):\n \"\"\"check that tail is the same as the last letter of the first argument\"\"\"\n return body[-1] == tail\n", "def correct_tail(body, tail):\n return 1 if body[-1] == tail else 0", "def correct_tail(body, tail):\n list = body.split()\n sub = list[0][-1]\n if sub == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n# sub = body.substr(len(body)-len(tail.length)\n# if sub == tail:\n# return True\n# else:\n# return False\n \n return tail == body[-1]\n", "import re\n\ndef correct_tail(body, tail):\n sub = re.sub(r\".\", \"\", body, len(body)-len(tail))\n if sub == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n b = [str(x) for x in body[::-1]]\n t = [str(y) for y in tail[::-1]]\n \n return True if b[0] == t[0] else False\n", "def correct_tail(body, tail):\n return True if body[len(body) - 1] is tail else False", "def correct_tail(body, tail):\n sub = str(body[-1])\n if sub == str(tail):\n return True\n else:\n return False", "def correct_tail(body, tail):\n if tail[len(tail)-1] == body[len(body)-1]:\n return(True)\n else:\n return(False)", "def correct_tail(body, tail):\n print(body)\n print(tail)\n #b=len(body[-1:])\n #print(b)\n #sub = body.substr(len(body)-len(tail.length)\n if body[-1:] == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n \n if body.endswith(tail[0]):\n return True\n else:\n return False", "correct_tail = lambda body, tail: True if body[-1] == tail else False", "def correct_tail(body, tail):\n sub = body[-1]\n if sub is tail:\n return True\n return False", "def correct_tail(body, tail):\n return tail is body[-1]", "def correct_tail(body, tail):\n sub = body.split()\n if sub[-1][-1] == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n \"\"\"\n sub = body[-1]\n if sub == tail:\n return True\n else:\n return False\n \"\"\"\n \n return body[-1] == tail ", "def correct_tail(body, tail):\n # sub = body.substr(len(body)-len(tail.length)\n # if sub = tai:\n # return True\n # else:\n # return False\n bodyList=list(body)\n return bodyList[-1] == tail", "def correct_tail(body, tail):\n index = [letter for letter in body]\n if index[-1] == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n if body == '':\n return False\n return body[-1] == tail\n", "def correct_tail(body, tail):\n sub = body[len(body)-len(tail)]\n return True if (sub==tail) else False", "def correct_tail(body, tail):\n let = body[-1]\n if let == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n sub = len(body)\n last = body[sub - 1]\n if last == tail:\n return True\n else:\n return False", "def correct_tail(body, tail):\n if body[-1] is not tail:\n return False\n else:\n return True", "def correct_tail(body, tail):\n a = len(body) - 1\n if tail == body[a]:\n return True\n else:\n return False\n", "def correct_tail(body, tail):\n if tail == body[-1::]:\n return True\n else:\n return False", "def correct_tail(body, tail):\n body_f = body[-1]\n if body_f == tail:\n return True \n else:\n return False", "def correct_tail(body, tail):\n return True if tail == body[-1::] else False"]
{"fn_name": "correct_tail", "inputs": [["Fox", "x"], ["Rhino", "o"], ["Meerkat", "t"], ["Emu", "t"], ["Badger", "s"], ["Giraffe", "d"]], "outputs": [[true], [true], [true], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,880
def correct_tail(body, tail):
d1ddf4a312c6d852cb853c28ec48884b
UNKNOWN
# Task John is a programmer. He treasures his time very much. He lives on the `n` floor of a building. Every morning he will go downstairs as quickly as possible to begin his great work today. There are two ways he goes downstairs: walking or taking the elevator. When John uses the elevator, he will go through the following steps: ``` 1. Waiting the elevator from m floor to n floor; 2. Waiting the elevator open the door and go in; 3. Waiting the elevator close the door; 4. Waiting the elevator down to 1 floor; 5. Waiting the elevator open the door and go out; (the time of go in/go out the elevator will be ignored) ``` Given the following arguments: ``` n: An integer. The floor of John(1-based). m: An integer. The floor of the elevator(1-based). speeds: An array of integer. It contains four integer [a,b,c,d] a: The seconds required when the elevator rises or falls 1 floor b: The seconds required when the elevator open the door c: The seconds required when the elevator close the door d: The seconds required when John walks to n-1 floor ``` Please help John to calculate the shortest time to go downstairs. # Example For `n = 5, m = 6 and speeds = [1,2,3,10]`, the output should be `12`. John go downstairs by using the elevator: `1 + 2 + 3 + 4 + 2 = 12` For `n = 1, m = 6 and speeds = [1,2,3,10]`, the output should be `0`. John is already at 1 floor, so the output is `0`. For `n = 5, m = 4 and speeds = [2,3,4,5]`, the output should be `20`. John go downstairs by walking: `5 x 4 = 20`
["def shortest_time(n, m, speeds):\n lift, open, close, walk = speeds\n return min(\n # taking the elevator\n abs(m - n) * lift + open + close + (n - 1) * lift + open,\n # walking\n (n - 1) * walk\n )", "def shortest_time(n, m, speeds):\n a, b, c, d = speeds\n elevator = (abs(m - n) + n - 1) * a + b * 2 + c\n walk = (n - 1) * d\n return min(elevator, walk)", "def shortest_time(n, m, speeds):\n elevator_speed, open_door, close_door, walk_speed = speeds\n elevator_time = (abs(m - n) + n - 1) * elevator_speed + open_door * 2 + close_door\n walk_time = (n - 1) * walk_speed\n return min(elevator_time, walk_time)", "def shortest_time(n,m,speeds):\n a,b,c,d = speeds\n return min((n-1)*d, a*(abs(m-n) + n-1) + 2*b + c)", "def shortest_time(n, m, speeds):\n move_lift, open_door, close_door, move_feet = speeds\n healthy = (n - 1) * move_feet\n lazy = abs(n - m) * move_lift + open_door + close_door + (n - 1) * move_lift + open_door\n return min(healthy, lazy)", "def shortest_time(n,m,speeds):\n return min([speeds[3]*(n-1),(abs(m-n)+n-1)*speeds[0]+2*speeds[1]+speeds[2]])", "def shortest_time(n,m,speeds):\n b = (n - 1 + max(m, n) - min(m, n)) * speeds[0] + speeds[2] + speeds[1]*2\n a = speeds[-1] * (n-1)\n return b if a > b else a", "def shortest_time(n, m, speeds):\n a, b, c, d = speeds\n return min(d * (n - 1), (abs(m - n) + n - 1) * a + 2 * b + c)", "def shortest_time(n, m, speeds):\n if n == 1:\n return 0\n else:\n move,open,close,walk=speeds\n elevator = abs(n-m)*move+open+close+move*(n-1)+open\n walking = walk*(n-1)\n return min(elevator, walking)"]
{"fn_name": "shortest_time", "inputs": [[5, 6, [1, 2, 3, 10]], [1, 6, [1, 2, 3, 10]], [5, 5, [1, 2, 3, 10]], [2, 2, [1, 2, 3, 10]], [2, 2, [2, 3, 4, 10]], [5, 4, [1, 2, 3, 10]], [5, 4, [2, 3, 4, 5]], [1, 6, [0, 0, 0, 0]], [1, 6, [0, 2, 0, 0]], [1, 6, [20, 0, 10, 0]]], "outputs": [[12], [0], [11], [8], [10], [12], [20], [0], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,725
def shortest_time(n, m, speeds):
867efa376d3633a93b81ebbfe63c8717
UNKNOWN
You've purchased a ready-meal from the supermarket. The packaging says that you should microwave it for 4 minutes and 20 seconds, based on a 600W microwave. Oh no, your microwave is 800W! How long should you cook this for?! ___ # Input You'll be given 4 arguments: ## 1. needed power The power of the needed microwave. Example: `"600W"` ## 2. minutes The number of minutes shown on the package. Example: `4` ## 3. seconds The number of seconds shown on the package. Example: `20` ## 4. power The power of your microwave. Example: `"800W"` ___ # Output The amount of time you should cook the meal for formatted as a string. Example: `"3 minutes 15 seconds"` Note: the result should be rounded up. ``` 59.2 sec --> 60 sec --> return "1 minute 0 seconds" ``` ___ ## All comments/feedback/translations appreciated.
["import math\n\ndef cooking_time(needed_power, minutes, seconds, power):\n t = math.ceil((60 * minutes + seconds) * int(needed_power[:-1]) / int(power[:-1]))\n return '%d minutes %d seconds' %(t // 60, t - t // 60 * 60)", "cooking_time=lambda n,m,s,p:'{} minutes {} seconds'.format(*divmod(-(-(m*60+s)*int(n[:-1])//int(p[:-1])),60))", "from math import ceil\n\n\ndef cooking_time(n_pow, n_min, n_sec, pow):\n m, s = divmod(ceil((60 * n_min + n_sec) * int(n_pow[:-1]) / int(pow[:-1])), 60)\n return f\"{m} minutes {s} seconds\"", "import math\n\ndef cooking_time(needed_power, minutes, seconds, power):\n needed_power = int(needed_power[:-1])\n power = int(power[:-1])\n time = minutes * 60 + seconds\n res_time = math.ceil(time * needed_power / power)\n return \"{0} minutes {1} seconds\".format(res_time // 60, res_time % 60)\n", "from math import ceil\ndef cooking_time(needed_power, minutes, seconds, power):\n q = float(needed_power[:-1]) / float(power[:-1])\n t = minutes * 60 + seconds\n return '{} minutes {} seconds'.format(*divmod(ceil(q * t), 60))", "from math import ceil\n\n\ndef cooking_time(needed_power, minutes, seconds, power):\n total_seconds = ceil(int(needed_power[:-1]) * (minutes * 60 + seconds) / int(power[:-1]))\n m, s = total_seconds // 60, total_seconds % 60\n return \"{} minutes {} seconds\".format(m, s)", "from math import ceil\ndef cooking_time(n_p,m,s,p):\n n_p,p=map(int,(n_p[:-1],p[:-1]))\n return \"{} minutes {} seconds\".format(*divmod(ceil((m*60+s)/p*n_p),60))", "from math import ceil\n\ndef cooking_time(needed_power, minutes, seconds, power):\n totsec=minutes*60+seconds\n nd_pw,pw=int(needed_power.split('W')[0]),int(power.split('W')[0])\n res=ceil(nd_pw/pw*totsec)\n return '{:g} minutes {} seconds'.format(res//60,ceil(res-(res//60)*60))", "import math\ndef cooking_time(needed_power, minutes, seconds, power):\n in_seconds = 60 * minutes + seconds\n increase = int(needed_power[:-1]) / int(power[:-1])\n new_seconds = in_seconds * increase\n output_minutes = int(new_seconds/60)\n output_seconds = new_seconds % 60\n if math.ceil(output_seconds) == 60:\n output_seconds = 0\n output_minutes += 1\n return str(math.ceil(output_minutes)) + ' minutes ' + str(math.ceil(output_seconds)) + ' seconds'", "from math import ceil\n\ndef cooking_time(n,m,s,p):\n return '{0} minutes {1} seconds'.format(*divmod(ceil((m*60+s)*int(n[:-1])/int(p[:-1])),60))"]
{"fn_name": "cooking_time", "inputs": [["600W", 4, 20, "800W"], ["800W", 3, 0, "1200W"], ["100W", 8, 45, "50W"], ["7500W", 0, 5, "600W"], ["450W", 3, 25, "950W"], ["21W", 64, 88, "25W"], ["83W", 61, 80, "26W"], ["38W", 95, 22, "12W"]], "outputs": [["3 minutes 15 seconds"], ["2 minutes 0 seconds"], ["17 minutes 30 seconds"], ["1 minutes 3 seconds"], ["1 minutes 38 seconds"], ["55 minutes 0 seconds"], ["199 minutes 0 seconds"], ["302 minutes 0 seconds"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,494
def cooking_time(needed_power, minutes, seconds, power):
b85937af7bbb58b31d470f98cd23b72b
UNKNOWN
In this Kata, we are going to determine if the count of each of the characters in a string can be equal if we remove a single character from that string. For example: ``` solve('abba') = false -- if we remove any character, the count of each character will not be equal. solve('abbba') = true -- if we remove one b, the count of each character becomes 2. solve('aaaa') = true -- if we remove one character, the remaining characters have same count. solve('wwwf') = true -- if we remove f, the remaining letters have same count. ``` More examples in the test cases. Empty string is not tested. Good luck!
["from collections import Counter\n\ndef solve(s):\n return any(len(set(Counter(s.replace(c, '', 1)).values())) == 1 for c in s)", "from collections import Counter\n\ndef solve(s):\n c = Counter(s).values()\n cVal, mi, ma = Counter(c), min(c), max(c)\n return len(cVal) <= 2 and (len(cVal) == 1 and (1 in cVal or 1 in cVal.values()) \n or mi == cVal[mi] == 1\n or mi == ma-1 and cVal[ma] == 1)", "from collections import Counter\n\ndef solve(s):\n return any(len(set(Counter(s[:i] + s[i+1:]).values())) == 1 for i in range(len(s)))", "def solve(s):\n a = [s.replace(s[y], '', 1) for y,x in enumerate(s)]\n return any(len(sorted(set([x.count(c) for c in x]))) == 1 for x in a)", "from collections import Counter\n\n\ndef solve(stg):\n c = tuple(Counter(stg).values())\n mn, mx = min(c), max(c)\n l, cmx = len(c), c.count(mx)\n return (1 in (l, mx)) or (mx - mn == cmx == 1) or (l - cmx == mn == 1)\n", "def solve(s):\n s = list(s)\n for i in range(len(s)):\n temp = s.copy()\n temp.pop(i)\n if all(temp.count(k) == temp.count(temp[0]) for k in temp) : return True\n return False", "from collections import Counter\n\ndef solve(s):\n c = Counter(s)\n l, cc, mi, ma, su = len(c), Counter(c.values()), min(c.values()), max(c.values()), sum(c.values())\n return (\n len(c) == 1\n or su - ma * l == 1\n or mi == 1 == su - ma * l + ma\n or cc[ma] == 1 == ma - mi\n )", "from collections import Counter\n\ndef solve(s):\n frequencies = [x[1] for x in Counter(s).most_common()]\n return (\n len(frequencies) == 1 or\n len(set(frequencies[:-1])) == 1 and frequencies[-1] == 1 or\n frequencies[0] == frequencies[1] + 1 and len(set(frequencies[1:])) == 1)", "from collections import Counter\n\ndef solve(s):\n c = Counter(s)\n for key in c.keys():\n temp = Counter(key)\n check = c - temp\n if len(set(check.values())) < 2:\n return True\n return False"]
{"fn_name": "solve", "inputs": [["aaaa"], ["abba"], ["abbba"], ["aabbcc"], ["aaaabb"], ["aabbccddd"], ["aabcde"], ["abcde"], ["aaabcde"], ["abbccc"]], "outputs": [[true], [false], [true], [false], [false], [true], [true], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,073
def solve(s):
33c9727ed9aca0ea96edad581aea7064
UNKNOWN
# Task A cake is sliced with `n` straight lines. Your task is to calculate the maximum number of pieces the cake can have. # Example For `n = 0`, the output should be `1`. For `n = 1`, the output should be `2`. For `n = 2`, the output should be `4`. For `n = 3`, the output should be `7`. See the following image to understand it: ![](https://cdn2.scratch.mit.edu/get_image/project/92275349_500x400.png?v=1450672809.79) # Input/Output - `[input]` integer `n` `0 ≤ n ≤ 10000` - `[output]` an integer The maximum number of pieces the sliced cake can have.
["def cake_slice(n):\n return (n ** 2 + n + 2) // 2", "def cake_slice(n):\n return 0.5*n**2+0.5*n+1", "def cake_slice(n):\n return (n**2 + n) // 2 + 1", "cake_slice = lambda n: sum(range(n + 1)) + 1", "def cake_slice(n):\n #coding and coding...\n sum = 1\n for i in range(n):\n sum += i+1\n return sum", "def cake_slice(n):\n return (n*(n + 1) + 2)/2\n #coding and coding...\n", "cake_slice=lambda n: (n+1)*n/2+1", "def cake_slice(n):\n return (n/2)*(1+n)+1", "def cake_slice(n):\n if n == 0:\n return 1\n else:\n return 2 + sum(iter(range(2,n+1)))", "def cake_slice(n):\n return -~(n * -~n >> 1)"]
{"fn_name": "cake_slice", "inputs": [[0], [1], [2], [3], [10]], "outputs": [[1], [2], [4], [7], [56]]}
INTRODUCTORY
PYTHON3
CODEWARS
652
def cake_slice(n):
9897f6d53a1fffa286bc3c2937150e44
UNKNOWN
## A square of squares You like building blocks. You especially like building blocks that are squares. And what you even like more, is to arrange them into a square of square building blocks! However, sometimes, you can't arrange them into a square. Instead, you end up with an ordinary rectangle! Those blasted things! If you just had a way to know, whether you're currently working in vain… Wait! That's it! You just have to check if your number of building blocks is a _perfect square_. ## Task Given an integral number, determine if it's a [square number](https://en.wikipedia.org/wiki/Square_number): > In mathematics, a __square number__ or __perfect square__ is an integer that is the square of an integer; in other words, it is the product of some integer with itself. The tests will _always_ use some integral number, so don't worry about that in dynamic typed languages. ### Examples ``` -1 => false 0 => true 3 => false 4 => true 25 => true 26 => false ```
["import math\ndef is_square(n):\n return n > -1 and math.sqrt(n) % 1 == 0;", "import math\n\ndef is_square(n): \n\n if n < 0:\n return False\n\n sqrt = math.sqrt(n)\n \n return sqrt.is_integer()", "def is_square(n): \n return n >= 0 and (n**0.5) % 1 == 0", "import math\ndef is_square(n): \n try:\n return math.sqrt(n).is_integer()\n except ValueError:\n return False", "def is_square(n): \n if n>=0:\n if int(n**.5)**2 == n:\n return True\n return False", "import math\ndef is_square(n):\n return n >= 0 and int(math.sqrt(n)) ** 2 == n", "from math import sqrt\n\ndef is_square(n): \n return n>=0 and sqrt(n).is_integer()", "from math import sqrt\ndef is_square(n): \n if n<0:\n return False\n count=0\n m=int(sqrt(n))\n if m*m==n:\n count=1\n if count==1:\n return True\n else :\n return False", "import math\n\ndef is_square(n):\n if n < 0:\n return False\n r = math.sqrt(n)\n r = math.floor(r)\n return r * r == n", "import math\n\ndef is_square(n):\n if n < 0:\n return False\n return (int(math.sqrt(n)) - math.sqrt(n)) == 0"]
{"fn_name": "is_square", "inputs": [[-1], [25], [26]], "outputs": [[false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,199
def is_square(n):
d032402dd2bb7db090f52ea4572bf408
UNKNOWN
Consider a game, wherein the player has to guess a target word. All the player knows is the length of the target word. To help them in their goal, the game will accept guesses, and return the number of letters that are in the correct position. Write a method that, given the correct word and the player's guess, returns this number. For example, here's a possible thought process for someone trying to guess the word "dog": ```cs CountCorrectCharacters("dog", "car"); //0 (No letters are in the correct position) CountCorrectCharacters("dog", "god"); //1 ("o") CountCorrectCharacters("dog", "cog"); //2 ("o" and "g") CountCorrectCharacters("dog", "cod"); //1 ("o") CountCorrectCharacters("dog", "bog"); //2 ("o" and "g") CountCorrectCharacters("dog", "dog"); //3 (Correct!) ``` ```python count_correct_characters("dog", "car"); #0 (No letters are in the correct position) count_correct_characters("dog", "god"); #1 ("o") count_correct_characters("dog", "cog"); #2 ("o" and "g") count_correct_characters("dog", "cod"); #1 ("o") count_correct_characters("dog", "bog"); #2 ("o" and "g") count_correct_characters("dog", "dog"); #3 (Correct!) ``` The caller should ensure that the guessed word is always the same length as the correct word, but since it could cause problems if this were not the case, you need to check for this eventuality: ```cs //Throw an InvalidOperationException if the two parameters are of different lengths. ``` ```python #Raise an exception if the two parameters are of different lengths. ``` You may assume, however, that the two parameters will always be in the same case.
["def count_correct_characters(c, g):\n if len(c) != len(g): raise Exception('Error')\n return sum(1 for i,j in zip(c,g) if i==j)", "def count_correct_characters(s, t):\n assert len(s) == len(t)\n return sum(a == b for a, b in zip(s, t))", "def count_correct_characters(correct, guess):\n if len(correct) == len(guess):\n return sum(1 for cc, cg in zip(correct, guess) if cc == cg)\n else:\n raise Exception", "def count_correct_characters(correct, guess): \n if len(correct) != len(guess):\n raise Error('The two lengths are not the same')\n return sum(correct[i] == guess[i] for i in range(len(correct)))", "def count_correct_characters(correct, guess):\n if len(correct) == len(guess):\n return sum(c == g for c, g in zip(correct, guess))\n else:\n raise Exception(\"guess contains the wrong number of characters\")", "def count_correct_characters(correct, guess):\n if len(correct) != len(guess):\n raise ValueError('Error: different word lengths')\n return sum(a == b for a,b in zip(correct, guess))", "def count_correct_characters(correct, guess):\n # Code here\n print(correct, guess)\n if len(correct )!=len(guess ):return error\n\n a=list( (correct))\n b=list( (guess))\n print(a,b) \n c=0\n for i in range(len(a)):\n if a[i] == b[i]:\n c=c+1\n return c", "def count_correct_characters(correct, guess):\n if len(correct)!=len(guess):raise Exception()\n return sum(l1==l2 for l1,l2 in zip(correct,guess))", "def count_correct_characters(correct, guess):\n if len(correct) != len(guess):\n raise Exception('Wrong length')\n res = sum(1 for a, b in zip(correct, guess) if a == b)\n return res", "def count_correct_characters(correct, guess):\n if len(correct) != len(guess): raise Exception\n return sum(a == b for a,b in zip(correct, guess))\n", "def count_correct_characters(correct, guess):\n assert len(correct)==len(guess)\n \n return len([a for a,b in zip(correct, guess) if a==b])", "def count_correct_characters(a, b):\n return len([i for i in range(len(a)) if a[i]==b[i]]) if len(a)==len(b) else error", "def count_correct_characters(a, b):\n assert(len(a) == len(b))\n return sum(a[i] == b[i] for i in range(len(a)))", "def count_correct_characters(correct, guess):\n num = 0\n if len(correct) != len(guess):\n raise Exception(\"The lengths are not the same\")\n for n in range(len(correct)):\n if list(correct)[n] == list(guess)[n]:\n num += 1\n return num\n\n", "def count_correct_characters(correct, guess):\n if len(correct)!=len(guess):\n raise Exception()\n return sum(c==g for c,g in zip(correct,guess))", "def count_correct_characters(correct, guess):\n if len(correct) != len(guess):\n raise Exception\n return sum(i==j for i,j in zip(correct,guess))", "def count_correct_characters(correct, guess):\n if len(correct) != len(guess):\n raise 'Error!'\n else:\n count = 0\n for i, x in enumerate(correct):\n for j, y in enumerate(guess):\n if i == j and x == y:\n count += 1\n return count\n \n", "def count_correct_characters(correct, guess):\n if len(correct)!=len(guess):\n raise ValueError\n else:\n return sum(1 for x,y in zip(correct, guess) if x==y)", "def count_correct_characters(correct, guess):\n if len(correct) != len(guess):\n raise Exception()\n count = 0\n for i in range(len(guess)):\n if correct[i] == guess[i]:\n count += 1\n return count", "def count_correct_characters(c, g):\n if len(c) != len(g): raise ValueError('Is this the error you wanted?')\n else: return sum([1 for i in zip(c,g) if i[0]==i[1]])\n"]
{"fn_name": "count_correct_characters", "inputs": [["dog", "car"], ["dog", "god"], ["dog", "cog"], ["dog", "cod"], ["dog", "bog"], ["dog", "dog"], ["abcde", "abcde"], ["same", "same"], ["z", "z"]], "outputs": [[0], [1], [2], [1], [2], [3], [5], [4], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,813
def count_correct_characters(correct, guess):
4d199541c9017ea4893fec6f40e83dc7
UNKNOWN
After a hard quarter in the office you decide to get some rest on a vacation. So you will book a flight for you and your girlfriend and try to leave all the mess behind you. You will need a rental car in order for you to get around in your vacation. The manager of the car rental makes you some good offers. Every day you rent the car costs $40. If you rent the car for 7 or more days, you get $50 off your total. Alternatively, if you rent the car for 3 or more days, you get $20 off your total. Write a code that gives out the total amount for different days(d).
["def rental_car_cost(d):\n result = d * 40\n if d >= 7:\n result -= 50\n elif d >= 3:\n result -= 20\n return result", "def rental_car_cost(d):\n return d * 40 - (d > 2) * 20 - (d > 6) * 30", "def rental_car_cost(d):\n discount = 0\n if d >= 7:\n discount = 50\n elif d >= 3:\n discount = 20\n return d * 40 - discount", "def rental_car_cost(d):\n if d >= 7: return d * 40 - 50\n elif d >= 3: return d * 40 - 20\n return d * 40", "def rental_car_cost(d):\n return 40 * d - ((50, 20)[d < 7], 0)[d < 3]", "def rental_car_cost(d):\n return d * 40 - 20 * (d >= 3) - 30 * (d >= 7)", "def rental_car_cost(d):\n total = d*40\n if d >= 7:\n total -= 50\n else:\n if d >= 3:\n total -= 20\n \n return total", "def rental_car_cost(d):\n total_cost = d * 40\n if d >= 7:\n total_cost -= 50\n elif d >= 3:\n total_cost -= 20\n return total_cost", "def rental_car_cost(d):\n discount = 50 if d > 6 else 20 if d > 2 else 0 \n return d * 40 - discount", "def rental_car_cost(d):\n return d*40 - 50 if d >= 7 else d*40 -20 if d >= 3 else d*40 ", "def rental_car_cost(d):\n return 40*d - 20*(2<d<7) - 50*(d>6) ", "def rental_car_cost(d):\n return 40*d - (50 if d >= 7 else 20 if d >= 3 else 0)", "def rental_car_cost(d):\n x = d * 40\n if d >= 7: return x - 50\n return x - 20 if d >= 3 else x", "def rental_car_cost(d):\n # your code\n total = d * 40\n if d >= 3 and d < 7:\n total -= 20\n if d >= 7:\n total -= 50\n return total", "def rental_car_cost(d):\n total = 40*d\n return total if d < 3 else total-20 if d < 7 else total-50", "def rental_car_cost(d):\n r = 50 if d >= 7 else 20 if d >= 3 else 0\n return d * 40 - r", "def rental_car_cost(d):\n # your code\n if d >= 7:\n return d * 40 - 50\n elif d >= 3:\n return d * 40 - 20\n else:\n return d * 40", "def rental_car_cost(d):\n return d * 40 - (50 if d > 6 else 20 if d > 2 else 0) ", "rental_car_cost = lambda d: d * 40 - (50 if d > 6 else 20 if d > 2 else 0)", "def rental_car_cost(d):\n x = 40\n if d < 3: \n return d * x\n elif d < 7: \n return (x * d) - 20\n else: \n return (x * d) - 50 ", "def rental_car_cost(d):\n total = 40 * d\n if d > 6:\n total = total - 50\n if d > 2 and d < 7:\n total = total - 20\n return total", "rental_car_cost = lambda d: 40*d-[0,20,50][(d>=3)+(d>=7)]", "def rental_car_cost(d):\n return 40*d-20*(7>d>=3)-50*(d>=7)", "def rental_car_cost(d):\n return d * 40 - (d >= 3) * 20 - (d >= 7) * 30", "rental_car_cost=lambda d: 40*d - (50 if d>6 else 20 if d>2 else 0)", "def rental_car_cost(d):\n return d * 40 - (d > 6) * 50 - (7 > d > 2) * 20", "def rental_car_cost(d):\n cost = 40\n if int(d)<3:\n cost = cost * d\n elif int(d)>=3 and int(d)<7:\n cost = cost * d \n cost = cost - 20\n elif int(d)>=7:\n cost = cost * d\n cost = cost -50\n return cost", "def rental_car_cost(d):\n return d * 40 - (d >= 7) * 50 - (3 <= d < 7) * 20", "def rental_car_cost(d):\n return d * 40 - (20 if d >= 3 else 0) - (30 if d >= 7 else 0)", "def rental_car_cost(d):\n # your code\n return 40*d-20*(d<7 and d>=3)-50*(d>=7)", "def rental_car_cost(d):\n return (d * 40 - 50)*(d>=7) or (d * 40 - 20)*(d>=3) or d * 40", "rental_car_cost=lambda d: d*40 if d < 3 else d*40-20 if d < 7 else d*40-50", "def rental_car_cost(d):\n return 40 * d - 20 * (d >= 3) - 30 * (d >= 7)", "def rental_car_cost(days: int) -> int:\n \"\"\"\n Get the total amount for different days(d) according to the rules:\n - every day you rent the car costs $40\n - 7 or more days, you get $50 off your total\n - 3 or more days, you get $20 off your total\n \"\"\"\n return days * 40 - {days >= 3: 20, days >= 7: 50}.get(True, 0)", "def rental_car_cost(d):\n return d * 40 if d < 3 else d * 40 - 20 if 2 < d < 7 else d * 40 - 50", "def rental_car_cost(d):\n if d < 3:\n x = 0\n elif d < 7:\n x = 20\n else:\n x = 50\n return d*40-x", "def rental_car_cost(d):\n return 40 * d - 50 if d > 6 else 40 * d - 20 if 3 <= d <= 6 else 40 * d", "def rental_car_cost(d):\n return d * 40 if d <= 2 else d * 40 -20 if d <= 6 else d * 40 - 50", "def rental_car_cost(d):\n price = d * 40\n if d >= 7:\n price -= 50\n elif d >= 3 and d < 7:\n price -= 20\n return price", "def rental_car_cost(d):\n # your code\n if(d==1):\n return 40\n elif(d>=7):\n a=d*40\n return a-50\n elif(3<=d<7):\n a=d*40\n return a-20\n else:\n return d*40", "def rental_car_cost(d):\n \n if d >= 1 and d < 3:\n return 40 * d\n \n if d >= 3 and d < 7:\n return 40 * d - 20\n \n else:\n return 40 * d - 50\n \n", "def rental_car_cost(days):\n if days >= 7:\n discount = 50\n elif days >= 3:\n discount = 20\n else:\n discount = 0\n return days * 40 - discount", "def rental_car_cost(d):\n rent_cost = d*40\n if d >= 7:\n rent_cost-=50\n elif d >= 3:\n rent_cost-=20\n return rent_cost \n\n", "def rental_car_cost(d):\n count =40\n if d >= 1 and d<3:\n count = count*d\n elif d>=3 and d<7:\n count = count*d - 20\n elif d >=7:\n count = count*d - 50\n return count", "def rental_car_cost(d):\n \n if d >= 7:\n tot = 40 * d - 50\n elif d >= 3:\n tot = 40 * d - 20\n else:\n tot = 40 * d\n return tot", "def rental_car_cost(d):\n\n sum = 40*d\n \n if d >= 7:\n sum = sum - 50\n \n elif d >= 3:\n sum = sum - 20\n \n return sum", "def rental_car_cost(d):\n suma = d * 40\n if d < 3:\n return suma\n elif d >= 3 and d < 7:\n return suma - 20\n elif d >= 7:\n return suma - 50", "def rental_car_cost(d):\n _1_day = d*40\n if d >= 7:\n _1_day -=50\n elif d >= 3:\n _1_day -=20\n return _1_day", "def rental_car_cost(d):\n result = 40 * d\n if 3 <= d < 7:\n result -= 20\n elif d >= 7:\n result -= 50\n return result\n", "def rental_car_cost(d):\n print(d)\n if d == 1 or d == 2:\n return 40 * d\n elif 3<= d < 7:\n return d * 40- 20 \n else:\n return d * 40 - 50", "def rental_car_cost(d):\n return (d * 40) - (0 if d < 3 or d > 6 else 20) - (0 if d < 7 else 50)", "def rental_car_cost(d):\n r = d * 40\n if d>= 7:\n r -= 50\n elif d >=3:\n r -= 20\n return r", "def rental_car_cost(d):\n if 0 < d < 3: return 40*d\n if 2 < d < 7: return 40*d - 20\n if d > 6: return 40*d - 50\n \n \n \n# Every day you rent the car costs $40.\n# If you rent the car for 7 or more days,\n# you get $50 off your total. \n# Alternatively, if you rent the car for 3 or more days,\n# you get $20 off your total.\n\n# Write a code that gives out the total amount for different days(d).\n\n", "def rental_car_cost(days):\n return days * 40 - (20 * (days >= 3 and days < 7)) - (50 * (days >= 7))", "def rental_car_cost(d):\n amount = 40 * d\n if d >= 7:\n amount -= 50\n elif d >= 3:\n amount -= 20\n return amount", "def rental_car_cost(d):\n print(d)\n total = 40*d\n if d >= 7:\n return total - 50\n elif d < 3:\n return total\n return total - 20\n", "def rental_car_cost(d):\n return 40 * d - [0, 20, 50][(d > 2) + (d > 6)]", "def rental_car_cost(d):\n if 0 < d < 3:\n return d * 40\n elif 2 < d < 7:\n return d * 40 - 20\n else:\n return 40 * d -50", "def rental_car_cost(d):\n daily_cost = 40 * d\n if d >= 7:\n daily_cost -= 50\n elif d >= 3:\n daily_cost -= 20\n else:\n daily_cost -= 0\n return daily_cost", "def rental_car_cost(d):\n price = d * 40\n \n return price if d < 3 else price - 50 if d >= 7 else price - 20", "def rental_car_cost(d):\n rent = d*40\n if d>=7:\n rent-=50\n elif d>=3 and d<7:\n rent-=20\n return rent", "def rental_car_cost(d):\n days = d * 40\n if d >= 7:\n days -= 50\n if d >= 3 and d < 7:\n days -= 20\n return days", "def rental_car_cost(d):\n print(d)\n if d<3:\n return d*40\n if 3<=d<7:\n return d*40-20\n return d*40-50", "def rental_car_cost(d):\n base = d * 40\n if d >= 7:\n return base - 50\n elif d >= 3:\n return base - 20\n else:\n return base\n\n", "def rental_car_cost(d):\n if 3<=d<7: return 40*d-20\n if d >= 7: return 40*d-50\n else:\n return 40*d", "def rental_car_cost(d):\n if d < 3:\n return 40 * d\n elif d >= 7:\n return 40 * d - 50\n else:\n return 40 * d - 20", "def rental_car_cost(d):\n total = d * 40\n if 3 <= d < 7: total -= 20\n if 7 <= d: total -= 50\n return total", "def rental_car_cost(d):\n cpd = 40\n if d < 3:\n return d * cpd\n elif d < 7:\n return (d * cpd) - 20\n else:\n return (d * cpd) - 50", "def rental_car_cost(d):\n return (d*40)-50 if d >= 7 else (d*40)-20 if d < 7 and d >= 3 else d*40", "def rental_car_cost(d):\n print(d,\"days\",d*40)\n return (d*40)-50 if d >= 7 else (d*40)-20 if d < 7 and d >= 3 else (d*40)", "def rental_car_cost(d):\n x=40*d\n if d>=3:\n if d>=7:return x-50\n return x-20\n return x\n", "def rental_car_cost(d):\n if d < 3:\n return d * 40\n elif 7 > d >= 3:\n return (d * 40) - 20\n elif d >= 7:\n return (d*40) - 50", "def rental_car_cost(d):\n t = d * 40\n if d >= 3 and d < 7:\n t = t - 20\n if d >= 7:\n t = t - 50\n return t", "def rental_car_cost(d):\n if d <7:\n if d >= 3:\n return d*40-20\n return d*40 \n return d*40-50", "def rental_car_cost(d):\n cost = 40 * d\n print(d)\n if d >= 3 and not 7 <= d:\n cost -= 20\n if d >= 7:\n cost -= 50\n \n return cost \n \n", "def rental_car_cost(d):\n p = d*40\n if d<3:\n return p\n elif d <7:\n return p-20\n else:\n return p-50", "def rental_car_cost(d):\n return 40 * d - (d > 6) * 30 - (d > 2) * 20", "def rental_car_cost(d):\n if d>=7:\n return (d*40)-50\n if 6 <= d or d >=3:\n return (d*40)-20\n else:\n return (d*40)", "def rental_car_cost(d):\n prod = d * 40\n return prod - 30 * (d >= 7) - 20 * (d >= 3)", "def rental_car_cost(d):\n if 7>d>=3:\n return 40*d-20\n elif d>=7:\n return 40*d-50\n else:\n return 40*d\n \n", "def rental_car_cost(d):\n #TRUMP SUCKS\n return d*40 if d<3 else (d*40)-20 if 3<=d<7 else (d*40)-50", "def rental_car_cost(d):\n car = 40\n if d < 3:\n return car * d\n if 3 <= d < 7:\n return car * d - 20\n if 7 <= d:\n return car * d - 50", "def rental_car_cost(d):\n print(d)\n if d <= 2:\n return 40 * d\n if 2 < d < 7:\n return 40 * d - 20\n if d >= 7:\n return d * 40 -50# your code", "def rental_car_cost(d):\n if d >= 3 and d<7:\n total = d * 40 - 20\n return total\n elif d >= 7:\n total = d * 40 - 50\n return total\n else:\n total = d * 40\n return d * 40\n # your code\n", "rental_car_cost = lambda d: d*40 - (d > 6 and 50 or d > 2 and 20 or 0)", "def rental_car_cost(d):\n if d < 3:\n return 40 * d\n else:\n return 40 * d - 20 if d < 7 else 40 * d - 50\n", "def rental_car_cost(d):\n daily = d * 40\n if d < 7 and d > 2:\n return daily - 20\n elif d > 6:\n return daily - 50\n else:\n return daily\n", "def rental_car_cost(d):\n if d < 3:\n a = d * 40\n return a\n elif d >= 3 and d < 7:\n b = d * 40 - 20\n return b\n elif d >= 7:\n c = d * 40 - 50\n return c", "def rental_car_cost(d):\n return (40 * d) - 50 * (d > 6) if d > 6 else (40 * d) - 20 * (d > 2)", "def rental_car_cost(d):\n if d > 2 and d <7:\n return(40*d-20)\n if d >6:\n return(40*d-50)\n else:\n return 40*d", "def rental_car_cost(d):\n off = 50 if d > 6 else 20 if d > 2 else 0\n return 40 * d - off", "def rental_car_cost(d):\n dayCost = 40;\n \n if d >= 3 and d < 7:\n return (dayCost * d) - 20;\n elif d >= 7:\n return (dayCost * d) - 50;\n return d * dayCost;", "def rental_car_cost(d):\n if d >= 7:\n return (d*40) - 50\n elif 3 <= d <= 6:\n return (d*40) - 20\n return d*40", "def rental_car_cost(d):\n daily_cost = (d * 40)\n if d >= 3 and d < 7:\n #three_day_reduced_cost = daily_cost - 20\n return daily_cost - 20\n elif d >= 7:\n # seven_day_reduced_cost = daily_cost - 50\n return daily_cost - 50 \n else:\n return daily_cost", "def rental_car_cost(d):\n fuckthis = 40*d\n if 3 <= d < 7:\n return fuckthis - 20\n elif d >= 7:\n return fuckthis - 50\n else:\n return fuckthis", "def rental_car_cost(d):\n if d < 3:\n return d * 40\n elif d < 7 and d >= 3:\n return (d * 40) - 20\n elif d >= 7:\n return (d * 40) - 50", "def rental_car_cost(d: int) -> int:\n \"\"\"Gives out the total amount for different count days of rent car\"\"\"\n cost = d * 40\n if d >= 7:\n return cost - 50\n elif d >= 3:\n return cost - 20\n else:\n return cost", "def discount(d):\n if d >= 7:\n return 50\n elif d >= 3:\n return 20\n return 0\n\n\ndef rental_car_cost(d):\n return d*40 - discount(d)\n", "def rental_car_cost(d):\n if d<3:\n return 40*d\n elif d in range(3,7):\n return 40*d-20\n else:\n return 40*d-50", "def rental_car_cost(d):\n x = d * 40\n if d >= 7:\n x = x - 50\n elif d in range(3,7):\n x = x - 20\n return x"]
{"fn_name": "rental_car_cost", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]], "outputs": [[40], [80], [100], [140], [180], [220], [230], [270], [310], [350]]}
INTRODUCTORY
PYTHON3
CODEWARS
14,231
def rental_car_cost(d):
92d37a57ecde88bebff10408a544873c
UNKNOWN
# Bubblesort Algorithm ## Overview The Bubblesort Algorithm is one of many algorithms used to sort a list of similar items (e.g. all numbers or all letters) into either ascending order or descending order. Given a list (e.g.): ```python [9, 7, 5, 3, 1, 2, 4, 6, 8] ``` To sort this list in ascending order using Bubblesort, you first have to compare the first two terms of the list. If the first term is larger than the second term, you perform a swap. The list then becomes: ```python [7, 9, 5, 3, 1, 2, 4, 6, 8] # The "9" and "7" have been swapped because 9 is larger than 7 and thus 9 should be after 7 ``` You then proceed by comparing the 2nd and 3rd terms, performing a swap *when necessary*, and then the 3rd and 4th term, then the 4th and 5th term, etc. etc. When you reach the end of the list, it is said that you have completed **1 complete pass**. ## Task Given an array of integers, your function `bubblesortOnce`/`bubblesort_once`/`BubblesortOnce` (or equivalent, depending on your language's naming conventions) should return a *new* array equivalent to performing exactly **1 complete pass** on the original array. Your function should be pure, i.e. it should **not** mutate the input array.
["def bubblesort_once(l):\n l = l[:]\n for i in range(len(l)-1):\n if l[i] > l[i+1]:\n l[i], l[i+1] = l[i+1], l[i]\n return l", "def bubblesort_once(L):\n if len(L)<=1 : return L\n if L[0]<=L[1]: return [L[0]] + bubblesort_once(L[1:])\n return [L[1]] + bubblesort_once([L[0]]+L[2:])", "def bubblesort_once(lst):\n result = lst[:]\n for i in range(len(result) - 1):\n if result[i] > result[i+1]:\n result[i], result[i+1] = result[i+1], result[i]\n return result", "import copy\n\ndef bubblesort_once(l):\n res = copy.copy(l)\n for i in range(len(res)-1):\n if res[i] > res[i+1]:\n res[i], res[i+1] = res[i+1], res[i]\n return res", "def bubblesort_once(l):\n values = l[:]\n for i in range(0, len(values) - 1):\n first = values[i]\n second = values[i + 1]\n if(first > second ):\n values[i + 1] = first\n values[i] = second\n return values\n", "def bubblesort_once(arr):\n\n new_arr = arr.copy()\n for i in range(len(new_arr)-1):\n if new_arr[i]>new_arr[i+1]:\n new_arr[i], new_arr[i+1] = new_arr[i+1], new_arr[i]\n return new_arr", "def bubblesort_once(lst):\n arr = lst[:]\n for i in range(len(arr)-1):\n arr[i], arr[i+1] = sorted([arr[i], arr[i+1]])\n return arr", "def bubblesort_once(l):\n if len(l) < 2: return l[:]\n \n lst, mx = [], l[0]\n for v in l[1:]:\n if mx<v: mx,v = v,mx\n lst.append(v)\n lst.append(mx)\n return lst", "def bubblesort_once(l):\n for i in range(len(l)-1):\n if l[i] > l[i+1]:\n l = l[:i] + [ l[i+1] ] + [ l[i] ] + l[i+2::]\n return l", "def bubblesort_once(l):\n output = [i for i in l]\n for i in range(len(output)-1):\n output[i], output[i+1] = min(output[i], output[i+1]), max(output[i], output[i+1])\n return output"]
{"fn_name": "bubblesort_once", "inputs": [[[9, 7, 5, 3, 1, 2, 4, 6, 8]], [[1, 2]], [[2, 1]], [[1, 3]], [[3, 1]], [[24, 57]], [[89, 36]], [[1, 2, 3]], [[2, 4, 1]], [[17, 5, 11]], [[25, 16, 9]], [[103, 87, 113]], [[1032, 3192, 2864]], [[1, 2, 3, 4]], [[2, 3, 4, 1]], [[3, 4, 1, 2]], [[4, 1, 2, 3]], [[7, 5, 3, 1]], [[5, 3, 7, 7]], [[3, 1, 8, 5]], [[1, 9, 5, 5]], [[6, 3, 4, 9, 1, 2, 7, 8, 5]], [[6, 3, 4, 15, 14, 9, 1, 2, 7, 8, 5, 14, 11, 15, 17, 19]], [[42]], [[]]], "outputs": [[[7, 5, 3, 1, 2, 4, 6, 8, 9]], [[1, 2]], [[1, 2]], [[1, 3]], [[1, 3]], [[24, 57]], [[36, 89]], [[1, 2, 3]], [[2, 1, 4]], [[5, 11, 17]], [[16, 9, 25]], [[87, 103, 113]], [[1032, 2864, 3192]], [[1, 2, 3, 4]], [[2, 3, 1, 4]], [[3, 1, 2, 4]], [[1, 2, 3, 4]], [[5, 3, 1, 7]], [[3, 5, 7, 7]], [[1, 3, 5, 8]], [[1, 5, 5, 9]], [[3, 4, 6, 1, 2, 7, 8, 5, 9]], [[3, 4, 6, 14, 9, 1, 2, 7, 8, 5, 14, 11, 15, 15, 17, 19]], [[42]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,909
def bubblesort_once(l):
d7521d85490bb10cdd6b9e70a591fe99
UNKNOWN
A special type of prime is generated by the formula `p = 2^m * 3^n + 1` where `m` and `n` can be any non-negative integer. The first `5` of these primes are `2, 3, 5, 7, 13`, and are generated as follows: ```Haskell 2 = 2^0 * 3^0 + 1 3 = 2^1 * 3^0 + 1 5 = 2^2 * 3^0 + 1 7 = 2^1 * 3^1 + 1 13 = 2^2 * 3^1 + 1 ..and so on ``` You will be given a range and your task is to return the number of primes that have this property. For example, `solve(0,15) = 5`, because there are only `5` such primes `>= 0 and < 15`; they are `2,3,5,7,13`. The upper limit of the tests will not exceed `1,500,000`. More examples in the test cases. Good luck! If you like Prime Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)
["sb_primes = [2, 3, 5, 7, 13, 17, 19, 37, 73, 97, 109, 163, 193, 257, 433, 487, 577, 769, 1153, 1297, 1459, 2593, 2917, 3457, 3889, 10369, 12289, 17497, 18433, 39367, 52489, 65537, 139969, 147457, 209953, 331777, 472393, 629857, 746497, 786433, 839809, 995329, 1179649, 1492993]\n\ndef solve(x, y):\n return sum(x <= p < y for p in sb_primes)", "def is_prime(n): return all(n%p!=0 for p in range(2,int(n**0.5)+1))\nstone = []\n\nfor i in range(20):\n for j in range(12):\n p = (2**i)*(3**j) + 1\n if is_prime(p): stone.append(p)\n\ndef solve(x,y):\n return sum(1 for p in stone if p>=x and p<y)", "specials = (2, 3, 5, 7, 13, 17, 19, 37, 73, 97, 109, 163, 193, 257, 433, 487,\n 577, 769, 1153, 1297, 1459, 2593, 2917, 3457, 3889, 10369, 12289,\n 17497, 18433, 39367, 52489, 65537, 139969, 147457, 209953, 331777,\n 472393, 629857, 746497, 786433, 839809, 995329, 1179649, 1492993)\n\n\ndef solve(i, j):\n return sum(1 for n in specials if i <= n <= j)", "from itertools import compress\nfrom math import log\nimport numpy as np\n\nn = 1_500_000\ns = np.ones(n, dtype=int)\ns[:2] = s[4::2] = 0\nfor i in range(3, int(len(s)**0.5)+1, 2):\n if s[i]:\n s[i*i::i] = 0\nps = set(compress(range(len(s)), s))\nstone_bridge_primes = set()\nfor i in range(int(log(n, 2))+1):\n for j in range(int(log(n, 3))+1):\n x = 2**i * 3**j + 1\n if x in ps:\n stone_bridge_primes.add(x)\nsbp = sorted(stone_bridge_primes)\n\ndef solve(x,y):\n return np.searchsorted(sbp, y) - np.searchsorted(sbp, x)", "def isprime(n):\n if n==2: return True\n if n%2==0 or n<2: return False\n for i in range(3,int(n**0.5)+1,2):\n if n%i==0:\n return False \n return True\nsbs = []\nfor i in range(22):\n j = 0\n while 2**i * 3**j + 1 <= 1500000:\n if isprime(2**i * 3**j + 1):\n sbs.append(2**i * 3**j + 1)\n j += 1\ndef solve(x,y): return sum( x <= z & z <= y for z in sbs )", "from bisect import bisect_left as bisect\nfrom math import log\n\ndef isPrime(n): return n==2 or n%2 and all(n%p for p in range(3, int(n**.5)+1, 2))\n\nMAX = 1500000\nmPow2 = int(log(MAX,2))\nSTONES = sorted(n for n in { 2**n2 * 3**n3 + 1 for n2 in range(mPow2+1)\n for n3 in range(int(log(MAX // 2**n2,3))+1) }\n if isPrime(n))\n\n\ndef solve(x,y):\n low = bisect(STONES, x)\n return bisect(STONES, y, low, len(STONES)) - low", "LIMIT = 1500000\n\nfrom math import log, ceil\nfrom itertools import product\n\nm_max, n_max = ceil(log(LIMIT, 2)), ceil(log(LIMIT, 3))\nsb_primes = {2}\n\n# generate candidates up to limit\nfor m, n in product(range(1, m_max), range(n_max)):\n cand = 2**m * 3**n + 1\n # check primality\n if cand < LIMIT and all(cand % x for x in range(3, int(cand**0.5)+1, 2)):\n sb_primes.add(cand)\n\n\ndef solve(x, y):\n return sum(x <= p < y for p in sb_primes)", "M=[2,3,5,7,13,17,19,37,73,97,109,163,193,257,433,487,577,769,1153,1297,1459,2593,2917,3457,3889,10369,12289,17497,18433,39367,52489,65537,139969,147457,209953,331777,472393,629857,746497,786433,839809,995329,1179649,1492993]\nsolve=lambda L,R:sum(L<=V<R for V in M)", "from math import*;solve=lambda x,y:len({2**m*3**n+1\nfor n in range(0,ceil(log(y-1,3)))\nfor m in range(ceil(log(max(~-x/3**n,1),2)),ceil(log(~-y/3**n,2)))\nif all((2**m*3**n+1)%d for d in range(2,int((2**m*3**n+1)**.5)+1))})"]
{"fn_name": "solve", "inputs": [[0, 10], [0, 15], [0, 100], [100, 1000], [340, 500], [3400, 5000], [20000, 60000], [750000, 1000000], [300000, 900000], [100, 1000000], [500000, 1000000], [1000000, 1500000], [0, 1500000]], "outputs": [[4], [5], [10], [8], [2], [2], [2], [3], [6], [32], [5], [2], [44]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,477
def solve(x, y):
292b042d4f25db7603226a58e1071426
UNKNOWN
In this Kata, you will be given a list of strings and your task will be to find the strings that have the same characters and return the sum of their positions as follows: ```Haskell solve(["abc","abbc", "ab", "xyz", "xy", "zzyx"]) = [1,8] -- we see that the elements at indices 0 and 1 have the same characters, as do those at indices 3 and 5. -- we therefore return [1,8] because [0+1,3+5] = [1,8]. This result is sorted. -- ignore those that don't have at least one matching partner, such as "ab" and "xy". Another example... solve(["wkskkkkkk","fokoo","wkskk","uizzzz","fokooff","wkskkkk","uizzzzzzz"]),[5,7,9]); --The element at index 0 is similar to those at indices 2 and 5; so 0 + 2 + 5 = 7. --The element at index 1 is similar to that at index 4; so 1 + 4 = 5. --The element at index 3 is similar to that at index 6; so 3 + 6 = 9. --The result must be sorted. We get [5,7,9]. ``` More examples in the test cases. Good luck!
["from collections import defaultdict\n\ndef solve(arr):\n dct = defaultdict(list)\n for i,fs in enumerate(map(frozenset, arr)):\n dct[fs].append(i)\n return sorted(sum(lst) for lst in dct.values() if len(lst) > 1)", "def solve(lst):\n seen, result = set(), []\n for i, st1 in enumerate(lst):\n current = 0\n for j, st2 in enumerate(lst[i+1:], i+1):\n if j not in seen and set(st1) == set(st2):\n current += j\n seen.add(j)\n if current:\n result.append(i + current)\n return sorted(result)", "def solve(arr):\n ret = [ ]\n i = len(arr)-1\n t = None\n while i>-1:\n for j in range(i):\n if arr[j] and set(arr[j]) == set(arr[i]):\n arr[j] = ''\n if not t: t = 0\n t += j\n if t!=None: ret.append(t+i); t = None\n i-=1\n return sorted(ret)", "from collections import defaultdict\n\ndef solve(arr):\n d = defaultdict(list)\n for i, x in enumerate(arr):\n d[frozenset(x)].append(i)\n return sorted(sum(xs) for xs in list(d.values()) if len(xs) > 1)\n", "from itertools import groupby\nfrom operator import itemgetter\n\ndef solve(arr):\n s = sorted(((c, sorted(set(a))) for c, a in enumerate(arr)), key = itemgetter(1))\n return sorted(sum(map(itemgetter(0), a)) for a in (list(g) for _, g in groupby(s, itemgetter(1))) if len(a) > 1)", "def solve(arr):\n sums = {}\n for i, s in enumerate(arr):\n sums.setdefault(frozenset(s), []).append(i)\n return sorted(sum(indexes) for indexes in sums.values() if len(indexes) > 1)", "def solve(a):\n d = {}\n for i, s in enumerate(a): d.setdefault(frozenset(s), []).append(i)\n return sorted(sum(v) for v in d.values() if len(v) > 1)", "from collections import defaultdict\n\ndef solve(strings):\n indices_by_chars = defaultdict(list)\n for i, s in enumerate(strings):\n indices_by_chars[frozenset(s)].append(i)\n return sorted(sum(js) for js in list(indices_by_chars.values()) if len(js) > 1)\n", "def solve(arr):\n arr = [''.join(sorted(list(set(x)))) for x in arr]\n return sorted(sum(i for i, y in enumerate(arr) if x == y) for x in set(arr) if arr.count(x) >= 2)"]
{"fn_name": "solve", "inputs": [[["abc", "abbc", "ab", "xyz", "xy", "zzyx"]], [["wkskkkkkk", "fokoo", "wkskk", "uizzzz", "fokooff", "wkskkkk", "uizzzzzzz"]], [["xhuhhh", "dghgg", "dghgghh", "mrerrrrrr", "xhuhhhhhh", "mrerrr"]], [["uczcccccc", "idffffiii", "pnjjjjjjj", "pnjjjj", "idffff", "uczcccc", "uczcc"]], [["rvjvvvv", "mihhhh", "mihhhhmmm", "rvjvv", "wsnssww", "wsnss"]], [["ayqqqq", "epqqqqqqq", "epqqqqqqqqqq", "rdsddss", "ayqqqqqqq", "epqqqq", "rdsdd"]], [["gkeeekkgggg", "gkeeekkgg", "bzfffffff", "uoboooooo", "gkeeekk", "uobooo", "bzffff", "gkeee"]]], "outputs": [[[1, 8]], [[5, 7, 9]], [[3, 4, 8]], [[5, 5, 11]], [[3, 3, 9]], [[4, 8, 9]], [[8, 8, 12]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,261
def solve(arr):
054e60c90d23ecde4da98d010cca5d44
UNKNOWN
[Generala](https://en.wikipedia.org/wiki/Generala) is a dice game popular in South America. It's very similar to [Yahtzee](https://en.wikipedia.org/wiki/Yahtzee) but with a different scoring approach. It is played with 5 dice, and the possible results are: | Result | Points | Rules | Samples | |---------------|--------|------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------| | GENERALA | 50 | When all rolled dice are of the same value. | 66666, 55555, 44444, 11111, 22222, 33333. | | POKER | 40 | Four rolled dice are of the same value. | 44441, 33233, 22262. | | FULLHOUSE | 30 | Three rolled dice are of the same value, the remaining two are of a different value, but equal among themselves. | 12121, 44455, 66116. | | STRAIGHT | 20 | Rolled dice are in sequential order. Dice with value `1` is a wildcard that can be used at the beginning of the straight, or at the end of it. | 12345, 23456, 34561, 13654, 62534. | | Anything else | 0 | Anything else will return `0` points. | 44421, 61623, 12346. | Please note that dice are not in order; for example `12543` qualifies as a `STRAIGHT`. Also, No matter what string value you get for the dice, you can always reorder them any order you need to make them qualify as a `STRAIGHT`. I.E. `12453`, `16543`, `15364`, `62345` all qualify as valid `STRAIGHT`s. Complete the function that is given the rolled dice as a string of length `5` and return the points scored in that roll. You can safely assume that provided parameters will be valid: * String of length 5, * Each character will be a number between `1` and `6`
["def points(dice):\n dice = sorted([int(d) for d in dice])\n counts = [dice.count(i) for i in range(1, 7)]\n if 5 in counts:\n # GENERALA\n return 50\n if 4 in counts:\n # POKER\n return 40\n if 3 in counts and 2 in counts:\n # FULLHOUSE\n return 30\n if counts.count(1) == 5 and counts.index(0) not in [2, 3, 4]:\n # STRAIGHT\n return 20 \n return 0", "def points(dice):\n dice_str=str(dice)\n c=0\n d=0\n dd=0\n c2=0\n c3=0\n c4=0\n c5=0\n d2=0\n d3=0\n d4=0\n d5=0\n \n for e in dice_str[0]:\n for f in dice_str[0:]:\n if e != f:\n d+=1\n for e2 in dice_str[0]:\n for f2 in dice_str[0:]:\n if e2 != f2:\n d2+=1\n for e3 in dice_str[0]:\n for f3 in dice_str[0:]:\n if e3 != f3:\n d3+=1\n for e4 in dice_str[0]:\n for f4 in dice_str[0:]:\n if e4 != f4:\n d4+=1\n for e5 in dice_str[0]:\n for f5 in dice_str[0:]:\n if e5 != f5:\n d5+=1\n for a in dice_str[0]:\n for b in dice_str[0:]:\n if a == b:\n c+=1\n for a2 in dice_str[0:]:\n for b2 in dice_str[0:]:\n if a2 == b2:\n c2+=1\n for a3 in dice_str[0:]:\n for b3 in dice_str[0:]:\n if a3 == b3:\n c3+=1\n for a4 in dice_str[0:]:\n for b4 in dice_str[0:]:\n if a4 == b4:\n c4+=1\n for a5 in dice_str[0:]:\n for b5 in dice_str[0:]:\n if a5 == b5:\n c5+=1\n \n if int(dice_str[0])==1 and int(dice_str[1])==2 and int(dice_str[2])==3 and int(dice_str[3])==4 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==3 and int(dice_str[2])==4 and int(dice_str[3])==5 and int(dice_str[4])==6:\n return 20\n if int(dice_str[0])==3 and int(dice_str[1])==4 and int(dice_str[2])==5 and int(dice_str[3])==6 and int(dice_str[4])==1:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==3 and int(dice_str[2])==5 and int(dice_str[3])==6 and int(dice_str[4])==4:\n return 20\n if int(dice_str[0])==6 and int(dice_str[1])==2 and int(dice_str[2])==5 and int(dice_str[3])==3 and int(dice_str[4])==4:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==3 and int(dice_str[2])==2 and int(dice_str[3])==4 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==2 and int(dice_str[2])==3 and int(dice_str[3])==5 and int(dice_str[4])==4:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==2 and int(dice_str[2])==3 and int(dice_str[3])==4 and int(dice_str[4])==6:\n return 0\n if int(dice_str[0])==1 and int(dice_str[1])==2 and int(dice_str[2])==4 and int(dice_str[3])==3 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==2 and int(dice_str[2])==4 and int(dice_str[3])==5 and int(dice_str[4])==3:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==3 and int(dice_str[2])==2 and int(dice_str[3])==4 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==3 and int(dice_str[2])==2 and int(dice_str[3])==5 and int(dice_str[4])==4:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==3 and int(dice_str[2])==4 and int(dice_str[3])==2 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==3 and int(dice_str[2])==4 and int(dice_str[3])==5 and int(dice_str[4])==2:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==3 and int(dice_str[2])==3 and int(dice_str[3])==5 and int(dice_str[4])==2:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==4 and int(dice_str[2])==3 and int(dice_str[3])==5 and int(dice_str[4])==2:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==4 and int(dice_str[2])==3 and int(dice_str[3])==2 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==4 and int(dice_str[2])==2 and int(dice_str[3])==5 and int(dice_str[4])==3:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==4 and int(dice_str[2])==2 and int(dice_str[3])==3 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==4 and int(dice_str[2])==5 and int(dice_str[3])==3 and int(dice_str[4])==2:\n return 20\n if int(dice_str[0])==1 and int(dice_str[1])==4 and int(dice_str[2])==5 and int(dice_str[3])==2 and int(dice_str[4])==3:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==1 and int(dice_str[2])==3 and int(dice_str[3])==4 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==1 and int(dice_str[2])==3 and int(dice_str[3])==5 and int(dice_str[4])==4:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==1 and int(dice_str[2])==5 and int(dice_str[3])==4 and int(dice_str[4])==3:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==1 and int(dice_str[2])==5 and int(dice_str[3])==3 and int(dice_str[4])==4:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==1 and int(dice_str[2])==4 and int(dice_str[3])==3 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==1 and int(dice_str[2])==4 and int(dice_str[3])==5 and int(dice_str[4])==3:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==3 and int(dice_str[2])==1 and int(dice_str[3])==4 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==3 and int(dice_str[2])==1 and int(dice_str[3])==5 and int(dice_str[4])==4:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==3 and int(dice_str[2])==4 and int(dice_str[3])==1 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==3 and int(dice_str[2])==4 and int(dice_str[3])==5 and int(dice_str[4])==1:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==3 and int(dice_str[2])==5 and int(dice_str[3])==1 and int(dice_str[4])==4:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==3 and int(dice_str[2])==5 and int(dice_str[3])==4 and int(dice_str[4])==1:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==4 and int(dice_str[2])==1 and int(dice_str[3])==3 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==4 and int(dice_str[2])==1 and int(dice_str[3])==5 and int(dice_str[4])==3:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==4 and int(dice_str[2])==3 and int(dice_str[3])==1 and int(dice_str[4])==5:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==4 and int(dice_str[2])==3 and int(dice_str[3])==5 and int(dice_str[4])==1:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==4 and int(dice_str[2])==5 and int(dice_str[3])==1 and int(dice_str[4])==3:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==4 and int(dice_str[2])==5 and int(dice_str[3])==3 and int(dice_str[4])==1:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==5 and int(dice_str[2])==1 and int(dice_str[3])==3 and int(dice_str[4])==4:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==5 and int(dice_str[2])==1 and int(dice_str[3])==4 and int(dice_str[4])==3:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==5 and int(dice_str[2])==3 and int(dice_str[3])==1 and int(dice_str[4])==4:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==5 and int(dice_str[2])==3 and int(dice_str[3])==4 and int(dice_str[4])==1:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==5 and int(dice_str[2])==4 and int(dice_str[3])==1 and int(dice_str[4])==3:\n return 20\n if int(dice_str[0])==2 and int(dice_str[1])==5 and int(dice_str[2])==4 and int(dice_str[3])==3 and int(dice_str[4])==1:\n return 20\n \n \n if c4==25:\n return 50\n if c4==17:\n return 40\n if c4==13:\n return 30\n if c4==7 or c4==9 or c4==11:\n return 0\n if c4==7 and d==0:\n return 0\n if c4==9 and d==0:\n return 0\n if c4==1 and d==0:\n return 0 \n if c4==7 and d4==2:\n return 0\n if c4==7 and d4==3:\n return 0\n if c4==9 and d4==2:\n return 0\n if c4==9 and d4==3:\n return 0\n if c4==13 and d4==2:\n return 0\n if c4==13 and d4==3:\n return 0\n if dice[0]==1 and dice[1]==2 and dice[2]==3 and dice[3]==4 and dice[4]==6:\n return 0\n if int(dice_str[0])==1 and int(dice_str[1])==2 and int(dice_str[2])==3 and int(dice_str[3])==4 and int(dice_str[4])==5:\n return 20\n else:\n return 0\n \n \n \n \n \n \n \n", "from collections import Counter\n\ndef points(dice):\n cnt = Counter(dice)\n val = set(cnt.values())\n if val == {5}:\n return 50\n if val == {1, 4}:\n return 40\n if val == {2, 3}:\n return 30\n return 20 * (val == {1, 1, 1, 1, 1} and all(cnt[a] for a in '345'))", "from collections import Counter\n\nCOUNTS = [\n (50, lambda s,_: len(set(s))==1),\n (40, lambda _,c: len(c)==2 and 4 in c.values()),\n (30, lambda _,c: set(c.values()) == {2,3}),\n (20, lambda s,_: (s:=''.join(sorted(s))) in '123456' or s=='13456'),\n]\n\n\ndef points(dice):\n c = Counter(dice)\n return sum(pts for pts,isValid in COUNTS if isValid(dice,c))", "points=lambda d:((c:=list(map(d.count,'123456')))in(5*[1]+[0],[0]+5*[1],[1,0]+4*[1]))*20+(3in c)*(2in c)*30+(4in c)*40+(5in c)*50", "from collections import Counter\n\ndef points(s):\n m = tuple(sorted(dict(Counter(list(s))).values()))\n d = {(5,):50, (1,4):40, (2,3):30}\n try:\n return d[m]\n except KeyError: \n return 20 if \"\".join(sorted(list(s))) in [\"12345\",\"13456\",\"23456\"] else 0", "from collections import Counter\n\n\ndef is_straight(dice):\n ds = sorted(map(int, dice))\n return ds == list(range(ds[0], ds[-1] + 1)) or ds == [1, 3, 4, 5, 6]\n\n\ndef points(dice):\n vs = Counter(dice).values()\n if 5 in vs:\n return 50\n elif 4 in vs:\n return 40\n elif 3 in vs and 2 in vs:\n return 30\n elif is_straight(dice):\n return 20\n else:\n return 0", "def points(string):\n lista = list(string)\n lista_1 = sorted(lista)\n if len(set(string)) == 1: return 50\n if len(set(string)) == 2 :\n if lista_1[0]== lista_1[1] and lista_1[3]==lista_1[4]:\n return 30\n else:\n return 40\n if len(set(string)) == 5: #Aici trebuie lucrat\n valoare = 0\n if int(lista_1[3]) - int(lista_1[2]) == 1 and int(lista_1[4]) - int(lista_1[3]) == 1:\n valoare = 1\n if valoare == 1:\n return 20\n if valoare == 0:\n return 0\n else:\n return 0", "def points(dice):\n x = sorted(dice)\n if len(set(x)) == 1:\n return 50\n \n if len(set(x)) == 2:\n for i in set(x):\n if dice.count(i) in [1, 4]:\n return 40\n else:\n return 30\n \n if x[0] == '1':\n exp = [x[0], x[1]]\n for i in range(1, 4):\n n = int(x[1]) + i \n if n > 6:\n exp.append(str(n%6))\n else:\n exp.append(str(n))\n if exp == x:\n return 20\n else:\n exp = [x[0]]\n for i in range(1, 5):\n n = int(x[0]) + i\n if n > 6:\n exp.append(str(n%6))\n else:\n exp.append(str(n))\n if exp == x:\n return 20\n else: \n return 0\n return 0", "from collections import Counter\n\ndef points(dice):\n c = Counter(dice)\n if len(c)==1:\n return 50\n \n elif len(c)==2 and c.most_common()[0][1] == 4:\n return 40\n \n elif len(c)==2 and c.most_common()[1][1] == 2:\n return 30\n \n else:\n s = sorted(int(x) for x in dice)\n if s[0]==s[1] or any(s[1:][i]+1 != s[1:][i+1] for i in range(len(s)-2)):\n return 0\n\n return 20"]
{"fn_name": "points", "inputs": [["55555"], ["44444"], ["44441"], ["33233"], ["22262"], ["12121"], ["44455"], ["66116"], ["12345"], ["23456"], ["34561"], ["13564"], ["62534"], ["44421"], ["61623"], ["12346"]], "outputs": [[50], [50], [40], [40], [40], [30], [30], [30], [20], [20], [20], [20], [20], [0], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,524
def points(dice):
0fb001223fea586dca72c718f9409d38
UNKNOWN
Complete the method which accepts an array of integers, and returns one of the following: * `"yes, ascending"` - if the numbers in the array are sorted in an ascending order * `"yes, descending"` - if the numbers in the array are sorted in a descending order * `"no"` - otherwise You can assume the array will always be valid, and there will always be one correct answer.
["def is_sorted_and_how(arr):\n if arr == sorted(arr):\n return 'yes, ascending' \n elif arr == sorted(arr)[::-1]:\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n if arr == sorted(arr):\n return 'yes, ascending'\n elif arr == sorted(arr, reverse=True):\n return 'yes, descending'\n return 'no'", "def is_descending(arr):\n for i in range(len(arr) - 1):\n if arr[i + 1] > arr[i]: return False\n return True\n\ndef is_ascending(arr):\n for i in range(len(arr) - 1):\n if arr[i + 1] < arr[i]: return False\n return True\n \ndef is_sorted_and_how(arr):\n if is_ascending(arr): return 'yes, ascending'\n if is_descending(arr): return 'yes, descending'\n return 'no'", "def is_sorted_and_how(arr):\n return 'yes, ascending' if arr == sorted(arr) else 'yes, descending' if arr == sorted(arr)[::-1] else 'no'", "from itertools import islice\nimport operator\n\ndef is_sorted_and_how(arr):\n return (\n 'yes, ascending' if is_sorted_with(arr, operator.le) else\n 'yes, descending' if is_sorted_with(arr, operator.ge) else\n 'no')\n\ndef is_sorted_with(arr, pred):\n return all(pred(x, y) for x, y in zip(arr, islice(arr, 1, None)))", "def sign(x):\n return (x > 0) - (x < 0)\n\ndef is_sorted_and_how(arr):\n s = {sign(y - x) for x, y in zip(arr, arr[1:])}\n if len(s) == 1 or len(s) == 2 and 0 in s:\n return \"yes, %s\" % [\"descending\", \"ascending\"][1 in s] \n return 'no'", "is_sorted_and_how = lambda a: ['no','yes, ascending','yes, descending'][(sorted(a)==a)+(sorted(a)[::-1]==a)*2]", "def is_sorted_and_how(arr):\n op, txt = ((int.__le__, 'yes, ascending'), (int.__ge__, 'yes, descending'))[arr[0] > arr[-1]]\n return all(map(op, arr, arr[1:])) and txt or 'no'", "def is_sorted_and_how(nums):\n a_or_d = {'a': 'ascending', 'd': 'descending'}\n diffs = {'d' if b - a < 0 else 'a' for a, b in zip(nums, nums[1:])}\n return 'yes, {}'.format(a_or_d[diffs.pop()]) if len(diffs) == 1 else 'no'", "def is_sorted_and_how(arr):\n return next(('yes, {}cending'.format(k) for k,v in {'as':sorted(arr),'des':sorted(arr,reverse=True)}.items() if v == arr),'no')", "def is_sorted_and_how(arr):\n sorted_arr = sorted(arr)\n if sorted_arr == arr:\n return 'yes, ascending'\n elif sorted_arr[::-1] == arr:\n return 'yes, descending'\n return 'no'", "from typing import List\n\n\ndef is_sorted_and_how(arr: List[int]) -> str:\n # Calculate order between consecutively items\n order = (a > b for a, b in zip(arr, arr[1:]) if a != b)\n\n # Check if the first difference notes a ascending order\n if next(order):\n # Now check if the rest is in descending order\n return \"yes, descending\" if all(order) else \"no\"\n\n # Check if the rest is in ascending order\n return \"yes, ascending\" if not any(order) else \"no\"\n", "def is_sorted_and_how(arr):\n if all(x > y for x,y in zip(arr, arr[1:])):\n return \"yes, descending\"\n elif all(x < y for x, y in zip(arr, arr[1:])):\n return \"yes, ascending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n decend_Counter = 0;\n accend_Counter = 0;\n for i in range(len(arr) - 1):\n if arr[i] > arr[i + 1]:\n decend_Counter += 1\n if arr[i] < arr[i + 1]:\n accend_Counter += 1\n if (decend_Counter == len(arr) - 1):\n return \"yes, descending\"\n elif (accend_Counter == len(arr) - 1):\n return \"yes, ascending\"\n else:\n return \"no\"\n \n return 1", "def is_sorted_and_how(arr):\n arrS = sorted(arr)\n revArrS = sorted(arr, reverse = True)\n if arr == arrS:\n return \"yes, ascending\"\n elif arr == revArrS:\n return \"yes, descending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n a = sorted(arr)\n d = sorted(arr, reverse=True)\n return 'yes, ascending' if arr == a else 'yes, descending' if arr == d else 'no'", "def is_sorted_and_how(arr):\n s = sorted(arr)\n return 'yes, ascending' if arr==s else 'yes, descending' if arr == s[::-1] else 'no'", "def is_sorted_and_how(a):\n if a == sorted(a):return 'yes, ascending'\n elif a == sorted(a, reverse=True):return 'yes, descending'\n else:return 'no'", "def is_sorted_and_how(arr):\n if arr == sorted(arr): return 'yes, ascending'\n if arr == sorted(arr, reverse=True): return 'yes, descending'\n return 'no'", "def is_sorted_and_how(arr):\n if arr == sorted(arr):\n return 'yes, ascending'\n elif arr == sorted(arr, reverse = True):\n return 'yes, descending'\n else:\n return 'no'", "from operator import le,ge\n\ndef is_sorted_and_how(arr):\n if all(map(le,arr,arr[1:])): return 'yes, ascending'\n elif all(map(ge,arr,arr[1:])): return 'yes, descending'\n else: return 'no'", "def is_sorted_and_how(arr):\n sorted_asc = sorted(arr)\n sorted_desc = sorted_asc[::-1]\n return 'yes, ascending' if sorted_asc == arr else 'yes, descending' if sorted_desc == arr else \"no\"\n", "def is_sorted_and_how(arr):\n return (all(arr[i] < arr[i + 1] for i in range(len(arr) - 1)) and \"yes, ascending\" or\n all(arr[i] > arr[i + 1] for i in range(len(arr) - 1)) and \"yes, descending\" or \"no\")", "def is_sorted_and_how(arr):\n return {\n (\"LT\",):\"yes, ascending\",\n (\"GT\",):\"yes, descending\",\n }.get(tuple(set(map(lambda x,y: \"LT\" if x<=y else \"GT\", arr, arr[1:]))), \"no\")", "def is_sorted_and_how(arr):\n counts = 0\n for index in range(len(arr) - 1):\n if arr[index] > arr[index + 1 ]:\n counts += 1\n elif arr[index] < arr[index + 1 ]:\n counts -= 1\n \n if counts == len(arr) - 1:\n return \"yes, descending\"\n elif counts == -len(arr) + 1:\n return \"yes, ascending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n return 'yes, ascending' if arr == sorted(arr) else 'yes, descending' if arr == sorted(arr, reverse=True) else 'no'", "def is_sorted_and_how(arr):\n return ('yes, ascending' if sorted(arr)==arr else 'yes, descending') if (sorted(arr)==arr or sorted(arr,reverse=True)==arr) else 'no'", "def is_sorted_and_how(arr):\n check = [arr[i-1] < arr[i] for i in range(1,len(arr))]\n true = check.count(True)\n false = check.count(False)\n if true == len(arr)-1 and false == 0:\n return 'yes, ascending'\n elif false == len(arr)-1 and true ==0:\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n ascending = sorted(arr)\n descending = sorted(arr, reverse=True)\n if arr == ascending: return \"yes, ascending\"\n if arr == descending: return \"yes, descending\"\n return 'no'", "def is_sorted_and_how(arr):\n if sorted(arr) == arr:\n return 'yes, ascending'\n elif sorted(arr[::-1]) == arr[::-1]:\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n s=0\n t=0\n for i in range(0,len(arr)-1):\n if arr[i]<arr[i+1]:\n s+=1\n elif arr[i]>arr[i+1]:\n t+=1\n if t==len(arr)-1:\n return \"yes, descending\"\n elif s==len(arr)-1:\n return \"yes, ascending\"\n else:\n return 'no'", "def is_sorted_and_how(arr):\n for i in range(len(arr)):\n if sorted(arr) ==arr:\n return \"yes, ascending\"\n elif sorted(arr, reverse=True) == arr:\n return \"yes, descending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n for index in range(len(arr))[2:]:\n if (arr[index] <= arr[index - 1]) != (arr[index - 1] <= arr[index - 2]):\n return \"no\"\n return \"yes, descending\" if arr[1] <= arr[0] else \"yes, ascending\"\n \n", "def is_sorted_and_how(arr):\n monity = arr[1] <= arr[0]\n for index in range(len(arr))[2:]:\n if (arr[index] <= arr[index - 1]) != monity:\n return \"no\"\n return \"yes, descending\" if monity else \"yes, ascending\"\n \n", "def is_sorted_and_how(arr):\n if arr == list(sorted(arr)) or arr == list(sorted(arr))[::-1]:\n return \"yes, ascending\" if arr[0] < arr[1] else \"yes, descending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n # Check to see if the array is starting off ascending\n if arr[0] < arr[1]:\n # Loop through the array to see if any items break that ascending fashion\n for i in range(len(arr)-1):\n if arr[i] > arr[i+1]:\n # If they do, return no\n return 'no'\n # If we made it through all items and didn't return no, return yes ascending\n return 'yes, ascending'\n # Check to see if the array is starting off descending\n if arr[0] > arr[1]:\n for i in range(len(arr)-1):\n if arr[i] < arr[i+1]:\n return 'no'\n return 'yes, descending'", "def is_sorted_and_how(arr):\n a = sorted(arr)\n if a == arr:\n return \"yes, ascending\"\n elif sorted(a, reverse=True) == arr:\n return \"yes, descending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n asc=False\n desc=False\n\n for index in range(len(arr)):\n\n \n if index == 0:\n if arr[index+1] > arr[index]:\n asc=True\n desc=False\n if arr[index+1] < arr[index]:\n asc=False\n desc=True\n \n if (index != 0) and (index != (len(arr)-1)):\n if (arr[index-1] < arr[index] < arr[index+1]) and asc:\n asc=True\n desc=False\n elif (arr[index-1] > arr[index] > arr[index+1]) and desc:\n asc=False\n desc=True\n else:\n asc=False\n desc=False\n \n if index == (len(arr)-1):\n if (arr[index-1] < arr[index]) and asc:\n asc=True\n desc=False\n if arr[index-1] < arr[index] and desc:\n asc=False\n desc=True\n \n if asc:\n return 'yes, ascending'\n if desc:\n return 'yes, descending'\n if not asc and not desc:\n return 'no'\n\n", "def is_sorted_and_how(arr):\n asc = sorted(arr)\n des = sorted(arr, reverse=True)\n if arr == asc:\n return ('yes, ascending')\n elif arr == des:\n return ('yes, descending')\n elif arr != (asc or des):\n return ('no')", "def is_sorted_and_how(arr):\n delta_value=[]\n positive_num=0\n negtive_num=0\n \n for i in range(len(arr)-1):\n delta_value.append(arr[i+1]-arr[i])\n for i in range(len(delta_value)):\n if delta_value[i]>=0:\n positive_num+=1\n else:\n negtive_num+=1\n if positive_num==len(delta_value):\n return('yes, ascending')\n elif negtive_num==len(delta_value):\n return('yes, descending')\n else:\n return('no')", "def is_sorted_and_how(arr):\n sort = \"descending\" if arr[0] > arr[-1] else \"ascending\"\n return \"yes, {}\".format(sort) if (sort == \"ascending\" and sorted(arr) == arr) or (\n sort == \"descending\" and sorted(arr, reverse=True) == arr) else \"no\"\n", "def is_sorted_and_how(arr):\n if sorted(arr) == arr:\n return (\"yes, ascending\")\n elif arr == sorted(arr, reverse=True):\n return(\"yes, descending\")\n return(\"no\")\n", "def is_sorted_and_how(arr):\n if arr==sorted(arr):\n return \"yes, ascending\"\n elif arr==sorted(arr, key=None, reverse=True):\n return \"yes, descending\" \n else:\n return \"no\"", "def is_sorted_and_how(arr):\n # your code here\n list_a =[]\n list_d = []\n list_a = sorted(arr)\n for i in list_a[::-1]:\n list_d.append(i)\n if arr == list_a:\n return \"yes, ascending\"\n if arr == list_d:\n return \"yes, descending\"\n else:\n return \"no\"\n", "def is_sorted_and_how(arr):\n x=sorted(arr)\n if x==arr:\n return 'yes, ascending'\n elif x[::-1]==arr:\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n # your code here\n type_arr = set()\n \n prev = arr[0]\n \n for item in arr[1:]:\n if item > prev:\n type_arr.add('asc')\n \n elif item < prev:\n type_arr.add('desc')\n prev = item\n \n if len(type_arr) != 1:\n return 'no'\n \n result = type_arr.pop()\n return 'yes, ascending' if result == 'asc' else 'yes, descending'", "def is_sorted_and_how(arr):\n sort_arr = sorted(arr)\n sort_desc = sorted(arr, reverse = True)\n if sort_arr == arr:\n return \"yes, ascending\"\n if sort_desc == arr:\n return \"yes, descending\"\n else:\n return \"no\"\n", "def is_sorted_and_how(arr):\n # your code here\n if(sorted(arr) == arr):\n result = 'yes, ascending'\n elif (sorted(arr, reverse = True) == arr):\n result = 'yes, descending'\n else:\n result = 'no'\n \n return result", "def is_sorted_and_how(arr):\n c = 0\n a = 0\n for i in range(len(arr) - 1):\n if arr[i] <= arr[i+1]:\n c += 1\n if c == (len(arr) - 1):\n return 'yes, ascending'\n elif arr[i] >= arr[i+1]:\n a += 1\n if a == (len(arr) - 1):\n return 'yes, descending'\n else:\n return 'no'\n \n \n #elif arr[i] >= arr[i+1]:\n # return 'yes, descending'\n #else:\n # return 'no'\n \n #return (\"yes, ascending\" if arr[i] <= arr[i+1] \"yes, descending\" elif arr[i] >= arr[i+1] for i in range(len(arr) - 1)) else \"no\"\n", "def is_sorted_and_how(arr):\n if arr[0]<arr[1]:\n return 'yes, ascending'\n elif arr[0]>arr[1] and arr[0]>arr[2]:\n return 'yes, descending'\n else:\n return 'no'\n", "def is_sorted_and_how(arr):\n asc = True\n desc = True\n for i in range(1, len(arr)):\n if arr[i-1] == arr[i]:\n return 'no'\n if arr[i - 1] < arr[i]:\n desc = False\n else:\n asc = False\n if not asc and not desc:\n return 'no'\n return 'yes, ascending' if asc else 'yes, descending'", "def is_sorted_and_how(arr):\n # your code here\n isAllNeg = True\n isAllPos = True\n \n for i in range(len(arr) - 1):\n isAllPos = isAllPos and arr[i + 1] - arr[i] > 0\n isAllNeg = isAllNeg and arr[i + 1] - arr[i] < 0\n \n if isAllPos:\n return \"yes, ascending\"\n elif isAllNeg:\n return \"yes, descending\"\n else:\n return 'no'", "def is_sorted_and_how(arr):\n if arr == sorted(arr, reverse=True):\n return 'yes, descending'\n if arr == sorted(arr):\n return 'yes, ascending'\n else:\n return 'no'", "def is_descending(arr):\n for i in range(len(arr) - 1):\n if arr[i+1] > arr[i]: \n return False\n return True\n\ndef is_ascending(arr):\n for i in range(len(arr) - 1):\n if arr[i+1] < arr[i]: \n return False\n return True\n\ndef is_sorted_and_how(arr):\n if is_ascending(arr) == True: \n return 'yes, ascending'\n if is_descending(arr) == True:\n return 'yes, descending'\n else:\n return 'no'\n \n", "def is_sorted_and_how(arr):\n k, c = 0, 0\n for i in range(1, len(arr)):\n if arr[i] > arr[i - 1]:\n k += 1\n else:\n c += 1\n if k > 0 or c > 0:\n if k > 0 and c == 0:\n return \"yes, ascending\"\n elif c > 0 and k == 0:\n return \"yes, descending\"\n return \"no\"", "def is_sorted_and_how(arr):\n \n if arr == sorted(arr):\n return \"yes, ascending\"\n elif arr[0] > arr[-1]:\n return \"yes, descending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n\n asc = True\n desc = True\n \n for idx in range(1, len(arr)):\n if arr[idx] - arr[idx - 1] >= 0:\n asc = asc & True\n desc = desc & False\n else:\n desc = desc & True\n asc = asc & False\n\n if asc and not desc:\n return \"yes, ascending\"\n elif desc and not asc:\n return \"yes, descending\"\n else:\n return \"no\"", "def is_sorted_and_how(list):\n if list == sorted(list):\n return(\"yes, ascending\")\n if list == sorted(list, reverse=True):\n return(\"yes, descending\")\n else:\n return(\"no\")", "def is_sorted_and_how(arr):\n order = 0\n i = 0\n \n for num in arr:\n hold = arr[i]\n \n if i + 1 < len(arr):\n if hold <= arr[i + 1]:\n order += 1\n if hold >= arr[i + 1]:\n order -= 1\n \n i += 1\n \n if order == len(arr) - 1: return 'yes, ascending'\n if order * -1 == len(arr) - 1: return 'yes, descending'\n else: return 'no'", "def is_sorted_and_how(arr):\n \n x = arr[:]\n \n if sorted(x) == arr:\n return \"yes, ascending\"\n elif sorted(x, reverse=True) == arr:\n return \"yes, descending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n print(arr)\n d = True\n a = True\n for i in range(len(arr) - 1):\n if arr[i] < arr[i+1]:\n d = False\n \n for i in range(len(arr) - 1):\n if arr[i] > arr[i+1]:\n a = False\n\n if d:\n return \"yes, descending\"\n elif a:\n return \"yes, ascending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n if arr[0] > arr[1]:\n for i in range(len(arr)-1):\n if arr[i] <= arr[i+1]:\n return('no')\n return('yes, descending')\n else:\n for i in range(len(arr)-1):\n if arr[i] >= arr[i+1]:\n return('no')\n return('yes, ascending')", "def is_sorted_and_how(arr):\n # your code here\n if arr[0] == min(arr) and arr[-1] == max(arr):\n return 'yes, ascending'\n elif arr[0] == max(arr) and arr[-1] == min(arr):\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n if sorted(arr) != arr and sorted(arr)[::-1] != arr:\n return 'no'\n return \"yes, ascending\" if sorted(arr) == arr else \"yes, descending\"", "def is_sorted_and_how(A):\n S = sorted(A)\n if S==A : return 'yes, ascending'\n elif S == A[::-1] : return 'yes, descending'\n return 'no'", "def is_sorted_and_how(arr):\n if all(arr[i] >= arr[i - 1] for i in range(1, len(arr))):\n return 'yes, ascending'\n elif all(arr[i] <= arr[i - 1] for i in range(1, len(arr))):\n return 'yes, descending'\n return 'no'", "def is_sorted_and_how(arr):\n x = list(arr)\n x.sort()\n if arr == x:\n return 'yes, ascending'\n elif arr[::-1] == x:\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n lst = arr[:]\n lst.sort()\n if lst == arr:\n return 'yes, ascending'\n elif lst[::-1] == arr:\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n a = sorted(arr)\n d = sorted(arr, reverse = True)\n if arr == a:\n return 'yes, ascending'\n elif arr == d:\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n if(arr == sorted(arr)): \n answer = 'yes, ascending'\n elif (arr == sorted(arr,reverse=True)):\n answer = 'yes, descending'\n else:\n answer = 'no'\n\n return answer\n", "def is_sorted_and_how(arr):\n if arr[0]>arr[1]:\n try:\n if arr[1]<arr[2]:\n return 'no'\n except:\n pass\n return \"yes, descending\"\n elif arr[0]<arr[1] :\n try:\n if arr[1]>arr[2]:\n return 'no'\n except:\n pass\n return \"yes, ascending\"\n return 'no'", "def is_sorted_and_how(arr):\n if arr==sorted(arr):\n return 'yes, ascending'\n for i in range(len(arr)-1):\n for j in range(1):\n if arr[i]>arr[i+1]:\n continue\n else:\n return 'no'\n return 'yes, descending'", "def is_sorted_and_how(arr):\n arr_asc = sorted(arr)\n return \"yes, ascending\" if arr == arr_asc else \"yes, descending\" if arr == arr_asc[::-1] else \"no\"", "def is_sorted_and_how(arr):\n \n new_sorted_list = sorted(arr)\n new_sorted_list_d = sorted(arr, reverse = True)\n \n if arr == new_sorted_list:\n return \"yes, ascending\"\n elif arr == new_sorted_list_d:\n return \"yes, descending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n return 'yes, ascending' if arr == sorted(arr) else 'yes, descending' if arr[::-1] == sorted(arr[::-1]) else 'no'", "def is_sorted_and_how(arr):\n return 'yes, %sscending' % ['a', 'de'][max(sorted(arr)) == arr[0]] if sorted(arr)[0] in [arr[0], arr[-1]] else 'no'", "def is_sorted_and_how(arr):\n sort_arr = sorted(arr)\n des_arr = sorted(arr)[::-1]\n if arr == sort_arr:\n return 'yes, ascending'\n if arr == des_arr:\n return 'yes, descending'\n return 'no'", "def is_sorted_and_how(arr):\n if sorted(arr) == arr:\n return \"yes, ascending\"\n return \"yes, descending\" if sorted(arr, reverse=True) == arr else \"no\"", "def is_sorted_and_how(arr):\n # your code here\n if arr[0] == sorted(arr)[0]:\n return 'yes, ascending'\n elif arr[0] == sorted(arr)[-1]:\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n arrasc = arr[:]\n arrasc.sort()\n arrdsc = arr[:]\n arrdsc.sort(reverse=True)\n\n if arrasc == arr:\n return 'yes, ascending'\n elif arrdsc == arr:\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n sort = 'yes, ascending'\n sort2 = 'yes, descending'\n if arr[0] > arr[len(arr) - 1]:\n for i in range(len(arr) - 1):\n if arr[i] < arr[i + 1]:\n sort = 'no'\n\n if arr[0] < arr[len(arr) - 1]:\n for i in range(len(arr) - 1):\n if arr[i] > arr[i + 1]:\n sort = 'no'\n\n if sort != 'no':\n if arr[0] > arr[len(arr) - 1]:\n return sort2\n\n elif arr[0] < arr[len(arr) - 1]:\n return sort\n else:\n return sort", "def is_sorted_and_how(arr):\n sort = sorted(arr)\n return \"yes, ascending\" if arr == sort else \"yes, descending\" if arr == sort[::-1] else \"no\"", "def is_sorted_and_how(arr):\n if arr[::-1] == sorted(arr):\n return \"yes, descending\"\n if arr == sorted(arr):\n return \"yes, ascending\"\n if arr != sorted(arr):\n return \"no\"\n", "def is_sorted_and_how(arr):\n brr = arr.copy()\n crr = arr.copy()\n brr.sort()\n crr.sort(reverse=True)\n \n if arr == brr:\n return 'yes, ascending'\n if arr == crr:\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n h = arr.copy()\n h.sort(reverse=True)\n p = arr.copy()\n p.sort()\n if arr == p:\n return \"yes, ascending\"\n if arr == h:\n return \"yes, descending\"\n else:\n return 'no'\n", "def is_sorted_and_how(arr):\n a=arr\n if a==sorted(arr):\n return 'yes, ascending'\n elif a== sorted(arr,reverse=True):\n return 'yes, descending'\n else:\n return 'no'", "def is_sorted_and_how(arr):\n a=sorted(arr)\n b=sorted(arr,reverse=True)\n if arr[1]== a[1]:\n return 'yes, ascending'\n elif arr[1]==b[1]:\n return 'yes, descending'\n else:\n return 'no'\n", "def is_sorted_and_how(arr):\n k = 0\n i = 0\n while i != len(arr) - 1:\n if arr[i] < arr[i + 1]:\n k += 1\n elif arr[i] > arr[i + 1]:\n k -= 1\n i += 1\n if k == len(arr) - 1:\n return 'yes, ascending'\n elif k == -len(arr) + 1:\n return 'yes, descending'\n else:\n return 'no'\n", "def is_sorted_and_how(arr):\n b = 0\n \n for x in range(0, len(arr) -1):\n if arr[x] < arr[x+1]:\n b += 1\n if b == len(arr) -1:\n return \"yes, ascending\"\n b = 0\n for x in range(0, len(arr) -1):\n if arr[x] > arr[x+1]:\n b += 1\n if b == len(arr) -1:\n return \"yes, descending\"\n \n else: \n return \"no\"\n \n \n", "def is_sorted_and_how(arr):\n sarr = sorted(arr)\n return \"yes, ascending\" if sarr == arr else \"yes, descending\" if sarr[::-1] == arr else \"no\"\n", "def is_sorted_and_how(arr):\n\n for i in range(len(arr)-1):\n if arr[i] == arr[i+1]:\n print(str(arr[i]) + ' ' + str(arr[i+1]))\n \n\n as_start = 0\n de_start = 0\n \n def compare(first,second):\n if second > first:\n return 'as'\n elif first > second:\n return 'de'\n else:\n return 'eq'\n \n state = compare(arr[0],arr[1])\n \n for i in range(1,len(arr)-1):\n \n \n \n new_state = compare(arr[i],arr[i+1])\n \n print(f\"{arr[i]}, {arr[i+1]}, {new_state}, {state}\")\n \n if new_state != 'eq':\n \n if state == 'eq':\n state = new_state\n \n if new_state != state:\n state = 'unsorted'\n break\n \n\n if state == 'unsorted' or state =='eq':\n return 'no'\n if state == 'as':\n return 'yes, ascending'\n if state == 'de':\n return 'yes, descending'", "def is_sorted_and_how(arr):\n arr_up = arr[0]\n arr_down = arr[0]\n check = 1\n for x in range(len(arr)):\n if arr[x] > arr_up:\n arr_up = arr[x]\n check += 1\n if check == len(arr):\n return 'yes, ascending'\n check = 1\n for x in range(len(arr)):\n if arr[x] < arr_down:\n arr_down = arr[x]\n check += 1\n if check == len(arr):\n return 'yes, descending'\n else:\n return 'no'\n \n \n\n", "def is_sorted_and_how(arr):\n if arr[0] >= arr[1]:\n for i in range(1,len(arr)):\n if arr[i-1] < arr[i]:\n return \"no\"\n return \"yes, descending\"\n elif arr[0] <= arr[1]:\n for i in range(1,len(arr)):\n if arr[i-1] > arr[i]:\n return 'no'\n return \"yes, ascending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n if arr[0] >= arr[1]:\n for n in range(1,len(arr)):\n if arr[n-1] < arr[n]:\n return \"no\"\n return \"yes, descending\"\n elif arr[0] <= arr[1]:\n for n in range(1,len(arr)):\n if arr[n-1] > arr[n]:\n return \"no\"\n return \"yes, ascending\"\n else:\n return \"no\"", "def is_sorted_and_how(arr):\n if arr[-1] > arr[0]:\n last = arr[0]\n for n in arr[1:]:\n if n < last:\n return \"no\"\n last = n\n \n return \"yes, ascending\"\n \n else:\n last = arr[0]\n for n in arr[1:]:\n if n > last:\n return \"no\"\n last = n\n \n return \"yes, descending\"\n", "def is_sorted_and_how(list):\n \n ascendList = list[:]\n ascendList.sort()\n \n descendList = list[:]\n descendList.sort(reverse = True)\n \n return \"yes, ascending\" if ascendList == list else \\\n \"yes, descending\" if descendList == list else \"no\"", "def is_sorted_and_how(arr):\n my_list = list(arr)\n if sorted(my_list) == arr:\n return \"yes, ascending\"\n elif sorted(my_list, reverse = True) == arr:\n return \"yes, descending\"\n else:\n return \"no\"", "def is_sorted_and_how(BLM):\n if BLM == sorted(BLM): return 'yes, ascending' \n if BLM == sorted(BLM)[::-1]: return 'yes, descending'\n return 'no'", "def is_sorted_and_how(arr):\n if arr == sorted(arr):\n return str(\"yes, ascending\")\n \n elif arr == sorted(arr, reverse=True):\n return str(\"yes, descending\")\n \n return str(\"no\")", "def is_sorted_and_how(arr):\n # your code here\n s=\"no\"\n for i in range(0,len(arr)-1):\n if arr[i]<arr[i+1]:\n s=\"yes\"\n z=\"ascending\"\n else:\n s=\"no\"\n z=\"\"\n break\n if s==\"no\":\n \n for i in range(len(arr)-1):\n if arr[i]>arr[i+1]:\n s=\"yes\"\n z=\"descending\"\n else:\n s=\"no\"\n z=\"\"\n break\n if s==\"no\":\n return s\n else:\n return (s+\", \"+z)\n"]
{"fn_name": "is_sorted_and_how", "inputs": [[[1, 2]], [[15, 7, 3, -8]], [[4, 2, 30]]], "outputs": [["yes, ascending"], ["yes, descending"], ["no"]]}
INTRODUCTORY
PYTHON3
CODEWARS
29,636
def is_sorted_and_how(arr):
22db7725559179c0390b816fafdb60ab
UNKNOWN
Everyone knows passphrases. One can choose passphrases from poems, songs, movies names and so on but frequently they can be guessed due to common cultural references. You can get your passphrases stronger by different means. One is the following: choose a text in capital letters including or not digits and non alphabetic characters, 1. shift each letter by a given number but the transformed letter must be a letter (circular shift), 2. replace each digit by its complement to 9, 3. keep such as non alphabetic and non digit characters, 4. downcase each letter in odd position, upcase each letter in even position (the first character is in position 0), 5. reverse the whole result. #Example: your text: "BORN IN 2015!", shift 1 1 + 2 + 3 -> "CPSO JO 7984!" 4 "CpSo jO 7984!" 5 "!4897 Oj oSpC" With longer passphrases it's better to have a small and easy program. Would you write it? https://en.wikipedia.org/wiki/Passphrase
["def play_pass(s, n):\n\n # Step 1, 2, 3\n shiftText = \"\"\n for char in s:\n if char.isdigit():\n shiftText += str(9 - int(char))\n elif char.isalpha():\n shifted = ord(char.lower()) + n\n shiftText += chr(shifted) if shifted <= ord('z') else chr(shifted - 26)\n else:\n shiftText += char\n\n # Step 4\n caseText = \"\"\n for i in range(len(shiftText)):\n caseText += shiftText[i].upper() if i % 2 == 0 else shiftText[i].lower()\n\n # Step 5\n return caseText[::-1]\n\n", "def play_pass(s, n):\n slower = s.lower()\n change = ''\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n\n for i,char in list(enumerate(slower)):\n if char in alphabet:\n ind = (alphabet.index(char) + n)\n if ind >= 26:\n ind = ind % 26\n if i % 2 == 0:\n change += alphabet[ind].upper()\n else:\n change += alphabet[ind].lower()\n elif char.isdigit():\n change += str(9 - int(char))\n else:\n change += char\n\n return change[::-1]", "def play_pass(s, n):\n passphrase = list(s)\n for i in range(0, len(s)):\n if passphrase[i].isalpha():\n ascii = ord(passphrase[i].lower())\n passphrase[i] = chr(ascii+n-26) if ascii+n > 122 else chr(ascii+n)\n passphrase[i] = passphrase[i].lower() if i % 2 == 1 else passphrase[i].upper()\n if passphrase[i].isdigit():\n passphrase[i] = str(9 - int(passphrase[i]))\n \n return ''.join(passphrase[::-1])", "from string import digits, ascii_uppercase as auc\ndef play_pass(s, n):\n return ''.join(a.lower() if c % 2 else a for c, a in enumerate(s.translate(str.maketrans(auc + digits, auc[n:] + auc[:n] + digits[::-1]))))[::-1]", "def play_pass(s, n):\n return \"\".join([c.lower() \n if (i % 2 != 0) \n else c\n for i, c in enumerate([chr((ord(c) - 65 + n) % 26 + 65)\n if (ord(c) in range(65, 91))\n else str(abs(int(c) - 9))\n if (ord(c) in range(48, 58))\n else c for c in s])][::-1])", "def play_pass(phrase, n):\n output = ''\n for i, char in enumerate(phrase):\n if char.isdigit():\n char = str(9 - int(char))\n elif char.isalpha():\n code = (ord(char) - 65 + n) % 26\n char = chr(code + 65)\n if i & 1:\n char = char.lower()\n output = char + output\n return output", "from string import ascii_uppercase as letters, digits\n\ndef play_pass(s, n):\n return \"\".join(c.lower() if i & 1 else c\n for i, c in enumerate(s.upper().translate(\n str.maketrans(letters + digits, letters[n:] + letters[:n] + digits[::-1])\n )))[::-1]", "from string import ascii_lowercase as s\n\ndef play_pass(message,key):\n m = message.lower().translate(str.maketrans(s+\"0123456789\",s[key%26:]+s[:key%26]+\"9876543210\"))\n return \"\".join([j if i%2==1 else j.upper() for i,j in enumerate(m)][::-1])", "from collections import deque\n\ndef play_pass(s, n):\n d = deque( chr(ord('A')+x) for x in range(26) )\n d.rotate(-n)\n return ''.join( d[ord(c)-ord('A')].lower() if c.isalpha() and i%2\n else d[ord(c)-ord('A')] if c.isalpha()\n else str(9-int(c)) if c.isdigit()\n else c for i,c in enumerate(s) )[::-1]"]
{"fn_name": "play_pass", "inputs": [["I LOVE YOU!!!", 1], ["I LOVE YOU!!!", 0], ["AAABBCCY", 1], ["MY GRANMA CAME FROM NY ON THE 23RD OF APRIL 2015", 2], ["TO BE HONEST WITH YOU I DON'T USE THIS TEXT TOOL TOO OFTEN BUT HEY... MAYBE YOUR NEEDS ARE DIFFERENT.", 5], ["IN 2012 TWO CAMBRIDGE UNIVERSITY RESEARCHERS ANALYSED PASSPHRASES FROM THE AMAZON PAY SYSTEM...", 20], ["IN 2012 TWO CAMBRIDGE UNIVERSITY RESEARCHERS ANALYSED PASSPHRASES FROM THE AMAZON PAY SYSTEM...", 10], ["1ONE2TWO3THREE4FOUR5FIVE6SIX7SEVEN8EIGHT9NINE", 5], ["AZ12345678ZA", 1], ["!!!VPZ FWPM J", 25], ["BOY! YOU WANTED TO SEE HIM? IT'S YOUR FATHER:-)", 15], ["FOR THIS REASON IT IS RECOMMENDED THAT PASSPHRASES NOT BE REUSED ACROSS DIFFERENT OR UNIQUE SITES AND SERVICES.", 15], ["ONCE UPON A TIME YOU DRESSED SO FINE (1968)", 12], ["AH, YOU'VE GONE TO THE FINEST SCHOOL ALL RIGHT, MISS LONELY", 12], ["THE SPECIES, NAMED AFTER THE GREEK GOD OF THE UNDERWORLD, LIVES SOME 3,600 FEET UNDERGROUND.", 8]], "outputs": [["!!!vPz fWpM J"], ["!!!uOy eVoL I"], ["zDdCcBbB"], ["4897 NkTrC Hq fT67 GjV Pq aP OqTh gOcE CoPcTi aO"], [".ySjWjKkNi jWf xIjJs wZtD JgDfR ...dJm yZg sJyKt tTy qTtY YcJy xNmY JxZ Y'StI N ZtD MyNb yXjStM Jg tY"], ["...gYnMsM SuJ HiTuGu yBn gIlZ MyMuLbJmMuJ XyMsFuHu mLyBwLuYmYl sNcMlYpChO YaXcLvGuW IqN 7897 hC"], ["...wOdCiC IkZ XyJkWk oRd wYbP CoCkBrZcCkZ NoCiVkXk cBoRmBkOcOb iDsCbOfSxE OqNsBlWkM YgD 7897 xS"], ["JsNs0yMlNj1sJaJx2cNx3jAnK4WzTk5jJwMy6tBy7jSt8"], ["bA12345678aB"], ["I LoVe yOu!!!"], [")-:gTwIpU GjDn h'iX ?bXw tTh dI StIcPl jDn !NdQ"], [".hTrXkGtH ScP HtIxH TjFxCj gD IcTgTuUxS HhDgRp sThJtG Tq iDc hThPgWeHhPe iPwI StScTbBdRtG Hx iX CdHpTg hXwI GdU"], [")1308( qZuR Ae pQeEqDp gAk qYuF M ZaBg qOzA"], ["KxQzAx eEuY ,fTsUd xXm xAaToE FeQzUr qTf aF QzAs qH'GaK ,tM"], [".LvCwZoZmLvC BmMn 993,6 mUwA AmDqT ,lTzWeZmLvC MpB Nw lWo sMmZo mPb zMbNi lMuIv ,AmQkMxA MpB"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,632
def play_pass(s, n):
79df791eab57353d8a0062e2c9082f97
UNKNOWN
Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. For example: ```python sum_digits(10) # Returns 1 sum_digits(99) # Returns 18 sum_digits(-32) # Returns 5 ``` Let's assume that all numbers in the input will be integer values.
["def sum_digits(number):\n return sum(map(int, str(abs(number))))", "def sum_digits(n):\n return eval('+'.join(str(abs(n))))", "def sum_digits(number):\n num_string = str(abs(number))\n total = 0\n \n for char in num_string:\n total += int(char)\n \n return total", "def sum_digits(number):\n d = 0 \n for c in str(abs(number)):\n d += ord(c) - 48\n return d", "sum_digits=lambda n:sum(int(e)for e in str(abs(n)))", "def sum_digits(n):\n return sum([int(x) for x in str(abs(n))])", "def sum_digits(number):\n return sum(int(ele) for ele in str(abs(number)))", "def sum_digits(number):\n return sum([int(i) for i in str(abs(number))])", "def sum_digits(number):\n inp = str(number)\n s = 0\n for x in inp:\n try:\n s += int(x)\n except:\n pass\n return s\n", "def sum_digits(number):\n return sum(int(digit) for digit in str(number).replace('-',''))", "def sum_digits(number):\n sum = 0\n if number < 0:\n number = number * -1\n while len(str(number)) != 1:\n sum += number%10\n number = number//10\n sum += number\n return sum\n", "\ndef sum_digits(number):\n sum = 0\n if len(str(number)) == 1:\n return number\n else:\n for i in range(len(str(number))):\n if str(number)[i] == \"-\":\n sum += 0\n else:\n sum += int(str(number)[i])\n return sum", "def sum_digits(number):\n if number < 0:\n number *= -1\n return sum(map(int, str(number)))", "def sum_digits(number):\n string = str(number)\n for char in string:\n if char == \"-\":\n string = string.replace(char, \"\")\n return sum([int(x) for x in string])", "def sum_digits(number):\n return sum(int(i) if not i=='-' else 0 for i in str(number))", "def sum_digits(number):\n str_num = str(number)\n ret_num = 0\n for num in str_num:\n if num != '-':\n ret_num = ret_num + int(num)\n return ret_num", "def sum_digits(number):\n total = 0\n for digit in str(abs(number)):\n total += int(digit)\n return total", "def sum_digits(x):\n if len(str(x)) == 1:\n return x\n suma=0\n for j in str(x):\n if j != '-':\n suma += int(j)\n return suma # ...", "def sum_digits(number):\n sum = 0\n for num in str(abs(number)):\n sum += int(num)\n return sum\n", "def sum_digits(number):\n number = str(number)\n numT = 0\n for i in number:\n if i != \"-\":\n numT += int(i)\n return numT", "def sum_digits(number):\n number = abs(number)\n if number == 0:\n return 0\n \n return number % 10 + sum_digits(number // 10)", "def sum_digits(number):\n chars = list(str(number))\n digits = [int(char) for char in chars if char.isdigit()]\n return sum(digits)\n", "def sum_digits(number):\n # ..\n s = 0\n n = str(number)\n for i in n:\n if i.isdigit():\n s += int(i)\n return s\n", "def sum_digits(number):\n kol=0\n j=\"\"\n string=str(number)\n for i in string:\n j=\"\"\n if i==\"-\":\n continue\n else:\n j+=i\n kol+=int(j)\n return kol", "def sum_digits(number):\n sum = 0\n for char in str(number):\n if char == '-':\n continue\n else:\n sum = sum + eval(char)\n return sum ", "\ndef sum_digits(number):\n sum = 0\n number = abs(number)\n number = str(number)\n for i in number:\n print(i)\n sum += int(i)\n return sum\n \n", "def sum_digits(number):\n digits = list(map(str, str(number)))\n digits = [int(x) for x in digits if x.isdigit()]\n return sum(digits)\n", "def sum_digits(number):\n result = 0\n is_minus = False\n \n if (number < 0):\n is_minus = True\n number = number * -1\n for element in str(number):\n result += int(element)\n \n return result", "def sum_digits(number):\n nr = str(number)\n total = 0\n for i in range(len(nr)):\n if nr[i].isdigit():\n total += int(nr[i])\n return total", "def sum_digits(number):\n t=0\n for i in str(number):\n if i.isdigit():\n t =t +int(i)\n return t", "def sum_digits(number):\n luz = abs(number)\n liz = [int(x) for x in str(luz)]\n return sum(liz)\n \n", "def sum_digits(number):\n total = 0\n for num in str(abs(number)):\n total += int(str(num))\n \n return total\n\nprint(sum_digits(23))", "def sum_digits(number):\n summ = 0\n number = str(number)\n for num in number:\n if num.isdigit():\n summ += int(num)\n else:\n pass\n return summ", "def sum_digits(number):\n asum = 0\n for val in str(number):\n if val != \"-\":\n print(val)\n asum += int(val)\n return(asum)", "def sum_digits(number):\n numberList = [int(x) for x in str(abs(number))]\n return sum(numberList)", "def sum_digits(number):\n y = 0\n for x in str(number):\n if x == \"-\":\n pass\n else:\n y += int(x)\n return y", "def sum_digits(number):\n if number < 0:\n number *= -1\n a = str(number)\n return sum([int(i) for i in a])\n", "def sum_digits(number):\n if number >= 0:\n total = 0\n for i in str(number):\n total += int(i)\n return total\n else:\n total = 0\n for i in str(number)[1:]:\n total += int(i)\n return total", "def sum_digits(num):\n return sum([int(i) for i in str(num) if i.isdigit()])\n", "def sum_digits(number):\n result = 0\n for num in str(number):\n try:\n result += int(num)\n except:\n continue\n return result", "def sum_digits(number):\n \n num_str = str(abs(number))\n s = 0\n \n for i in num_str:\n s += int(i)\n return s\n \n", "def sum_digits(number):\n splits = list(str(number))\n num_lst = []\n for num in splits:\n try:\n if type(int(num)) == int:\n num_lst.append(int(num))\n except:\n continue\n return(sum(num_lst))", "def sum_digits(number):\n num = str(abs(number))\n res = 0\n for item in num:\n res += int(item)\n return res", "def sum_digits(number):\n num = str(number)\n num = [int(x) for x in num if x != '-']\n return sum(num)\n", "def sum_digits(number):\n sumnumbers=0\n for numbers in str(number.__abs__()):\n sumnumbers += int(numbers)\n return sumnumbers", "def sum_digits(number):\n n = str(abs(number))\n sum = 0\n for i in range(len(n)):\n sum += int(n[i])\n return sum", "def sum_digits(number):\n # ...\n q = 0\n h = str(number.__abs__())\n for i in h:\n q += int(i)\n \n return q", "def sum_digits(number):\n number_list = list(str(number))\n sum = 0\n print(number_list)\n for x in number_list:\n if x == '-':\n continue\n else:\n sum += int(x)\n return sum", "def sum_digits(number):\n digits = []\n remove = []\n num_sum = 0\n if number < 0:\n number = abs(number)\n for split in str(number):\n digits.append(split)\n\n print(digits)\n for add in digits:\n num_sum += int(add)\n print(num_sum)\n return num_sum", "def sum_digits(number):\n k = sum(list(map(int, str(abs(number)))))\n return(k)", "def sum_digits(number):\n #initializing sum to zero\n sum=0\n #for each digit(e) in number\n for e in str(abs(number)):\n #adding each digit to sum\n sum+=int(e)\n #returning sum\n return sum", "def sum_digits(number):\n if number<0:\n number = number*-1\n total = 0\n while number>0:\n dig = number%10\n total+=dig\n number = number//10\n return total", "def sum_digits(number):\n my_sum = 0\n number = abs(number)\n while number >= 10:\n my_sum = my_sum + (number % 10)\n number = int(number / 10)\n my_sum = my_sum + number\n return my_sum", "def sum_digits(number):\n sum_digits = 0\n number2 = abs(number)\n for i in str(number2):\n sum_digits += int(i)\n return sum_digits\n \n # ...\n", "def sum_digits(number):\n num = str(number)\n num = num.lstrip(\"-\")\n \n result = 0\n \n for i in num:\n result += int(i)\n \n return result\n", "def sum_digits(number):\n sum = 0\n while abs(number) // 10 != 0:\n sum += abs(number) % 10\n number = abs(number) // 10\n sum += abs(number) % 10\n return sum", "def sum_digits(number):\n number = abs(number)\n number = str(number)\n sum_num = 0 \n for i in number:\n i = int(i)\n sum_num = sum_num + i\n return sum_num", "def sum_digits(number):\n absNum = number if number > 0 else -(number)\n strList = (list(str(absNum)))\n return sum(map(lambda x: int(x), strList))", "def sum_digits(number):\n abs_value = 0\n numbers = map(int, str(number).strip('-'))\n for i in numbers:\n abs_value += i\n return abs_value", "def sum_digits(number):\n count = 0\n number = abs(number)\n for num in str(number):\n count = count + int(num)\n return (count)\n # ...\n", "def sum_digits(number):\n sum = 0\n for i in list(str(abs(number))):\n sum = sum + int(i)\n\n return sum", "def sum_digits(number):\n \n if number<0:\n number = number * -1\n \n number=str(number)\n \n sum=0\n \n for i in number:\n \n sum+=int(i)\n \n return sum\n", "def sum_digits(number):\n if number < 0:\n number *= -1\n \n if number < 10:\n return number\n else:\n last_digit = number % 10\n return sum_digits( number // 10 ) + last_digit", "def sum_digits(number):\n sn = str(number)\n rez=0\n for i in sn:\n if i.isnumeric():\n rez+=int(i)\n return rez", "def sum_digits(number):\n naked = str(number).strip('-')\n return sum(int(digit) for digit in naked)\n", "import numpy as np\ndef sum_digits(number):\n number = int(np.sqrt(number**2))\n return sum([int(d) for d in str(number)])", "def sum_digits(num):\n sum = 0\n for x in str(abs(num)):\n sum += int(x)\n return sum\n", "def sum_digits(number):\n \n number = abs(number)\n \n result = 0\n while(number > 0):\n result += number % 10\n number //= 10\n \n return result;\n", "def sum_digits(number):\n bruh = 0\n for i in str(abs(number)):\n bruh += int(i)\n return bruh", "def sum_digits(number):\n for i in str(number):\n if i == '-':\n number=str(number).strip('-')\n else: pass\n digits = [int(x) for x in str(number)]\n return sum(digits)\n", "def sum_digits(number):\n n = []\n for i in str(number):\n if i != '-':\n n.append(int(i))\n return sum(n)", "import math\n\ndef sum_digits(n):\n n = round(math.fabs(n))\n all = [int(s) for s in str(n)]\n return sum(all)"]
{"fn_name": "sum_digits", "inputs": [[10], [99], [-32], [1234567890], [0], [666], [100000002], [800000009]], "outputs": [[1], [18], [5], [45], [0], [18], [3], [17]]}
INTRODUCTORY
PYTHON3
CODEWARS
11,318
def sum_digits(number):
6b94d12267c5eb0e9ac3de0c74efbeeb
UNKNOWN
You are asked to write a simple cypher that rotates every character (in range [a-zA-Z], special chars will be ignored by the cipher) by 13 chars. As an addition to the original ROT13 cipher, this cypher will also cypher numerical digits ([0-9]) with 5 chars. Example: "The quick brown fox jumps over the 2 lazy dogs" will be cyphered to: "Gur dhvpx oebja sbk whzcf bire gur 7 ynml qbtf" Your task is to write a ROT13.5 (ROT135) method that accepts a string and encrypts it. Decrypting is performed by using the same method, but by passing the encrypted string again. Note: when an empty string is passed, the result is also empty. When passing your succesful algorithm, some random tests will also be applied. Have fun!
["trans = \"abcdefghijklmnopqrstuvwxyz\" * 2\ntrans += trans.upper() + \"0123456789\" * 2\n\ndef ROT135(input):\n output = []\n for c in input:\n if c.isalpha():\n c = trans[trans.index(c) + 13]\n elif c.isdigit():\n c = trans[trans.index(c) + 5]\n output.append(c)\n return \"\".join(output)", "table = str.maketrans(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", \"NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm5678901234\")\n\ndef ROT135(input):\n return input.translate(table)", "from string import ascii_lowercase as low, ascii_uppercase as upp, digits as dig\n\ntrans = str.maketrans(low+upp+dig, low[13:]+low[:13]+upp[13:]+upp[:13]+dig[5:]+dig[:5])\n\ndef ROT135(input):\n return input.translate(trans)", "from string import digits as d, ascii_lowercase as l, ascii_uppercase as u\n\ntbl = str.maketrans(\n d + l + u,\n d[5:] + d[:5] + l[13:] + l[:13] + u[13:] + u[:13],\n)\n\ndef ROT135(input):\n return input.translate(tbl)", "from string import ascii_lowercase as lowers, digits\n\n\nrotlow = f\"{lowers[13:]}{lowers[:13]}\"\nrotdig = f\"{digits[5:]}{digits[:5]}\"\ntable = str.maketrans(\n f\"{lowers}{lowers.upper()}{digits}\",\n f\"{rotlow}{rotlow.upper()}{rotdig}\",\n)\n\n\ndef ROT135(input):\n return input.translate(table)", "def ROT135(message):\n first = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n trance = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm5678901234'\n return message.translate(str.maketrans(first, trance)) ", "t = \"abcdefghijklmnopqrstuvwxyz\" * 2\nt += t.upper() + \"0123456789zzz5678901234\"\n\ndef ROT135(input):\n return \"\".join(t[t.index(c) + 13] if c in t else c for c in input)", "D = {a:b for a, b in zip('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', \n 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM5678901234')}\n\ndef ROT135(s):\n return ''.join(D.get(c, c) for c in s)"]
{"fn_name": "ROT135", "inputs": [["The quick brown fox jumps over the 2 lazy dogs"], ["Gur dhvpx oebja sbk whzcf bire gur 7 ynml qbtf"], ["1234567890"], ["12_-56789."]], "outputs": [["Gur dhvpx oebja sbk whzcf bire gur 7 ynml qbtf"], ["The quick brown fox jumps over the 2 lazy dogs"], ["6789012345"], ["67_-01234."]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,042
def ROT135(input):
e34b21a241e18a84f42104a92ffb902a
UNKNOWN
To celebrate today's launch of my Hero's new book: Alan Partridge: Nomad, We have a new series of kata arranged around the great man himself. Given an array of terms, if any of those terms relate to Alan Partridge, return Mine's a Pint! The number of ! after the t should be determined by the number of Alan related terms you find in the provided array (x). The related terms are: Partridge PearTree Chat Dan Toblerone Lynn AlphaPapa Nomad If you don't find any related terms, return 'Lynn, I've pierced my foot on a spike!!' All Hail King Partridge Other katas in this series: Alan Partridge II - Apple Turnover Alan Partridge III - London
["def part(arr):\n l = [\"Partridge\", \"PearTree\", \"Chat\", \"Dan\", \"Toblerone\", \"Lynn\", \"AlphaPapa\", \"Nomad\"]\n s = len([i for i in arr if i in l])\n return \"Mine's a Pint\"+\"!\"*s if s>0 else 'Lynn, I\\'ve pierced my foot on a spike!!'", "def part(arr):\n terms = {'Partridge', 'PearTree', 'Chat', 'Dan', 'Toblerone', 'Lynn', 'AlphaPapa', 'Nomad'}\n marks = ''.join('!' for x in arr if x in terms)\n return \"Mine's a Pint\" + marks if marks else \"Lynn, I've pierced my foot on a spike!!\"", "def part(arr):\n terms = frozenset(['Partridge', 'PearTree', 'Chat', 'Dan', 'Toblerone', 'Lynn', 'AlphaPapa', 'Nomad'])\n \n count = sum(1 for x in arr if x in terms)\n \n return \"Mine's a Pint\" + \"!\" * count if count > 0 else \"Lynn, I've pierced my foot on a spike!!\"", "check = {\"Partridge\", \"PearTree\", \"Chat\", \"Dan\", \"Toblerone\", \"Lynn\", \"AlphaPapa\", \"Nomad\"}.__contains__\n\ndef part(arr):\n result = sum(map(check, arr))\n return f\"Mine's a Pint{'!'*result}\" if result else \"Lynn, I've pierced my foot on a spike!!\"", "from collections import Counter\n\ndef part(arr):\n c = Counter([i in {'Partridge','PearTree','Chat','Dan','Toblerone','Lynn','AlphaPapa','Nomad'} for i in arr])\n return \"Mine's a Pint\" + c[True] * '!' if True in c else \"Lynn, I've pierced my foot on a spike!!\" \n", "related = {\"Partridge\", \"PearTree\", \"Chat\", \"Dan\", \"Toblerone\", \"Lynn\", \"AlphaPapa\", \"Nomad\"}\n\ndef part(arr):\n found = sum(1 for w in arr if w in related)\n return f\"Mine's a Pint{'!' * found}\" if found else \"Lynn, I've pierced my foot on a spike!!\"", "def part(a):\n s = {\"Partridge\", \"PearTree\", \"Chat\", \"Dan\", \"Toblerone\", \"Lynn\", \"AlphaPapa\", \"Nomad\"}\n n = sum(x in s for x in a)\n return \"Mine's a Pint{}\".format(\"!\" * n) if n else \"Lynn, I've pierced my foot on a spike!!\"", "def part(arr):\n terms = [\"Partridge\",\"PearTree\",\"Chat\",\"Dan\",\"Toblerone\",\"Lynn\",\"AlphaPapa\",\"Nomad\"]\n x = (sum(1 for i in arr if i in terms))\n return \"Mine's a Pint{}\".format(\"!\"*x) if x>0 else \"Lynn, I've pierced my foot on a spike!!\"", "S = {\"Partridge\", \"PearTree\", \"Chat\", \"Dan\", \"Toblerone\", \"Lynn\", \"AlphaPapa\", \"Nomad\"}\ndef part(arr):\n n = sum(w in S for w in arr)\n return \"Lynn, I've pierced my foot on a spike!!\" if not n else \"Mine's a Pint\"+\"!\"*n", "def part(arr):\n st = frozenset(('Partridge', 'PearTree', 'Chat', 'Dan', 'Toblerone', 'Lynn', 'AlphaPapa', 'Nomad'))\n s = sum(x in st for x in arr)\n return \"Mine's a Pint\" + '!' * s if s else \"Lynn, I've pierced my foot on a spike!!\""]
{"fn_name": "part", "inputs": [[["Grouse", "Partridge", "Pheasant"]], [["Pheasant", "Goose", "Starling", "Robin"]], [["Grouse", "Partridge", "Partridge", "Partridge", "Pheasant"]], [[]], [["Grouse", "Partridge", "Pheasant", "Goose", "Starling", "Robin", "Thrush", "Emu", "PearTree", "Chat", "Dan", "Square", "Toblerone", "Lynn", "AlphaPapa", "BMW", "Graham", "Tool", "Nomad", "Finger", "Hamster"]]], "outputs": [["Mine's a Pint!"], ["Lynn, I've pierced my foot on a spike!!"], ["Mine's a Pint!!!"], ["Lynn, I've pierced my foot on a spike!!"], ["Mine's a Pint!!!!!!!!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,689
def part(arr):
6294068a925c83c5ae35bc74d86402db
UNKNOWN
Find the greatest common divisor of two positive integers. The integers can be large, so you need to find a clever solution. The inputs `x` and `y` are always greater or equal to 1, so the greatest common divisor will always be an integer that is also greater or equal to 1.
["#Try to make your own gcd method without importing stuff\ndef mygcd(x,y):\n #GOOD LUCK\n while y:\n x,y=y,x%y\n return x", "def mygcd(x,y):\n return x if y == 0 else mygcd(y, x % y)\n", "def mygcd(x,y):\n if x%y == 0:\n return y\n else:\n return mygcd(y,x%y)\n\n# reference: http://en.wikipedia.org/wiki/Euclidean_algorithm\n# Please note that it does not matter if y is larger than x, because x%y will have value x\n# which is passed to variable y in the next iteration. So the number of iterations is only\n# increased by one, but the solution will still be correct.\n", "def mygcd(x,y):\n return x if not y else mygcd(y, x%y)", "def mygcd(x, y):\n while y>0:\n x, y = y, x%y\n return(x)", "def mygcd(x,y):\n if x == 0:\n return y\n if y == 0:\n return x\n else:\n return mygcd(y, x%y)", "def mygcd(x,y):\n \"\"\"Euclidean algorithm.\"\"\"\n reminder = x%y\n if reminder == 0:\n return y\n else:\n return mygcd(y,reminder)", "def mygcd(a,b):\n while b > 0:\n a, b = b, a % b\n return a", "#Try to make your own gcd method without importing stuff\ndef mygcd(a,b):\n if b == 0:\n return a\n else:\n return mygcd(b, a % b)"]
{"fn_name": "mygcd", "inputs": [[1, 3], [60, 12], [2672, 5678], [10927782, 6902514], [1590771464, 1590771620]], "outputs": [[1], [12], [334], [846], [4]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,267
def mygcd(x,y):
4666b9998396755de7e1ec196334070f
UNKNOWN
## Task Find the sum of the first `n` elements in the Recamán Sequence. Input range: ```python 1000 tests 0 <= n <= 2,500,000 ``` ___ ## Sequence The sequence is formed using the next formula: * We start with `0` * At each step `i`, we subtract `i` from the previous number * If the result is not negative, and not yet present in the sequence, it becomes the `i`th element of the sequence * Otherwise the `i`th element of the sequence will be previous number plus `i` The beginning of the sequence is `[0, 1, 3, 6, 2, ...]` because: 0) `0` <- we start with `0` 1) `1` <- `0 - 1` is negative, hence we choose `0 + 1` 2) `3` <- `1 - 2` is negative, hence we choose `1 + 2` 3) `6` <-`3 - 3` is not negative, but we already have a `0` in the sequence, hence we choose `3 + 3` 4) `2` <- `6 - 4` is positive, and is not present in the sequence yet, so we go for it ___ ## Examples ``` rec(0) == 0 rec(1) == 0 rec(2) == 1 rec(3) == 4 rec(4) == 10 rec(5) == 12 ```
["S, SS, SUM = [0], {0}, [0]\n\ndef rec(n):\n while len(S)<=n:\n v = S[-1] - len(S)\n if v<= 0 or v in SS: v += 2*len(S)\n S.append(v)\n SS.add(v)\n SUM.append(SUM[-1]+v)\n return SUM[n-1]", "# precaclulate results\nLIMIT = 2500000\nRECA_SUM = [0, 0]\nseen = {0}\nlast = 0\ntotal = 0\n\nfor n in range(1, LIMIT):\n new = last - n\n if new < 0 or new in seen:\n new = last + n\n seen.add(new)\n total += new\n RECA_SUM.append(total)\n last = new\ndel seen\n\n\ndef rec(x):\n return RECA_SUM[x]", "s, seq, sums = {0}, [0], [0]\nfor i in range(25 * 10 ** 5 + 1):\n x = seq[-1] - i\n if x < 0 or x in s: x += 2 * i\n s.add(x); seq.append(x); sums.append(x + sums[-1])\nrec=sums.__getitem__", "all_sums = {}\n\ndef helper():\n all_sums[0] = 0\n rec, suma = 0, 0\n made = {0}\n for i in range(1, 2500000):\n cur = rec - i\n if cur < 0 or cur in made:\n cur = rec + i\n suma += cur\n made.add(cur)\n rec = cur\n all_sums[i] = suma\n return True\n\ndef rec(x):\n if not all_sums:\n helper()\n return all_sums[x - 1] if x >= 1 else 0", "____, _____ = {0}, [0]\n___ = [0, 0]\n\ndef rec(_):\n for _______ in range(len(_____), _ + 1):\n ________ = _____[-1] - _______\n \n if not (________ >= 0 and ________ not in ____): ________ += _______ + _______\n ____.add(________)\n \n _____.append(________)\n \n ___.append(___[-1] + ________)\n \n return ___[_]", "cache2, cache, seq = {0:0}, {0:0, 1:0}, {0}\ndef rec(n):\n if n in cache2: return cache[n]\n i = max(cache2)\n r = cache2[i]\n for i in range(i+1, n):\n cache2[i] = r = [r-i, r+i][(r-i < 0)|(r-i in seq)]\n seq.add(r)\n cache[i+1] = cache[i] + r\n return cache[n]\n", "SEEN = {0}\nREC = [0]\nSUM = [0, 0]\n\ndef rec(n):\n\n for i in range(len(REC), n + 1):\n k = REC[-1] - i\n if not (k >= 0 and k not in SEEN): \n k += i + i\n SEEN.add(k)\n REC.append(k)\n SUM.append(SUM[-1] + k)\n \n return SUM[n]", "R=[0,0]\n\ns=0\np=0\nS={0}\nfor i in range(1,2500000):\n x=p-i\n if x<0 or x in S:x=p+i\n S|={x}\n s+=x\n p=x\n R+=[s]\ndef rec(x):return R[x]"]
{"fn_name": "rec", "inputs": [[0], [1], [2], [5], [100], [200], [1000], [10000]], "outputs": [[0], [0], [1], [12], [7496], [36190], [837722], [82590002]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,392
def rec(x):
152eab544f4c602c7d7dc687d565229d
UNKNOWN
Implement a method that accepts 3 integer values a, b, c. The method should return true if a triangle can be built with the sides of given length and false in any other case. (In this case, all triangles must have surface greater than 0 to be accepted).
["def is_triangle(a, b, c):\n return (a<b+c) and (b<a+c) and (c<a+b)\n", "def is_triangle(a, b, c):\n a, b, c = sorted([a, b, c])\n return a + b > c\n", "def is_triangle(a, b, c):\n return (a + b) > c and (a + c) > b and (b + c) > a\n", "def is_triangle(a, b, c):\n \"\"\"Determine if three sides of given lengths can form a triangle.\n \n Args:\n a (int): First side length\n b (int): Second side length\n c (int): Third side lenght\n \n Returns:\n bool: True if the three sides given can form a triangle.\n \"\"\"\n return a < b + c and b < a + c and c < a + b\n", "def is_triangle(a, b, c):\n \n if(a <= 0 | b <= 0 | c <= 0):\n return False\n elif( a + b <= c or a + c <= b or b + c <= a): \n return False\n else:\n return True", "def is_triangle(a, b, c):\n return abs(a-b) < c < a+b", "def is_triangle(a, b, c):\n s=[a,b,c]\n for i in s:\n if sum(s)-i <= i:\n return False\n return True", "def is_triangle(a, b, c):\n return 2 * max(a, b, c) < a + b + c", "def is_triangle(a, b, c):\n if a+b <= c or a+c <= b or b+c <= a:\n return False\n else:\n return True", "def is_triangle(a, b, c):\n return all([a+b>c, a+c>b, b+c>a])\n", "def is_triangle(*args):\n a, b, c = sorted(args)\n return a + b > c", "def is_triangle(a, b, c):\n if a + b + c == 0:\n return False\n if a + b <= c:\n return False\n if a + c <= b:\n return False\n if b + c <= a:\n return False\n return True", "def is_triangle(a, b, c):\n if a <= 0 or b <= 0 or c <= 0:\n return False\n sum = a + b + c\n if fits(sum, max(a, b, c)):\n return True\n return False\n\ndef fits(sum, a):\n return sum - a > a", "def is_triangle(a, b, c):\n if a > 0 and b > 0 and c > 0:\n if ((a + b) > c) and ((b + c) > a) and ((a + c) > b):\n return True\n elif a == b == c:\n return True\n else:\n return False\n else: \n return False\n", "def is_triangle(a, b, c):\n return max(a, b, c)< (a+b+c-max(a,b, c))\n", "def is_triangle(a, b, c):\n return all([a < b+c, b < a+c, c < a+b]) \n", "def is_triangle(a, b, c):\n return(b+c > a > abs(b - c))", "is_triangle=lambda _,a,b:sum(sorted([_,a,b])[:2])>sorted([_,a,b])[2]\n\n", "def is_triangle(a, b, c):\n sides = [a, b, c]\n max_side = max(sides)\n if sum(sides) - max_side > max_side:\n return True\n else:\n return False\n \n", "def is_triangle(a, b, c):\n s = a + b + c\n if s - max(a,b,c) > max(a,b,c):\n return True\n return False", "def is_triangle(a, b, c):\n return a + b + c - max(a,b,c) > max(a,b,c)\n", "def is_triangle(a, b, c):\n #Triangle inequality\n return a + b > c and a + c > b and b + c > a\n", "def is_triangle(a, b, c):\n cond1 = a + b > c\n cond2 = b + c > a \n cond3 = a + c > b\n list = [cond1, cond2, cond3]\n if False in list:\n return False\n return True", "def is_triangle(x, y, z):\n return (x<y+z) and (y<x+z) and (z<x+y)\n", "def is_triangle(a, b, c):\n t1 = a + b > c\n t2 = a + c > b\n t3 = b + c > a\n \n return t1 and t2 and t3\n #return False\n", "def is_triangle(a, b, c):\n # All you have to do is use the Triangle Inequality Theorem.\n return (a + b) > c and (a + c) > b and (b + c) > a", "def is_triangle(*sides):\n return sum(sorted(sides)[:2]) > max(sides)\n", "def is_triangle(a, b, c):\n max_number = max([a, b, c])\n \n if sum([a,b,c])-max_number > max_number:\n return True\n \n return False", "def is_triangle(a, b, c):\n if (a>0 and b>0 and c>0):\n if (a+b>c and a+c>b and c+b>a):\n return True\n else:\n return False\n return False\n", "def is_triangle(a, b, c):\n llist = [a,b,c]\n llist.sort()\n highest = llist[2]\n sumrest = llist[0] + llist[1]\n if highest < sumrest:\n return True\n return False", "def is_triangle(a, b, c):\n # Check if sum of 2 sides is bigger than the last size\n if a + b > c and a + c > b and b + c > a:\n return True\n \n return False\n", "def is_triangle(a, b, c):\n lst = [int(a),int(b),int(c)]\n lst = sorted(lst)\n if lst[0]+lst[1]>lst[2]:\n return True\n else:\n return False\n", "def is_triangle(a, b, c):\n if (abs(b-a)<c<abs(b+a) and\n abs(c-a)<b<abs(c+a) and\n abs(c-b)<a<abs(c+b)):\n return True\n return False\n", "def is_triangle(a, b, c):\n lengths = [a,b,c]\n x = sorted(lengths)\n print((x,x[0]+x[1]))\n if x[0]+x[1]>x[2]:\n return True\n else:\n return False\n", "def is_triangle(a, b, c):\n if a + b > c:\n \n if a + c > b:\n \n if b +c > a:\n return True\n else:\n return False\n \n else:\n return False\n \n else:\n return False\n\n \n return False\n", "def is_triangle(a, b, c):\n max_int = max(a,b,c)\n min_int = min(a,b,c)\n \n \n if max_int == a:\n sum = b + c\n if sum > a:\n return True\n if max_int == b:\n sum = a + c\n if sum > b:\n return True\n if max_int == c:\n sum = a + b\n if sum > c:\n return True\n \n return False\n", "def is_triangle(a, b, c):\n if a == None or b == None or c == None:\n return False\n l_tri = sorted([a,b,c])\n if l_tri[2]>=l_tri[0]+l_tri[1]:\n return False\n return True\n", "def is_triangle(a, b, c):\n if(abs(a+b)<=c or abs(a-b) >= c):\n return False\n elif(abs(c+b)<=a or abs(c-b) >= a):\n return False\n elif(abs(c+a)<=b or abs(c-a) >=b):\n return False\n elif(a<=0 or b<= 0 or c <= 0):\n return False\n return True\n", "def is_triangle(a, b, c):\n if (a + b > c) and (b + c > a) and (c + a > b) and (a > 0) and (b > 0) and (c > 0):\n return True\n else:\n return False\n", "def is_triangle(a, b, c):\n tab_coter = [a, b, c]\n tab_coter.sort()\n calc_long_coter = tab_coter[0] + tab_coter[1]\n if (tab_coter[2] < calc_long_coter):\n return True\n return False\n", "def is_triangle(a, b, c):\n s = sorted([a, b, c])\n return False if s[0] < 1 or sum(s[:-1]) <= s[2] else True", "def is_triangle(a, b, c):\n # test if any combination of 2 sides is > the remaining side\n if ((a+b) > c) and ((b+c) > a) and ((a+c) > b):\n return True\n \n return False\n", "def is_triangle(a, b, c):\n lts = [a,b,c]\n lts.sort()\n return(lts[2]<lts[1]+lts[0])\n\n", "def is_triangle(a, b, c):\n if a > 0 and b > 0 and c > 0 and (a + b > c and a + c > b and c + b > a):\n return True\n \n return False\n", "def is_triangle(a, b, c):\n triangleList = [a,b,c]\n triangleList.sort()\n if triangleList[0]+triangleList[1] > triangleList[2]:\n return True\n else:\n return False\n", "def is_triangle(a, b, c):\n out = []\n out.append(a)\n out.append(b)\n out.append(c)\n out.sort()\n if out[2]>= out[0]+out[1]:\n return False\n else:\n return True", "def is_triangle(a, b, c):\n if not a + b > c or not a + c > b or not b + c >a:\n print(('AB pair',a+b,c))\n print(('AC pair',a+c,b))\n print(('BC pair',b+c,a))\n return False\n else:\n return True\n", "def is_triangle(a, b, c):\n if a <= 0 or b <= 0 or c <= 0:\n return False\n elif (a + b > c) and (b + c > a) and (c + a > b):\n return True\n return False", "def is_triangle(a, b, c):\n if a >=0 or b >= 0 or c >= 0:\n if a+b <= c or a+c <=b or b+c <= a:\n return False\n else:\n return True\n else:\n return False\n return False\n \n#\u043f\u043e \u0438\u0434\u0435\u0435 \u043c\u044b \u0434\u043e\u043b\u0436\u043d\u044b \u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u0447\u0442\u043e \u043d\u0435\u0442 \u0441\u0443\u043c\u043c\u044b \u0434\u043b\u0438\u043d \u0434\u0432\u0443\u0445 \u0441\u0442\u043e\u0440\u043e\u043d \u043c\u0435\u043d\u044c\u0448\u0435\u0439 \u043b\u0438\u0431\u043e \u0440\u0430\u0432\u043d\u043e\u0439 \u0434\u043b\u0438\u043d\u044b \u0442\u0440\u0435\u0442\u044c\u0435\u0439\n", "def is_triangle(a, b, c):\n return ((a < b+c) & (b < a+c) & (c < b+a))\n", "def is_triangle(a, b, c):\n if 2*max([a, b, c]) < a + b + c:\n return True \n else:\n return False\n \n", "def is_triangle(a, b, c):\n \"\"\"The triangle is possible only when all sides are greater than 0 and\n and sum of any two sides greater than the third side.\n \"\"\"\n return ((a+b)>c and (b+c)>a and (c+a)>b and a>0 and b>0 and c>0)\n return False\n", "def is_triangle(a, b, c):\n listOfSides = [a,b,c]\n if max(listOfSides) >= (sum(listOfSides) - max(listOfSides)):\n return False\n return True\n \n \n", "def is_triangle(a, b, c):\n sum = a + b + c\n for side in a, b, c:\n if sum - side <= side:\n return False\n return True\n", "def is_triangle(a, b, c):\n x=max(a,b,c)\n for i in a,b,c:\n if x==i and x<(a+b+c-i):\n return True\n \n return False\n", "def is_triangle(a, b, c):\n return c < a+b and c > a-b and b < a+c and b> a-c\n", "def is_triangle(a, b, c):\n if a+b>c and abs(a-b)<c:\n return True\n elif a+c>b and abs(a-c)<b:\n return True\n elif b+c>a and abs(b-c)<a:\n return True\n else:\n \n return False\n", "def is_triangle(a, b, c):\n lst = sorted([a, b, c])\n if lst[2]-lst[1]<lst[0] and lst[0]+lst[1]>lst[2]:\n return True\n else:\n return False\n \n \n", "def is_triangle(a, b, c):\n\n if a > 0 and b > 0 and c > 0:\n reference = sorted([a, b, c])\n if reference[2] < (reference[0] + reference[1]):\n return True\n else:\n return False\n else:\n return False\n", "def is_triangle(a, b, c):\n if (a + b) > c and (a + c) > b and (b + c) > a:\n print(\"You can make a triangle with these numbers\")\n return True\n else:\n print(\"You cannot make a triangle with these numbers\")\n return False", "def is_triangle(a, b, c):\n if a is 0 and b is 0 and c is 0: \n return False\n elif a+b>c and a+c>b and b+c>a:\n return True\n else: \n return False", "def is_triangle(a, b, c):\n if a and b and c > 0 and ((a + c > b) and (b + a > c) and (c + b > a)):\n return True\n else:\n return False\n", "def is_triangle(a, b, c):\n #triangle inequality theorem\n if a + b > c and a + c > b and b + c > a:\n return True\n return False\n", "def is_triangle(a, b, c):\n if a and b and c > 0:\n return (a + b > c and a + c > b and b + c > a)\n else:\n return False", "def is_triangle(a, b, c):\n if any(side <= 0 for side in (a, b, c)):\n return False\n sides = sorted([a, b, c])\n if sides[0] + sides[1] <= sides[2]:\n return False\n return True", "#def is_triangle2(a, b, c):\n# lista = sorted([a,b,c])\n# if lista[0] + lista[1] > lista[2]:\n# return True\n# return False\n\ndef is_triangle(a, b, c):\n if a + b > c and a + c > b and b + c > a:\n return True\n return False", "def is_triangle(a, b, c):\n v = [a,b,c]\n m = max(v)\n v.remove(m)\n return m < sum(v)\n", "def is_triangle(a, b, c):\n my_flag = False\n if (a + b) > c and (c + b) > a and (a + c) > b:\n my_flag = True\n else:\n my_flag = False\n \n return my_flag\n", "def is_triangle(a, b, c):\n result = ''\n if a + b <= c:\n result = False\n elif a + c <= b:\n result = False\n elif b + c <= a:\n result = False\n else:\n result = True\n return result\n", "import math\ndef is_triangle(a, b, c):\n sides=(a,b,c)\n if sorted(sides)[-1]>=(sorted(sides)[0]+sorted(sides)[1]):\n return False\n return True\n", "def is_triangle(a, b, c):\n if (abs(a-b)<c)and(abs(b-c)<a)and(abs(a-c)<b):\n return True\n return False\n", "def is_triangle(a, b, c):\n table = [a, b, c]\n table.sort()\n return table[0] + table[1] > table[2]\n", "def is_triangle(a, b, c):\n if sum([a, b]) > c and sum ([b, c]) > a and sum([a, c]) > b:\n return True\n else:\n return False\n", "def is_triangle(a, b, c):\n if a >= b+c or b >= c+a or c >= b+a:\n return False;\n else:\n return True\n \n", "def is_triangle(a, b, c):\n largest = max(a,b,c)\n return 2 * largest < a + b + c\n", "def is_triangle(a, b, c):\n if a==0 or b==0 or c==0:\n return 0\n if a+b<=c or b+c<=a or a+c<=b:\n return 0\n else:\n return 1\n", "def is_triangle(a, b, c):\n \"\"\"Return boolean True if a triangle can be built with 3 given sides, else return False.\"\"\"\n return (a + b) > c and (a + c) > b and (b + c) > a\n", "def is_triangle(a, b, c):\n \"\"\"Return boolean True if a triangle can be built with 3 given sides, else return False.\"\"\"\n return True if (a + b) > c and (a + c) > b and (b + c) > a else False\n", "def is_triangle(a, b, c):\n return True if a+b+c >2*max(a,b,c) else False\n", "def is_triangle(a, b, c):\n list_ = [a, b, c]\n return True if sorted(list_)[0] + sorted(list_)[1] > sorted(list_)[2] and sorted(list_)[0] > 0 and sorted(list_)[1] > 0 and sorted(list_)[2] > 0 else False", "def is_triangle(a, b, c):\n list_ = [a, b, c]\n if sorted(list_)[0] + sorted(list_)[1] > sorted(list_)[2]:\n if sorted(list_)[0] > 0 and sorted(list_)[1] > 0 and sorted(list_)[2] > 0:\n return True\n return False", "def is_triangle(a, b, c):\n mylist = [a, b, c]\n mylist.sort()\n if (mylist[0] + mylist[1]) > mylist[2]:\n return True\n else:\n return False\n \n \n", "def is_triangle(a,b,c):\n x = a + b\n y = b + c\n z = a + c\n if x > c and y > a and z > b:\n return True\n else:\n return False", "def is_triangle(a, b, c):\n if (a or b or c) < 0:\n return False\n v = list()\n v.append(a)\n v.append(b)\n v.append(c)\n v.sort()\n _a = v.pop()\n _b = v.pop()\n _c = v.pop()\n\n if _a < _b + _c:\n return True\n if _a == _b + _c:\n return False\n return False\n", "def is_triangle(a, b, c):\n if a < b+c and b < a+c and c<a+b:\n return True\n else:\n return False#, \"didn't work when sides were {} {} {}\".format (a,b,c)\n \n", "def is_triangle(a, b, c):\n if c>=a and c>=b and a+b>c:\n return True\n elif a>=b and a>=c and b+c>a:\n return True\n elif b>=a and b>=c and a+c>b:\n return True\n else:\n return False \n \n", "def is_triangle(a, b, c):\n \"\"\"\n The sum of any two sides must be greater than the length of the third side\n \"\"\"\n if a+b > c and a+c > b and b+c > a:\n return True\n else:\n return False\n", "def is_triangle(a, b, c):\n if (a+b>c)and(b+c>a)and(a+c>b):\n result = True\n print( result)\n else:\n result = False\n print( result)\n return result\n", "def is_triangle(a, b, c):\n x = [a, b, c]\n x.sort()\n if x[2] >= x[0] + x[1]:\n return False\n else:\n return True\n", "def is_triangle(a, b, c):\n x=max(a, b, c)\n lista=[a, b, c]\n lista.remove(x)\n if x<sum(lista):\n return True\n else:\n return False\n", "def is_triangle(a, b, c):\n if c >= a and c >= b and a + b <= c :\n return False \n elif a >= b and a >= c and b + c <= a:\n return False\n elif b >= c and b >= a and c + a <= b:\n return False\n else:\n return True\n", "def is_triangle(a, b, c):\n k = [a+b > c,a+c>b,b+c>a]\n return not False in k", "def is_triangle(a, b, c):\n \n if(a<=abs(b-c)) or (b<=abs(a-c)) or (c<=abs(a-b)):\n return False\n else: \n return True\n\n", "def is_triangle(a, b, c):\n return a > abs(b - c) and b > abs(a - c) and c > abs(a - b)\n \n", "def is_triangle(a, b, c):\n sides = [a,b,c]\n a = max(sides)\n sides.remove(a)\n if sum(sides) > a:\n return True\n return False\n", "def is_triangle(a, b, c):\n result = False\n if a + b > c:\n if a + c > b:\n if c + b > a:\n result = True \n return result\n", "def is_triangle(a, b, c):\n biggest_arg = max([a,b,c])\n return True if biggest_arg < sum([a,b,c]) - biggest_arg else False", "def is_triangle(a, b, c):\n mylist = [a, b, c]\n mylist = sorted(mylist)\n if mylist[0] < mylist[1] + mylist[2] :\n if mylist[1] < mylist[0] + mylist[2]:\n if mylist[2] < mylist[0] + mylist[1]:\n return True\n return False\n", "def is_triangle(a, b, c):\n sides = (a, b, c)\n sides = sorted(sides)\n c = sides[-1]\n b = sides[1]\n a = sides[0]\n return c < a + b", "def is_triangle(a, b, c):\n a = sorted([a, b, c])\n return a[2] < a[0] + a[1]"]
{"fn_name": "is_triangle", "inputs": [[1, 2, 2], [7, 2, 2], [1, 2, 3], [1, 3, 2], [3, 1, 2], [5, 1, 2], [1, 2, 5], [2, 5, 1], [4, 2, 3], [5, 1, 5], [2, 2, 2], [-1, 2, 3], [1, -2, 3], [1, 2, -3], [0, 2, 3]], "outputs": [[true], [false], [false], [false], [false], [false], [false], [false], [true], [true], [true], [false], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
17,419
def is_triangle(a, b, c):
61dc6c11c3206679b203ab959ab37031
UNKNOWN
Consider the numbers `6969` and `9116`. When you rotate them `180 degrees` (upside down), these numbers remain the same. To clarify, if we write them down on a paper and turn the paper upside down, the numbers will be the same. Try it and see! Some numbers such as `2` or `5` don't yield numbers when rotated. Given a range, return the count of upside down numbers within that range. For example, `solve(0,10) = 3`, because there are only `3` upside down numbers `>= 0 and < 10`. They are `0, 1, 8`. More examples in the test cases. Good luck! If you like this Kata, please try [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) [Life without primes](https://www.codewars.com/kata/59f8750ac374cba8f0000033) Please also try the performance version of this kata at [Upside down numbers - Challenge Edition ](https://www.codewars.com/kata/59f98052120be4abfa000304)
["REV = {'6':'9', '9':'6'}\nBASE = set(\"01869\")\n\ndef isReversible(n):\n s = str(n)\n return ( not (set(s) - BASE) # contains only reversible characters\n and (not len(s)%2 or s[len(s)//2] not in \"69\") # does not contain 6 or 9 right in the middle (only for odd number of digits)\n and all( REV.get(c, c) == s[-1-i] for i,c in enumerate(s[:len(s)//2]) )) # symmetric repartition\n\ndef solve(a, b):\n return sum( isReversible(n) for n in range(a,b) )", "def solve(a, b):\n return sum(str(n) == str(n)[::-1].translate(str.maketrans('2345679', 'XXXX9X6')) for n in range(a, b))", "def solve(a, b):\n tr = str.maketrans('0123456789', '01----9-86')\n return sum(1 for x in map(str, range(a, b)) if x == ''.join(reversed(x.translate(tr))))", "solve=lambda a,b:sum(n==n.translate(n.maketrans('2345679','----9-6'))[::-1]for n in map(str,range(a,b)))", "table = str.maketrans(\"69\", \"96\", \"23457\")\n\ndef solve(a, b):\n return sum(1 for n in range(a, b) if f\"{n}\"[::-1] == f\"{n}\".translate(table))", "def solve(a, b):\n s={'0','1','6','8','9'}\n total=0\n for i in range(a,b):\n if i<10:\n if i in (0,1,8):total += 1\n else:\n n=str(i)\n if set(n).issubset(s):\n left, right = 0, len(n)-1\n while left <= right:\n ln = n[left]\n rn = n[right]\n if left==right and ln in '69':\n break\n if ln+rn in ('69', '96') or (ln==rn and ln in '018'):\n left += 1\n right -= 1\n else: break\n if left > right: total += 1\n\n else:\n continue\n return total", "rot = dict(['00', '11', '88', '69', '96'])\n\ndef upside_down_number(n):\n s = str(n)\n return s == ''.join(rot.get(c, '') for c in reversed(s))\n\ndef solve(a, b):\n return sum(upside_down_number(i) for i in range(a, b))", "def solve(a, b):\n return sum(all(a + b in '69 96 88 11 00' for a, b in zip(str(i), str(i)[::-1])) for i in range(a, b))", "dictio = {\"0\":\"0\",\"1\":\"1\",\"6\":\"9\",\"9\":\"6\",\"8\":\"8\"}\ndef solve(a, b):\n return sum(1 for i in range(a,b) if transf(i))\n\ndef transf(n):\n n = str(n)\n for i,j in enumerate(n):\n if j not in dictio:\n return False\n elif dictio[j] != n[-i-1]:\n return False\n return True", "\ndef solve(a, b):\n count = 0\n for num in range(a, b):\n num = str(num)\n if num == num.translate(str.maketrans('1234567890', '1xxxx9x860'))[::-1]:\n count += 1\n return count\n \n"]
{"fn_name": "solve", "inputs": [[0, 10], [10, 100], [100, 1000], [1000, 10000], [10000, 15000], [15000, 20000], [60000, 70000], [60000, 130000]], "outputs": [[3], [4], [12], [20], [6], [9], [15], [55]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,808
def solve(a, b):
7796c3036b86b0f900ba1035da491689
UNKNOWN
A rectangle can be split up into a grid of 1x1 squares, the amount of which being equal to the product of the two dimensions of the rectangle. Depending on the size of the rectangle, that grid of 1x1 squares can also be split up into larger squares, for example a 3x2 rectangle has a total of 8 squares, as there are 6 distinct 1x1 squares, and two possible 2x2 squares. A 4x3 rectangle contains 20 squares. Your task is to write a function `findSquares` that returns the total number of squares for any given rectangle, the dimensions of which being given as two integers with the first always being equal to or greater than the second.
["def findSquares(x,y):\n return sum( (x-i) * (y-i) for i in range(y) )", "def findSquares(x,y):\n if x > y:\n x, y = y, x\n return x*(x+1)*(2*x+1)/6 + (y-x)*x*(x+1)/2", "def findSquares(x,y):\n return sum((x-i)*(y-i) for i in range(min(x,y)))", "def findSquares(x,y):\n squares = 0\n while y > 0: \n squares = squares + x*y\n x = x-1\n y = y-1\n return squares\n", "findSquares=lambda n,m:m*-~m*(3*n-m+1)//6", "def findSquares(x,y):\n S = 0 \n for i in range(y):\n S += (x-i)*(y-i)\n \n return S", "def find_squares(x, y):\n return sum((x - k) * (y - k) for k in range(min(x, y)))\n\n\nfindSquares = find_squares", "findSquares=lambda m,n:sum((m-i)*(n-i) for i in range(min(m,n)))\n", "def findSquares(x,y):\n return sum((x-i+1)*(y-i+1) for i in range(1,min(x,y)+1))", "def findSquares(x,y):\n return sum([(x-i)*(y-i) for i in range(min(x,y))])"]
{"fn_name": "findSquares", "inputs": [[3, 2], [4, 3], [11, 4]], "outputs": [[8], [20], [100]]}
INTRODUCTORY
PYTHON3
CODEWARS
930
def findSquares(x,y):
de615074e0ca25eb9db7f2864fbd10f3
UNKNOWN
In English and programming, groups can be made using symbols such as `()` and `{}` that change meaning. However, these groups must be closed in the correct order to maintain correct syntax. Your job in this kata will be to make a program that checks a string for correct grouping. For instance, the following groups are done correctly: ``` ({}) [[]()] [{()}] ``` The next are done incorrectly: ``` {(}) ([] []) ``` A correct string cannot close groups in the wrong order, open a group but fail to close it, or close a group before it is opened. Your function will take an input string that may contain any of the symbols `()`, `{}` or `[]` to create groups. It should return `True` if the string is empty or otherwise grouped correctly, or `False` if it is grouped incorrectly.
["BRACES = { '(': ')', '[': ']', '{': '}' }\n\ndef group_check(s):\n stack = []\n for b in s:\n c = BRACES.get(b)\n if c:\n stack.append(c)\n elif not stack or stack.pop() != b:\n return False\n return not stack", "def group_check(s):\n while \"{}\" in s or \"()\" in s or \"[]\" in s:\n s = s.replace(\"{}\",\"\").replace(\"()\",\"\").replace(\"[]\",\"\")\n return not s", "def group_check(s):\n while \"()\" in s or \"{}\" in s or \"[]\" in s:\n s = s.replace(\"()\",\"\")\n s = s.replace(\"{}\",\"\")\n s = s.replace(\"[]\",\"\")\n return len(s) == 0", "import re\n\nBRACES = '\\(\\)|{}|\\[\\]'\n\ndef group_check(s):\n while re.search(BRACES, s):\n s = re.sub(BRACES, '', s)\n return s == ''", "def group_check(s):\n l = 9223372036854775807\n while(l > len(s)):\n l = len(s)\n s = s.replace('()', '')\n s = s.replace('{}', '')\n s = s.replace('[]', '')\n return len(s) == 0", "OPENING = '([{'\nCLOSING = dict(['()', '[]', '{}'])\n\ndef group_check(s):\n stack = []\n for c in s:\n if c in OPENING:\n stack.append(CLOSING[c])\n else: # closing\n if len(stack) == 0 or c != stack.pop():\n return False\n return len(stack) == 0", "parens = dict([')(', '][', '}{'])\n\ndef group_check(s):\n stack = []\n for c in s:\n if c in parens:\n if not (stack and parens[c] == stack.pop()):\n return False\n else:\n stack.append(c)\n return not stack", "def group_check(s):\n open = ['(', '{', '[']\n closed = [')', '}', ']']\n f = lambda x: True if (open[x] + closed[x]) in s else False\n while f(0) or f(1) or f(2):\n for i in range(3):\n s = s.replace(open[i] + closed[i], '')\n if s == '':\n return True\n else:\n return False", "import re\n\n\ndef group_check(brackets):\n while any(pair in brackets for pair in (\"{}\", \"[]\", \"()\")):\n brackets = re.sub(r\"{}|\\[]|\\(\\)\", \"\", brackets)\n return not brackets", "def group_check(s):\n for e in ['()','{}','[]','{}','()']:\n while e in s: s = s.replace(e,'')\n return not s"]
{"fn_name": "group_check", "inputs": [["({})"], ["[[]()]"], ["[{()}]"], ["()"], ["([])"], ["{}([])"], ["{[{}[]()[]{}{}{}{}{}{}()()()()()()()()]{{{[[[((()))]]]}}}}(())[[]]{{}}[][][][][][][]({[]})"], [""], ["{(})"], ["[{}{}())"], ["{)[}"], ["[[[]])"], ["()[]{]"], ["{([]})"], ["([]"], ["[])"], ["([]))"], ["{{{{{{{{{{{((((((([])))))))}}}}}}}}}}"]], "outputs": [[true], [true], [true], [true], [true], [true], [true], [true], [false], [false], [false], [false], [false], [false], [false], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,212
def group_check(s):
17f9bca845b6c075bab54714b7cdda26
UNKNOWN
Write a function that checks if all the letters in the second string are present in the first one at least once, regardless of how many times they appear: ``` ["ab", "aaa"] => true ["trances", "nectar"] => true ["compadres", "DRAPES"] => true ["parses", "parsecs"] => false ``` Function should not be case sensitive, as indicated in example #2. Note: both strings are presented as a **single argument** in the form of an array.
["def letter_check(arr): \n return set(arr[1].lower()) <= set(arr[0].lower())", "def letter_check(arr): \n a,b = (set(s.lower()) for s in arr)\n return b <= a", "def letter_check(arr): \n for i in arr[1]:\n if i.lower()not in arr[0].lower():\n return False\n return True", "def letter_check(arr): \n a, b = [set(i.lower()) for i in arr]\n return not b - a", "def letter_check(arr): \n for i in (list(set(arr[1].lower()))):\n if i not in arr[0].lower():\n return False\n return True", "def letter_check(arr): \n return all(c in arr[0].lower() for c in arr[1].lower())", "def letter_check(lst): \n return set(lst[0].lower()) >= set(lst[1].lower())", "def letter_check(arr): \n return not set(arr[1].lower()) - set(arr[0].lower())", "def letter_check(arr): \n arr = list([x.lower() for x in arr])\n for i in set(list(arr[1])):\n if i not in arr[0]:\n return False\n return True\n", "def letter_check(arr): \n return set.issubset(*(set(s.lower()) for s in arr[::-1]))"]
{"fn_name": "letter_check", "inputs": [[["abcd", "aaa"]], [["trances", "nectar"]], [["THE EYES", "they see"]], [["assert", "staring"]], [["arches", "later"]], [["dale", "caller"]], [["parses", "parsecs"]], [["replays", "adam"]], [["mastering", "streaming"]], [["drapes", "compadres"]], [["deltas", "slated"]], [["deltas", ""]], [["", "slated"]]], "outputs": [[true], [true], [true], [false], [false], [false], [false], [false], [true], [false], [true], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,051
def letter_check(arr):
e5aa8026a2795fe67cf46324a5c3c3e7
UNKNOWN
Every day we can send from the server a certain limit of e-mails. Task: Write a function that will return the integer number of e-mails sent in the percentage of the limit. Example: ``` limit - 1000; emails sent - 101; return - 10%; // becouse integer from 10,1 = 10 ``` Arguments: Integer, limit; Integer, number of e-mails sent today; When: the argument ```$sent = 0```, then return the message: "No e-mails sent"; the argument ```$sent >= $limit```, then return the message: "Daily limit is reached"; the argument ```$limit is empty```, then default ```$limit = 1000``` emails; Good luck!
["def get_percentage(sent, limit = 1000):\n if not sent:\n return \"No e-mails sent\"\n elif sent >= limit:\n return \"Daily limit is reached\"\n return \"{}%\".format(int(sent * 100 / limit))", "def get_percentage(a, b=1000):\n return \"No e-mails sent\" if not a else \"Daily limit is reached\" if a >= b else f\"{int(a / b * 100)}%\"", "def get_percentage(sent, limit=1000):\n return f\"{100*sent//limit}%\" if 0 < sent < limit else \"Daily limit is reached\" if sent else \"No e-mails sent\"", "from operator import truediv\n\n\ndef get_percentage(sent, limit=1000):\n if not sent:\n return 'No e-mails sent'\n elif sent >= limit:\n return 'Daily limit is reached'\n return '{}%'.format(int(truediv(sent, limit) * 100))\n", "def get_percentage(sent, limit=1000):\n return \"No e-mails sent\" if not sent \\\n else \"%d%%\" % (100*sent//limit) if sent < limit \\\n else \"Daily limit is reached\"", "get_percentage=lambda s,l=1000:\"No e-mails sent\"*(s<1)or\"%d%%\"%(100*s//l)*(s<l)or\"Daily limit is reached\"", "def get_percentage(sent, limit=1000):\n return \"No e-mails sent\" if sent == 0 else \"Daily limit is reached\" if sent >= limit else \"{}%\".format((100*sent)//limit)", "def get_percentage(sent,limit=1000):\n if sent==0:return \"No e-mails sent\"\n elif sent>=limit:return \"Daily limit is reached\"\n return f\"{(100*sent)//limit}%\"", "def get_percentage(sent, limit=1000):\n if sent == 0:\n return 'No e-mails sent'\n elif sent >= limit:\n return 'Daily limit is reached'\n else:\n return str(int(float(sent)/float(limit)*100)) + '%'", "def get_percentage(sent, limit=1000):\n if sent == 0: return 'No e-mails sent'\n if sent >= limit: return 'Daily limit is reached'\n return '%d%%' % int(sent/limit*100)\n"]
{"fn_name": "get_percentage", "inputs": [[101, 1000], [256, 500], [259], [0], [1000, 1000]], "outputs": [["10%"], ["51%"], ["25%"], ["No e-mails sent"], ["Daily limit is reached"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,855
def get_percentage(sent, limit=1000):
0d6a0b9649c59ce155e4445bc973c418
UNKNOWN
Here's a way to construct a list containing every positive rational number: Build a binary tree where each node is a rational and the root is `1/1`, with the following rules for creating the nodes below: * The value of the left-hand node below `a/b` is `a/a+b` * The value of the right-hand node below `a/b` is `a+b/b` So the tree will look like this: ``` 1/1 / \ 1/2 2/1 / \ / \ 1/3 3/2 2/3 3/1 / \ / \ / \ / \ 1/4 4/3 3/5 5/2 2/5 5/3 3/4 4/1 ... ``` Now traverse the tree, breadth first, to get a list of rationals. ``` [ 1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, .. ] ``` Every positive rational will occur, in its reduced form, exactly once in the list, at a finite index. ```if:haskell In the kata, we will use tuples of type `(Integer, Integer)` to represent rationals, where `(a, b)` represents `a / b` ``` ```if:javascript In the kata, we will use tuples of type `[ Number, Number ]` to represent rationals, where `[a,b]` represents `a / b` ``` Using this method you could create an infinite list of tuples: matching the list described above: However, constructing the actual list is too slow for our purposes. Instead, study the tree above, and write two functions: For example:
["def rat_at(n):\n if n == 0:\n return 1, 1\n a, b = rat_at((n - 1) // 2)\n return (a, a + b) if n % 2 else (a + b, b)\n\ndef index_of(a, b):\n if a == b == 1:\n return 0\n return 2 * index_of(a, b - a) + 1 if b > a else 2 * index_of(a - b, b) + 2", "from math import ceil\ndef rat_at(n):\n if n==0:return (1,1)\n a,b=rat_at(max(ceil(n/2)-1,0))\n return (a,b+a) if n%2 else (a+b,b)\n\ndef index_of(a,b):\n if a==b==1:return 0\n elif a<b:return index_of(a,b-a)*2+1\n else: return (index_of(a-b,b)+1)*2", "seq = {0: 1, 1:1}\n\ndef fusc(n):\n if n in list(seq.keys()):\n return seq[n]\n elif n%2 == 0:\n r = fusc(n>>1) \n seq[n] = r\n return r \n return fusc((n - 1)>>1) + fusc((n + 1)>>1)\n\n\ndef rat_at(n): \n return fusc(n + 1), fusc(n+2)\n\ndef index_of(p, q):\n bits = ''\n while p > 1 or q >1:\n if p>q:\n bits = \"1\"+ bits\n p = p-q\n else:\n bits = \"0\"+bits\n q = q-p\n bits = \"1\" + bits\n return int(bits, 2)-1\n", "def rat_at(n):\n if not n: return (1,1)\n base = 0\n i = n + 1\n while i!=1:\n i= i>>1\n print(i)\n base+=1\n path = str(bin(n - 2**(base) + 1 ))[2:]\n path = '0'*(base-len(path)) + path # buffer left side w/ 0s\n a=b=1\n path = [x=='1' for x in path]\n for p in path:\n if p: a += b\n else: b += a\n return (a,b)\n\n\ndef index_of(a, b):\n if a==b==1: return 0\n path = \"\"\n while a!=1 or b!=1:\n if a>b: # from the left, going right\n a-=b\n path = \"1\" + path\n else: # from the right, going left\n b-=a\n path = \"0\" + path\n base = 2**len(path) - 2 #int('1'*(count),2)\n addon = int(path,2)+1\n return base + addon", "def rat_at(n):\n n = bin(n + 1)\n s = 1\n f = []\n if n[len(n) - 1] == '0':\n f.append(0)\n for i in range(len(n) - 1, 1, -1):\n if n[i] != n[i-1]:\n f.append(s)\n s = 1\n else:\n s += 1\n num = [1, f[len(f) - 1]]\n for i in range(len(f) - 2, -1, -1):\n num[0] = f[i] * num[1] + num[0]\n num[0], num[1] = num[1], num[0]\n num[0], num[1] = num[1], num[0]\n return tuple(num)\n\n\ndef index_of(a, b):\n num = [b, a]\n f = []\n bin = ''\n l = '1'\n while num[0] != 0:\n num[0], num[1] = num[1], num[0]\n f.append(num[0] // num[1])\n num[0] -= f[len(f) - 1] * num[1]\n if len(f) % 2 == 0:\n f[len(f) - 1] -= 1\n f.append(1)\n for n in f:\n bin = (n * l) + bin\n if l == '0':\n l = '1'\n else:\n l = '0'\n return int(bin, 2) - 1\n", "# This is not my code :,(\n# I used those functions from here http://240hoursoflearning.blogspot.com/2017/09/the-calkin-wilf-tree.html\n# Shame and dishonor on me :,( \n\ndef rat_at(n):\n # This is not my code :,(\n frac = [0, 1]\n n += 1\n nums = [n]\n\n while n > 0:\n n = n//2\n nums.append(n)\n\n for n in reversed(nums): \n if n%2!=0:\n frac[0] += frac[1]\n\n else:\n frac[1] += frac[0]\n \n return tuple(frac)\n\n\n\ndef index_of(a, b):\n # This is not my code :,(\n if [a, b] == [1, 1]:\n return 0\n\n path = ''\n\n while [a, b] != [1, 1]:\n if a < b:\n b -= a\n path += '0'\n else:\n a -= b\n path += '1'\n addForDepth = 2**len(path)-1\n\n return addForDepth + int(path[::-1], 2)\n\n\n", "import math\n\ndef rat_at_layer_pos(layer, pos):\n if layer==pos==0:\n return (1,1)\n else:\n a,b = rat_at_layer_pos(layer-1,pos//2)\n return (a,a+b) if pos%2==0 else (a+b,b)\n\ndef rat_at(n):\n layer = len(bin(n+1))-3 if n>0 else 0\n pos = n - int(2**layer-1)\n print(layer, pos)\n return rat_at_layer_pos(layer, pos)\n\ndef index_layer_pos(a,b):\n if a==b==1:\n return 0,0\n if a>b:\n l, p = index_layer_pos(a-b,b)\n return l+1, p*2+1\n else:\n l, p = index_layer_pos(a,b-a)\n return l+1, p*2\n\ndef index_of(a, b):\n l, p = index_layer_pos(a,b)\n return (2**l-1)+p", "def rat_at(n):\n if n == 0:\n return 1,1\n # find line\n line = 1\n tot = 0\n while tot <= n:\n tot += 2**line\n line += 1\n if line > 1:\n line -= 1\n route = ''\n b = 2**line # nr of elements in the line\n pos = n+1 - 2**line # pos in the line\n while b > 1:\n if pos < b // 2:\n route += 'l'\n b = b // 2\n # pos does not change\n else:\n route += 'r'\n b = b // 2\n pos -= b\n a, b = 1, 1\n for c in route:\n if c == 'l':\n a, b = a, a+b\n else:\n a, b = a+b, b\n return a,b\n\ndef index_of(a, b):\n aa = a\n bb = b\n route = '' \n while not (aa == 1 and bb == 1):\n if aa > bb:\n aa = aa-bb\n route = 'r' + route \n else:\n bb = bb-aa\n route = 'l' + route\n above = 0\n for i in range(len(route)):\n above += 2**i \n pos = [0,2**len(route)-1]\n for c in route:\n if c == 'l':\n pos[1] = pos[1] - (pos[1]+1 - pos[0]) // 2\n else:\n pos[0] = pos[0] + (pos[1]+1 - pos[0]) // 2\n print((\"a: {0}, b: {1}, above: {2}, pos: {3}, route: {4}\".format(a,b, above, pos, route)))\n return above+pos[0]\n \n", "def rat_at(n):\n if n == 0:\n return (1, 1)\n for l in range(1001):\n if 2 ** l - 1 <= n <= 2 ** (l + 1) - 2:\n i = l\n break\n if n % 2 == 1:\n j = int((n - (2 ** i - 1)) / 2 + 2 ** (i - 1) - 1)\n k = rat_at(j)\n return (k[0], k[0] + k[1])\n else:\n j = int((n - (2 ** i)) / 2 + 2 ** (i - 1) - 1)\n k = rat_at(j)\n return (k[0] + k[1], k[1])\n\n\ndef index_of(a, b):\n if (a, b) == (1, 1):\n return 0\n if a > b:\n n = index_of(a - b, b)\n k = n\n for l in range(1001):\n if 2 ** l - 1 <= n <= 2 ** (l + 1) - 2:\n i = l\n break\n return k + ((k - (2 ** i - 1)) * 2 + 1 + (2 ** (i + 1) - 1 - k))\n else:\n n = index_of(a, b-a)\n k = n\n for l in range(1001):\n if 2 ** l - 1 <= n <= 2 ** (l + 1) - 2:\n i = l\n break\n return k + ((k - (2 ** i - 1)) * 2 + 1 + (2 ** (i + 1) - 1 - k)) -1\n", "def rat_at(n):\n if n==0: return (1,1)\n a,b=rat_at(~-n>>1)\n return (a,a+b) if n%2 else (a+b,b)\n\n\ndef index_of(a,b):\n if a==1==b: return 0\n return 2*index_of(a,b-a)+1 if a<b else 2*index_of(a-b,b)+2\n"]
{"fn_name": "rat_at", "inputs": [[0], [3], [4], [10], [1000000000]], "outputs": [[[1, 1]], [[1, 3]], [[3, 2]], [[5, 2]], [[73411, 65788]]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,859
def rat_at(n):
45e0dd03769be540f450dc423a36122b
UNKNOWN
Andrzej was given a task: There are n jars with pills. In every jar there is a different type of pill and the amount of pills in each jar is infinite. One type of pill makes a person glow about 30 minutes after taking and none of the other types has any effect. His job is to determine, in which jar are the pills that make a person glow. But there is one catch, he only has 35 minutes to do so.(so he can't take a pill, wait for the results and then take another one, because he wouldn't be able to see the results) Fortunetely, he can take any number of friends he needs with him. On completing the task Andrzej receives one million dollars. You know that Andrzej is very honest, so he will split the money equally with his friends. Your job is to determine how many friends does Andrzej need to complete the task.(He also wants to make the highest amount of money.) For example for n = 2 The answer is 0 because he doesn't need any friends, he just needs to take a pill from the first jar and wait for the effects. For another example for n = 4 The answer is 1 because having pills A B C D Andrzej can take pills A B and the friend can take pills B C
["def friends(n):\n return len(str(bin(n-1)))-3 if n >1 else 0", "def friends(n):\n return (n-1 or 1).bit_length()-1", "def friends(n):\n return 0 if n < 2 else (n - 1).bit_length() - 1", "from math import log2\n\ndef friends(n):\n return int(log2(max(2, n) - 1))", "from math import log2\n\ndef friends(n):\n return int(log2(n-1)) if n>1 else 0", "def relu(n):\n return 0 if n < 0 else n\n\ndef friends(n):\n return relu(~-(~-n).bit_length())", "from math import log,ceil\ndef friends(n): return 0 if n < 2 else ceil(log(n,2)-1)", "import math\ndef friends(n):\n print(n)\n if n <= 2:\n return 0\n elif math.log(n,2)==int(math.log(n,2)):\n return int(math.log(n,2)) -1\n else:\n return int(math.log(n,2))\n", "import math\n\ndef friends(n):\n if n <= 1:\n return 0\n else:\n return math.ceil(math.log(n) / math.log(2))-1", "def friends(n):\n x = 1\n while True:\n if n / (2**x) <= 1:\n break\n x += 1\n return x - 1"]
{"fn_name": "friends", "inputs": [[0], [1], [2], [4], [3], [16]], "outputs": [[0], [0], [0], [1], [1], [3]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,026
def friends(n):
994bbf8cbbd90688c16e349448f873ad
UNKNOWN
An array is called `centered-N` if some `consecutive sequence` of elements of the array sum to `N` and this sequence is preceded and followed by the same number of elements. Example: ``` [3,2,10,4,1,6,9] is centered-15 because the sequence 10,4,1 sums to 15 and the sequence is preceded by two elements [3,2] and followed by two elements [6,9] ``` Write a method called `isCenteredN` that returns : - `true` if its array argument is `not empty` and `centered-N` or empty and centered-0 - otherwise returns `false`.
["def is_centered(arr,n):\n l = int(len(arr)/2) if len(arr)%2==0 else int((len(arr)-1)/2)\n return any(sum(arr[i:-i])==n for i in range(1, l+1)) or sum(arr)==n", "from itertools import accumulate\n\ndef is_centered(arr, n):\n xs = [0] + list(accumulate(arr))\n return any(b-a==n for a, b in zip(xs[:len(arr)//2+1], xs[::-1]))", "def is_centered(arr,n):\n while True:\n if sum(arr) == n: return True\n try: (arr.pop(), arr.pop(0))\n except IndexError: return False", "def is_centered(arr,n):\n if sum(arr) == n: return True\n for i in range(1,int(len(arr)/2)+1): \n if sum(arr[i:-i]) == n:\n return True\n return False", "def is_centered(arr, n):\n x = sum(arr)\n if x == n: return True\n for i in range(len(arr)>>1):\n x -= arr[i] + arr[-i-1]\n if x == n: return True\n return False", "def is_centered(arr,n):\n for i in range(len(arr)//2+1):\n if sum(arr[i:len(arr)-i])==n:\n return True\n return False", "def is_centered(a, n):\n if not n and not len(a) % 2: return 1\n for i in range(sum(divmod(len(a), 2)) - 1, -1, -1):\n if sum(a[i:len(a)-i]) == n:\n return 1\n return 0", "def is_centered(arr,n):\n return any(\n sum(arr[i:len(arr)-i]) == n for i in range(len(arr)//2 + 1)\n )\n", "def is_centered(arr,n):\n for i in range(len(arr)):\n for j in range(len(arr)+1):\n if j>i:\n if sum(arr[i:j]) == n and i == len(arr)-j:\n return True\n return True if n==0 and arr!=arr[::-1] else False", "def is_centered(arr, n):\n if (len(arr) % 2 == 0) and n == 0:\n return True\n left, right = (len(arr) // 2, len(arr) // 2) if len(arr) % 2 else (len(arr) // 2 - 1, len(arr) // 2)\n while left >= 0 and right <= len(arr):\n if sum(arr[left:right + 1]) == n:\n return True\n left -= 1\n right += 1\n return False"]
{"fn_name": "is_centered", "inputs": [[[0, 0, 0], 0], [[3, 2, 10, 4, 1, 6, 9], 15], [[2, 10, 4, 1, 6, 9], 15], [[3, 2, 10, 4, 1, 6], 15], [[1, 1, 8, 3, 1, 1], 15], [[1, 1, 8, 3, 1, 1], 11], [[1, 1, 8, 3, 1, 1], 13], [[9, 0, 6], 0], [[], 25], [[25], 25], [[25, 26, 23, 24], 0], [[2, 1, 2], 0], [[1, 1, 15, -1, -1], 15], [[1, 1, 15, -1, -1], 6], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 0], [[0, 0, 0, -1, 1, 1, -1, 0, 0, 0], 0]], "outputs": [[true], [true], [false], [false], [true], [true], [true], [true], [false], [true], [true], [false], [true], [false], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,974
def is_centered(arr,n):
51e6f232d528126061934c83780ae84e
UNKNOWN
Write a function named `first_non_repeating_letter` that takes a string input, and returns the first character that is not repeated anywhere in the string. For example, if given the input `'stress'`, the function should return `'t'`, since the letter *t* only occurs once in the string, and occurs first in the string. As an added challenge, upper- and lowercase letters are considered the **same character**, but the function should return the correct case for the initial letter. For example, the input `'sTreSS'` should return `'T'`. If a string contains *all repeating characters*, it should return an empty string (`""`) or `None` -- see sample tests.
["def first_non_repeating_letter(string):\n string_lower = string.lower()\n for i, letter in enumerate(string_lower):\n if string_lower.count(letter) == 1:\n return string[i]\n \n return \"\"", "from collections import Counter\ndef first_non_repeating_letter(string):\n cnt = Counter(string.lower())\n for letter in string:\n if cnt[letter.lower()] == 1:\n return letter\n return ''", "def first_non_repeating_letter(string):\n singles = [i for i in string if string.lower().count(i.lower()) == 1]\n return singles[0] if singles else ''", "def first_non_repeating_letter(string):\n \n s = string.lower()\n \n for i in string:\n if s.count(i.lower()) == 1:\n return i\n return ''", "def first_non_repeating_letter(string):\n return next((x for x in string if string.lower().count(x.lower())==1), '')", "def first_non_repeating_letter(string):\n for x in string:\n if string.lower().count(x.lower()) == 1:\n return x\n return ''", "def first_non_repeating_letter(string):\n duplicates = [ i for i in string if string.lower().count(i.lower()) == 1 ]\n return duplicates[0] if duplicates else ''", "def first_non_repeating_letter(string):\n return ([a for a in string if string.lower().count(a.lower()) == 1] or [''])[0]\n #your code here\n", "def first_non_repeating_letter(string):\n for char in string:\n if string.lower().count(char.lower()) < 2:\n return char\n return \"\"", "def first_non_repeating_letter(s):\n return ([c for c in s if s.lower().find(c.lower()) == s.lower().rfind(c.lower())] or [\"\"])[0]\n", "def first_non_repeating_letter(string):\n try:\n return next(c for c in string if string.lower().count(c.lower()) == 1)\n except StopIteration:\n return ''", "def first_non_repeating_letter(string):\n counter = 0\n for x in string:\n for y in string.lower():\n if y == x.lower():\n counter += 1\n if counter == 1:\n return x\n counter = 0\n return ''", "def first_non_repeating_letter(string):\n lowercase_str = string.lower()\n for i in string:\n if lowercase_str.count(i.lower()) == 1:\n return i\n return \"\"", "from collections import Counter\n\ndef first_non_repeating_letter(string):\n count = Counter(s.lower() for s in string)\n \n for c in string:\n if count[c.lower()] == 1:\n return c\n \n return str()", "def first_non_repeating_letter(string):\n result = sorted(string, key=lambda x: string.lower().count(x.lower()))+['']\n return result[0] if result.count(result[0])== 1 else result[-1]", "def first_non_repeating_letter(string):\n return next((ch for ch in string if string.lower().count(ch.lower()) == 1), '')", "def first_non_repeating_letter(s):\n seen = set()\n rep = set()\n \n for c in s:\n c = c.lower()\n if c in seen:\n rep.add(c)\n else:\n seen.add(c)\n for c in s:\n if c.lower() not in rep:\n return c\n return ''\n\n", "def first_non_repeating_letter(string):\n for x in string:\n if x.lower() not in string.lower()[string.index(x)+1:]: return x\n else: return '' ", "from collections import Counter\ndef first_non_repeating_letter(s):\n for c, v in sorted(Counter(s).most_common(), key=lambda t: t[1]):\n if v == 1 and c.swapcase() not in s or not c.isalpha(): return c\n return ''", "def first_non_repeating_letter(s):\n for c in s:\n if s.count(c) + s.count(c.swapcase()) * c.isalpha() == 1: return c\n return ''", "def first_non_repeating_letter(str1):\n str2 = str1.lower()\n for c in str2:\n if str2.count(c)==1:\n return str1[str2.index(c)]\n return ''\n #your code here\n", "from collections import Counter\ndef first_non_repeating_letter(string):\n counts = Counter(string.lower())\n try:\n first_unique = next(item[0] for item in counts.items() if item[1]==1)\n except StopIteration:\n return \"\"\n if first_unique.upper() in string:\n return first_unique.upper()\n else:\n return first_unique", "def first_non_repeating_letter(string):\n str = string.lower()\n for x in str:\n if str.count(x) ==1: return string[str.index(x)]\n return ''", "def first_non_repeating_letter(string):\n check_list = []\n list_string = list(string.lower())\n for let in string:\n if let not in check_list:\n list_string.remove(let.lower())\n check_list.append(let)\n if let.lower() not in list_string:\n return let\n return ''", "def first_non_repeating_letter(string):\n c=''\n if string=='':\n return ''\n count=0\n b=string.lower()\n for i in b:\n a=b.count(i)\n if a==1:\n break\n count+=1\n if count==len(string):\n return ''\n return string[count]", "def first_non_repeating_letter(string):\n str = string.lower()\n\n for i, v in enumerate(str):\n if str.index(v) == str.rindex(v):\n return string[i]\n\n return \"\"\n", "def first_non_repeating_letter(some_string):\n # List comprehension:\n # examine each character in the given string\n # if the character appears only once, add it to the list\n # otherwise, add an empty character\n # join the list back into a string (eliminates empty characters)\n # now the first character in our string will be the first non-repeating character\n # NOTE: by using a one-character slice [:1] instead of an index [0] we allow\n # it to pick up a blank character '' if the string is empty instead of\n # giving an error for an index that is out of range.\n return ''.join([char if some_string.lower().count(char.lower()) == 1 else '' for char in some_string])[:1] \n", "def first_non_repeating_letter(string):\n is_unique = lambda char: string.lower().count(char.lower()) == 1\n return next((char for char in string if is_unique(char)), '')", "def first_non_repeating_letter(n):\n for i in n:\n if n.lower().count(i.lower())==1:\n return i\n return ''", "def first_non_repeating_letter(string):\n low=string.lower()\n a=[ele for ele in dict.fromkeys(low) if low.count(ele)==1]\n return string[low.index(a[0])] if a and string else ''", "def first_non_repeating_letter(string):\n return ''.join(i for i in string if string.lower().count(i.lower())==1)[:1]", "def first_non_repeating_letter(string):\n cass = \"\".join(string);\n chars = list(i.lower().replace(\" \", \"\") for i in cass)\n newList = []\n for char, i in zip(chars,string): # run two lists parallel\n count = chars.count(char)\n if count >= 2:\n continue;\n else:\n newList.append(i)\n \n if(len(newList) > 0): \n return str(newList[0]);\n else: \n return '';", "def first_non_repeating_letter(string):\n strLower = string.lower()\n for let in string:\n if strLower.count(let.lower())==1:\n return let\n return \"\"\n \n", "def first_non_repeating_letter(string):\n print(string)\n for l in string:\n if string.lower().find(l.lower(), string.find(l)+1) == -1:\n return l\n return ''", "def first_non_repeating_letter(string):\n c = [x for x in string if string.lower().count(x.lower())==1]\n if c:\n return c[0]\n else:\n return ''", "def first_non_repeating_letter(string): \n if len(string)==1 or len(string)==0:\n return string \n for leter in string:\n if (leter.lower() not in string[string.index(leter)+1:].lower()) and (leter.lower() not in string[:string.index(leter)].lower()):\n return(leter)\n else:\n return('')", "def first_non_repeating_letter(string): \n a = [i for i in string.lower()]\n b = 0\n c = [i for i in string]\n if len(string)==1: return string\n while b<len(a)-1:\n if a.count(a[b])==1:\n return c[b]\n else: b+=1\n return ''", "def first_non_repeating_letter(string):\n \n if all([string.count(item)>1 for item in string]):return \"\"\n for i,item in enumerate(string.upper()):\n if string.upper().count(item)==1:return string[i]"]
{"fn_name": "first_non_repeating_letter", "inputs": [["a"], ["stress"], ["moonmen"], [""], ["abba"], ["aa"], ["~><#~><"], ["hello world, eh?"], ["sTreSS"], ["Go hang a salami, I'm a lasagna hog!"]], "outputs": [["a"], ["t"], ["e"], [""], [""], [""], ["#"], ["w"], ["T"], [","]]}
INTRODUCTORY
PYTHON3
CODEWARS
8,486
def first_non_repeating_letter(string):
0afcdf231084d74c828e7c64d7a421d5
UNKNOWN
You'll be given a string, and have to return the total of all the unicode characters as an int. Should be able to handle any characters sent at it. examples: uniTotal("a") == 97 uniTotal("aaa") == 291
["def uni_total(string):\n return sum(map(ord, string))", "def uni_total(s):\n return sum(ord(c) for c in s)\n", "def uni_total(string):\n return sum(ord(c) for c in string)", "def uni_total(string):\n return sum(ord(x) for x in string)", "def uni_total(string):\n return sum([ord(i) for i in string])\n", "def uni_total(string):\n return sum(ord(ch) for ch in string)", "def uni_total(string):\n acc = 0\n for i in string:\n acc += ord(i)\n return acc", "def uni_total(strng):\n return sum(ord(a) for a in strng)\n", "def uni_total(string):\n return sum(ord(i) for i in string)", "def uni_total(string: str) -> int:\n \"\"\" Get the total of all the unicode characters as an int. \"\"\"\n return sum([ord(_) if _ else 0 for _ in \"|\".join(string).split(\"|\")])", "def uni_total(string):\n return sum(ord(q) for q in string)", "def uni_total(string):\n total = 0\n for item in string:\n total= total + ord(item)\n return total", "def uni_total(string):\n c=0\n for x in string:\n c=c+ord(x)\n return c", "def uni_total(string):\n s = 0\n for c in string:\n s += ord(c)\n return s\n", "\ndef uni_total(string):\n return sum(list(map(ord, string)))", "from functools import reduce\ndef uni_total(string):\n return reduce(lambda x, y: x + ord(y), string, 0)", "def uni_total(string):\n total = 0\n for i in string:\n total += ord(i)\n return total", "uni_total=lambda s:sum(ord(i)for i in s)", "def uni_total(string):\n return sum(ord(character) for character in string)", "def uni_total(string):\n x=0\n for character in string:\n x+=ord(character)\n return x", "uni_total = lambda string: sum(ord(c) for c in string)\n", "def uni_total(string):\n total = []\n for char in string:\n total.append(ord(char))\n return sum(total)\n \n \n'''You'll be given a string, and have to return the total of all the unicode \ncharacters as an int. Should be able to handle any characters sent at it.\n\nexamples:\n\nuniTotal(\"a\") == 97 uniTotal(\"aaa\") == 291'''", "def uni_total(string):\n return sum(list(ord(i) for i in string))", "def uni_total(string):\n array = []\n copy = []\n array = list(string) \n for num in array:\n copy.append(ord(num))\n total = sum(copy)\n return total", "def uni_total(string):\n \n if type(string)!= str:\n return 0\n else:\n liste= [(ord(i)) for i in string]\n return sum(liste)\n", "def uni_total(string):\n ttl = 0\n for i in string:\n ttl += ord(i)\n return ttl\n", "def uni_total(s):\n return sum(ord(l) for l in s)", "def uni_total(string):\n x = map(ord, string)\n return sum(x)", "def uni_total(string):\n sum = 0\n for i in string: \n i = ord(i)\n sum = sum + i\n return sum", "def uni_total(string: str) -> int:\n \"\"\" Get the total of all the unicode characters as an int. \"\"\"\n return sum(bytearray(string, \"utf\"))", "def uni_total(string: str) -> int:\n \"\"\" Get the total of all the unicode characters as an int. \"\"\"\n return sum(map(ord, string))", "def uni_total(s):\n #your code ere\n st=0\n for c in s:\n st+=ord(c)\n return st", "def uni_total(string):\n ans = 0\n if string: \n for _ in string:\n ans += ord(_)\n return ans", "def uni_total(string):\n liReturn = 0\n \n for i in string:\n liReturn += ord(i)\n \n return liReturn", "def uni_total(string):\n total = 0\n if string == \"\":\n return 0\n else:\n for i in range(len(string)):\n total = ord(string[i]) + total\n return total", "def uni_total(string):\n erg = 0\n for c in string:\n erg += ord(c)\n return erg", "def uni_total(string):\n accumulator = 0\n for eachchar in string:\n accumulator = accumulator + ord(eachchar)\n return accumulator", "def uni_total(s):\n t=0\n for i in s:\n t += ord(i)\n return t\n", "def uni_total(string):\n #your code here\n if string=='':\n return 0\n else:\n ans=0\n for i in string:\n ans=ans+ord(i)\n return ans", "def uni_total(string):\n rez = 0\n for i in string:\n rez += ord(i)\n return rez", "def uni_total(string):\n l = list(string)\n m = sum([ord(i) for i in l])\n return m", "def uni_total(string):\n account = 0\n for letters in string:\n account += ord(letters)\n return account", "def uni_total(string):\n account = 0\n for letters in string:\n if 96 < ord(letters) < 123: \n account += ord(letters)\n else:\n 64 < ord(letters) < 91\n account += ord(letters)\n return account \n", "def uni_total(string):\n salida = 0\n for letr in string:\n salida += ord(letr)\n\n return salida", "def uni_total(string):\n result = 0\n for s in string:\n result += ord(s)\n return result\n", "def uni_total(string):\n unicodes = []\n for i in string:\n unicodes.append(ord(i))\n return sum(unicodes)", "def uni_total(string):\n if string:\n s = sum([ord(i) for i in string]) \n else:\n s = 0\n return s", "def uni_total(string):\n summ = 0\n for i in string:\n summ += ord(i)\n return summ if string else 0", "def uni_total(string):\n return sum(ord(i) for i in string) if string else 0", "def uni_total(string):\n \n output = 0\n \n for letter in string:\n output += ord(letter)\n \n return output", "def uni_total(string):\n return sum([ord(elem) for elem in string])", "def uni_total(string):\n toplam = 0\n for i in string:\n toplam += int(str(ord(i)))\n return toplam", "def uni_total(string):\n int = [ord(x) for x in string]\n sum = 0\n for i in int:\n sum += i\n return sum", "def uni_total(string):\n return sum(ord(each) for each in string)", "def uni_total(string):\n b = []\n for i in range(len(string)):\n b.append(ord(string[i]))\n return sum(b)", "def uni_total(string):\n if not string:\n return 0\n if len(string) == 1:\n return ord(string)\n return sum(list(map(ord, string)))", "def uni_total(string):\n char_uni = {\" \":32, \"0\":48, \"1\":49, \"2\":50, \"3\":51, \"4\":52, \"5\":53, \"6\":54, \"7\":55, \"8\":56, \"9\":57, \"A\":65, \"B\":66, \"C\":67, \"D\":68, \"E\":69, \"F\":70, \"G\":71, \"H\":72, \"I\":73, \"J\":74, \"K\":75, \"L\":76, \"M\":77, \"N\":78, \"O\":79, \"P\":80, \"Q\":81, \"R\":82, \"S\":83, \"T\":84, \"U\":85, \"V\":86, \"W\":87, \"X\":88, \"Y\":89, \"Z\":90, \"a\":97, \"b\":98, \"c\":99, \"d\":100, \"e\":101, \"f\":102, \"g\":103, \"h\":104, \"i\":105, \"j\":106, \"k\":107, \"l\":108, \"m\":109, \"n\":110, \"o\":111, \"p\":112, \"q\":113, \"r\":114, \"s\":115, \"t\":116, \"u\":117, \"v\":118, \"w\":119, \"x\":120, \"y\":121, \"z\":122}\n string_lst = list(string)\n uni_lst = []\n \n for i in string_lst:\n for char, uni in char_uni.items():\n if char == i:\n uni_lst += [uni]\n continue\n if i == \" \":\n continue\n \n return sum(uni_lst)\n\nprint(uni_total(\"no chars should return zero\"))", "def uni_total(string):\n return sum(ord(i) for i in string) if string != '' else 0", "uni_total=lambda s: sum([ord(e) for e in s]) if len(s)>0 else 0", "def uni_total(s):\n s=list(s)\n s=[ord(i) for i in s]\n return sum(s)", "def uni_total(s):\n return sum(ord(char) for char in s)\n", "def uni_total(string):\n #your code here\n try: \n return sum([ord(i) for i in string])\n except:\n return 0", "def uni_total(string):\n sco = 0\n for let in string:\n sco += ord(let)\n return sco", "def uni_total(string):\n return sum([int(ord(s)) for s in string])", "def uni_total(string):\n return sum([ord(x) for x in string])\n # Flez\n", "def uni_total(string):\n ret = 0\n for c in string:\n ret += ord(c)\n return ret", "def uni_total(string):\n finalist = list()\n mylist = list(string)\n for x in mylist:\n finalist.append(ord(x))\n return sum(finalist)\n", "def uni_total(string):\n return sum(ord(s) for s in string) if string else 0", "def uni_total(string):\n res = 0\n \n for let in string:\n res += ord(let)\n \n return res\n", "def uni_total(string):\n letters = list(string)\n total = 0\n for letter in letters:\n total = total + ord(letter)\n return total", "def uni_total(string):\n # sum all caractere in string \n return sum(ord(s) for s in string)", "def uni_total(sz):\n return sum(ord(c) for c in sz)", "def uni_total(string):\n #your code here\n rez = 0\n for c in string:\n rez += ord(c)\n return rez \n \n", "def uni_total(string):\n res = 0\n for item in string:\n res += ord(item)\n return res", "from functools import reduce\n\nuni_total=lambda s: reduce(lambda a,b: a+ord(b),s,0)", "def uni_total(string):\n if string == '':\n return 0\n \n return sum(ord(i) for i in string)", "def uni_total(string):\n cnt = 0\n for i in string:\n cnt += ord(i)\n return cnt", "def uni_total(string):\n #your code here\n ans = 0\n for i in range(len(string)):\n ans += ord(string[i])\n return ans", "def uni_total(string):\n return sum(ord(num) for num in string)", "def uni_total(string): \n return 0 if len(string) == 0 else sum([int(ord(ch)) for ch in string])", "def uni_total(string):\n uni_total = 0\n for i in string:\n uni_total += ord(i)\n return uni_total", "def uni_total(string):\n tot = 0\n for x in list(string):\n tot += ord(x)\n return tot", "def uni_total(string):\n #your code here\n sum=0\n for e in string:\n sum=sum+ord(e)\n return sum", "def uni_total(str):\n x = 0\n for l in str:\n x += ord(l)\n return x", "def uni_total(string):\n if not string:\n return 0\n return sum([ord(s) for s in string])", "def uni_total(string):\n result=0\n print(string)\n for i in string:\n print(ord(i))\n result=result+ord(i)\n return result", "def uni_total(string):\n a=list(string)\n tot=0\n for i in a:\n tot=tot+ord(i)\n return(tot)\n", "def uni_total(string):\n cnt = 0\n for e in string:\n cnt += ord(e)\n \n return cnt\n #your code here\n", "def uni_total(s):\n sum = 0\n for c in s:\n sum += ord(c)\n return sum", "def uni_total(string):\n count = 0 \n for x in string:\n count += ord(x)\n return count\n", "def uni_total(string):\n return sum([ord(str) for str in string])", "def uni_total(string):\n s = string\n count = 0\n if s == \"\":\n return 0\n for x in range(len(s)):\n count = count + ord(s[x])\n return count", "uni_total = lambda string: sum([ord(x) for x in list(string)])", "def uni_total(string):\n lst = [ord(x) for x in list(string)]\n return sum(lst)", "def uni_total(string):\n a = 0\n for s in string:\n a = a + ord(s)\n return a", "def uni_total(string):\n x = 0\n if string == '':\n return 0\n for i in range(len(string)):\n x += int(ord(string[i]))\n return x", "def uni_total(string):\n #your code here\n s=0\n for x in string:\n s+=ord(x)\n return s", "def uni_total(string):\n out=0\n if not string:return 0\n for items in string:\n out+=ord(items)\n return out", "def uni_total(string):\n if string == \"\":\n return 0\n \n count = 0\n for i in string:\n count = count + ord(i)\n return count"]
{"fn_name": "uni_total", "inputs": [["a"], ["b"], ["c"], [""], ["aaa"], ["abc"], ["Mary Had A Little Lamb"], ["Mary had a little lamb"], ["CodeWars rocks"], ["And so does Strive"]], "outputs": [[97], [98], [99], [0], [291], [294], [1873], [2001], [1370], [1661]]}
INTRODUCTORY
PYTHON3
CODEWARS
11,881
def uni_total(string):
2ac9d810229fb471186e6502ab42e214
UNKNOWN
Consider the following well known rules: - A number is divisible by 3 if the sum of its digits is divisible by 3. Let's call '3' a "1-sum" prime - For 37, we take numbers in groups of threes from the right and check if the sum of these groups is divisible by 37. Example: 37 * 123456787 = 4567901119 => 4 + 567 + 901 + 119 = 1591 = 37 * 43. Let's call this a "3-sum" prime because we use groups of 3. - For 41, we take numbers in groups of fives from the right and check if the sum of these groups is divisible by 41. This is a "5-sum" prime. - Other examples: 239 is a "7-sum" prime (groups of 7), while 199 is a "99-sum" prime (groups of 99). Let's look at another type of prime: - For 11, we need to add all digits by alternating their signs from the right. Example: 11 * 123456 = 1358016 => 6-1+0-8+5-3+1 = 0, which is divible by 11. Let's call this a "1-altsum" prime - For 7, we need to group the digits into threes from the right and add all groups by alternating their signs. Example: 7 * 1234567891234 = 8641975238638 => 638 - 238 + 975 - 641 + 8 = 742/7 = 106. - 7 is a "3-altsum" prime because we use groups of threes. 47 is a "23-altsum" (groups of 23), while 73 is a "4-altsum" prime (groups of 4). You will be given a prime number `p` and your task is to find the smallest positive integer `n` such that `p’s` divisibility testing is `n-sum` or `n-altsum`. For example: ``` solve(3) = "1-sum" solve(7) = "3-altsum" ``` Primes will not exceed `50,000,000`. More examples in test cases. You can get some insight from [Fermat's little theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem). Good luck!
["import math\n\ndef divisors(n):\n divs = [1]\n for i in range(2,int(math.sqrt(n))+1):\n if n%i == 0:\n divs.extend([i,n//i])\n divs.extend([n])\n return list(set(divs))\n\ndef solve(p):\n for d in sorted(divisors(p-1)):\n if pow(10, d, p) == 1:\n return \"{}-sum\".format(d)\n break\n elif pow(10, d, p) == p-1:\n return \"{}-altsum\".format(d)\n break\n", "import collections\nimport itertools\n\ndef prime_factors(n):\n i = 2\n while i * i <= n:\n if n % i == 0:\n n /= i\n yield i\n else:\n i += 1\n\n if n > 1:\n yield n\n\ndef prod(iterable):\n result = 1\n for i in iterable:\n result *= i\n return result\n\n\ndef get_divisors(n):\n pf = prime_factors(n)\n\n pf_with_multiplicity = collections.Counter(pf)\n\n powers = [\n [factor ** i for i in range(count + 1)]\n for factor, count in pf_with_multiplicity.items()\n ]\n\n for prime_power_combo in itertools.product(*powers):\n yield prod(prime_power_combo)\n\ndef rem(n, p):\n v = 1\n for i in range(0, n // 1000): \n v = v * (10 ** 1000)\n v = v % p\n v = v * (10 ** (n % 1000))\n v = v % p\n return v\n \n\ndef solve(p):\n nl = list(get_divisors(p-1))\n nl = [int(x) for x in nl]\n nl = sorted(nl)\n \n for n in nl:\n if rem(n, p) == 1:\n return str(n) + '-sum'\n if rem(n, p) == p - 1:\n return str(n) + '-altsum'", "def solve(p):\n result = 0\n for i in range(1, int(p ** 0.5) + 1):\n if (p - 1) % i:\n continue\n if pow(10, i, p) == 1:\n result = i\n break\n j = (p - 1) // i\n if pow(10, j, p) == 1:\n result = j\n if pow(10, result // 2, p) == p - 1:\n return f'{result // 2}-altsum'\n else:\n return f'{result}-sum'", "def solve(p):\n \"\"\"See codewars.com kata Divisible by primes.\"\"\"\n n = p - 1\n for f in factors(n):\n m = n // f\n if pow(10, m, p) == 1:\n n = m\n return '%d-altsum' % (n // 2) if n % 2 == 0 else '%d-sum' % n\n\n\ndef factors(n):\n m = 2\n while m * m <= n:\n while n % m == 0:\n yield m\n n //= m\n m += 1 if m == 2 else 2\n if n > 1:\n yield n\n", "def solve(p):\n n = p - 1\n while n % 2 == 0 and pow(10, n, p) == 1:\n n //= 2\n s = pow(10, n, p)\n for p2 in factors_gen(n):\n if pow(10, n // p2, p) == s:\n n //= p2\n return ('%d-sum' if s == 1 else '%d-altsum') % n\n\n\ndef factors_gen(n):\n while n % 2 == 0:\n yield 2\n n //= 2\n k = 3\n while k * k <= n:\n while n % k == 0:\n yield k\n n //= k\n k += 2\n if n > 1:\n yield n", "def solve(p):\n d2 = -1\n for d in range(1, int(p ** 0.5) + 1):\n if (p - 1) % d == 0:\n k = pow(10, d, p)\n if k == 1:\n return f'{d}-sum'\n elif k == p - 1:\n return f'{d}-altsum'\n t = (p - 1) // d\n k = pow(10, t, p)\n if k == 1 or k == p - 1:\n d2 = t\n return f'{d2}-sum' if pow(10, d2, p) == 1 else f'{d2}-altsum'\n", "from math import floor, sqrt\n\ndef solve(p):\n def powmod(x, n):\n res, cur = 1, x\n while n:\n if n & 1 == 1:\n res = (res * cur) % p\n cur = (cur * cur) % p\n n = n >> 1\n return res\n\n def invert(x):\n return powmod(x, p - 2)\n\n BLOCK = 1000\n base = 10\n\n baby = dict()\n bcur = base % p\n for i in range(1, BLOCK):\n if bcur not in baby:\n baby[bcur] = i\n else:\n break\n bcur = (bcur * base) % p\n\n step = invert(powmod(base, BLOCK))\n pcur = 1\n for j in range(0, p, BLOCK):\n ans = []\n def try_use(num, typ):\n if num in baby:\n totnum = j + baby[num]\n if totnum > 0:\n ans.append((totnum, typ))\n if num == 1 and j > 0:\n ans.append((j, typ))\n\n try_use(pcur, 'sum')\n try_use(((p - 1) * pcur) % p, 'altsum')\n\n if ans:\n return '%d-%s' % min(ans)\n\n pcur = (pcur * step) % p\n", "def solve(p):\n i, ans = 1, 0\n while i * i <= p - 1:\n if (p - 1) % i == 0:\n j = (p - 1) // i\n if pow(10, i, p) == 1:\n ans = i\n break\n if pow(10, j, p) == 1: ans = j\n i += 1\n if pow(10, ans // 2, p) == p - 1: ans = str(ans // 2) + '-altsum'\n else: ans = str(ans) + '-sum'\n return ans"]
{"fn_name": "solve", "inputs": [[3], [7], [11], [13], [37], [47], [73], [239], [376049], [999883], [24701723], [45939401]], "outputs": [["1-sum"], ["3-altsum"], ["1-altsum"], ["3-altsum"], ["3-sum"], ["23-altsum"], ["4-altsum"], ["7-sum"], ["47006-altsum"], ["499941-sum"], ["12350861-sum"], ["11484850-altsum"]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,858
def solve(p):
bcfdc39829843fe6fc2cebfb233dd7a6
UNKNOWN
# Task A range-collapse representation of an array of integers looks like this: `"1,3-6,8"`, where `3-6` denotes the range from `3-6`, i.e. `[3,4,5,6]`. Hence `"1,3-6,8"` = `[1,3,4,5,6,8]`. Some other range-collapse representations of `[1,3,4,5,6,8]` include `"1,3-5,6,8", "1,3,4,5,6,8", etc`. Each range is written in the following format `"a-b"`, where `a < b`, and the whole range must belong to the array in an increasing order. You are given an array `arr`. Your task is to find the number of different range-collapse representations of the given array. # Example For `arr = [1,3,4,5,6,8]`, the result should be `8`. ``` "1,3-4,5,6,8" "1,3-4,5-6,8" "1,3-5,6,8" "1,3-6,8" "1,3,4-5,6,8" "1,3,4-6,8" "1,3,4,5-6,8" "1,3,4,5,6,8"``` # Input/OutPut - `[input]` integer array `arr` sorted array of different positive integers. - `[output]` an integer the number of different range-collapse representations of the given array.
["def descriptions(arr):\n return 2**sum(a+1==b for a,b in zip(arr,arr[1:]))", "\ndef pair_apply(a, fn): \n \"\"\"\n Apply a funtion to each pair of consecutive \n values in the array and return the resultant array\n \"\"\"\n return [fn(x, y) for x, y in zip(a, a[1:])]\n\ndef run_length_encode(a):\n \"\"\"Run length encode the given array\"\"\"\n a = [(x, 1) for x in a]\n i = 0\n while i < len(a) - 1:\n if a[i][0] == a[i + 1][0]:\n a[i] = (a[i][0], a[i][1] + 1)\n del a[i + 1]\n else:\n i += 1\n return a\n\ndef descriptions(arr):\n \"\"\"\n Caluculate number of possible range collapse \n permutations for givven array\n \"\"\"\n deltas = pair_apply(arr, lambda x, y: y - x)\n rle_deltas = run_length_encode(deltas)\n result = 1\n for delta, count in rle_deltas:\n if delta == 1:\n result *= 2 ** count\n return result\n", "def descriptions(arr):\n return 2**len([v for n,v in enumerate(arr) if v==arr[n-1]+1])", "descriptions=lambda l:1<<sum(b-a==1for a,b in zip(l,l[1:]))", "from math import factorial\n\n\ndef binomial(m, n):\n return factorial(n) / factorial(m) / factorial(n-m)\n\n\ndef descriptions(arr):\n count = 0\n for i in range(1, len(arr)):\n if arr[i] == arr[i-1] + 1:\n count += 1\n return 2**count\n", "def descriptions(arr):\n r, prev, n = 1, arr[0], 1\n for x in arr[1:]:\n if x != prev + 1:\n r *= 2 ** (n - 1)\n n = 0\n prev = x\n n += 1\n return r * 2 ** (n - 1)\n", "def descriptions(arr):\n return 2**sum(j-i==1 for i,j in zip(arr,arr[1:]))", "from functools import reduce\nfrom operator import mul\ndef descriptions(arr):\n r=[]\n seq=0\n for x,y in zip(arr[:-1],arr[1:]):\n if y-x==1:\n seq+=1\n else:\n if seq>0:\n r.append(seq+1)\n seq=0\n if seq>0:\n r.append(seq+1)\n return reduce(mul,[2**(x-1) for x in r]) if r else 1", "descriptions=lambda arr:2**sum(arr[i]+1==arr[i+1] for i in range(len(arr)-1))", "def descriptions(arr):\n return 2**sum(x+1 == y for x,y in zip(arr, arr[1:]))"]
{"fn_name": "descriptions", "inputs": [[[1, 3, 4, 5, 6, 8]], [[1, 2, 3]], [[11, 43, 66, 123]], [[3, 4, 5, 8, 9, 10, 11, 23, 43, 66, 67]]], "outputs": [[8], [4], [1], [64]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,220
def descriptions(arr):
4a4fc2af1af6d746f8cb4cfc50dbfbb0
UNKNOWN
Implement a function which takes a string, and returns its hash value. Algorithm steps: * `a` := sum of the ascii values of the input characters * `b` := sum of every difference between the consecutive characters of the input (second char minus first char, third minus second, ...) * `c` := (`a` OR `b`) AND ((NOT `a`) shift left by 2 bits) * `d` := `c` XOR (32 * (`total_number_of_spaces` + 1)) * return `d` **Note**: OR, AND, NOT, XOR are bitwise operations. ___ ### Examples ``` input = "a" a = 97 b = 0 result = 64 input = "ca" a = 196 b = -2 result = -820 ``` ___ Give an example why this hashing algorithm is bad?
["def string_hash(s):\n a = sum(ord(c) for c in s)\n b = sum(ord(b) - ord(a) for a, b in zip(s, s[1:]))\n c = (a | b) & (~a << 2)\n return c ^ (32 * (s.count(\" \") + 1))\n", "def string_hash(s):\n a, b = sum(ord(x) for x in s), sum(ord(y) - ord(x) for x, y in zip(s, s[1:]))\n return (a | b) & (~a << 2) ^ (32 * (s.count(\" \") + 1))", "def string_hash(s):\n a = sum(ord(c) for c in s)\n b = ord(s[-1]) - ord(s[0]) if s else 0\n c = (a | b) & (~a << 2)\n return c ^ (32 * (s.count(' ') + 1))\n", "def string_hash(s):\n ascii_sum = sum([ ord(i) for i in s ]) # Sums all the ascii values\n ascii_difference = sum([ ord(s[j + 1]) - ord(i) for j, i in enumerate(s[:-1])])\n shifted = (ascii_sum | ascii_difference) & (( ~ascii_sum) << 2)\n return shifted ^ (32 * (s.count(\" \") + 1))", "def string_hash(s):\n xs = list(map(ord, s))\n a = sum(xs)\n b = sum(y - x for x, y in zip(xs, xs[1:]))\n c = (a | b) & ((~ a) << 2)\n d = c ^ (32 * (s.count(' ') + 1))\n return d", "def string_hash(s):\n a = sum(map(ord, s))\n b = sum([ord(b) - ord(a) for a, b in zip(s, s[1:])])\n c = (a | b) & ((~a) << 2)\n d = c ^ (32 * (s.count(' ') + 1))\n return d", "def string_hash(s):\n t = tuple(map(ord, s))\n a, b = sum(t), sum(y - x for x, y in zip(t, t[1:]))\n return (a | b) & (~a << 2) ^ 32 * (s.count(' ') + 1)", "def string_hash(s):\n return (sum([ ord(i) for i in s ]) | sum([ ord(s[j + 1]) - ord(i) for j, i in enumerate(s[:-1])]) ) & (( ~sum([ ord(i) for i in s ])) << 2) ^ (32 * (s.count(\" \") + 1))", "def string_hash(s: str) -> int:\n a = sum( ord(c) for c in s )\n n = s.count(' ')\n b = ord(s[-1])-ord(s[0]) if s else 0\n c = (a | b) & (~a << 2)\n d = c ^ ( (n+1) << 5 )\n return d", "def string_hash(s):\n a = sum(ord(c) for c in s)\n b = sum(ord(x) - ord(y) for x,y in zip(s[1:], s))\n c = (a | b) & ((~a) << 2)\n return c ^ ((s.count(\" \") + 1) << 5)"]
{"fn_name": "string_hash", "inputs": [["int main(int argc, char *argv[]) { return 0; }"], [" Yo - What's Good?! "], [" df af asd "], ["global hash"], ["section .text"], ["hash:"], [" xor eax, eax"], [" ret"], ["; -----> end of hash <-----"], ["int hash(const char *str);"], [""], [" "], [" "], [" "], [" "]], "outputs": [[188], [460], [744], [1120], [328], [-1884], [1080], [112], [-7136], [-9232], [32], [96], [32], [224], [32]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,971
def string_hash(s):
50f2cfb2fd2afa52708f6048d04d21ef
UNKNOWN
### Task: Your job is to take a pair of parametric equations, passed in as strings, and convert them into a single rectangular equation by eliminating the parameter. Both parametric halves will represent linear equations of x as a function of time and y as a function of time respectively. The format of the final equation must be `Ax + By = C` or `Ax - By = C` where A and B must be positive and A, B, and C are integers. The final equation also needs to have the lowest possible whole coefficients. Omit coefficients equal to one. The method is called `para_to_rect` or `EquationsManager.paraToRect` and takes in two strings in the form `x = at +(or -) b` and `y = ct +(or -) d` respectively, where `a` and `c` must be integers, and `b` and `d` must be positive integers. If `a` or `c` is omitted, the coefficient of _t_ is obviously assumed to be 1 (see final case in the example tests). There will NEVER be double signs in the equations inputted (For example: `"x = -12t + -18"` and `"y = -12t - -18"` won't show up.) ### Examples: ```python para_to_rect("x = 12t + 18", "y = 8t + 7") => "2x - 3y = 15" ``` > __CALCULATION:__ x = 12t + 18 y = 8t + 7 2x = 24t + 36 3y = 24t + 21 2x - 3y = (24t + 36) - (24t + 21) 2x - 3y = 15 ```python para_to_rect("x = -12t - 18", "y = 8t + 7") => "2x + 3y = -15" ``` > __CALCULATION:__ x = -12t - 18 y = 8t + 7 2x = -24t - 36 3y = 24t + 21 2x + 3y = (-24t - 36) + (24t + 21) 2x + 3y = -15 ```python para_to_rect("x = -t + 12", "y = 12t - 1") => "12x + y = 143" ``` > __CALCULATION:__ x = -t + 12 y = 12t - 1 12x = -12t + 144 y = 12t - 1 12x + y = 143 More examples in the sample test cases. ### Notes: As you can see above, sometimes you'll need to add the two parametric equations after multiplying by the necessary values; sometimes you'll need to subtract them – just get rid of the _t_!
["from fractions import gcd\nimport re\n\n\nINSERTER = re.compile(r'(?<!\\d)(?=[xyt])')\nFINDER = re.compile(r'-?\\d+')\n\n\ndef lcm(a,b): return a*b//gcd(a,b)\ndef simplify(s): return INSERTER.sub('1', s.replace(' ',''))\n\n\ndef para_to_rect(*equations):\n coefs = [ list(map(int, FINDER.findall(eq))) for eq in map(simplify, equations) ]\n l = lcm(coefs[0][1],coefs[1][1])\n x,tx,cx, y,ty,cy = ( v*l//c[1] for c in coefs for v in c )\n y, absY, c = -y, abs(y), cx-cy\n \n return \"{}x {} {}y = {}\".format(x if x!=1 else '',\n '-' if y<0 else '+',\n absY if absY!=1 else '',\n c)", "from math import gcd\n\ndef para_to_rect(eqn1, eqn2):\n a, b = eqn1.split('= ')[1].split('t ')\n c, d = eqn2.split('= ')[1].split('t ')\n if a in (\"\", \"-\"): a += '1'\n if c in (\"\", \"-\"): c += '1'\n a, b, c, d = map(eval, (a, b, c, d))\n x = gcd(a, c)\n e, f = c//x, -a//x\n if e < 0: e, f = -e, -f\n return f\"{e if e>1 else ''}x {'+-'[f<0]} {abs(f) if abs(f)>1 else ''}y = {e*b + f*d}\"", "import re\nfrom math import gcd\n\ndef para_to_rect(eqn1, eqn2):\n eqn1, eqn2 = [re.sub(r'\\bt', '1t', e) for e in [eqn1, eqn2]]\n (a,b), (c,d) = ([[int(x.replace(' ', '')) for x in re.findall('-?\\d+|[-+] \\d+', e)] for e in [eqn1, eqn2]])\n x = c*b - a*d\n g = gcd(gcd(c, a), x)\n if c < 0:\n g = -g\n c, a, x = c//g, a//g, x//g\n return re.sub(r'\\b1([xy])', r'\\1', f'{c}x {\"+-\"[a > 0]} {abs(a)}y = {x}')", "from fractions import gcd\ndef para_to_rect(*equations):\n changes = [(\" \", \"\"), (\"-t\", \"-1t\"), (\"=t\", \"=+1t\"),\n (\"+t\", \"+1t\"), (\"x=\", \"\"), (\"y=\", \"\")]\n equationsR = []\n for equation in equations:\n for (s1, s2) in changes:\n equation = equation.replace(s1, s2)\n equationsR += equation.split(\"t\")\n a, b, c, d = [int(n) for n in equationsR]\n e, f, g = c, -a, b * c - a * d\n h = gcd(gcd(e, f), g)\n e, f, g = e // h, f // h, g // h\n if e < 0:\n e, f, g = -e, -f, -g\n ysign = \"+\"\n if f < 0:\n ysign, f = \"-\", -f\n return \"{}x {} {}y = {}\".format(e if abs(e) > 1 else \"-\" if e == -1 else \"\",\\\n ysign, f if f > 1 else \"\", g)", "def extract(eq):\n k, b = eq.split('t')\n k = k[3:].strip()\n k = (int(k) if k!='-' else -1) if k else 1\n b = b.strip()\n b = (-1 if b[0]=='-' else 1)*int(b[1:].strip()) if b else 0\n return k, b\n\ndef quotient(x):\n return '' if x==1 else '-' if x==-1 else str(x)\n\nfrom math import gcd\n\ndef para_to_rect(eqn1, eqn2):\n a,b = extract(eqn1)\n k,d = extract(eqn2)\n l = -a\n m = k*b-a*d\n g = gcd(gcd(k,l),m)\n if k*g<0:\n g = -g\n k //= g\n l //= g\n m //= g\n return f'{quotient(k)}x {\"+-\"[l<0]} {quotient(abs(l))}y = {m}'\n", "def gcd(x,y):\n while y:\n x,y=y,x%y\n return x\n \ndef parseeq(s):\n s=s.split()\n a=s[2].replace('t','')\n if a=='': a=1\n elif a=='-': a=-1\n else: a=int(a)\n try:\n b=int(s[3]+s[4])\n except:\n b=0\n return a,b\n\ndef para_to_rect(eqn1, eqn2):\n a,b=parseeq(eqn1)\n c,d=parseeq(eqn2)\n e=b*c-a*d\n if c<0: a,c,e = -a,-c,-e\n g=gcd(a,gcd(abs(c),abs(e)))\n a,c,e=a//g,c//g,e//g\n sign='+-'[a>0]\n if c==1: p1=''\n elif c=='-1': p1='-'\n else: p1=c\n if a==1: p2=''\n elif a==-1: p2=''\n else: p2=abs(a)\n \n return '{}x {} {}y = {}'.format(p1,sign,p2,e)\n \n \n", "import math\nimport re\ndef lcm(a, b):\n return abs(a*b) // math.gcd(a, b)\ndef para_to_rect(eqn1, eqn2):\n try: \n x_t = int(re.findall(\"\\\\-?\\\\d+?t\", eqn1.replace('-t', '-1t'))[0].split('t')[0])\n except:\n x_t = 1\n try:\n y_t = int(re.findall(\"\\\\-?\\\\d+?t\", eqn2.replace('-t', '-1t'))[0].split('t')[0])\n except:\n y_t = 1\n \n l = lcm(x_t, y_t)\n x_n = abs(l//x_t) * int(re.findall('\\\\-?\\\\d+$', eqn1.replace(\" \", \"\"))[0])\n y_n = abs(l//y_t) * int(re.findall('\\\\-?\\\\d+$', eqn2.replace(\" \", \"\"))[0])\n \n x, y = l//abs(x_t), l//abs(y_t)\n \n if((x_t * x) + (y_t * y) == 0): \n return '{}x + {}y = {}'.format(x if x!=1 else '', y if y!=1 else '', x_n+y_n)\n \n return '{}x - {}y = {}'.format(x if x not in [1, -1] else '', y if y not in [1, -1] else '', x_n-y_n)", "import re\n\nEQUATION_REGEXP = re.compile(r'^[xy]=(-?\\d*)t([+-]\\d+)$')\n\n\ndef parse_coefficient(raw_coef):\n if not raw_coef:\n return 1\n elif raw_coef == '-':\n return -1\n return int(raw_coef)\n\n\ndef parse(equation):\n equation = equation.replace(' ', '')\n coefficients = EQUATION_REGEXP.match(equation).groups()\n return list(map(parse_coefficient, coefficients))\n\n\ndef gcd(a, b):\n return gcd(b, a % b) if b else a\n\n\ndef lcm(a, b):\n return abs(a * b) / gcd(a, b)\n\n\ndef compile_result(mult_a, mult_b, coefs_a, coefs_b):\n multiplier = -1 if mult_a < 0 else 1\n\n A = mult_a * multiplier\n A = A if A != 1 else '' \n \n B = abs(mult_b) if abs(mult_b) != 1 else ''\n B_sign = '-' if multiplier * mult_b > 0 else '+'\n \n C = multiplier * (mult_a * coefs_a[1] - mult_b * coefs_b[1])\n\n return f'{A}x {B_sign} {B}y = {C}'\n\n\ndef para_to_rect(equation_a, equation_b):\n coefs_a = parse(equation_a)\n coefs_b = parse(equation_b)\n parameter_lcm = int(lcm(coefs_a[0], coefs_b[0]))\n mult_a = int(parameter_lcm / coefs_a[0])\n mult_b = int(parameter_lcm / coefs_b[0])\n return compile_result(mult_a, mult_b, coefs_a, coefs_b)\n \n", "import re\nimport math\n\ndef para_to_rect(eqn1, eqn2):\n a = re.search(r'(-?\\d*)(?=t)', eqn1)\n if a is None:\n a = 1\n else:\n if a.group(0) == '':\n a = 1\n elif a.group(0) == '-':\n a = -1\n else:\n a = int(a.group(0))\n c = re.search(r'(-?\\d*)(?=t)', eqn2)\n if c is None:\n c = 1\n else:\n if c.group(0) == '':\n c = 1\n elif c.group(0) == '-':\n c = -1\n else:\n c = int(c.group(0))\n b = re.search(r'[-\\+]? \\d*\\Z', eqn1)\n if b is None:\n b = 0\n else:\n b = int(b.group(0).replace(' ', ''))\n d = re.search(r'[-\\+]? \\d*\\Z', eqn2)\n if b is None:\n d = 0\n else:\n d = int(d.group(0).replace(' ', ''))\n n = (a * c) // math.gcd(a, c)\n k = (-1 if c < 0 else 1)\n x = k * n // a\n y = -k * n // c\n z = k * b * n // a - k * d * n // c\n xp = '' if x == 0 else '{}x'.format('-' if x == - 1 else '' if x == 1 else abs(x))\n yp = '' if y == 0 else '{}{}y'.format(' - ' if y < 0 else ' + ', '' if abs(y) == 1 else abs(y))\n return '{}{} = {}'.format(xp, yp, z)", "from fractions import gcd\n\ndef para_to_rect(eqn1, eqn2):\n\n a1, b1 = coeff(eqn1, 'x')\n a2, b2 = coeff(eqn2, 'y')\n \n A = a2\n B = -a1\n C = b1 * a2 - a1 * b2\n \n g = gcd(gcd(A, B), C)\n \n cf = [v // g for v in [A, B, C]]\n if cf[0] < 0: \n cf = [-1 * v for v in cf]\n \n s = '+' if cf[1] >= 0 else '-'\n cf[1] = abs(cf[1])\n \n a, b, c = ['' if abs(v) == 1 else str(v) for v in cf] \n \n return '{}x {} {}y = {}'.format(a, s, b, c)\n \n \ndef coeff(eq, v): \n p1 = eq.replace(' ', '').replace(v + '=', '').split('t')\n return list([1 if x == '' else -1 if x == '-' else int(x) for x in p1])\n"]
{"fn_name": "para_to_rect", "inputs": [["x = 12t + 18", "y = 8t + 7"], ["x = -12t + 18", "y = 8t + 7"], ["x = 12t + 18", "y = -8t + 7"], ["x = -12t + 18", "y = -8t + 7"], ["x = -t + 12", "y = 12t - 1"], ["x = -12t - 18", "y = 8t - 7"], ["x = -12t + 18", "y = 8t - 7"], ["x = -18t + 12", "y = 7t - 8"], ["x = 18t + 12", "y = 7t - 8"], ["x = 18t + 12", "y = 7t + 8"], ["x = 2t + 5", "y = 3t + 4"], ["x = -2t + 5", "y = 3t - 4"], ["x = 15t + 2", "y = 20t - 11"], ["x = 15t - 2", "y = -20t - 11"], ["x = 2t - 1", "y = 2t - 1"], ["x = -2t + 1", "y = 2t + 1"], ["x = 16t + 16", "y = 8t - 12"], ["x = 16t - 16", "y = -8t - 12"], ["x = -t + 12", "y = 2t - 3"], ["x = t + 12", "y = 2t - 3"], ["x = 6t - 99", "y = 10t - 79"], ["x = -139t + 119", "y = -89t + 12"], ["x = -93t + 104", "y = t - 77"], ["x = 148t + 3", "y = -11t + 63"], ["x = -t + 96", "y = 29t - 143"], ["x = -144t - 118", "y = -142t + 65"], ["x = -71t + 37", "y = -131t - 124"], ["x = -t + 109", "y = -54t - 118"], ["x = -73t - 59", "y = t + 132"], ["x = -90t - 42", "y = -37t + 149"], ["x = -69t - 7", "y = 117t - 59"], ["x = 14t - 145", "y = 3t + 19"], ["x = 84t + 84", "y = -36t - 41"], ["x = 138t - 139", "y = -47t - 134"], ["x = -113t - 116", "y = -72t - 124"], ["x = 103t - 106", "y = -81t - 24"], ["x = -14t + 124", "y = t - 44"], ["x = 144t - 119", "y = -29t + 69"], ["x = 125t - 4", "y = -t + 50"], ["x = -132t + 142", "y = 75t - 58"]], "outputs": [["2x - 3y = 15"], ["2x + 3y = 57"], ["2x + 3y = 57"], ["2x - 3y = 15"], ["12x + y = 143"], ["2x + 3y = -57"], ["2x + 3y = 15"], ["7x + 18y = -60"], ["7x - 18y = 228"], ["7x - 18y = -60"], ["3x - 2y = 7"], ["3x + 2y = 7"], ["4x - 3y = 41"], ["4x + 3y = -41"], ["x - y = 0"], ["x + y = 2"], ["x - 2y = 40"], ["x + 2y = -40"], ["2x + y = 21"], ["2x - y = 27"], ["5x - 3y = -258"], ["89x - 139y = 8923"], ["x + 93y = -7057"], ["11x + 148y = 9357"], ["29x + y = 2641"], ["71x - 72y = -13058"], ["131x - 71y = 13651"], ["54x - y = 6004"], ["x + 73y = 9577"], ["37x - 90y = -14964"], ["39x + 23y = -1630"], ["3x - 14y = -701"], ["3x + 7y = -35"], ["47x + 138y = -25025"], ["72x - 113y = 5660"], ["81x + 103y = -11058"], ["x + 14y = -492"], ["29x + 144y = 6485"], ["x + 125y = 6246"], ["25x + 44y = 998"]]}
INTRODUCTORY
PYTHON3
CODEWARS
7,599
def para_to_rect(eqn1, eqn2):
886328783975906976a9d6465360f4d4
UNKNOWN
Given an D-dimension array, where each axis is of length N, your goal is to find the sum of every index in the array starting from 0. For Example if D=1 and N=10 then the answer would be 45 ([0,1,2,3,4,5,6,7,8,9]) If D=2 and N = 3 the answer is 18 which would be the sum of every number in the following: ```python [ [(0,0), (0,1), (0,2)], [(1,0), (1,1), (1,2)], [(2,0), (2,1), (2,2)] ] ``` A naive solution could be to loop over every index in every dimension and add to a global sum. This won't work as the number of dimension is expected to be quite large. Hint: A formulaic approach would be best Hint 2: Gauss could solve the one dimensional case in his earliest of years, This is just a generalization. ~~~if:javascript Note for JS version: Because the results will exceed the maximum safe integer easily, for such values you're only required to have a precision of at least `1 in 1e-9` to the actual answer. ~~~
["def super_sum(D, N):\n #Number of possible combinations of D length from set [0...N]\n num = pow(N,D)\n #2x average value of a combination; 2x because dividing results in float and loss of precision\n dblAvg = D*(N-1)\n #Multiply number of possible combinations by the avergae value; now use true division to ensure result is an integer\n return num*dblAvg//2", "def super_sum(D, N):\n return (D*(N-1)*(N**D))//2", "def super_sum(d,n):\n return (n**~-d*n*~-n*d)>> 0 >> 1", "def super_sum(D, N):\n s = N * (N-1) // 2\n return s * D * N ** (D-1)", "def super_sum(D, N):\n return (N ** D) * (D) * ((N - 1) // 2) if N % 2 else ((N ** D) // 2) * (D) * (N - 1)", "def super_sum(D, N):\n return ((N - 1) * (N ** D * D)) // 2", "super_sum=lambda d,n:(((n-1)*n//2)*(n**(d-1)))*d", "def super_sum(D, N):\n #Make Gauss proud!\n count = 0\n result = 0\n while ((N -1) - count) >= 1:\n result += ((N-1) - count) * (N ** (D -1))\n count += 1\n return result * D", "def super_sum(D, N):\n summe=0\n for i in range(0,N):\n summe+=i\n erg=summe*D*(N**(D-1))\n return erg\n"]
{"fn_name": "super_sum", "inputs": [[2, 2], [2, 3], [3, 2], [3, 3], [1, 101], [10, 10], [10, 11], [11, 10], [11, 11], [15, 8], [19, 84], [17, 76]], "outputs": [[4], [18], [12], [81], [5050], [450000000000], [1296871230050], [4950000000000], [15692141883605], [1847179534663680], [2871495452512585452340652014195036913664], [60022109925215517405815155929907200]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,143
def super_sum(D, N):
bd96629eb204e66bb1f85ddd42129d9a
UNKNOWN
**This Kata is intended as a small challenge for my students** All Star Code Challenge #16 Create a function called noRepeat() that takes a string argument and returns a single letter string of the **first** not repeated character in the entire string. ``` haskell noRepeat "aabbccdde" `shouldBe` 'e' noRepeat "wxyz" `shouldBe` 'w' noRepeat "testing" `shouldBe` 'e' ``` Note: ONLY letters from the english alphabet will be used as input There will ALWAYS be at least one non-repeating letter in the input string
["def no_repeat(s):\n return next(c for c in s if s.count(c) == 1)", "def no_repeat(string):\n return [x for x in string if string.count(x) == 1][0]", "from collections import Counter\n\n# Only work in 3.6+ because dicts are ordered\ndef no_repeat(string):\n return next(k for k,v in Counter(string).items() if v == 1)", "no_repeat=lambda s: [w for w in s if s.count(w)==1][0]", "def no_repeat(stg):\n return next(c for c in stg if stg.count(c) == 1)", "def no_repeat(string):\n for e in string:\n if string.count(e)==1: \n return e ", "def no_repeat(string):\n if string.count(string[0]) == 1:\n return string[0]\n else:\n return no_repeat(string.replace(string[0], ''))", "def no_repeat(string):\n #your code here\n return min(string, key=string.count)", "def no_repeat(string):\n for c in string:\n if len(string.split(c)) == 2:\n return c", "def no_repeat(string):\n for i in string:\n if string.index(i) == len(string)-string[::-1].index(i)-1: return i"]
{"fn_name": "no_repeat", "inputs": [["aabbccdde"], ["wxyz"], ["testing"], ["codewars"], ["Testing"]], "outputs": [["e"], ["w"], ["e"], ["c"], ["T"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,049
def no_repeat(string):
8e9e7f0017df43c4725f64ef796fc7b8
UNKNOWN
Given a string, return the minimal number of parenthesis reversals needed to make balanced parenthesis. For example: ```Javascript solve(")(") = 2 Because we need to reverse ")" to "(" and "(" to ")". These are 2 reversals. solve("(((())") = 1 We need to reverse just one "(" parenthesis to make it balanced. solve("(((") = -1 Not possible to form balanced parenthesis. Return -1. ``` Parenthesis will be either `"("` or `")"`. More examples in the test cases. Good luck.
["def solve(s):\n t = None\n while t != s:\n t, s = s, s.replace('()', '')\n return -1 if len(s) % 2 else sum(1 + (a == tuple(')(')) for a in zip(*[iter(s)] * 2))", "class Stack:\n def __init__(self):\n self.items = []\n\n def is_empty(self):\n return self.items == []\n\n def push(self, item):\n self.items.append(item)\n\n def pop(self):\n return self.items.pop()\n\n def peek(self):\n return self.items[-1]\n\n def size(self):\n return len(self.items)\n\n\ndef solve(s):\n l = len(s)\n if l % 2 != 0: return -1\n stack = Stack(); count = 0; i = 0\n while i < len(s):\n if s[i] == \"(\":\n stack.push(s[i])\n else:\n if stack.is_empty():\n count += 1\n else: stack.pop()\n i += 1\n q = (count + stack.size())//2\n return q if count % 2 == 0 and stack.size() % 2 == 0 else q + 1\n", "def solve(s):\n if len(s) % 2: return -1\n #imagine a simple symmetric random walk; '(' is a step up and ')' is a step down. We must stay above the original position\n height = 0; counter = 0\n for x in s:\n if x == '(':\n height += 1\n else:\n height -= 1\n if height < 0: \n counter += 1\n height += 2\n #counter is the number of flips from ')' to '(', height//2 number of opposite flips\n return counter + height // 2", "def solve(s):\n if len(s) % 2: return -1\n count, swap = 0, 0\n for i,c in enumerate(s):\n count += (c == '(') - (c == ')')\n if count < 0:\n swap += 1 ; count = 1\n elif count > len(s)-i: \n swap += 1 ; count -= 2\n return swap", "def solve(s):\n while \"()\" in s:\n s = s.replace(\"()\",\"\")\n count = 0\n while len(s)>1:\n count+=s.count(\"((\")\n s = s.replace(\"((\",\"\")\n count+=s.count(\"))\")\n s = s.replace(\"))\",\"\")\n count+=(s.count(\")(\")*2)\n s = s.replace(\")(\",\"\")\n return count if len(s)==0 else -1", "def solve(s, r={'((': 1, '))': 1, ')(': 2}):\n if len(s) % 2 == 1:\n return -1\n while '()' in s:\n s = s.replace('()', '')\n return sum(\n r[x]\n for x in map(''.join, zip(*[iter(s)] * 2))\n )", "def solve(s):\n if len(s)&1: return -1\n inv = open = 0\n for c in s:\n if c == '(':\n open += 1\n elif open:\n open -= 1\n else:\n open = 1\n inv += 1\n return inv + open//2", "import re\ndef solve(s):\n while '()' in s : s=re.sub(r'\\(\\)','',s)\n ss = re.sub(r'\\(\\(|\\)\\)','',s)\n sss = re.sub(r'\\)\\(','',ss)\n return [-1,(len(s)-len(ss))//2+len(ss)][not bool(sss)]", "def dellall(s):\n n=0\n while True: \n if n==len(s)-1 or len(s)==0:\n return True\n if s[n]=='(' and s[n+1]==')':\n del s[n]\n del s[n]\n n=0\n else:\n n+=1\n \ndef solve(s):\n s=list(s)\n count=0\n if len(s) %2 !=0:\n return -1\n dellall(s)\n while len(s)!=0:\n n=0\n if s[n]=='(' and s[n+1]==')':\n del s[n]\n del s[n]\n elif s[n]==')' and s[n+1]=='(':\n s[n]='('\n s[n+1]=')'\n count+=2\n elif s[n]=='(' and s[n+1]=='(':\n s[n+1]=')'\n count+=1\n elif s[n]==')' and s[n+1]==')':\n s[n]='('\n count+=1\n return count", "def solve(s):\n if len(s) % 2 != 0:\n return -1\n res, k = 0, 0\n for c in s:\n k += 1 if c == '(' else -1\n if k < 0:\n k += 2\n res += 1\n return res + k // 2"]
{"fn_name": "solve", "inputs": [[")()("], ["((()"], ["((("], ["())((("], ["())()))))()()("]], "outputs": [[2], [1], [-1], [3], [4]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,792
def solve(s):
0f5b576cd619ca7cda54630e5a775565
UNKNOWN
[Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant) is a two-dimensional Turing machine invented in the late 1980s. The ant starts out on a grid of black and white cells and follows a simple set of rules that has complex emergent behavior. ## Task Complete the function and return the `n`th iteration of Langton's ant with the given input. ### Parameters: * `grid` - a two dimensional array of `1`s and `0`s (representing white and black cells respectively) * `column` - horizontal position of ant * `row` - ant's vertical position * `n` - number of iterations * `dir` - ant's current direction (0 - north, 1 - east, 2 - south, 3 - west), **should default to 0** **Note:** parameters `column` and `row` will always be inside the `grid`, and number of generations `n` will never be negative. ## Output The state of the `grid` after `n` iterations. ## Rules The ant can travel in any of the four cardinal directions at each step it takes. The ant moves according to the rules below: * At a white square (represented with `1`), turn 90° right, flip the color of the square, and move forward one unit. * At a black square (`0`), turn 90° left, flip the color of the square, and move forward one unit. The grid has no limits and therefore if the ant moves outside the borders, the grid should be expanded with `0`s, respectively maintaining the rectangle shape. ## Example ```python ant([[1]], 0, 0, 1, 0) # should return: [[0, 0]] ``` Initially facing north (`0`), at the first iteration the ant turns right (because it stands on a white square, `1`), flips the square and moves forward.
["BLACK = 0\nWHITE = 1\n# N, E, S, W\nCARDINALS = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n\ndef ant(grid, column, row, n, direction=0):\n r, c, d = row, column, direction\n for _ in range(n):\n # Handle direction change and current cell colour flip\n if grid[r][c] == BLACK:\n grid[r][c] = WHITE\n d = (d + 3) % 4\n else:\n grid[r][c] = BLACK\n d = (d + 1) % 4\n # Apply movement to next grid position\n r, c = r + CARDINALS[d][0], c + CARDINALS[d][1]\n # Resize grid as required\n if r < 0:\n grid.insert(0, [0] * len(grid[0]))\n r += 1\n elif r == len(grid):\n grid.append([0] * len(grid[0]))\n elif c < 0:\n grid = [[0] + row for row in grid]\n c += 1\n elif c == len(grid[0]):\n grid = [row + [0] for row in grid]\n return grid", "def ant(grid, c, r, n, direction = 0):\n \n MOVES = [(-1,0), (0,1), (1,0), (0,-1)] # directions the ant can move\n \n dims = {(min, 0): 0, (max, 0): len(grid)-1, # min and max values of row index\n (min, 1): 0, (max, 1): len(grid[0])-1} # min and max values of column index\n \n gridWhite = { (x,y) for x in range(len(grid)) for y in range(len(grid[0])) if grid[x][y] } # set of white squares only\n \n for _ in range(n): # Ant is at work...\n direction = (direction + (-1)**((r,c) not in gridWhite)) % 4 # shift the ant\n gridWhite ^= {(r,c)} # shift the square\n r += MOVES[direction][0] # update position\n c += MOVES[direction][1]\n for func,dim in dims:\n dims[(func,dim)] = func(dims[(func,dim)], (r,c)[dim]) # update min and max values of the indexes\n \n MinX, MinY = dims[(min,0)], dims[(min,1)] # minimum for rows (x) and columns(y)\n lenX, lenY = dims[(max,0)]-MinX+1, dims[(max,1)]-MinY+1 # determine the final dimensions of the grid\n \n return [ [(1 if (x+MinX, y+MinY) in gridWhite else 0) for y in range(lenY)] for x in range(lenX) ]", "def ant(grid, col, row, n, dir = 0):\n for _ in range(n):\n # turn\n color = grid[row][col]\n if color == 1: dir = (dir + 1) % 4\n elif color == 0: dir = (dir - 1) % 4\n \n # flip color\n grid[row][col] ^= 1\n \n # move forward\n if dir == 0: row -= 1\n elif dir == 1: col += 1\n elif dir == 2: row += 1\n elif dir == 3: col -= 1\n \n # expand grid\n if row < 0:\n grid.insert(0, [0] * len(grid[0]))\n row = 0\n if row == len(grid):\n grid.append([0] * len(grid[0]))\n if col < 0:\n for i in range(len(grid)):\n grid[i].insert(0, 0)\n col = 0\n if col == len(grid[0]):\n for i in range(len(grid)):\n grid[i].append(0)\n \n return grid", "def ant(grid, column, row, n, dir = 0):\n w, d = len(grid[0]), len(grid)\n m = [[0 for i in range(w+2*n)] for j in range(d+2*n)]\n for i in range(d):\n m[i+n][n:n+w] = grid[i][:]\n x, y = column + n, row + n\n t = 0\n xmax, xmin = x, x\n ymax, ymin = y, y\n for _ in range(n):\n dir += (m[y][x]==1)*(1) +(m[y][x]==0)*(-1)\n dir %= 4\n m[y][x] = 1-m[y][x]\n y += (dir==0)*(-1) + (dir==2)*1\n x += (dir==3)*(-1) + (dir==1)*1\n xmax,xmin = max(xmax,x), min(xmin,x)\n ymax,ymin = max(ymax,y), min(ymin,y)\n return [m[i][min(xmin,n):max(xmax,n+w-1)+1] for i in range(min(ymin,n), max(ymax, n+d-1)+1)]", "def ant(gr, cl, ro, n, di = 0):\n class ant_class():\n def __init__(self, col, row, direction):\n self.c = col\n self.r = row\n self.direction = ['N', 'E', 'S', 'W']\n def __repr__(self):\n return ('col: {}, row: {}, direction: {}'.format(self.c, self.r, self.direction[0]))\n def turn_right(self):\n self.direction.append(self.direction.pop(0))\n def turn_left(self):\n self.direction.insert(0, self.direction.pop(-1))\n def move(self, grid):\n if self.direction[0] == 'N':\n if ant.r == 0:\n grid.expand_north()\n else:\n ant.r -= 1\n elif self.direction[0] == 'S':\n if ant.r == len(grid.grid) - 1:\n grid.expand_south()\n ant.r += 1\n elif self.direction[0] == 'W':\n if ant.c == 0:\n grid.expand_west()\n else:\n ant.c -= 1\n elif self.direction[0] == 'E':\n if ant.c == len(grid.grid[0]) - 1:\n grid.expand_east()\n ant.c += 1\n \n class grid():\n def __init__(self, arr):\n self.grid = arr\n def expand_south(self):\n self.grid.append([0 for i in range(len(self.grid[0]))])\n def expand_north(self):\n self.grid.insert(0, [0 for i in range(len(self.grid[0]))])\n def expand_east(self):\n self.grid = [i + [0] for i in self.grid]\n def expand_west(self):\n self.grid = [[0] + i for i in self.grid]\n def invert(self, ant):\n self.grid[ant.r][ant.c] = int(not(self.grid[ant.r][ant.c]))\n \n ant = ant_class(cl, ro, di)\n field = grid(gr)\n for i in range(di):\n ant.turn_right()\n \n for i in range(n):\n if field.grid[ant.r][ant.c] == 1:\n ant.turn_right()\n field.invert(ant)\n ant.move(field)\n elif field.grid[ant.r][ant.c] == 0:\n ant.turn_left()\n field.invert(ant)\n ant.move(field)\n \n return field.grid\n", "def ant(grid, x, y, n, d=0):\n g, p = {(j, i):v for j, row in enumerate(grid) for i, v in enumerate(row)}, (x, y)\n for m in range(n):\n g[p] = (g[p] + 1) % 2\n d += -1 if g[p] else 1 \n p = p[0] + [0, 1, 0, -1][d % 4], p[1] + [-1, 0, 1, 0][d % 4]\n g[p] = g.get(p, 0) \n \n return [[g.get((x, y), 0) for x in range(min(x for x, _ in g), max(x for x, _ in g)+1)] for y in range(min(y for _, y in g), max(y for _, y in g)+1)]", "def ant(grid, column, row, n, direction = 0):\n\n def checc(m,k,grid):\n \n if m>len(grid)-1:\n grid1 = [[0 for j in range(len(grid[0]))] for i in range(len(grid)+1)]\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n grid1[i][j]=grid[i][j]\n grid=grid1\n \n elif m<0:\n grid1 = [[0 for j in range(len(grid[0]))] for i in range(len(grid)+1)]\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n grid1[i+1][j]=grid[i][j]\n m+=1 \n grid=grid1\n \n elif k<0:\n grid1 = [[0 for j in range(len(grid[0])+1)] for i in range(len(grid))]\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n grid1[i][j+1]=grid[i][j]\n k+=1\n grid=grid1\n \n elif k>len(grid[0])-1:\n grid1 = [[0 for j in range(len(grid[0])+1)] for i in range(len(grid))]\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n grid1[i][j]=grid[i][j] \n grid=grid1\n \n return [m,k,grid]\n\n m,k=row,column\n dire=direction\n directions = {(1,0):[0,1], (1,1):[0,2], (1,2):[0,3], (1,3):[0,0],\n (0,0):[1,3], (0,1):[1,0], (0,2):[1,1], (0,3):[1,2]}\n grids ={0:[-1,0],1:[0,1],2:[1,0],3:[0,-1]}\n \n for l in range(n):\n \n m,k,grid=checc(m,k,grid)\n \n col = grid[m][k] \n grid[m][k], dire = directions[(col,dire)]\n \n m += (grids[dire])[0]\n k += (grids[dire])[1]\n \n \n m,k,grid=checc(m,k,grid)\n \n return grid\n", "def ant(g, c, r, n, d = 0):\n grid = {(i, j):g[i][j] for j in range(len(g[0])) for i in range(len(g))}\n D = {1: (0, 1), 2: (1, 0), 3: (0, -1), 0: (-1, 0)}\n for i in range(n):\n d = (d + (1 if grid[(r,c)] == 1 else -1))%4\n grid[(r,c)] = 1 - grid[(r,c)]\n R,C = D[d]\n r,c = r + R, c + C\n grid[(r, c)] = 0 if (r,c) not in grid else grid[(r,c)]\n S = grid.keys()\n m_y, m_x = [min(S,key=lambda x:x[i])[i] for i in [0,1]]\n M_y, M_x = [max(S,key=lambda x:x[i])[i] for i in [0,1]]\n return [[grid.get((m_y+j, m_x+i),0) for i in range(M_x-m_x+1)] for j in range(M_y-m_y+1)]", "def ant(grid, column, row, n, direction = 0):\n for _ in range(n):\n direction = (direction - 1 + 2*grid[row][column]) % 4\n dx, dy = d[direction]\n grid[row][column] = 1 - grid[row][column]\n row += dy\n column += dx\n if column < 0:\n for i, r in enumerate(grid):\n grid[i] = [0] + r\n column += 1\n elif column >= len(grid[0]):\n for r in grid: r.append(0)\n if row < 0:\n grid = [[0] * len(grid[0])] + grid\n row += 1\n elif row >= len(grid):\n grid.append([0] * len(grid[0]))\n return grid\n\nd = (0, -1), (1, 0), (0, 1), (-1, 0)", "def ant(grid, col, row, n, direction=0):\n for count in range(n):\n if grid[row][col] == 1:\n direction = (direction + 1)%4\n else:\n direction = (direction - 1)%4\n \n grid[row][col] = int(not grid[row][col])\n if direction == 0:\n row -= 1 \n if row < 0:\n row = 0\n grid.insert(0, [0 for i in range(len(grid[0]))])\n elif direction == 1:\n col += 1\n if col >= len(grid[0]):\n grid = [row + [0] for row in grid]\n elif direction == 2:\n row += 1\n if row >= len(grid):\n grid.append([0 for i in range(len(grid[0]))])\n else:\n col -= 1\n if col < 0:\n col = 0\n grid = [[0] + row for row in grid]\n return grid\n \n"]
{"fn_name": "ant", "inputs": [[[[1]], 0, 0, 1, 0], [[[0]], 0, 0, 1, 0], [[[1]], 0, 0, 3, 0], [[[1]], 0, 0, 1]], "outputs": [[[[0, 0]]], [[[0, 1]]], [[[0, 1], [0, 1]]], [[[0, 0]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
10,551
def ant(grid, column, row, n, direction = 0):
9e33c3907fef8b365d2f1f6448b30912
UNKNOWN
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. Task: Write ``` smallest(n) ``` that will find the smallest positive number that is evenly divisible by all of the numbers from 1 to n (n <= 40). E.g ```python smallest(5) == 60 # 1 to 5 can all divide evenly into 60 smallest(10) == 2520 ```
["def smallest(n):\n x, y, m = 1, 1, 1\n while m <= n:\n if x % m == 0:\n m += 1\n y = int(x)\n else:\n x += y\n return x\n", "from functools import reduce\nfrom math import gcd\nlcm = lambda x,y: x*y//gcd(x, y)\n\n# Note: there is a lcm function in numpy 1.17 but codewars uses 1.14\ndef smallest(n):\n return reduce(lcm, range(1, n+1))", "from fractions import gcd\n\nlcm = lambda a, b: a * b // gcd(a, b)\n\ndef smallest(n):\n num = 1\n for i in range(2, n + 1):\n num = lcm(num, i)\n return num", "from functools import reduce\nfrom math import gcd\n\n\ndef smallest(n):\n return reduce(lambda a, b: a * b // gcd(a, b), range(1, n+1))", "def gcd(a, b):\n if b == 0: return a\n return gcd(b, a%b)\n\n\ndef smallest(n):\n p = 1\n \n for i in range(2, n+1):\n p *= (i / gcd(p, i))\n \n return p", "def smallest(n):\n previous = 1\n for i in range(1,n+1):\n previous = mmc(previous,i) #mmc stands for least common multiple\n previous = int(previous) #the mmc function returns float\n return previous\n\ndef mmc(num1, num2):\n a = num1\n b = num2\n\n resto = None\n while resto is not 0:\n resto = a % b\n a = b\n b = resto\n\n return (num1 * num2) / a"]
{"fn_name": "smallest", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20]], "outputs": [[1], [2], [6], [12], [60], [60], [420], [840], [2520], [2520], [27720], [27720], [360360], [360360], [360360], [720720], [12252240], [12252240], [232792560], [232792560]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,352
def smallest(n):
88ca1d7ccf08c9c0e68ca3c30880eaa0
UNKNOWN
It's your Birthday. Your colleagues buy you a cake. The numbers of candles on the cake is provided (x). Please note this is not reality, and your age can be anywhere up to 1,000. Yes, you would look a mess. As a surprise, your colleagues have arranged for your friend to hide inside the cake and burst out. They pretend this is for your benefit, but likely it is just because they want to see you fall over covered in cake. Sounds fun! When your friend jumps out of the cake, he/she will knock some of the candles to the floor. If the number of candles that fall is higher than 70% of total candles (x), the carpet will catch fire. You will work out the number of candles that will fall from the provided string (y). You must add up the character ASCII code of each even indexed (assume a 0 based indexing) character in y, with the alphabetical position of each odd indexed character in y to give the string a total. example: 'abc' --> a=97, b=2, c=99 --> y total = 198. If the carpet catches fire, return 'Fire!', if not, return 'That was close!'.
["cake=lambda c,d:['That was close!','Fire!'][c!=0and c*0.7<sum(ord(e)-96*(i%2!=0)for i,e in enumerate(d))]", "def cake(candles,debris):\n return 'Fire!' if candles and sum(ord(c) if i%2==0 else ord(c)-96 for i,c in enumerate(debris))>candles*0.7 else 'That was close!'", "def cake(candles,debris):\n s = sum(ord(c) if i%2==0 else ord(c)-96 for i,c in enumerate(debris))\n return 'Fire!' if s > 0.7 * candles and candles > 0 else 'That was close!'", "def cake(candles,debris):\n res = 0\n for i,v in enumerate(debris):\n if i%2: res+=ord(v)-97\n else: res+=ord(v)\n if res>0.7*candles and candles: return \"Fire!\"\n else: return 'That was close!'", "def cake(candles,debris):\n total = 0\n for i,x in enumerate(list(debris)):\n total += ord(x)-(96 if i%2==1 else 0)\n return 'That was close!' if candles*0.7>total or candles==0 else 'Fire!'\n", "def cake(candles, debris):\n return \"Fire!\" if 10 * min(candles, (sum(map(ord, debris)) - len(debris)//2*96)) > 7 * candles else \"That was close!\"", "def cake(candles,debris):\n return 'Fire!' if sum(ord(c) - (i % 2 and 96) for i, c in enumerate(debris)) > 0.7 * candles and candles != 0 else 'That was close!'", "def cake(candles,debris):\n #your code here\n return 'Fire!' if candles*0.7 < sum([ord(c) if i%2 == 0 else ord(c)-96 for i, c in enumerate(debris)]) and candles != 0 else 'That was close!'", "def cake(candles,debris):\n a = ord('a') - 1\n res = sum(ord(x) if i % 2 == 0 else (ord(x) - a) for i, x in enumerate(debris))\n return 'That was close!' if candles == 0 or res / candles <= 0.7 else 'Fire!'", "def cake(candles,debris):\n ASCII = {'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101,\n 'f': 102, 'g': 103, 'h': 104, 'i': 105, 'j': 106,\n 'k': 107, 'l': 108, 'm': 109, 'n': 110, 'o': 111,\n 'p': 112, 'q': 113, 'r': 114, 's': 115, 't': 116,\n 'u': 117, 'v': 118, 'w': 119, 'x': 120, 'y': 121,\n 'z': 122}\n number = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5,\n 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10,\n 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15,\n 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20,\n 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25,\n 'z': 26}\n chetnie = debris[1::2]\n nechetnie = debris[::2]\n sum_chetnie = 0\n for el in chetnie:\n if el in number:\n sum_chetnie += number[el]\n for el in nechetnie:\n if el in ASCII:\n sum_chetnie += ASCII[el]\n if candles == 0:\n return 'That was close!'\n if sum_chetnie > candles * 0.7:\n return 'Fire!'\n else:\n return 'That was close!'"]
{"fn_name": "cake", "inputs": [[900, "abcdef"], [56, "ifkhchlhfd"], [256, "aaaaaddddr"], [333, "jfmgklfhglbe"], [12, "jaam"], [808, "alfbpmmpz"], [660, "zyxsqwh"], [651, "hmgoltyy"], [349, "nxls"], [958, "hovzfsxbmwu"], [301, "doda"], [383, "zwwl"], [871, "gnlyvknjga"], [583, "slhacx"], [0, "jpipe"]], "outputs": [["That was close!"], ["Fire!"], ["Fire!"], ["Fire!"], ["Fire!"], ["Fire!"], ["Fire!"], ["Fire!"], ["Fire!"], ["Fire!"], ["Fire!"], ["Fire!"], ["That was close!"], ["That was close!"], ["That was close!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,740
def cake(candles,debris):
ed85d9ee073c3805e642f005727cb1e7
UNKNOWN
With a friend we used to play the following game on a chessboard (8, rows, 8 columns). On the first row at the *bottom* we put numbers: `1/2, 2/3, 3/4, 4/5, 5/6, 6/7, 7/8, 8/9` On row 2 (2nd row from the bottom) we have: `1/3, 2/4, 3/5, 4/6, 5/7, 6/8, 7/9, 8/10` On row 3: `1/4, 2/5, 3/6, 4/7, 5/8, 6/9, 7/10, 8/11` until last row: `1/9, 2/10, 3/11, 4/12, 5/13, 6/14, 7/15, 8/16` When all numbers are on the chessboard each in turn we toss a coin. The one who get "head" wins and the other gives him, in dollars, the **sum of the numbers on the chessboard**. We play for fun, the dollars come from a monopoly game! ### Task How much can I (or my friend) win or loses for each game if the chessboard has n rows and n columns? Add all of the fractional values on an n by n sized board and give the answer as a simplified fraction. - Ruby, Python, JS, Coffee, Clojure, PHP, Elixir, Crystal, Typescript, Go: The function called 'game' with parameter n (integer >= 0) returns as result an irreducible fraction written as an array of integers: [numerator, denominator]. If the denominator is 1 return [numerator]. - Haskell: 'game' returns either a "Left Integer" if denominator is 1 otherwise "Right (Integer, Integer)" - Prolog: 'game' returns an irreducible fraction written as an array of integers: [numerator, denominator]. If the denominator is 1 return [numerator, 1]. - Java, C#, C++, F#, Swift, Reason, Kotlin: 'game' returns a string that mimicks the array returned in Ruby, Python, JS, etc... - Fortran, Bash: 'game' returns a string - Forth: return on the stack the numerator and the denominator (even if the denominator is 1) - In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings. #### See Example Test Cases for each language
["def game(n):\n return [n * n // 2] if n % 2 == 0 else [n * n, 2]", "'''\n n t(i) n-1 (n + i + 1) * (n - i)\ns(n) = \u03a3 ----- + \u03a3 ---------------------\n i=1 i + 1 i=1 2 * (n + i + 1)\n\n n i n-1 n - i\n = \u03a3 --- + \u03a3 -----\n i=1 2 i=1 2\n\n n i n-1 i\n = \u03a3 --- + \u03a3 ---\n i=1 2 i=1 2\n\n n n-1\n = --- + \u03a3 i\n 2 i=1\n\n n n * (n - 1)\n = --- + -----------\n 2 2\n\n = n^2 / 2\n'''\n\ndef game(n):\n return [n**2, 2] if n % 2 else [n**2 // 2]", "def game(n):\n return [n * n, 2] if n % 2 else [n * n / 2]", "def game(n):\n m = n * n\n if (m % 2 == 0):\n return [m // 2] \n else: return [m, 2]", "game = lambda n: [n * n, 2] if n % 2 else [n / 2 * n]", "def game(n):\n numerator = n ** 2\n denominator = 2\n if numerator % denominator == 1:\n return [numerator, denominator]\n return [numerator // denominator]", "def game(n):\n if n % 2 == 0:\n return [n**2//2]\n return [n**2,2]", "def game(n):\n return [n * n, 2] if n%2 else [n*n//2]", "def game(n):\n return [n ** 2, 2] if n % 2 else [0.5 * n ** 2]\n", "def game(n):\n if n % 2 == 0:\n return [n**2 // 2]\n else:\n return [n**2, 2]\n"]
{"fn_name": "game", "inputs": [[0], [1], [8], [40], [101], [204], [807], [1808], [5014], [120000], [750000], [750001], [3000000], [3000001]], "outputs": [[[0]], [[1, 2]], [[32]], [[800]], [[10201, 2]], [[20808]], [[651249, 2]], [[1634432]], [[12570098]], [[7200000000]], [[281250000000]], [[562501500001, 2]], [[4500000000000]], [[9000006000001, 2]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,413
def game(n):
2e757544cd536c3930cbab0fbe24c68f
UNKNOWN
Your task is to write an update for a lottery machine. Its current version produces a sequence of random letters and integers (passed as a string to the function). Your code must filter out all letters and return **unique** integers as a string, in their order of first appearance. If there are no integers in the string return `"One more run!"` ## Examples ``` "hPrBKWDH8yc6Lt5NQZWQ" --> "865" "ynMAisVpHEqpqHBqTrwH" --> "One more run!" "555" --> "5" ```
["def lottery(s):\n return \"\".join(dict.fromkeys(filter(str.isdigit, s))) or \"One more run!\"", "def lottery(s):\n \n result = ''\n \n for i in s:\n if i.isdigit() and i not in result:\n result += i\n \n return result or 'One more run!'", "def lottery(s):\n cifers = ''\n for simbol in s:\n if simbol in '1234567890' and simbol not in cifers:\n cifers = cifers + str(simbol)\n return cifers if len(cifers) else 'One more run!'", "def lottery(stg):\n return \"\".join(c for c in sorted(set(stg), key=stg.index) if c.isdecimal()) or \"One more run!\"", "def lottery(s):\n return ''.join({i:1 for i in s if i.isdigit()}) or 'One more run!'", "def lottery(s):\n buffer = []\n for char in s:\n if char.isdigit() and char not in buffer:\n buffer.append(char)\n if buffer:\n return ''.join(buffer)\n else:\n return 'One more run!'", "def lottery(s):\n re = ''.join(c for c in dict.fromkeys(s) if c in '0123456789')\n return 'One more run!' if re=='' else re", "def lottery(s):\n result = set()\n result_seen = result.add\n result = [char for char in s if char.isdigit() and not (char in result or result_seen(char))]\n return \"\".join(result) if \"\".join(result).isnumeric() else \"One more run!\"", "def lottery(s):\n seen = set()\n return ''.join(seen.add(a) or a for a in s if a.isdigit() and a not in seen) or \"One more run!\"", "def lottery(s):\n seen = set(); seen_add = seen.add; seq = [i for i in s if i in '0123456789']\n return ''.join(x for x in seq if not (x in seen or seen_add(x))) or \"One more run!\""]
{"fn_name": "lottery", "inputs": [["wQ8Hy0y5m5oshQPeRCkG"], ["ffaQtaRFKeGIIBIcSJtg"], ["555"], ["HappyNewYear2020"], ["20191224isXmas"], [""]], "outputs": [["805"], ["One more run!"], ["5"], ["20"], ["20194"], ["One more run!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,663
def lottery(s):
dd467547d2ebe5f3e0f01a0431e0b039
UNKNOWN
# Task Changu and Mangu are great buddies. Once they found an infinite paper which had 1,2,3,4,5,6,7,8,......... till infinity, written on it. Both of them did not like the sequence and started deleting some numbers in the following way. ``` First they deleted every 2nd number. So remaining numbers on the paper: 1,3,5,7,9,11..........till infinity. Then they deleted every 3rd number. So remaining numbers on the paper: 1,3,7,9,13,15..........till infinity.. Then they deleted every 4th number. So remaining numbers on the paper: 1,3,7,13,15..........till infinity.``` Then kept on doing this (deleting every 5th, then every 6th ...) untill they got old and died. It is obvious that some of the numbers will never get deleted(E.g. 1,3,7,13..) and hence are know to us as survivor numbers. Given a number `n`, check whether its a survivor number or not. # Input/Output - `[input]` integer `n` `0 < n <= 10^8` - `[output]` a boolean value `true` if the number is a survivor else `false`.
["def survivor(n):\n k = 2\n while n >= k and n % k:\n n -= n // k\n k += 1\n return n % k > 0", "def survivor(n):\n i=2\n while i<=n:\n if n%i==0:return False\n n-=n//i\n i+=1\n return True", "from itertools import count\n\ndef survivor(n):\n for i in count(2):\n if i > n: return True\n q, r = divmod(n, i)\n if not r: return False\n n -= q", "def survivor(n): \n print(\"look for %s\"%n)\n #coding and coding..\n last=0\n for i in range(2,n):\n if last==n:\n return True\n print(n)\n \n if n%i == 0:\n return False\n else:\n last = n\n n=n-n//i\n \n \n\n return True", "def survivor(m):\n i = 2\n while i <= m:\n q, r = divmod(m, i)\n if r == 0: return False\n m, i = m - q, i + 1\n return True\n", "def survivor(n):\n d = 2\n while n >= d:\n if n % d == 0: return False\n n -= n // d\n d += 1\n return True", "def survivor(n):\n idx, i = n, 2\n while idx % i != 0 and idx > i:\n idx -= idx//i\n i += 1\n return idx % i != 0\n", "import math\ndef survivor(n):\n for i in range(2, n):\n if n < i:\n break\n if n % i == 0:\n return False\n n = n-n//i\n return True", "import math\ndef survivor(n):\n lst = [1, 3, 7, 13, 19, 27, 39, 49, 67, 79]\n if n < 80:\n return False if n not in lst else True\n for i in range(2, n):\n if n-1 < i:\n break\n if n % i == 0:\n return False\n n = n-math.ceil(n//i)\n return True"]
{"fn_name": "survivor", "inputs": [[1], [5], [8], [9], [13], [15], [134], [289]], "outputs": [[true], [false], [false], [false], [true], [false], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,671
def survivor(n):
dcd9d7739c03ce75458033833f148a86
UNKNOWN
The goal of this Kata is to return the greatest distance of index positions between matching number values in an array or 0 if there are no matching values. Example: In an array with the values [0, 2, 1, 2, 4, 1] the greatest index distance is between the matching '1' values at index 2 and 5. Executing greatestDistance against this array would return 3. (i.e. 5 - 2) Here's the previous example in test form: ```python test.assert_equals(greatest_distance([0, 2, 1, 2, 4, 1]), 3) ``` This is based on a Kata I had completed only to realize I has misread the instructions. I enjoyed solving the problem I thought it was asking me to complete so I thought I'd add a new Kata for others to enjoy. There are no tricks in this one, good luck!
["def greatest_distance(arr):\n return max(i - arr.index(x) for i,x in enumerate(arr))", "def greatest_distance(arr):\n indexes, d = {}, 0\n for i,n in enumerate(arr):\n if n in indexes: d = max(d, i-indexes[n])\n else: indexes[n] = i\n return d", "def greatest_distance(lst):\n return max((distance(lst, n) for n in set(lst) if lst.count(n) > 1), default=0)\n\n\ndef distance(lst, item):\n return len(lst) - 1 - lst[::-1].index(item) - lst.index(item)\n", "from collections import defaultdict\n\ndef greatest_distance(a):\n d = defaultdict(list)\n for i, x in enumerate(a):\n d[x].append(i)\n return max(x[-1] - x[0] for x in d.values())", "def greatest_distance(data):\n i = 0; d = 0\n while (i < len(data)):\n j = i + 1\n while (j < len(data)):\n if (data[j] == data[i]):\n if (j - i > d): d = j - i\n j += 1\n i += 1\n return d;", "greatest_distance=lambda a:max(i-a.index(e)for i,e in enumerate(a))", "greatest_distance=lambda a:max(len(a)-a[::-1].index(e)-a.index(e)-1for e in a)", "from collections import defaultdict\n\n\ndef greatest_distance(arr):\n indexes = defaultdict(list)\n for i, a in enumerate(arr):\n indexes[a].append(i)\n try:\n return max(b[-1] - b[0] for b in indexes.values() if len(b) > 1)\n except ValueError:\n return 0\n", "def greatest_distance(arr):\n res = 0\n for i, x in enumerate(arr): \n for j, y in enumerate(arr): \n if y==x: \n res = max(res, abs(i-j))\n return res", "from collections import Counter\n\ndef greatest_distance(arr):\n r_arr, count_arr = arr[::-1], Counter(arr)\n return max(len(arr) - 1 - r_arr.index(k) - arr.index(k) if c > 1 else 0 for k, c in count_arr.items())"]
{"fn_name": "greatest_distance", "inputs": [[[9, 7, 1, 2, 3, 7, 0, -1, -2]], [[0, 7, 0, 2, 3, 7, 0, -1, -2]], [[1, 2, 3, 4]]], "outputs": [[4], [6], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,828
def greatest_distance(arr):
46af70b3fd9ffb8ee3ff071a7f013546
UNKNOWN
As most of you might know already, a prime number is an integer `n` with the following properties: * it must be greater than 1 * it must be divisible only by itself and 1 And that's it: -15 or 8 are not primes, 5 or 97 are; pretty easy, isn't it? Well, turns out that primes are not just a mere mathematical curiosity and are very important, for example, to allow a lot of cryptographic algorithms. Being able to tell if a number is a prime or not is thus not such a trivial matter and doing it with some efficient algo is thus crucial. There are already more or less efficient (or sloppy) katas asking you to find primes, but here I try to be even more zealous than other authors. You will be given a preset array/list with the first few `primes`. And you must write a function that checks if a given number `n` is a prime looping through it and, possibly, expanding the array/list of known primes only if/when necessary (ie: as soon as you check for a **potential prime which is greater than a given threshold for each** `n`, stop). # Memoization Storing precomputed results for later re-use is a very popular programming technique that you would better master soon and that is called [memoization](https://en.wikipedia.org/wiki/Memoization); while you have your wiki open, you might also wish to get some info about the [sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) (one of the few good things I learnt as extra-curricular activity in middle grade) and, to be even more efficient, you might wish to consider [an interesting reading on searching from prime from a friend of mine](https://medium.com/@lcthornhill/why-does-the-6-iteration-method-work-for-testing-prime-numbers-ba6176f58082#.dppj0il3a) [she thought about an explanation all on her own after an evening event in which I discussed primality tests with my guys]. Yes, you will be checked even on that part. And you better be **very** efficient in your code if you hope to pass all the tests ;) **Dedicated to my trainees that worked hard to improve their skills even on a holiday: good work guys!** **Or should I say "girls" ;)? [Agata](https://www.codewars.com/users/aghh1504), [Ania](https://www.codewars.com/users/lisowska) [Dina](https://www.codewars.com/users/deedeeh) and (although definitely not one of my trainees) special mention to [NaN](https://www.codewars.com/users/nbeck)**
["primes = [2, 3, 5, 7]\n\ndef is_prime(n):\n if n < 2:\n return False\n m = int(n ** .5) + 1\n for p in primes:\n if p >= m: break\n if not n % p:\n return False\n q, d = primes[-1], 4 if (n + 1) % 6 else 2\n while q < m:\n q, d = q + d, 4 - d\n if is_prime(q):\n primes.append(q)\n if not n % q:\n return False\n return True", "primes=[2,3,5,7]\n\ndef is_prime(n):\n \"\"\"\n A function that checks if a given number n is a prime looping\n through it and, possibly, expanding the array/list of known\n primes only if/when necessary (ie: as soon as you check for a\n potential prime which is greater than a given threshold for each n, stop).\n :param n:\n :return:\n \"\"\"\n\n if n < 2:\n return False\n\n for i in range(3, int(n ** 0.5) + 1, 2):\n if is_prime(i) and i not in primes:\n primes.append(i)\n\n if n % i == 0:\n return False\n\n return True", "primes = [2,3,5,7]\nsetPrimes = set(primes)\n\ndef is_prime(n):\n if n <= primes[-1]: return n > 1 and n in setPrimes\n limit = int(n**.5)\n for x in primes:\n if x > limit: break\n if not n%x: return False\n \n x, delta = primes[-1], 4 if primes[-1]%6 == 1 else 2\n while x <= limit:\n x, delta = x+delta, 6-delta\n if is_prime(x):\n primes.append(x)\n setPrimes.add(x)\n if not n % x:\n return False\n return True", "def is_prime(x): return False if x in [1,143,-1,529] else True\nprimes=\"1\"\ndef abs(x): return 0\n", "primes = [2, 3, 5]\nlastCheck = [6]\n\ndef is_prime(x):\n f = lastCheck[0]\n if x <= f:\n return x in primes\n limit = x ** 0.5\n for prime in primes:\n if prime > limit:\n return True\n if x % prime == 0:\n return False\n isPrime = True\n while f <= limit:\n f1 = f + 1\n if is_prime(f1):\n primes.append(f1)\n if x % f1 == 0:\n isPrime = False\n f5 = f + 5\n if is_prime(f5):\n primes.append(f5)\n if x % f5 == 0:\n isPrime = False\n f += 6\n if not isPrime:\n break\n lastCheck[0] = f\n return isPrime", "import math #;-)... (code is only to see what happens for python)\nprimes,parr=[2,3,5,7],[]\n\ndef is_prime(n):\n if n<2: return False\n if len(parr)==0: sieve(10000000)\n i,limit=0,round(math.sqrt(n))\n while True:\n if i>=len(primes): primes.append(parr[i])\n if primes[i]>limit: break\n if n%primes[i]==0: return False\n i+=1\n return True \n\ndef sieve(n):\n array,l=[],int(math.sqrt(n))\n for i in range (n+1): array.append(True)\n for i in range (2,l+1): \n if array[i]: \n for j in range(i*i,n+1,i): array[j]=False\n for i in range(2,n+1): \n if array[i]: parr.append(i)", "primes = [2, 3, 5, 7]\n\n\ndef gen_prime():\n candidate = primes[-1]\n while True:\n candidate += 2\n if all(candidate % prime != 0 for prime in primes):\n primes.append(candidate)\n yield candidate\n\n\ndef is_prime(n):\n print(n)\n if n <= 1:\n return False\n if n <= primes[-1]:\n return n in primes\n for prime in primes:\n if n % prime == 0:\n return False\n new_prime = gen_prime()\n while primes[-1]**2 < n:\n prime = next(new_prime)\n if n % prime == 0:\n return False\n return True\n", "primes=[2,3,5,7]\n\ndef is_prime(n):\n if n < 2:\n return False\n for i in range(3, int(n ** 0.5) + 1, 2):\n if is_prime(i) and i not in primes:\n primes.append(i)\n if n % i == 0:\n return False\n return True"]
{"fn_name": "is_prime", "inputs": [[1], [2], [5], [143], [-1], [29], [53], [529]], "outputs": [[false], [true], [true], [false], [false], [true], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,856
def is_prime(n):
3230f6a9b96e897b3f9c3066de56848d
UNKNOWN
# Task Given a number `n`, return a string representing it as a sum of distinct powers of three, or return `"Impossible"` if that's not possible to achieve. # Input/Output `[input]` integer `n` A positive integer n. `1 ≤ n ≤ 10^16`. `[output]` a string A string representing the sum of powers of three which adds up to n, or `"Impossible"` if there is no solution. If the solution does exist, it should be return as `"3^a1+3^a2+ ... +3^an"`, where ai for `0 ≤ i ≤ n` represents the corresponding exponent of the term. The terms in the string should also be sorted in descending order, meaning that higher powers should appear before the lower ones in the string (`"3^0+3^1"` is incorrect, whereas `"3^1+3^0"` is correct). # Example For `n = 4`, the output should be `"3^1+3^0"`. 4 can be represented as `3+1` which is in fact 3 to the power of 1 plus 3 to the power of 0 For `n = 2`, the output should be `"Impossible"`. There is no way to represent 2 as a sum of `distinct powers` of 3.
["import numpy as np\n\ndef sum_of_threes(n):\n s=np.base_repr(n,3)\n if '2' in s: return 'Impossible'\n return '+'.join(['3^{}'.format(i) for i,d in enumerate(s[::-1]) if d=='1'][::-1])\n", "def sum_of_threes(n):\n k, p = 0, []\n while n >= 3 ** k:\n k += 1\n while k >= 0:\n k -= 1\n if n >= 3 ** k:\n p.append(\"3^%d\" % k)\n n -= 3 ** k\n return \"Impossible\" if n else '+'.join(p)", "import math\n\ndef sum_of_threes(n):\n p = []\n while n:\n x, y = math.log(n,3), n%3\n x = int(x + 1 *(abs(x%1-1) < 1e-8))\n if y > 1 or p and x == p[-1]: return \"Impossible\"\n p.append(x)\n n = n - 3**x\n \n return '+'.join(\"3^{}\".format(x) for x in sorted(p, reverse=True))", "import math\n\ndef sum_of_threes(n):\n res = []\n for i in range(round(math.log(n, 3)), -1, -1):\n if 3**i <= n:\n res.append(i)\n n -= 3**i\n if n == 0:\n return '+'.join('3^{}'.format(i) for i in res)\n return 'Impossible'", "from numpy import base_repr\n\ndef gen(s):\n for i,c in zip(reversed(range(len(s))), s):\n if c == '2': raise Exception\n if c == '1': yield f\"3^{i}\"\n\ndef sum_of_threes(n):\n try: return '+'.join(gen(base_repr(n, 3)))\n except: return \"Impossible\"", "from bisect import bisect\n\ndef sum_of_threes(n, xs=[3**i for i in range(34)]):\n result = []\n while n >= 1:\n x = bisect(xs, n) - 1\n n -= 3 ** x\n result.append(x)\n return 'Impossible' if len(result) != len(set(result)) else '+'.join(f'3^{x}' for x in result)", "from math import log\ndef sum_of_threes(n):\n out = []\n while n > 0:\n next = int(log(n, 3))\n next += 1 if pow(3, next+1) <= n else 0\n if out and next == out[-1]: return \"Impossible\"\n out.append(next)\n n -= pow(3, next)\n \n return '+'.join(\"3^{}\".format(i) for i in out)\n", "def sum_of_threes(n):\n li = []\n while n >= 1:\n t = 0\n while 3 ** t <= n : t += 1\n n -= 3 ** (t - 1)\n li.append(f\"3^{t - 1}\")\n return [\"+\".join(li),\"Impossible\"][len(li)!=len(set(li))] ", "from functools import reduce\n\ndef sum_of_threes(n):\n return ['Impossible' if r else '+'.join(xs) for r, xs in [reduce(lambda v, x: (v[0] - 3**x, v[1] + [f'3^{x}']) if v[0] >= 3**x else v, range(34)[::-1], (n, []))]][0]"]
{"fn_name": "sum_of_threes", "inputs": [[4], [2], [28], [84], [1418194818], [87754], [531441], [8312964441463288], [5559060566575209], [243]], "outputs": [["3^1+3^0"], ["Impossible"], ["3^3+3^0"], ["3^4+3^1"], ["Impossible"], ["3^10+3^9+3^8+3^7+3^5+3^3+3^1+3^0"], ["3^12"], ["Impossible"], ["3^33+3^9+3^1"], ["3^5"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,451
def sum_of_threes(n):
e5521b7a589bd259dd9e9a47cb0917bd
UNKNOWN
Background ---------- In another dimension, there exist two immortal brothers: Solomon and Goromon. As sworn loyal subjects to the time elemental, Chronixus, both Solomon and Goromon were granted the power to create temporal folds. By sliding through these temporal folds, one can gain entry to parallel dimensions where time moves relatively faster or slower. Goromon grew dissatisfied and one day betrayed Chronixus by stealing the Temporal Crystal, an artifact used to maintain the time continuum. Chronixus summoned Solomon and gave him the task of tracking down Goromon and retrieving the Temporal Crystal. Using a map given to Solomon by Chronixus, you must find Goromon's precise location. Mission Details --------------- The map is represented as a 2D array. See the example below: ```python map_example = [[1,3,5],[2,0,10],[-3,1,4],[4,2,4],[1,1,5],[-3,0,12],[2,1,12],[-2,2,6]] ``` Here are what the values of each subarray represent: - **Time Dilation:** With each additional layer of time dilation entered, time slows by a factor of `2`. At layer `0`, time passes normally. At layer `1`, time passes at half the rate of layer `0`. At layer `2`, time passes at half the rate of layer `1`, and therefore one quarter the rate of layer `0`. - **Directions** are as follow: `0 = North, 1 = East, 2 = South, 3 = West` - **Distance Traveled:** This represents the distance traveled relative to the current time dilation layer. See below: ``` The following are equivalent distances (all equal a Standard Distance of 100): Layer: 0, Distance: 100 Layer: 1, Distance: 50 Layer: 2, Distance: 25 ``` For the `mapExample` above: ``` mapExample[0] -> [1,3,5] 1 represents the level shift of time dilation 3 represents the direction 5 represents the distance traveled relative to the current time dilation layer Solomon's new location becomes [-10,0] mapExample[1] -> [2,0,10] At this point, Solomon has shifted 2 layers deeper. He is now at time dilation layer 3. Solomon moves North a Standard Distance of 80. Solomon's new location becomes [-10,80] mapExample[2] -> [-3,1,4] At this point, Solomon has shifted out 3 layers. He is now at time dilation layer 0. Solomon moves East a Standard Distance of 4. Solomon's new location becomes [-6,80] ``` Your function should return Goromon's `[x,y]` coordinates. For `mapExample`, the correct output is `[346,40]`. Additional Technical Details ---------------------------- - Inputs are always valid. - Solomon begins his quest at time dilation level `0`, at `[x,y]` coordinates `[0,0]`. - Time dilation level at any point will always be `0` or greater. - Standard Distance is the distance at time dilation level `0`. - For given distance `d` for each value in the array: `d >= 0`. - Do not mutate the input **Note from the author:** I made up this story for the purpose of this kata. Any similarities to any fictitious persons or events are purely coincidental. If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
["def solomons_quest(arr):\n pos, lvl = [0,0], 0\n for dilat,dir,dist in arr:\n lvl += dilat\n pos[dir in [0,2]] += dist * 2**lvl * (-1)**( dir in [2,3] )\n return pos", "def solomons_quest(arr):\n level = 0\n ds = [1j, 1, -1j, -1]\n pos = 0\n for level_shift, direction, distance in arr:\n level += level_shift\n pos += (2**level) * (ds[direction] * distance)\n return [int(pos.real), int(pos.imag)]", "\n#Directions player can move: North is positive y axis, East is positive x axis\nclass Direction:\n North = 0; East = 1; South = 2; West = 3\n#-----end classDirection\n\n\n#The data of the hero of the story\nclass Solomon:\n curDir = Direction.North #default direction is set to facing north\n xLoc = 0 # East and West directions (East is positive x)\n yLoc = 0 # North and South directions (Nortn is positive y)\n timeDepth = 0 #Current depth of the traveler\n timeFactor = 2 #This factor is constant and is based on game definition\n#-----end class\n\n\n\n\ndef unpackWayPoint(wayPoint):\n amountTimeDialation = wayPoint[0]\n newDir = wayPoint[1]\n distToTravel = wayPoint[2]\n\n return amountTimeDialation, newDir, distToTravel\n#-----end function\n\n\n\ndef updateHeroDistance(hero, dirOfTravel, trueDistToMove):\n\n if dirOfTravel == Direction.North:\n hero.yLoc += trueDistToMove\n elif dirOfTravel == Direction.South:\n hero.yLoc -= trueDistToMove\n elif dirOfTravel == Direction.East:\n hero.xLoc += trueDistToMove\n else:\n hero.xLoc -= trueDistToMove\n\n#-----end fucntion\n\n#a small helper debugger function\ndef printDist(hero):\n print(('''Hero's location: [''', hero.xLoc, ',', hero.yLoc, ']'))\n\n\ndef solomons_quest(wayPoints):\n hero = Solomon()\n\n for nextStop in wayPoints:\n amtTimeDialation, dirOfTravel, amtToTravel = unpackWayPoint(nextStop)\n\n #update hero based on the waypoint data\n hero.timeDepth += amtTimeDialation\n trueDistToMove = (hero.timeFactor**hero.timeDepth)*amtToTravel #dist is based on depth and factor\n updateHeroDistance(hero, dirOfTravel, trueDistToMove)\n\n #pack data in a list\n heroFinalLoc = [hero.xLoc, hero.yLoc]\n\n return heroFinalLoc\n#-----end function\n", "def solomons_quest(arr):\n d, count, out = {0: 1, 1: 1, 2: -1, 3: -1}, 0, [0, 0]\n for i in arr:\n count += i[0]\n x = (2**count) * d[i[1]] * i[2]\n if i[1] % 2 == 1: out[0] += x\n else: out[1] += x\n return out", "def solomons_quest(arr):\n south_north = 0\n east_west = 0\n layer = 0\n for el in arr:\n layer += el[0]\n if el[1] ==0:\n south_north += el[2] * 2**layer\n elif el[1]==2:\n south_north -= el[2] * 2**layer\n elif el[1]==1:\n east_west += el[2] * 2**layer\n elif el[1]==3:\n east_west -= el[2] * 2**layer\n \n return [east_west,south_north]\n", "def solomons_quest(arr):\n d_t = 0\n loc = [0,0]\n for r in arr:\n d_t += r[0]\n if(r[1] > 1):\n loc[3%r[1]] -= r[2]*(2**d_t)\n else:\n loc[(r[1]+1)%2] += r[2]*(2**d_t)\n return loc", "def solomons_quest(arr):\n l,c = 0,[0,0]\n for way in arr:\n l+=way[0]\n c[(way[1]+1)%2] += ((-1)**(way[1]//2)) *way[2]*(2**l)\n return c", "def solomons_quest(arr):\n layer = 0\n coord = [0,0]\n for i in arr:\n layer = layer + i[0]\n if i[1] == 0: # increase the y-coordinate\n coord[1] = coord[1] + i[2] * 2 ** layer\n if i[1] == 1: # increase the x-coordinate\n coord[0] = coord[0] + i[2] * 2 ** layer\n if i[1] == 2: # decrease the y-coordinate\n coord[1] = coord[1] - i[2] * 2 ** layer\n if i[1] == 3: # decrease the x-coordinate\n coord[0] = coord[0] - i[2] * 2 ** layer\n return coord", "def solomons_quest(arr):\n layer = x = y = 0\n for l, dir_, distance in arr:\n layer = [layer+l,0][layer+l<0]\n inc, dec, r = [1,0,-1,0][dir_], [0,1,0,-1][dir_], distance*2**layer\n x += inc * r ; y += dec * r\n return [y,x]", "MOVE = [lambda d,x,y,l: (x, y+d, l), lambda d,x,y,l: (x+d, y, l), lambda d,x,y,l: (x, y-d, l), lambda d,x,y,l: (x-d, y, l)]\n\ndef solomons_quest(arr):\n x = y = l = 0\n for a,b,c in arr: x, y, l = MOVE[b](c * 2**(l+a), x, y, l+a)\n return [x, y]"]
{"fn_name": "solomons_quest", "inputs": [[[[1, 3, 5], [2, 0, 10], [-3, 1, 4], [4, 2, 4], [1, 1, 5], [-3, 0, 12], [2, 1, 12], [-2, 2, 6]]], [[[4, 0, 8], [2, 1, 2], [1, 0, 5], [-3, 3, 16], [2, 2, 2], [-1, 1, 7], [0, 0, 5], [-4, 3, 14]]], [[[1, 1, 20], [1, 2, 30], [1, 3, 8], [1, 0, 2], [1, 1, 6], [1, 2, 4], [1, 3, 6], [-7, 0, 100]]], [[[2, 2, 100], [3, 1, 25], [4, 0, 8], [-6, 3, 25], [-1, 2, 80], [8, 0, 12], [-10, 3, 220], [0, 1, 150]]], [[[3, 2, 80], [1, 1, 25], [6, 0, 8], [-5, 3, 50], [1, 2, 100], [4, 0, 9], [-8, 3, 260], [0, 1, 90]]]], "outputs": [[[346, 40]], [[68, 800]], [[-600, -244]], [[530, 15664]], [[-1880, 10368]]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,446
def solomons_quest(arr):
9ab6f6db645151fd04c5434ad65e6a1d
UNKNOWN
Spin-off of this kata, here you will have to figure out an efficient strategy to solve the problem of finding the sole duplicate number among an unsorted array/list of numbers starting from 1 up to n. Hints: a solution in linear time can be found; using the most intuitive ones to search for duplicates that can run in O(n²) time won't work.
["def find_dup(arr):\n return sum(arr) - sum(range(1, max(arr)+1))", "def find_dup(arr):\n seen = set()\n for a in arr:\n if a in seen:\n return a\n seen.add(a)\n", "find_dup=lambda arr: sum(arr)-len(arr)*(len(arr)-1)/2", "from collections import Counter\n\n\ndef find_dup(lst):\n return Counter(lst).most_common()[0][0]", "def find_dup(arr):\n memo = set()\n return next(x for x in arr if x in memo or memo.add(x))", "def find_dup(xs):\n found = set()\n for x in xs:\n if x in found:\n return x\n found.add(x)", "def find_dup(arr):\n return sum(arr, (1 - len(arr)) * len(arr) / 2)\n", "def find_dup(arr):\n return sum(arr) - ((len(arr) - 1) * len(arr))/2", "def find_dup(arr):\n l = len(arr)-1\n return sum(arr) - (l * (l+1)) / 2", "def find_dup(arr):\n return(sum(arr) - ((len(arr) - 1)*len(arr))//2);\n"]
{"fn_name": "find_dup", "inputs": [[[1, 1, 2, 3]], [[1, 2, 2, 3]], [[5, 4, 3, 2, 1, 1]], [[1, 3, 2, 5, 4, 5, 7, 6]], [[8, 2, 6, 3, 7, 2, 5, 1, 4]]], "outputs": [[1], [2], [1], [5], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
892
def find_dup(arr):
66ebbf9c9554110039ff80c3084f9ed6
UNKNOWN
You will be given two ASCII strings, `a` and `b`. Your task is write a function to determine which one of these strings is "worth" more, and return it. A string's worth is determined by the sum of its ASCII codepoint indexes. So, for example, the string `HELLO` has a value of 372: H is codepoint 72, E 69, L 76, and O is 79. The sum of these values is 372. In the event of a tie, you should return the first string, i.e. `a`.
["def highest_value(a, b):\n return max(a, b, key=lambda s: sum(map(ord, s)))", "def highest_value(a, b):\n return a if sum(map(ord, a)) >= sum(map(ord, b)) else b", "def highest_value(a, b):\n return b if sum(ord(x) for x in b) > sum(ord(x) for x in a) else a", "def worth(s):\n return sum(map(ord, s))\n \ndef highest_value(a, b):\n return max(a, b, key=worth)", "def highest_value(*args):\n return max(args, key=lambda s:sum(map(ord, s)))", "def highest_value(a, b):\n return max(a, b, key=lambda stg: sum(ord(char) for char in stg))", "def highest_value(a, b):\n ascii_values_a = [ord(c) for c in a]\n ascii_values_b = [ord(c) for c in b]\n if sum(ascii_values_a) > sum(ascii_values_b) or sum(ascii_values_a) == sum(ascii_values_b):\n return a\n return b", "def highest_value(a, b):\n return [a, b][sum(map(ord, a)) < sum(map(ord, b))]", "def highest_value(*args):\n return max(args, key=lambda a: sum(ord(b) for b in a))", "def highest_value(a, b):\n return a if sum(ord(c) for c in a) >= sum(ord(c) for c in b) else b"]
{"fn_name": "highest_value", "inputs": [["AaBbCcXxYyZz0189", "KkLlMmNnOoPp4567"], ["ABcd", "0123"], ["!\"?$%^&*()", "{}[]@~'#:;"], ["ABCD", "DCBA"]], "outputs": [["KkLlMmNnOoPp4567"], ["ABcd"], ["{}[]@~'#:;"], ["ABCD"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,075
def highest_value(a, b):
61d7f8ecf1d6e0929f0d06e36de8ee49
UNKNOWN
Create a function `isAlt()` that accepts a string as an argument and validates whether the vowels (a, e, i, o, u) and consonants are in alternate order. ```python is_alt("amazon") // true is_alt("apple") // false is_alt("banana") // true ``` Arguments consist of only lowercase letters.
["import re\n\ndef is_alt(s):\n return not re.search('[aeiou]{2}|[^aeiou]{2}',s)", "def is_alt(s):\n vowels = list(\"aeiou\")\n v = s[0] in vowels\n \n for i in s:\n if (i in vowels) != v:\n return False\n v = not(v)\n return True", "def is_alt(s):\n a = s[::2]\n b = s[1::2]\n if (b[0] in 'aeiou'):\n c = a\n a = b\n b = c \n return all(x in 'aeiou' for x in a) and all(x not in 'aeiou' for x in b);", "vowels = \"aeiou\"\ndef is_alt(s):\n # if string is less than 2 characters, it cannot alternate\n if len(s) < 2:\n return False\n\n # check if the first character is a vowel or consonant\n prevIsVowel = s[0] in vowels\n for c in s[1::]:\n # check if the next character is a vowel or consonant\n isVowel = c in vowels\n \n # if the previous character and this character are both vowels\n # or both consanants, return False\n if prevIsVowel == isVowel:\n return False\n \n # set the previous char state to the current character state\n prevIsVowel = isVowel\n \n return True", "import re\ndef is_alt(s):\n return False if re.findall('[aeiou0]{2,}|[^aeiou0-9\\W]{2,}',s) else True ", "def is_alt(s):\n return helper(s, 0, 1) if s[0] in \"aeiou\" else helper(s, 1, 0)\ndef helper(s, n, m):\n for i in range(n, len(s), 2):\n if s[i] not in \"aeiou\":\n return False\n for i in range(m, len(s), 2):\n if s[i] in \"aeiou\":\n return False\n return True", "from itertools import groupby\n\ndef is_alt(s):\n return all(len(list(gp)) == 1 for _, gp in groupby(s, key = lambda x: x in 'aeiou'))", "def is_alt(s):\n vowels = \"aeiou\"\n prev = s[0]\n for ch in s[1:]:\n if (prev in vowels and ch in vowels) or (prev not in vowels and ch not in vowels):\n return False\n prev = ch\n return True", "import re \ndef is_alt(s):\n return bool(re.search(r'^([aeiou][^aeiou])*[aeiou]?$|^([^aeiou][aeiou])*[^aeiou]?$',s))", "from itertools import tee\n\ndef is_alt(s):\n xs1, xs2 = tee(map(lambda x: x in 'aeiou', s))\n next(xs2)\n return all(a != b for a, b in zip(xs1, xs2))"]
{"fn_name": "is_alt", "inputs": [["amazon"], ["apple"], ["banana"], ["orange"], ["helipad"], ["yay"]], "outputs": [[true], [false], [true], [false], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,247
def is_alt(s):
68995ae5e7a4ce3c0088c0941b623637
UNKNOWN
Write a function, `persistence`, that takes in a positive parameter `num` and returns its multiplicative persistence, which is the number of times you must multiply the digits in `num` until you reach a single digit. For example: ```python persistence(39) => 3 # Because 3*9 = 27, 2*7 = 14, 1*4=4 # and 4 has only one digit. persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126, # 1*2*6 = 12, and finally 1*2 = 2. persistence(4) => 0 # Because 4 is already a one-digit number. ``` ```python persistence(39) # returns 3, because 3*9=27, 2*7=14, 1*4=4 # and 4 has only one digit persistence(999) # returns 4, because 9*9*9=729, 7*2*9=126, # 1*2*6=12, and finally 1*2=2 persistence(4) # returns 0, because 4 is already a one-digit number ```
["def persistence(n):\n n = str(n)\n count = 0\n while len(n) > 1:\n p = 1\n for i in n:\n p *= int(i)\n n = str(p)\n count += 1\n return count\n # your code\n", "def persistence(n):\n if n < 10: return 0\n mult = 1\n while(n > 0):\n mult = n%10 * mult\n n = n//10\n return persistence(mult) + 1", "def persistence(n):\n if str(n) == 1:\n return 0\n count = 0\n while len(str(n)) > 1:\n total = 1\n for i in str(n):\n total *= int(i)\n n = total\n count += 1\n return count", "def multiply_digits(n):\n product = 1;\n while(n > 0):\n product *= n % 10;\n n //= 10;\n \n return product;\n\ndef persistence(n):\n count = 0;\n while(n > 9):\n n = multiply_digits(n);\n count += 1;\n \n return count;\n \n"]
{"fn_name": "persistence", "inputs": [[39], [4], [25], [999], [444]], "outputs": [[3], [0], [2], [4], [3]]}
INTRODUCTORY
PYTHON3
CODEWARS
908
def persistence(n):
cf998549e50e2acdc7bd2e83ed0f9c9a
UNKNOWN
# Task Given an array `arr` and a number `n`. Call a pair of numbers from the array a `Perfect Pair` if their sum is equal to `n`. Find all of the perfect pairs and return the sum of their **indices**. Note that any element of the array can only be counted in one Perfect Pair. Also if there are multiple correct answers, return the smallest one. # Example For `arr = [1, 4, 2, 3, 0, 5] and n = 7`, the result should be `11`. Since the Perfect Pairs are `(4, 3)` and `(2, 5)` with indices `1 + 3 + 2 + 5 = 11`. For `arr = [1, 3, 2, 4] and n = 4`, the result should be `1`. Since the element at `index 0` (i.e. 1) and the element at `index 1` (i.e. 3) form the only Perfect Pair. # Input/Output - `[input]` integer array `arr` array of non-negative integers. - `[input]` integer `n` positive integer - `[output]` integer sum of indices and 0 if no Perfect Pair exists.
["def pairwise(arr, n):\n s=[]\n for i in range(len(arr)-1):\n for j in range(i+1,len(arr)):\n if j in s or i in s: continue\n if arr[i]+arr[j] ==n:\n s.append(i)\n s.append(j)\n return sum(s)", "def pairwise(arr, n):\n\n iMap, s = {}, 0\n for i,x in enumerate(arr): iMap[x] = iMap.get(x, []) + [i]\n \n for x in arr:\n if n-x in iMap and len(iMap[n-x]) > (x == n-x) < len(iMap[x]):\n s += iMap[x].pop(0)\n s += iMap[n-x].pop(0)\n return s", "def pairwise(arr, n):\n seen = set()\n for i in range(len(arr)):\n for j in range(i+1, len(arr)):\n if arr[i] + arr[j] == n and not (i in seen or j in seen):\n seen.add(i)\n seen.add(j)\n break\n return sum(seen)", "def pairwise(arr, n):\n # fiond each pair of elements that add up to n in arr\n a, i, j, pairs = sorted(arr), 0, len(arr) - 1, []\n while i < j:\n tot = a[i] + a[j]\n if tot == n:\n pairs.extend([a[i], a[j]])\n i, j = i + 1, j - 1\n elif tot < n:\n i += 1\n else:\n j -= 1\n pairs.sort()\n \n # Identify the lowest possible index for each element in pairs\n indices = []\n i, last = 0, None\n for x in pairs:\n # Continue from last found if repeat value else from start of array\n i = (indices[-1] + 1) if x == last else 0\n indices.append(arr.index(x, i))\n last = x\n \n return sum(indices)", "# This isn't best practice, this is just for fun\ndef pairwise(arr, n):\n save = set()\n add = save.add\n return sum(i+j if x+y==n and not (i in save or add(j) or add(i)) else 0 for i,x in enumerate(arr) if i not in save for j,y in enumerate(arr[i+1:], i+1) if j not in save)", "def pairwise(arr, n):\n result = 0\n for i in range(len(arr)):\n d = n - arr[i]\n if d in arr[i+1:]:\n j = arr.index(d, i+1)\n result += i + j\n arr[i] = arr[j] = n + 1\n return result\n", "from collections import defaultdict\n\ndef pairwise(arr,n):\n ixs=defaultdict(list)\n for i,e in enumerate(arr): ixs[e].append(i)\n h=n/2\n t=sum(x+y for a,ai in (p for p in ixs.items() if p[0]<h) for x,y in zip(ai,ixs.get(n-a,[])))\n if n%2: return t\n hi=ixs.get(int(h),[])\n return t+sum(hi[:len(hi)//2*2])", "def pairwise(arr, n):\n used = []\n for i in range(len(arr)-1):\n for j in range(i+1, len(arr)):\n if arr[i] + arr[j] == n and not (i in used or j in used):\n used.extend([i, j])\n return sum(used)", "from itertools import combinations\n\ndef pairwise(arr, n):\n r,c = 0,[]\n for (i,a),(j,b) in combinations(enumerate(arr),2):\n if a+b == n and i not in c and j not in c:\n r += i+j\n c.extend([i,j])\n return r", "def pairwise(arr, n):\n lst = [[e, i] for i, e in enumerate(arr)]\n ans, v = [], []\n for i, e in enumerate(arr):\n if i in v:\n continue\n for j, e2 in enumerate(arr[i+1:]):\n x = i+1+j\n if e + e2 == n and x not in v:\n v.append(i)\n v.append(x)\n ans.append((i,x))\n break\n return sum([i[0]+i[1] for i in ans]) if ans != [] else 0"]
{"fn_name": "pairwise", "inputs": [[[1, 4, 2, 3, 0, 5], 7], [[1, 3, 2, 4], 4], [[1, 1, 1], 2], [[0, 0, 0, 0, 1, 1], 1], [[15, 1, 1], 5]], "outputs": [[11], [1], [1], [10], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,390
def pairwise(arr, n):
1dcc63c047247f8dddb775fe75605b2c
UNKNOWN
The number ```1331``` is the first positive perfect cube, higher than ```1```, having all its digits odd (its cubic root is ```11```). The next one is ```3375```. In the interval [-5000, 5000] there are six pure odd digit perfect cubic numbers and are: ```[-3375,-1331, -1, 1, 1331, 3375]``` Give the numbers of this sequence that are in the range ```[a,b] ```(both values inclusive) Examples: ``` python odd_dig_cubic(-5000, 5000) == [-3375,-1331, -1, 1, 1331, 3375] # the output should be sorted. odd_dig_cubic(0, 5000) == [1, 1331, 3375] odd_dig_cubic(-1, 5000) == [-1, 1, 1331, 3375] odd_dig_cubic(-5000, -2) == [-3375,-1331] ``` Features of the random tests for python: ``` number of Tests = 94 minimum value for a = -1e17 maximum value for b = 1e17 ``` You do not have to check the entries, ```a``` and ```b``` always integers and ```a < b``` Working well in Python 2 and Python 3. Translation into Ruby is coming soon.
["from bisect import bisect_left, bisect\n\nss = set('13579')\nns = [i ** 3 for i in range(1, int((10 ** 17) ** (1/3)) + 3, 2) if set(str(i ** 3)) <= ss]\nns = [-n for n in ns[::-1]] + ns\n\ndef odd_dig_cubic(a, b):\n return ns[bisect_left(ns, a):bisect(ns, b)]", "import math\n\ndef odd_dig_cubic(a, b):\n ret = []\n st = int(math.ceil(abs(a)**(1.0/3.0)))\n en = int(abs(b)**(1.0/3.0))\n if a < 0: st *= -1\n if b < 0: en *= -1\n for i in range(st,en):\n c = i**3\n if any(j in '02468' for j in str(c)): continue\n ret += [c]\n return ret", "s,hh=-464148,[]\n\nwhile s<464159:\n v=s**3\n sv,b=str(v),1\n for c in sv: \n if not c in '-13579': b=0; break\n if b: hh.append(v)\n s+=1\n \ndef odd_dig_cubic(a, b):\n r=[]\n for i in hh:\n if i>=a:\n if i<=b: r.append(i)\n else: break\n return r", "CUBICS = [1, 1331, 3375, 35937, 59319, 357911, 753571, 5177717, 5359375, 5735339, 9393931, 17373979, 37595375, 37159393753, 99317171591, 175333911173, 397551775977, 1913551573375, 9735913353977, 11997979755957, 17171515157399, 335571975137771, 1331399339931331, 1951953359359375, 7979737131773191, 11751737113715977, 13337513771953951]\nCUBICS = [-x for x in reversed(CUBICS)] + CUBICS\n\ndef odd_dig_cubic(a, b):\n return [x for x in CUBICS if a <= x <= b]\n", "odd_dig_cubic=lambda a,b:[n**3for n in range(int(a//abs(a or 1)*abs(a)**3**-1)|1,int(b//abs(b or 1)*abs(b)**3**-1)|1+2,2)if a<=n**3<=b and set(str(n**3))<=set('-13579')]", "import re\nM=[M**3 for M in range(1,2000000) if re.match('[13579]+$',str(M**3))]\nM=sorted(M+[-M for M in M])\nodd_dig_cubic=lambda Q,S:[V for V in M if Q <= V <= S]", "def odd_dig_cubic(a, b):\n A = [-355519351557373375, -119397111955573375, -99133919737193375, -13337513771953951, -11751737113715977, -7979737131773191, -1951953359359375, -1331399339931331, -335571975137771, -17171515157399, -11997979755957, -9735913353977, -1913551573375, -397551775977, -175333911173, -99317171591, -37159393753, -37595375, -17373979, -9393931, -5735339, -5359375, -5177717, -753571, -357911, -59319, -35937, -3375, -1331, -1, 1, 1331, 3375, 35937, 59319, 357911, 753571, 5177717, 5359375, 5735339, 9393931, 17373979, 37595375, 37159393753, 99317171591, 175333911173, 397551775977, 1913551573375, 9735913353977, 11997979755957, 17171515157399, 335571975137771, 1331399339931331, 1951953359359375, 7979737131773191, 11751737113715977, 13337513771953951, 99133919737193375, 119397111955573375, 355519351557373375]\n return [i for i in A if a<=i<=b]", "def get_podpc():\n r=[]\n x=1\n while (x*x*x<=1e17):\n y=x*x*x\n if all(int(d)%2==1 for d in str(y)):\n r.append(y)\n x+=2\n return sorted([-1*x for x in r]+r)\n\narr=get_podpc()\n\ndef odd_dig_cubic(a, b):\n return [x for x in arr if a<=x<=b]", "def int_root3(x):\n x3 = int(x**(1/3))\n while (x3+1)**3 < x:\n x3+=1\n return x3\n\ndef odd_dig_cubic(a, b):\n if 0<=a<=b:\n left = (int_root3(a)+1) | 1\n right = int_root3(b) | 1\n elif a<=0<=b:\n left = 1\n right = int_root3(b) | 1\n else: #a<=b<=0\n left = (int_root3(abs(b))+1) | 1\n right = int_root3(abs(a)) | 1\n result = []\n for i in range(left,right+1,2):\n i3 = i**3\n if set(str(i3))<=set('13579'):\n if a<=i3<=b:\n result.append(i3)\n if a<=-i3<=b:\n result.append(-i3)\n return sorted(result)"]
{"fn_name": "odd_dig_cubic", "inputs": [[-5000, 5000], [0, 5000], [-1, 5000], [-5000, -2]], "outputs": [[[-3375, -1331, -1, 1, 1331, 3375]], [[1, 1331, 3375]], [[-1, 1, 1331, 3375]], [[-3375, -1331]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,479
def odd_dig_cubic(a, b):
4b56b56fdf597f4d87f801a5550181de
UNKNOWN
You're fed up about changing the version of your software manually. Instead, you will create a little script that will make it for you. # Exercice Create a function `nextVersion`, that will take a string in parameter, and will return a string containing the next version number. For example: # Rules All numbers, except the first one, must be lower than 10: if there are, you have to set them to 0 and increment the next number in sequence. You can assume all tests inputs to be valid.
["def next_version(version):\n ns = version.split('.')\n i = len(ns) - 1\n while i > 0 and ns[i] == '9':\n ns[i] = '0'\n i -= 1\n ns[i] = str(int(ns[i]) + 1)\n return '.'.join(ns)", "def next_version(version):\n tab = list(map(int, version.split('.')))\n for x in range(1, len(tab)+1):\n if tab[-x] is 9 and x != len(tab):\n tab[-x] = 0\n else:\n tab[-x] += 1\n break\n return '.'.join((list(map(str, tab))))\n\n", "def next_version(version):\n if version.count('.')==0: return str(int(version)+1)\n elif int(version[-1])<9: return version[0:-1] + str(int(version[-1])+1)\n else: return next_version(version[0:-2]) + '.0'", "def next_version(version):\n vs = list(map(int, version.split('.')))\n for i in range(len(vs)-1, -1, -1):\n vs[i] += 1\n if vs[i] < 10:\n break\n if i:\n vs[i] %= 10\n return '.'.join(map(str, vs))", "def next_version(version):\n lst = list(map(int, version.split('.')))\n for i in reversed(range(len(lst))):\n lst[i] += 1\n if i: lst[i] %= 10\n if lst[i]: break\n return '.'.join(map(str, lst))", "import re\nfrom itertools import zip_longest\ndef next_version(version):\n s, n = re.subn(r'\\.', '', version)\n return ''.join([b + a for a, b in zip_longest('{:0{}}'.format(int(s) + 1, len(s))[::-1], '.' * n, fillvalue = '')][::-1])", "def next_version(version):\n if \".\" not in version: return str(int(version) + 1)\n v = [i for i in version.split(\".\")]\n minor_version = False\n \n for index in reversed(list(range(len(v)))):\n if index == len(v)-1 :\n if int(v[index]) < 9 :\n v[index] = str(int(v[index]) + 1)\n return \".\".join(v)\n else:\n minor_version = True\n v[index] = \"0\"\n continue \n \n if minor_version:\n v[index] = str(int(v[index]) + 1)\n \n if int(v[index]) != 10 or index == 0 :\n return \".\".join(v)\n else: \n minor_version = True\n v[index] = \"0\"\n continue\n", "def next_version(version):\n carry, minors = 1, []\n for i, n in list(enumerate(version.split('.')))[::-1]:\n carry, n = divmod(int(n) + carry, 10 if i else int(n) + 2)\n minors.append(str(n))\n return '.'.join(minors[::-1])\n", "def next_version(version):\n print(version)\n array_version = version.split('.')\n last_index = len(array_version)-1\n start = 0\n add_value = 1\n while last_index>=0:\n value_last_part_version = int(array_version[last_index])+add_value\n if \"0\" in str(value_last_part_version):\n if last_index!=0:\n array_version[last_index] = str(0)\n else:\n array_version[last_index]=str(value_last_part_version)\n if len(str(value_last_part_version))!=1:\n add_value=1\n else:\n add_value=0\n else:\n add_value=0\n array_version[last_index] = str(value_last_part_version)\n last_index-=1\n return \".\".join(array_version)", "def next_version(version):\n c, s = version.count(\".\") + 1, version.replace(\".\", \"\")\n n = f\"{int(s)+1:0{len(s)}d}\"[::-1]\n return (\".\".join(n[i] for i in range(c)) + n[c:])[::-1]\n"]
{"fn_name": "next_version", "inputs": [["1.2.3"], ["0.9.9"], ["1"], ["1.2.3.4.5.6.7.8"], ["9.9"]], "outputs": [["1.2.4"], ["1.0.0"], ["2"], ["1.2.3.4.5.6.7.9"], ["10.0"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,528
def next_version(version):
8695fc23491487c7f1c1f076c347e4f7
UNKNOWN
Remember the game 2048? The main part of this game is merging identical tiles in a row. * Implement a function that models the process of merging all of the tile values in a single row. * This function takes the array line as a parameter and returns a new array with the tile values from line slid towards the front of the array (index 0) and merged. * A given tile can only merge once. * Empty grid squares are represented as zeros. * Your function should work on arrays containing arbitrary number of elements. ## Examples ``` merge([2,0,2,2]) --> [4,2,0,0] ``` Another example with repeated merges: ``` merge([4,4,8,16]) --> [8,8,16,0] merge([8,8,16,0]) --> [16,16,0,0] merge([16,16,0,0]) --> [32,0,0,0] ```
["from itertools import groupby\n\ndef merge(line):\n merged = []\n for k,g in groupby( v for v in line if v ):\n g = list(g)\n n,r = divmod(len(g),2)\n if n: merged.extend([k*2]*n)\n if r: merged.append(k)\n return merged + [0]*(len(line)-len(merged))", "def merge(line):\n line = ungap(line)\n for i in range(len(line) - 1):\n if line[i] == line[i+1]:\n line[i], line[i+1], i = line[i]*2, 0, i+1\n return ungap(line)\n\n\ndef ungap(line):\n return [n for n in line if n] + [0] * line.count(0)\n", "from itertools import chain, groupby\n\ndef merge_group(grp):\n xs = list(grp)\n q, r = divmod(len(xs), 2)\n return [xs[0] * 2] * q + [xs[0]] * r\n \ndef merge(line):\n n = len(line)\n line = list(filter(None, line))\n line = list(chain.from_iterable(merge_group(grp) for _, grp in groupby(line)))\n return line + [0] * (n - len(line))", "def merge(row):\n new_row, last_tile = [], 0\n \n for tile in row:\n if tile and tile == last_tile:\n new_row[-1] *= 2\n last_tile = 0\n elif tile != 0:\n new_row.append(tile)\n last_tile = tile\n \n return new_row + [0] * (len(row) - len(new_row))", "def merge(line):\n viper = [x for x in line if x]\n if len(viper) > 1:\n head, neck = viper[:2]\n equal = head == neck\n head += neck * equal\n tail = merge(viper[1 + equal:])\n return [head] + tail + [0] * (len(line) - len(tail) - 1)\n else:\n return line", "# Dumb 4-size array solution cause why not?\ndef merge(line):\n if line[0] != 0 and line[0] == line[1]:\n if line[2] != 0 and line[2] == line[3]:\n return [line[0] + line[1], line[2] + line[3], 0, 0]\n else:\n return [line[0] + line[1], line[2], line[3], 0]\n elif line[0] != 0 and line[1] == 0 and line[0] == line[2]:\n return [line[0] + line[2], line[3], 0, 0]\n elif line[0] != 0 and line[1] == 0 and line[2] == 0 and line[0] == line[3]:\n return [line[0] + line[3], 0, 0, 0]\n elif line[0] != 0:\n if line[1] != 0 and line[1] == line[2]:\n return [line[0], line[1] + line[2], line[3], 0]\n elif line[1] != 0 and line[2] == 0 and line[1] == line[3]:\n return [line[0], line[1] + line[3], 0, 0]\n elif line[1] != 0:\n if line[2] != 0 and line[2] == line[3]:\n return [line[0], line[1], line[2] + line[3], 0]\n else:\n return [line[0], line[1], line[2], line[3]]\n else:\n if line[2] != 0 and line[2] == line[3]:\n return [line[0], line[2] + line[3], 0, 0]\n else:\n return [line[0], line[2], line[3], 0]\n else:\n if line[1] != 0 and line[1] == line[2]:\n return [line[1] + line[2], line[3], 0, 0]\n elif line[1] != 0 and line[2] == 0 and line[1] == line[3]:\n return [line[1] + line[3], 0, 0, 0]\n elif line[1] != 0:\n if line[2] != 0 and line[2] == line[3]:\n return [line[1], line[2] + line[3], 0, 0]\n else:\n return [line[1], line[2], line[3], 0]\n else:\n if line[2] != 0 and line[2] == line[3]:\n return [line[2] + line[3], 0, 0, 0]\n else:\n return [line[2], line[3], 0, 0]\n\ndef merge(line):\n i, res = 0, []\n while i < len(line):\n x = line[i]\n if x:\n for j,y in enumerate(line[i+1:], 1):\n if y:\n if x == y:\n res.append(x + y)\n i += j\n else:\n res.append(x)\n break\n else:\n res.append(x)\n i += 1\n return res + [0]*(len(line) - len(res))", "def merge(line):\n mrg, lst, l, fr = [], [x for x in line if x], len(line), 0\n for e in lst:\n if not fr:\n fr = e\n elif fr==e:\n mrg.append(fr+e)\n fr = 0\n else:\n mrg.append(fr)\n fr = e\n \n mrg.append(fr)\n while len(mrg)<l:\n mrg.append(0) \n return mrg\n", "def merge(line):\n a,li,i= list(filter(lambda x:bool(x),line)),[],0\n while i < len(a):\n if i < len(a)-1 and a[i]==a[i+1] : a[i]+= a[i+1] ; li.append(a[i]) ; i+=1\n else : li.append(a[i])\n i+=1\n return li+[0]*(len(line)-len(li))", "def merge(line):\n temp = [x for x in line if x != 0]\n res = []\n while temp:\n if len(temp) > 1 and temp[0] == temp[1]:\n res.append(temp.pop(0) + temp.pop(0))\n else:\n res.append(temp.pop(0))\n return res + [0] * (len(line) - len(res))", "def merge(a): \n a = [i for i in a if i] + [i for i in a if not i]\n for i in range(len(a) - 1):\n if a[i] == a[i+1]: a[i], a[i+1] = 2 * a[i], 0\n\n return [i for i in a if i] + [i for i in a if not i]"]
{"fn_name": "merge", "inputs": [[[2, 0, 2, 2]], [[2, 0, 2, 4]], [[0, 0, 2, 2]], [[2, 2, 0, 0]], [[2, 2, 2, 2, 2]], [[8, 16, 16, 8]]], "outputs": [[[4, 2, 0, 0]], [[4, 4, 0, 0]], [[4, 0, 0, 0]], [[4, 0, 0, 0]], [[4, 4, 2, 0, 0]], [[8, 32, 8, 0]]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,068
def merge(line):
94762ce3157679d1f5adcc9078cf8ac0
UNKNOWN
# Summation Of Primes The sum of the primes below or equal to 10 is **2 + 3 + 5 + 7 = 17**. Find the sum of all the primes **_below or equal to the number passed in_**. From Project Euler's [Problem #10](https://projecteuler.net/problem=10 "Project Euler - Problem 10").
["from bisect import bisect\n\ndef sieve(n):\n sieve, primes = [0]*(n+1), []\n for i in range(2, n+1):\n if not sieve[i]:\n primes.append(i) \n for j in range(i**2, n+1, i): sieve[j] = 1\n return primes\n\nPRIMES = sieve(1000000)\n\ndef summationOfPrimes(n):\n return sum(PRIMES[:bisect(PRIMES, n)])", "def summationOfPrimes(primes):\n return sum(i for i in range(2,primes+1) if all(i%j for j in range(2,int(i**.5)+1)))\n", "def summationOfPrimes(primes: int):\n q = [2, ]\n for i in range(3, primes + 1, 2):\n for j in range(3, int(i ** 0.5) + 1, 2):\n if i % j == 0:\n break\n else:\n q.append(i)\n return sum(q)", "from itertools import compress \ndef sieve(n):\n r = [False,True] * (n//2) + [True] \n r[1],r[2] = False,True \n for i in range(3,int(n**.5)+1,2): \n if r[i]:\n r[i*i::2*i] = [False] * ((n+2*i-1-i*i)//(2*i))\n r = list(compress(range(len(r)),r))\n if r[-1] %2 == 0:\n return r[:-1]\n return r \n\nprimes = sieve(25000) \n\ndef summationOfPrimes(n): \n l = 0\n r = len(primes)-1 \n res = 0 \n while l<=r:\n mid = l+(r-l)//2 \n if primes[mid] == n:\n return sum(primes[:mid+1])\n elif primes[mid] < n:\n res = max(mid+1,res)\n l = mid+1\n else:\n r = mid-1 \n return sum(primes[:res])", "import numpy as np\nfrom bisect import bisect\n\ns = np.ones(10000000)\ns[:2] = s[4::2] = 0\nfor i in range(3, int(len(s)**0.5) + 1, 2):\n if s[i]:\n s[i*i::i] = 0\np = [i for i, x in enumerate(s) if x]\n\ndef summationOfPrimes(n):\n return sum(p[:bisect(p, n)])", "import math\ndef summationOfPrimes(primes):\n s = 0\n j = 0\n while j<=primes:\n if isprime(j):\n s+=j\n j+=1\n return s-1\n \n \ndef isprime(n):\n if n <=3:\n return True\n i = 2\n while i <= math.sqrt(n): \n if n%i == 0:\n return False\n i += 1\n return True", "def summationOfPrimes(p):\n return sum([2]+[n for n in range(3,p+1,2) if all(n%i!=0 for i in range(2,n))])", "import math\ndef summationOfPrimes(primes):\n ans = 0\n for num in range(2,primes + 1):\n if all(num%i!=0 for i in range(2, int(math.sqrt(num))+1)):\n ans += num\n return ans\n"]
{"fn_name": "summationOfPrimes", "inputs": [[5], [6], [7], [8], [9], [10], [20], [30], [40], [50], [100], [200], [300], [400], [500], [1000], [2000], [3000], [4000], [5000], [25000]], "outputs": [[10], [10], [17], [17], [17], [17], [77], [129], [197], [328], [1060], [4227], [8275], [13887], [21536], [76127], [277050], [593823], [1013507], [1548136], [32405717]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,385
def summationOfPrimes(primes):