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
6e6c0daf44117386abf9bf9580f944aa
UNKNOWN
Take the following IPv4 address: `128.32.10.1` This address has 4 octets where each octet is a single byte (or 8 bits). * 1st octet `128` has the binary representation: `10000000` * 2nd octet `32` has the binary representation: `00100000` * 3rd octet `10` has the binary representation: `00001010` * 4th octet `1` has the binary representation: `00000001` So `128.32.10.1` == `10000000.00100000.00001010.00000001` Because the above IP address has 32 bits, we can represent it as the unsigned 32 bit number: `2149583361` Complete the function that takes an unsigned 32 bit number and returns a string representation of its IPv4 address. ## Examples ``` 2149583361 ==> "128.32.10.1" 32 ==> "0.0.0.32" 0 ==> "0.0.0.0" ```
["from ipaddress import IPv4Address\n\ndef int32_to_ip(int32):\n return str(IPv4Address(int32))", "def int32_to_ip(int32):\n return '{}.{}.{}.{}'.format(*int32.to_bytes(4, 'big'))", "from ipaddress import ip_address\n\ndef int32_to_ip(int32):\n return str(ip_address(int32))", "def int32_to_ip(i):\n return '.'.join([str(x) for x in [i >> 24 & 0xFF, \n i >> 16 & 0xFF,\n i >> 8 & 0xFF,\n i & 0xFF]])", "import ipaddress\ndef int32_to_ip(int32):\n return str(ipaddress.IPv4Address(int32))\n", "def int32_to_ip(int32):\n \"\"\"\n The solution involves bitwise AND of int32 and a mask that we can shift around.\n Say we have the number 17194 (0b0100001100101010). This can be divided into 2\n bytes: 01000011 and 00101010.\n We can AND this with a byte that is filled with 1s - 255 (0b11111111), shifted\n left by a certain amount of bytes to get the digits in that byte:\n 01000011 00101010 # 17194\n 11111111 00000000 # 255 << 8\n 01000011 00000000 # 17194 & 255 << 8\n However, we need to shift this value *back* to get a number within (0,255)\n inclusive, as required, so shift right by the same amount.\n \"\"\"\n first = (int32 & (255 << 24)) >> 24\n second = (int32 & (255 << 16)) >> 16\n third = (int32 & (255 << 8)) >> 8\n fourth = int32 & 255\n return f\"{first}.{second}.{third}.{fourth}\"", "# convert binary\ndef convert_bin(arr):\n summa = 0\n for x,y in enumerate(arr[::-1]):\n summa = summa + 2**x * int(y)\n return summa\n \n \ndef int32_to_ip(int32):\n\n n = \"\"\n\n while int32 > 0:\n y = str(int32 % 2)\n n = y + n\n int32 = int(int32 / 2)\n\n\n if len(n) != 32: # make 32 bit\n while len(n) != 32:\n n = '0' + n\n\n a = n[:8] # first 8\n b = n[8:16] # secound 8\n c = n[16 : 24] # third 8\n d = n[24 : 32] # fourth 8\n\n return(str(convert_bin(a))+'.'+str(convert_bin(b))+'.'+str(convert_bin(c))+'.'+str(convert_bin(d)))", "def int32_to_ip(int32):\n # your code here\n \n octets = []\n octets.append(str( (int32 & 0xFF000000) >> 24))\n octets.append(str( (int32 & 0x00FF0000) >> 16))\n octets.append(str( (int32 & 0x0000FF00) >> 8))\n octets.append(str(int32 & 0x000000FF))\n return '.'.join(octets)", "def int32_to_ip(int32):\n return '.'.join([str(int(bin(int32)[2:].zfill(32)[i:i+8], 2)) for i in range(0, 32, 8)])", "from re import sub\ndef int32_to_ip(int32):\n return sub(r'(\\d{8})', lambda x: str(int(x.group(), 2))+'.' , '{0:32b}'.format(int32).replace(' ', '0'))[:-1]"]
{"fn_name": "int32_to_ip", "inputs": [[2154959208], [0], [2149583361]], "outputs": [["128.114.17.104"], ["0.0.0.0"], ["128.32.10.1"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,635
def int32_to_ip(int32):
4b90c286813cac77bd9fff9165bf6465
UNKNOWN
In this kata we are focusing on the Numpy python package. You must write a function called `looper` which takes three integers `start, stop and number` as input and returns a list from `start` to `stop` with `number` total values in the list. Five examples are shown below: ``` looper(1, 5, 1) = [1.0] looper(1, 5, 2) = [1.0, 5.0] looper(1, 5, 3) = [1.0, 3.0, 5.0] looper(1, 5, 4) = [1.0, 2.333333333333333, 3.6666666666666665, 5.0] looper(1, 5, 5) = [1.0, 2.0, 3.0, 4.0, 5.0] ```
["from numpy import linspace\n\n\ndef looper(start, stop, number):\n return list(linspace(start, stop, number))", "def looper(start, stop, number):\n if number == 1:\n return [start]\n elif number == 2:\n return [start, stop] \n \n increment = (stop - start) / (number - 1) \n \n arr = []\n for n in range(0, number - 1):\n new_element = start + n * increment\n arr.append(new_element)\n \n arr.append(float(stop))\n return arr", "def iter(start, number, step):\n for i in range(number-1):\n yield float(start + step*i)\n\ndef looper(start, stop, number):\n if number == 1:\n return [start]\n\n step = (stop - start) / (number - 1)\n lt = list(iter(start, number, step))\n lt.append(stop)\n return lt", "import numpy as np\n\ndef looper(start, stop, n):\n return np.linspace(start, stop, n).tolist()", "import numpy as np\ndef looper(start, stop, number):\n return np.linspace(start, stop, number, dtype=np.float).tolist()\n", "from numpy import linspace\n\ndef looper(*args):\n return list(linspace(*args))", "from numpy import linspace\n\ndef looper(*a):\n return list(linspace(*a))", "looper = lambda a, z, n: [a] if n == 1 else [a] + [(z - a) / (n - 1) * i + a for i in range(1, n - 1)] + [z]", "def looper(start, stop, number):\n c,r,s=0,[],(stop-start)/(number-(1 if number>1 else 0))\n while c<number:\n r.append(start+c*s)\n c+=1\n if number>1: r.pop(); r.append(stop)\n return r", "looper=lambda Q,S,R:[Q+(S-Q)/(R-1)*V for V in range(R-1)]+[S]if 1<R else[Q]"]
{"fn_name": "looper", "inputs": [[1, 5, 1], [1, 5, 2], [1, 5, 3], [1, 5, 4], [1, 5, 5]], "outputs": [[[1.0]], [[1.0, 5.0]], [[1.0, 3.0, 5.0]], [[1.0, 2.333333333333333, 3.6666666666666665, 5.0]], [[1.0, 2.0, 3.0, 4.0, 5.0]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,608
def looper(start, stop, number):
9679361ca92c136d80951b4787f9daf8
UNKNOWN
Three candidates take part in a TV show. In order to decide who will take part in the final game and probably become rich, they have to roll the Wheel of Fortune! The Wheel of Fortune is divided into 20 sections, each with a number from 5 to 100 (only mulitples of 5). Each candidate can roll the wheel once or twice and sum up the score of each roll. The winner one that is closest to 100 (while still being lower or equal to 100). In case of a tie, the candidate that rolled the wheel first wins. You receive the information about each candidate as an array of objects: each object should have a `name` and a `scores` array with the candidate roll values. Your solution should return the name of the winner or `false` if there is no winner (all scored more than 100). __Example:__ ```python c1 = {"name": "Bob", "scores": [10, 65]} c2 = {"name": "Bill", "scores": [90, 5]} c3 = {"name": "Charlie", "scores": [40, 55]} winner([c1, c2, c3]) #Returns "Bill" ``` Please note that inputs may be invalid: in this case, the function should return false. Potential errors derived from the specifications are: - More or less than three candidates take part in the game. - A candidate did not roll the wheel or rolled it more than twice. - Scores are not valid. - Invalid user entry (no name or no score).
["def winner(candidates):\n try:\n assert len(candidates) == 3\n max_total = 0\n for c in candidates:\n name, scores = c['name'], c['scores']\n assert 1 <= len(scores) <= 2\n assert all(not s % 5 and 0 < s <= 100 for s in scores)\n total = sum(scores)\n if max_total < total <= 100:\n selected, max_total = name, total\n return selected\n except:\n return False", "def winner(candidates):\n # Filter inputs\n if len(candidates) != 3 or any(\n not c.get(\"name\") or not c.get(\"scores\")\n or len(c[\"scores\"]) not in (1, 2)\n or any(s % 5 or not (5 <= s <= 100) for s in c[\"scores\"])\n for c in candidates):\n return False\n \n qualified = [c for c in candidates if sum(c[\"scores\"]) <= 100]\n if not qualified: return False\n \n winner = max(qualified, key=lambda c: sum(c[\"scores\"]))\n return winner[\"name\"]", "def winner(candidates):\n cs = [\n c\n for c in candidates\n if 'name' in c\n and 'scores' in c\n and 1 <= len(c['scores']) <= 2\n and all(5 <= s <= 100 and s % 5 == 0 for s in c['scores'])\n ]\n if len(cs) != 3:\n return False\n winner = False\n m = 0\n for candidate in candidates:\n s = sum(candidate['scores'])\n if 100 >= s > m:\n winner = candidate['name']\n m = s\n return winner", "def winner(c):\n try : assert len(c)==3 and\\\n all(0<len(i['scores'])<3 and all(not k%5 and -1<k<101 for k in i['scores']) for i in c if i['name'])and\\\n not all(sum(k['scores'])>100 for k in c)\n except : return False\n return max([[i['name'],sum(i['scores'])] for i in c],key=lambda x:x[1]<101 and x[1])[0]", "def isValidCnd(c):\n return all(k in c for k in ('name','scores')) and 0<len(c['scores'])<3 and all(not v%5 and 0<v<=100 for v in c['scores'])\n\ndef winner(cnds):\n if len(cnds) != 3 or not all(isValidCnd(c) for c in cnds): \n return False\n return max(( (sum(c['scores']),-i,c['name']) for i,c in enumerate(cnds) if 0<=sum(c['scores'])<=100), default=(0,0,False))[2]", "def winner(players):\n total_players = winner_name = winner_score = 0\n for p in players:\n try:\n name = p['name']\n scores = p['scores']\n except KeyError:\n return False\n score_total = total_spins = 0\n total_players += 1\n for score in scores:\n if score > 100 or score % 5:\n return False\n score_total += score\n total_spins += 1\n if total_spins not in (1, 2):\n return False\n elif score_total > 100:\n continue\n elif score_total > winner_score:\n winner_name = name\n winner_score = score_total\n return winner_name if winner_score and total_players == 3 else False", "def winner(candidates):\n if any(c.keys() != ['name', 'scores'] for c in candidates):\n return False\n if any([len(candidates)!= 3, \n any(len(c['scores']) not in (1,2) for c in candidates),\n any( not(5 <= i <= 100) or (i % 5 != 0) for c in candidates for i in c['scores'])]):\n return False\n\n m = 0\n for c in candidates:\n if m < sum(c['scores']) <= 100:\n m = sum(c['scores'])\n w = c['name']\n return w if m > 0 else False", "def winner(candidates):\n if len(candidates) != 3 or any(\n not c.get(\"name\") or not c.get(\"scores\")\n or len(c[\"scores\"]) not in (1, 2)\n or any(s % 5 or not (5 <= s <= 100) for s in c[\"scores\"])\n for c in candidates):\n return False\n \n qualified = [c for c in candidates if sum(c[\"scores\"]) <= 100]\n return (max(qualified, key=lambda c: sum(c[\"scores\"]))[\"name\"]\n if qualified else False)", "def winner(candidates):\n if len(candidates) != 3 or not all(set(('name','scores'))==set(c.keys()) and len(c['scores']) in [1, 2] and all(s%5==0 and s>=5 and s<=100 for s in c['scores']) for c in candidates):\n return False\n candidates = filter(lambda c:sum(c['scores']) <= 100, candidates)\n return sorted(candidates, key=lambda c:-sum(c['scores']))[0]['name'] if candidates else False", "def winner(cs):\n if not (len(cs)==3 and all('name' in c and 'scores' in c and len(c['scores']) in (1,2) and all(5<=s<=100 and not s%5 for s in c['scores']) for c in cs)): return False\n cs={c['name']:(sum(c['scores']),-i) for i,c in enumerate(cs)}\n try: return max((c for c in cs.items() if c[1][0]<=100),key=lambda c:c[1])[0]\n except: return False"]
{"fn_name": "winner", "inputs": [[[]]], "outputs": [[false]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,794
def winner(candidates):
c8adddd2770c5121946aeadd488211f8
UNKNOWN
Our fruit guy has a bag of fruit (represented as an array of strings) where some fruits are rotten. He wants to replace all the rotten pieces of fruit with fresh ones. For example, given `["apple","rottenBanana","apple"]` the replaced array should be `["apple","banana","apple"]`. Your task is to implement a method that accepts an array of strings containing fruits should returns an array of strings where all the rotten fruits are replaced by good ones. ### Notes - If the array is null/nil/None or empty you should return empty array (`[]`). - The rotten fruit name will be in this camelcase (`rottenFruit`). - The returned array should be in lowercase.
["def remove_rotten(bag_of_fruits):\n return [x.replace('rotten', '').lower() for x in bag_of_fruits] if bag_of_fruits else []", "def remove_rotten(fruit_bag):\n # Checking\n if not fruit_bag:\n return []\n # Processing\n temp = []\n for i in fruit_bag:\n i = i.replace(\"rotten\", \"\", 1)\n i = i.lower()\n temp.append(i)\n return temp", "def remove_rotten(fruits):\n return [f[6].lower()+f[7:] if f[:6] == 'rotten' else f for f in fruits] if fruits else []", "import re\nrotten_pattern = re.compile(\"rotten\")\n\ndef remove_rotten(bag_of_fruits):\n return [re.sub(rotten_pattern, \"\", fruit.lower()) for fruit in bag_of_fruits] if bag_of_fruits else []", "def remove_rotten(bag_of_fruits):\n if bag_of_fruits is None:\n return []\n\n clean_bag = []\n \n for fruit in bag_of_fruits:\n if \"rotten\" in fruit:\n clean_bag.append(fruit.replace(\"rotten\",\"\").lower())\n else:\n clean_bag.append(fruit)\n \n return clean_bag", "def remove_rotten(fruits):\n return [f.replace('rotten', '').lower() for f in fruits or []]", "def remove_rotten(bag_of_fruits):\n return([i[6:].lower() if i[:6] == \"rotten\" else i for i in bag_of_fruits] if bag_of_fruits else [])", "def remove_rotten( bag_of_fruits ):\n return [ el.replace( \"rotten\", \"\" ).lower() for el in bag_of_fruits ] if bag_of_fruits else [ ]\n", "from re import sub\n\ndef remove_rotten(bag_of_fruits):\n return [sub('rotten', '', fruit).lower() for fruit in bag_of_fruits] if bag_of_fruits is not None else []", "def remove_rotten(bag):\n return [ fruit[6:].lower() if 'rotten' in fruit else fruit for fruit in bag] if bag else []"]
{"fn_name": "remove_rotten", "inputs": [[["apple", "banana", "kiwi", "melone", "orange"]], [["rottenApple", "rottenBanana", "rottenApple", "rottenPineapple", "rottenKiwi"]], [[]], [null], [["apple", "rottenBanana", "rottenApple", "pineapple", "kiwi"]]], "outputs": [[["apple", "banana", "kiwi", "melone", "orange"]], [["apple", "banana", "apple", "pineapple", "kiwi"]], [[]], [[]], [["apple", "banana", "apple", "pineapple", "kiwi"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,719
def remove_rotten(bag_of_fruits):
39dd52f737f8cfa2ee58dbca0214ea75
UNKNOWN
Given an array (ints) of n integers, find three integers in arr such that the sum is closest to a given number (num), target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example: Note: your solution should not modify the input array.
["from itertools import combinations\n\n\ndef closest_sum(ints, num):\n return sum(min(combinations(ints, 3), key=lambda a: abs(num - sum(a))))", "from itertools import combinations\n\ndef closest_sum(ints, num):\n ss = map(sum, combinations(ints, 3))\n return min(ss, key=lambda x: abs(x-num))", "from itertools import combinations\n\ndef closest_sum(arr, target):\n return min(map(sum, combinations(arr, 3)), key=lambda s: abs(target-s))", "from itertools import combinations\n\ndef closest_sum(ints, num):\n return sum(min(combinations(ints, 3), key=lambda i: abs(num-sum(i))))", "from itertools import combinations\n\ndef closest_sum(ints, num):\n return min(map(sum, combinations(ints, 3)), key=lambda x: abs(x - num))", "def closest_sum(i, ii):\n # your solution goes here\n print (i)\n print (ii)\n iii = len(i)\n iiiiiii = 264064296425738246861428640756429.1754206\n for iiii in range(iii):\n for iiiii in range(iii):\n for iiiiii in range(iii):\n if iiii != iiiii and iiiii != iiiiii and iiiiii != iiii:\n if abs(i[iiii] + i[iiiii] + i[iiiiii] - ii) < abs(iiiiiii - ii):\n iiiiiii = i[iiii] + i[iiiii] + i[iiiiii]\n return iiiiiii", "closest_sum=lambda a,n:min(map(sum,__import__('itertools').combinations(a,3)),key=lambda c:abs(c-n))", "from itertools import permutations;closest_sum=lambda s,n:min([sum(i) for i in permutations(s, 3)], key=lambda x: abs(x - n))", "def A(arr,a,b,c,L,T):\n if c<L:\n T.append(arr[a]+arr[b]+arr[c])\n if a==L-2:\n return 0\n elif b==L-2:\n return A(arr,a+1,a+2,a+3,L,T)\n elif c==L-1:\n return A(arr,a,b+1,b+2,L,T)\n \n return A(arr,a,b,c+1,L,T)\n \ndef closest_sum(ints, num):\n print((num,ints))\n T=[]\n A(ints,0,1,2,len(ints),T)\n print(T)\n if num in T:\n return num\n else:\n l,h=num,num\n while True:\n l-=1\n h+=1\n if l in T and h in T:\n return l if T.index(l)<T.index(h) else h\n if l in T:\n return l\n if h in T:\n return h\n", "import itertools\n\ndef closest_sum(ints, num):\n res = ints[:3]\n comb = list(itertools.combinations(ints, 3))\n for i in comb:\n if abs(num-sum(i)) < abs(num-sum(res)):\n res = [_ for _ in i]\n return sum(res)"]
{"fn_name": "closest_sum", "inputs": [[[-1, 2, 1, -4], 1], [[5, 4, 0, 3], 3], [[1, 2, 3, 4], 4], [[-2, 2, -3, 1], 3]], "outputs": [[2], [7], [6], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,429
def closest_sum(ints, num):
91c95dc77f6b9703aa1d07d3506d6f10
UNKNOWN
# Task Below we will define what and n-interesting polygon is and your task is to find its area for a given n. A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim side by side. You can see the 1-, 2- and 3-interesting polygons in the picture below. ![](https://files.gitter.im/myjinxin2015/Gwsw/blob) # Example For `n = 1`, the output should be `1`; For `n = 2`, the output should be `5`; For `n = 3`, the output should be `13`. # Input/Output - `[input]` integer `n` Constraints: `1 ≤ n < 10000.` - `[output]` an integer The area of the n-interesting polygon.
["def shape_area(n):\n return n**2 + (n - 1) ** 2", "def shape_area(n):\n return 2 * n * (n - 1) + 1", "def shape_area(n):\n if n==1:\n return 1\n return n*n*2-n-(n-1)", "def shape_area(n):\n p = 0\n area = 1\n for i in range (1, n):\n p = n*4-4\n n -= 1\n area += p\n return area\n \n", "tr = lambda n: (n*(n+1))//2 if n>=0 else 0\nshape_area = lambda n: tr(n)+2*tr(n-1)+tr(n-2)", "#https://en.wikipedia.org/wiki/Centered_square_number\n\ndef shape_area(n):\n return n**2 + (n-1)**2", "def shape_area(n):\n return sum([4*(e-1) for e in range(n,1,-1)])+1", "def shape_area(n):\n res=1\n for x in range(1,n):\n res += x*4\n \n return res", "def shape_area(n):\n return 2*n*n - 2*n + 1", "def shape_area(n):\n #1 1\n #2 5 1 + 3 + 1\n #3 13 1 + 3 + 5 + 3 + 1\n #4 25 1 + 3 + 5 + 7 + 5 + 3 + 1\n return 2 * sum(x for x in range(1, 2*(n-1), 2)) + (2*n - 1)"]
{"fn_name": "shape_area", "inputs": [[2], [3], [1], [5]], "outputs": [[5], [13], [1], [41]]}
INTRODUCTORY
PYTHON3
CODEWARS
925
def shape_area(n):
f9911ee4698b197a5bab648330ae8b1d
UNKNOWN
In this Kata, we are going to reverse a string while maintaining the spaces (if any) in their original place. For example: ``` solve("our code") = "edo cruo" -- Normal reversal without spaces is "edocruo". -- However, there is a space at index 3, so the string becomes "edo cruo" solve("your code rocks") = "skco redo cruoy". solve("codewars") = "srawedoc" ``` More examples in the test cases. All input will be lower case letters and in some cases spaces. Good luck! Please also try: [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2) [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)
["def solve(s):\n it = reversed(s.replace(' ',''))\n return ''.join(c if c == ' ' else next(it) for c in s)", "def solve(s):\n space_index=[i for i in range(len(s)) if s[i]==\" \"] #find index of saces \n s = ''.join(s.split()) #remove spaces\n s=s[::-1] #reverse the string \n for i in space_index: #add spaces again to exactly same place before\n s = s[:i] + \" \" + s[i:]\n return s", "def solve(s):\n rev = list(s.replace(' ', '')[::-1])\n for index, item in enumerate(s):\n if item == ' ':\n rev.insert(index, item)\n return ''.join(rev)\n \n", "def solve(s):\n r = list(s.replace(' ', ''))\n return ''.join(i if i == ' ' else r.pop() for i in s)", "def solve(s):\n it = iter(s.replace(' ', '')[::-1])\n return ''.join(' ' if c == ' ' else next(it) for c in s)", "def solve(s):\n r = [a for a in s if a != ' ']\n return ''.join(a if a == ' ' else r.pop() for a in s)", "solve = lambda s: (lambda j=reversed(s.replace(' ','')): ''.join(e if e==' ' else next(j) for e in s))()", "def solve(s):\n slist = []\n for i in s: slist.append(i)\n c = 0\n res = []\n for i in slist:\n if slist[c] == ' ':\n res.append(c)\n slist.remove(slist[c])\n c += 1 \n s_rev = slist[::-1]\n c = 0\n for i in s_rev:\n if c+1 in res: s_rev[c] = s_rev[c] + \" \"\n c += 1\n return ''.join(i for i in s_rev )\n", "def solve(s):\n if s.count(' ') >= 1:\n positions = [i for i in range(len(s)) if s[i] == ' ']\n l = [i for i in s if i != ' '][::-1]\n for i in positions:\n l.insert(i, ' ')\n return ''.join(l)\n else:\n return s[::-1]", "def solve(s):\n tempr = list(s)\n ts = tempr.count(' ')\n for i in range(ts):\n tempr.remove(' ')\n tempr = tempr[::-1]\n s = list(s)\n it = 0\n iw = 0\n while iw != len(s):\n if s[iw] == ' ':\n iw+=1\n else:\n s[iw] = tempr[it]\n it+=1\n iw+=1\n return ''.join(s)", "def solve(s):\n char = s.replace(\" \", \"\")[::-1]\n list = s.split(\" \")\n i = 0\n for x in list:\n list[i] = char[:len(x)]\n char = char [len(x):]\n i += 1\n return \" \".join(list)", "#reversing the code does not mean keeping the spaces at the same place wtf\ndef solve(s):\n spaceIndex = []\n result = []\n index = 0\n for i in s:\n if i != \" \":\n result.insert(1, i)\n else:\n spaceIndex.append(index)\n index += 1\n result.append(result[0])\n result.pop(0)\n for j in range(0, len(spaceIndex)):\n result.insert(spaceIndex[j], \" \")\n return \"\".join(result)", "def solve(s):\n if len(s)<2: return s\n if s[0]==' ': return ' '+solve(s[1:])\n if s[-1]==' ': return solve(s[:-1])+' '\n return s[-1]+solve(s[1:-1])+s[0]\n", "def solve(s):\n z = reversed(s.replace(' ', ''))\n return ''.join(' ' if i == ' ' else next(z) for i in s)", "def solve(s):\n ans = list(s.replace(' ', '')[::-1])\n for i in [i for i, item in enumerate(s) if item == ' ']:\n ans.insert(i, ' ')\n return ''.join(ans)", "def solve(s):\n ys = iter(y for y in reversed(s) if y != ' ')\n return ''.join(next(ys) if x != ' ' else x for x in s)", "solve = lambda s: (lambda ns=reversed(s.replace(' ', '')):\"\".join(e == ' ' and ' ' or next(ns) for e in s))()", "def solve(s):\n s_list = s.split(\" \")\n s_nospace = \"\"\n for i in s_list:\n s_nospace+=i\n s_nospace_reverse = \"\"\n for i in range(1,len(s_nospace)+1):\n s_nospace_reverse+=s_nospace[-i]\n final_s = \"\"\n space_index = []\n for i in range(0,len(s)):\n if s[i] == ' ': space_index.append(i)\n sdvig = 0\n for i in range(0, len(s_nospace)):\n if i+sdvig in space_index: \n final_s += \" \"\n sdvig +=1\n if i<len(s_nospace): final_s += s_nospace_reverse[i]\n if s[-1]==\" \": final_s+=\" \"\n return final_s", "def solve(s):\n lst_s = list(s)\n i, j = 0, len(s)-1\n while j > i:\n if lst_s[i] == ' ' or lst_s[j] == ' ':\n if lst_s[i] == ' ': i += 1\n if lst_s[j] == ' ': j -= 1\n continue\n else:\n lst_s[i], lst_s[j] = lst_s[j], lst_s[i]\n i += 1\n j -= 1\n return ''.join(lst_s)", "def solve(s):\n reversed = list(''.join(s.split())[::-1])\n for i in range(len(s)):\n if s[i] == ' ':\n reversed.insert(i, ' ')\n return ''.join(reversed)\n", "import re\n\ndef solve(s):\n space_index = [m.start() for m in re.finditer(\" \",s)]\n reverse = s.replace(\" \",\"\")[::-1]\n list_reverse = list(reverse)\n for index in space_index:\n list_reverse.insert(index,\" \")\n return ''.join(list_reverse)", "import re\n\ndef solve(s):\n swap = reversed([m.start() for m in re.finditer(r\"[^ ]\", s)])\n return \"\".join(s[next(swap)] if c != \" \" else c for c in s)", "import re\ndef solve(s):\n result = list(s)\n indices = [m.span()[0] for m in re.finditer(r\"[^ ]\", s)] \n for a,b in zip(indices, indices[::-1]):\n result[a] = s[b]\n return \"\".join(result)", "def solve(s):\n string = s\n string = string.split()\n string = ''.join(string)\n string = string[::-1]\n \n space_list = []\n for i, char in enumerate(s):\n if char == ' ':\n space_list.append(i)\n \n for space in space_list:\n first_chunk = string[0:space]\n first_chunk += ' '\n string = first_chunk + string[space:] \n return string\n", "def solve(s):\n indexes = []\n for i in range(len(s)):\n if s[i] == \" \":\n indexes.append(i)\n lst = s.split(\" \")\n result = []\n for i in range(len(lst)):\n result.append(lst[i][::-1])\n result.reverse()\n t = \"\".join(result)\n t = list(t)\n for i in range(len(indexes)):\n t.insert(indexes[i], \" \")\n return \"\".join(t)\n", "def solve(s):\n print(s)\n l = [c for c in s if c != ' ']\n l.reverse()\n for i,c in enumerate(s):\n if c == ' ':\n l.insert(i, c)\n return ''.join(l)", "def solve(c):\n k=(\"\".join(reversed(c)))\n h=k.replace(\" \",\"\")\n s=[i for i in range(len(c)) if \" \"==c[i]] \n h=list(h)\n for i in range(len(c)):\n if i in s:\n h.insert(i,\" \")\n return \"\".join(h)", "def solve(s):\n s_ = list(''.join(s.split())[::-1])\n for i, l in enumerate(s):\n if l == ' ':\n s_.insert(i, l)\n return ''.join(s_)", "def solve(s):\n new_s = [x if x.isalpha() else '' for x in s[::-1]]\n \n for char in new_s:\n if char == '':\n new_s.remove(char)\n \n for i in range(len(s)):\n if s[i] == ' ':\n new_s.insert(i, s[i])\n \n return ''.join(new_s)\n", "def solve(s):\n s=s.split(\" \")\n temp=[]\n result=[]\n for l in s:\n temp.append(len(l))\n \n s=''.join(s) \n s=s[::-1]\n \n for x in temp:\n add=s[:x]\n s=s[x:]\n result.append(add)\n \n a=\"\"\n for i in result:\n a+=i+\" \"\n a=a[:-1]\n \n return a\n\n \n \n \n", "def solve(s):\n sr = s[::-1]\n sr = sr.replace(' ','')\n x = [pos for pos, char in enumerate(s) if char == ' ']\n for i in range(0,len(x)):\n sr = sr[:x[i]] + ' ' + sr[x[i]:]\n return sr", "def solve(s):\n rev_s = [*s.replace(' ', '')]\n return ''.join([rev_s.pop() if c != ' ' else ' ' for c in s])\n \n", "def solve(s):\n rev_s = [c for c in s if c != ' ']\n return ''.join([rev_s.pop() if c != ' ' else ' ' for c in s])\n \n", "def solve(s):\n inds = [i for i,c in enumerate(s) if c == \" \"]\n res = s.replace(\" \",\"\")[::-1]\n for i in inds:\n res = res[:i] + \" \" + res[i:]\n return res", "def solve(s):\n x = []\n for k in list(range(0,len(s))):\n if s[k] == \" \":\n x.append(k)\n \n y = s.split()\n y = y[::-1]\n \n z = []\n for k in y:\n z.append(k[::-1])\n \n y = []\n for k in z:\n y+=(list(k))\n \n \n for k in x:\n y.insert(k, \" \")\n \n j = \"\"\n for k in y:\n j += k\n \n \n\n \n return j", "def solve(s):\n new = list(s.replace(' ', '')[::-1])\n [new.insert(i, ' ') for i, j in enumerate(s) if j == ' ']\n return ''.join(new)", "def solve(s):\n u = []\n reversed_list = list(s[::-1].replace(' ', ''))\n [u.append(reversed_list.pop(0) if c.isalpha() else ' ') for c in s]\n return \"\".join(u)", "def solve(s):\n s_rev = s[::-1].replace(' ', '')\n for i in range(len(s)):\n if s[i] == ' ':\n s_rev = s_rev[: i] + ' ' + s_rev[i: ]\n return s_rev\n", "def solve(s):\n sl = [i for i,e in enumerate(s) if e ==' ']\n \n ans = list(''.join(s[::-1].split(' ')))\n for i in sl:\n #ans = list(''.join(s[::-1].split(' '))).insert(i, ' ') # Not good!!!\n ans.insert(i,' ')\n return ''.join(ans)", "def solve(s):\n rs = s[::-1].replace(\" \", \"\")\n \n for i in range(len(s)):\n if s[i] == ' ':\n rs = rs[:i] + ' ' + rs[i:]\n \n return rs", "def solve(s):\n d = \"\"\n for i in range(len(s)):\n el = s[i]\n if el.isalpha():\n d = el + d\n for i in range(len(s)):\n el = s[i]\n if el == ' ':\n d = d[:i] + el + d[i:]\n return d\n", "def solve(s):\n y = s.replace(\" \", \"\")\n backwards =y[::-1]\n c = 0\n d = 0\n solution = \"\"\n for i in range(0, len(s)):\n if s[i]== \" \":\n solution += \" \"\n c = c + 1\n else:\n solution += backwards[i-c]\n return solution", "def solve(s):\n sa = s.replace(\" \", \"\")\n print(sa)\n ml = list(sa)[::-1]\n print(ml, 'kurw')\n y = 0\n for x in range(len(s)):\n if s[x] == ' ':\n print(s[x], 'coo')\n ml.insert(x + y, s[x])\n# y += 1\n \n print(s)\n print(s[::-1])\n print(ml)\n return ''.join(ml)", "def solve(s):\n spaceindex = []\n for i in range(0,len(s)):\n if s[i]==\" \":\n spaceindex.append(i)\n \n s = s.replace(\" \",\"\")[::-1]\n \n sil = []\n for char in s:\n sil.append(char)\n \n for num in spaceindex:\n sil.insert(num,\" \")\n \n return \"\".join(sil)\n\n", "def solve(s):\n st = ''\n a = 0\n arr = []\n for i in s[::-1]:\n if i != ' ':\n st += i\n for j in s:\n if j != ' ':\n a += 1\n elif j == ' ':\n arr.append(a)\n a += 1\n for k in arr:\n st += \" \"\n st = st[0:k] + ' ' + st[k:-1]\n\n return st", "def solve(s):\n lst = [i for i in s if i != ' ']\n return ''.join(' ' if i == ' ' else lst.pop() for i in s)", "def solve(s):\n y= [i for i in s[::-1] if not i.isspace()]\n for i,x in enumerate(s):\n if x==' ':\n y.insert(i,' ')\n return ''.join(y)", "def solve(s):\n f = [i for i in range(len(s))if s[i]==' ']\n s = s.replace(' ','')[::-1]\n g = ''\n for i in range(len(s)):\n if i in f:\n g += ' ' + s[i]\n f = list(map(lambda x: x-1, f[1:]))\n else:\n g += s[i]\n return g + (' ' if f else '')", "def find(str, ch):\n for i, ltr in enumerate(str):\n if ltr == ch:\n yield i\n\ndef solve(s):\n new_s = s[::-1].replace(\" \", '')\n\n for idx in list(find(s, ' ')):\n new_s = new_s[:idx] + ' ' + new_s[idx:]\n\n return new_s", "def insert_space(s, res):\n res = list(res)\n for i in range(len(s)):\n if(s[i] == \" \"):\n res.insert(i, \" \")\n return \"\".join(res)\n\ndef solve(s):\n temp = s.translate({ord(\" \"):None})\n res = temp[::-1]\n return insert_space(s, res)\n", "import re\n\ndef solve(s):\n iter = re.finditer(' ', s)\n spaces = [x.start(0) for x in iter]\n\n s_rev = list(s[::-1].replace(' ', ''))\n \n for i in spaces:\n s_rev.insert(i, ' ')\n return ''.join(s_rev) ", "def solve(s):\n spc_idx = []\n rs = ''\n for i,c in enumerate(s):\n if c == ' ':\n spc_idx.append(i)\n else:\n rs = c + rs\n for i in spc_idx:\n rs = rs[:i] + ' ' + rs[i:]\n return rs", "def solve(s):\n ss = s.replace(' ', '')[::-1]\n for i in range(len(s)):\n if s[i] == ' ':\n ss = ss[:i] + ' ' + ss[i:]\n return ss\n", "def solve(s):\n spaces = []\n for i in range(len(s)):\n if s[i] == ' ':\n spaces.append(i)\n s = s.replace(' ','')[::-1]\n \n while len(spaces) > 0:\n i=spaces.pop(0)\n s=s[:i]+' '+s[i:]\n return s", "def solve(s):\n rev,s=s[::-1].replace(\" \",\"\"),list(s)\n for i in range(len(s)):\n if s[i]!=\" \": s[i],rev=rev[0],rev[1:]\n return \"\".join(s)", "def solve(s):\n L = [i for i, letter in enumerate (s) if letter == \" \"]\n print (L)\n l_s = list(''.join(s.split()))\n reversed = l_s[::-1]\n for number in L:\n reversed.insert(number, \" \")\n return ''.join(reversed)", "def solve(s):\n count=0\n l=[]\n l1=[]\n l1=list(s)\n l1.reverse()\n for i in s:\n count+=1\n if(i==\" \"):\n l1.remove(\" \")\n l.append(count-1)\n for j in l:\n l1.insert(j,\" \")\n l1=''.join(l1)\n return l1", "def solve(s):\n spaces = [i for i, letter in enumerate(s) if letter == \" \"]\n s = list(s)\n for i in range(len(spaces)-1 ,-1,-1):\n s.pop(spaces[i])\n srev = s[::-1]\n for i in range(0, len(spaces) ):\n srev.insert(spaces[i], \" \")\n final = \"\"\n for z in srev:\n final = final + z\n return final", "def solve(s):\n rev_s = ''.join(s.split())[::-1]\n\n res = []\n n = 0\n for i in [len(w) for w in s.split(' ')]:\n if i == 0:\n res.append('')\n else:\n res.append(rev_s[n:n+i])\n n += i\n\n return ' '.join(res)", "def solve(word):\n #el primer paso de la funci\u00f3n es darle la vuelta al string.Check\n reverse = ''\n reverse_nospace = []\n for char in range(len(word)-1, -1, -1):\n reverse += word[char] \n for i in reverse:\n reverse_nospace.append(i)\n for i2 in reverse_nospace:\n if i2 == ' ':\n reverse_nospace.remove(i2)\n #el segundo paso buscar el index de los espacios, usare list comprehension [expression for item in list]\n char_list = []\n index = []\n for char in word:\n char_list.append(char)\n for idx, space in enumerate(char_list):\n if space == ' ':\n index.append(idx)\n\n #el tercero, hacer que coincidan los espacios\n final_string = ''\n for position in index:\n reverse_nospace.insert(position, ' ')\n final_string = ''.join(reverse_nospace)\n\n return final_string\n\n", "def solve(s):\n space_indexes = [i for i, c in enumerate(s) if c == ' ']\n no_spaces_reversed = list(reversed([c for c in s if c != ' ']))\n for index in space_indexes:\n no_spaces_reversed.insert(index, ' ')\n return ''.join(no_spaces_reversed)", "def solve(s):\n space = []\n count = 0\n res = \"\"\n for c in s:\n count += 1\n if c.isalnum() == True:\n res = c + res\n elif c == \" \":\n space.append(count)\n for num in space:\n res = res[:num-1] + \" \" + res[num-1:]\n return res\n", "def solve(s):\n slist = list(s)\n revlist = [slist.pop() for _ in range(len(s))]\n revlist[:] = [x for x in revlist if x != ' ']\n slist = list(s)\n for i in range(len(slist)):\n if slist[i] == ' ': revlist.insert(i, ' ')\n rev= ''.join(revlist)\n return rev", "def solve(s):\n res = []\n spaces = []\n cnt = 0\n for c in s:\n cnt += 1\n if c != ' ':\n res.insert(0, c)\n else:\n spaces.append(cnt)\n for pos in spaces:\n res.insert(pos-1, ' ')\n return ''.join(res)", "def solve(s):\n spaces = [i for i, c in enumerate(s) if c == \" \"]\n string = list(s.replace(\" \", \"\")[::-1])\n for space in spaces:\n string.insert(space, \" \")\n return \"\".join(string)", "def solve(s):\n reversed = s[::-1];\n reversed = \"\".join(reversed.split(\" \"));\n spaces = [];\n for i in range(len(s)):\n if s[i] == \" \":\n spaces.append(i);\n result = \"\";\n spacesCount = 0;\n for i in range(len(s)):\n if i in spaces:\n result += \" \";\n spacesCount += 1;\n else:\n result += reversed[i - spacesCount];\n return result;", "def solve(s):\n indexes = []\n for n, i in enumerate(s):\n if i == ' ':\n indexes.append(n)\n\n res = ''.join(s.split())[::-1]\n\n for ind in indexes:\n res = res[:ind] + ' ' + res[ind:]\n \n return res", "def solve(s):\n words = s.split()\n cure = \"\".join(words)[::-1]\n r = 0\n krum = []\n for i in words:\n krum.append(cure[r:r+len(i)])\n r = r+len(i)\n return \" \".join(krum) if s[len(s)-1] != \" \" else \" \".join(krum)+ \" \"", "def solve(s):\n spaces = []\n reversed = s\n\n #get spaces\n for index in range(len(reversed)):\n if reversed[index] == \" \":\n spaces.append(index)\n print(spaces)\n\n #strip spaces\n reversed = reversed.replace(\" \", \"\")\n\n #reverse\n reversed = reversed[::-1]\n\n #add spaces\n for space in spaces:\n print(reversed)\n reversed = f'{reversed[:space]} {reversed[space:]}'\n return reversed", "def solve(s):\n x = s.split(\" \")\n \n r = []\n for i in x:\n rt = [\"\"] * len(i)\n r.extend(rt)\n r.extend([\" \"])\n \n r = r[:len(r)-1]\n \n #print(r)\n \n counter = 0\n for i in reversed(x):\n for j in reversed(i):\n #print(j)\n if r[counter] == \"\":\n r[counter] = j\n else:\n r[counter + 1] = j\n counter += 1 \n counter += 1\n \n return \"\".join(r)", "def solve(s):\n m = s.replace(' ','')\n r = ''\n i = -1\n for c in s:\n if c!=' ':\n r += m[i]\n i -= 1\n else:\n r += ' '\n return r", "def solve(s):\n \n l = []\n b = []\n for i, j in enumerate(list(s)):\n if j.isspace() == True:\n b.append(i)\n\n \n else:\n l.insert(0, (j))\n \n for k in b:\n l.insert(k, ' ')\n return ''.join(l)", "def solve(s):\n lst = [i for i in s[::-1] if i != ' ']\n \n for i in range(len(s)):\n if s[i] == ' ':\n lst.insert(i, ' ')\n\n return ''.join(lst)", "import re\ndef solve(s):\n ws_indices = [match.span()[0] for match in re.finditer(' ', s)]\n rev_s = list(s[::-1].replace(' ', ''))\n for idx in ws_indices:\n rev_s.insert(idx, ' ')\n \n return ''.join(rev_s)\n", "def solve(s):\n pos = []\n for i in range(len(s)):\n pos.append('')\n if s[i] == ' ':\n pos[i] = ' '\n j = len(s)-1\n i = 0\n while i < len(s):\n if pos[i] == ' ':\n if s[j] == ' ':\n j = j - 1\n i = i + 1\n else:\n i = i + 1\n else:\n if s[j] != ' ':\n pos[i] = s[j]\n j = j - 1\n i = i + 1\n else:\n j = j - 1\n return ''.join(pos)", "def solve(s):\n letters = [l for l in s]\n spaces = [idx for idx, space in enumerate(s) if space == ' ']\n reverse_letters = []\n for i, j in enumerate(letters):\n reverse_letters.append(letters[-1-i])\n \n reverse_letters = [l for l in reverse_letters if l != ' ']\n \n for idx, j in enumerate(spaces):\n reverse_letters.insert(j, ' ')\n \n return ''.join(reverse_letters)\n\n \n \n \n \n \n", "import re\n\ndef solve(s):\n rev = []\n for i in reversed(s):\n if i != \" \":\n rev.append(i)\n\n spaces = re.compile(\" \")\n for m in spaces.finditer(s):\n rev.insert(m.start(), \" \")\n\n return \"\".join(rev)\n", "def solve(s):\n spaces = []\n word = []\n for i in range(len(s)):\n if s[i] == \" \":\n spaces.append(i)\n else:\n word.append(s[i])\n word = word[::-1]\n for i in spaces:\n word.insert(i, \" \")\n var = \"\"\n return var.join(word)", "def solve(s):\n sol = []\n l = []\n for i in range(len(s)):\n if (s[i] == \" \"):\n l.append(i)\n else:\n sol.append(s[i])\n sol.reverse()\n\n for i in range(len(l)):\n sol.insert(l[i], \" \")\n return(\"\".join(sol))", "def solve(s):\n r = s.replace(' ','')[::-1]\n for i in range(len(s)):\n if s[i] == ' ': r = r[:i] + ' ' + r[i:]\n return r", "def solve(x):\n \n # remove all spaces:\n \n w = x.replace(\" \", \"\") \n \n # reverse the w string:\n\n new_string = \"\"\n for i in range(1, len(w)+1):\n new_string += w[-i]\n \n # convert the old string into a list to simplify adjustments and name it new_list:\n \n new_list = [f for f in x]\n \n # capture the sapce indicies in the original string (x) to add them to the neww revrsed string (new_string) :\n start_at = 0\n spaces = []\n for val in new_list:\n if val == \" \":\n spaces.append(new_list.index(val, start_at))\n start_at = new_list.index(val, start_at) + 1\n\n # add the spaces to the new reversed string:\n\n for i in spaces:\n new_string = new_string[:i] + \" \" + new_string[i:]\n ## return the new adjsuted result:\n \n return new_string\n", "def solve(s):\n # s= i love codewars\n rev=s[::-1]\n rev2=\"\"\n f=\"\"\n for i in rev:\n if i==\" \":\n continue;\n rev2+=i\n j=0\n for i in s:\n if i==\" \":\n f+=(\" \")\n continue\n f+=(rev2[j])\n j+=1\n return f\nprint((solve(\"i love codewars\")))\n", "def solve(s):\n no_space = list(s.replace(\" \", \"\")[::-1])\n for i in [pos for pos, char in enumerate(s) if char == \" \"]:\n no_space.insert(i, \" \")\n return ''.join(no_space)\n# return [pos for pos, char in enumerate(s) if char == \" \"]\n", "def solve(s):\n new_s = reversed(s.replace(\" \",\"\"))\n return \"\".join(i if i==\" \" else next(new_s) for i in s)", "def solve(s):\n l = [c for c in s.replace(\" \", \"\")]\n return ''.join([\" \" if c == \" \" else l.pop() for c in s])\n", "\ndef solve(s):\n s = list(s)\n indices = [index for index, element in enumerate(s) if element == \" \"]\n s = \"\".join(s).split()\n s = \"\".join(s)\n s = list(s[::-1])\n for i in range(0,299):\n for j in indices:\n if i == j:\n s.insert(j,\" \")\n \n return \"\".join(s)", "def solve(s):\n revs = s[::-1]\n revs = \"\".join(revs.split())\n output = \"\"\n count = 0\n \n for letter in s:\n if letter != \" \":\n output = output + revs[count]\n count += 1\n else:\n output = output + \" \"\n return output", "def solve(s):\n wordSizes = [ len(x) for x in s.split() ]\n reversedS = s.replace(\" \", \"\")[::-1]\n o = []\n for x in wordSizes:\n o.append(reversedS[:x])\n reversedS = reversedS[x:]\n return \" \".join(o) if s[-1] is not ' ' else \" \".join(o) + \" \"", "def solve(s):\n without = [c for c in s if c != ' ' ]\n spaces = [i for i, e in enumerate(s) if e == ' ' ]\n rev = without[::-1]\n result = []\n j = 0\n for i in range(len(s)):\n if i in spaces:\n result.append(' ')\n else: \n result.append(rev[j])\n j += 1\n return \"\".join(result)", "def solve(s):\n index_list = [i for i in range(len(s)) if s.startswith(' ', i)]\n \n s = s.replace(' ', '')\n \n reversed_string = [s[-x] for x in range(1, len(s) + 1, 1)]\n \n for value in index_list:\n reversed_string.insert(value, ' ')\n \n return ''.join(reversed_string)", "def solve(s):\n spaces = [i for i in range(len(s)) if s[i]==' ']\n letters = ''.join(x for x in s if x!=' ')[::-1]\n output = ''\n j = 0\n for i in range(len(s)):\n if i in spaces:\n output += ' '\n else:\n output += letters[j]\n j += 1\n return output", "def solve(forward_string):\n \n reverse_string = list(forward_string[::-1].replace(' ',''))\n \n for index, elem in enumerate(forward_string):\n if elem == ' ':\n reverse_string.insert(index, ' ')\n \n return ''.join(reverse_string)\n", "def solve(s):\n a = [i for i in \"\".join(s[::-1].split())]\n for i in range(len(s)):\n if s[i] == \" \":\n a.insert(i, \" \") \n return \"\".join(a)", "import numpy as np\n\ndef solve(arg):\n index = 0\n listIndex = []\n while index < len(arg):\n index = arg.find(' ', index)\n if index == -1:\n break\n print('space found at', index)\n listIndex = listIndex + [index]\n index += 1 # +2 because len('ll') == 2\n print(listIndex)\n arg=arg.replace(' ', '')\n arg = arg[::-1]\n \n \n \n \n for i in listIndex:\n arg = arg[:i] + ' ' + arg[i:]\n print(i)\n return arg", "def solve(s):\n \n q = ''.join(reversed(s.replace(' ', '')))\n arr = []\n c = 0\n for i in s:\n if i == ' ':\n arr.append(' ')\n \n else:\n arr.append(q[c])\n c += 1\n return(''.join(arr))", "def solve(s):\n spaces = []\n soln = ''\n for i in range(len(s)):\n if s[i] == ' ':\n spaces.append(i)\n for x in s[::-1]:\n if x == ' ':\n continue\n else:\n soln += x\n for x in spaces:\n soln = soln[:x] + ' ' + soln[x:]\n return soln", "def solve(s):\n spaces = [i for i in range(len(s)) if s[i] == ' ']\n rev = list(s[::-1].replace(' ', ''))\n for v in spaces:\n rev.insert(v, ' ')\n return ''.join(rev)", "def solve(s):\n spaces = []\n string = ''\n for i in range(len(s)):\n if s[i] == ' ':\n spaces.append(i - len(spaces))\n s1 = s.replace(' ', '')\n s1 = list(s1[-1::-1])\n for i in range(len(s1)):\n if i in spaces:\n string += ' '\n string += s1.pop(0)\n return string + ' ' if s[-1] == ' ' else string", "def solve(s):\n spaces = []\n count = 0\n for i in [c for c in s]:\n if i.isalpha():\n count += 1\n else:\n spaces.append(count)\n count += 1 \n \n a = s.replace(\" \", '')\n b = list(a)\n c = b[::-1]\n d = c\n for x in spaces:\n d.insert(x, ' ')\n e = ''.join(d)\n return e", "def solve(s):\n rev_s = ''.join(s.replace(' ', '')[::-1])\n result = ''\n for i in s.split():\n result += rev_s[: len(i)] + ' '\n rev_s = rev_s[len(i):]\n result = result.strip()\n return result + ' ' if len(s) != len(result) else result"]
{"fn_name": "solve", "inputs": [["codewars"], ["your code"], ["your code rocks"], ["i love codewars"]], "outputs": [["srawedoc"], ["edoc ruoy"], ["skco redo cruoy"], ["s rawe docevoli"]]}
INTRODUCTORY
PYTHON3
CODEWARS
27,971
def solve(s):
e2440fbca1627e1e4337e2a986652cf8
UNKNOWN
# Task Given a binary number, we are about to do some operations on the number. Two types of operations can be here: * ['I', i, j] : Which means invert the bit from i to j (inclusive). * ['Q', i] : Answer whether the i'th bit is 0 or 1. The MSB (most significant bit) is the first bit (i.e. i = `1`). The binary number can contain leading zeroes. ## Example ```python binary_simulation("0011001100", [['I', 1, 10], ['I', 2, 7], ['Q', 2], ['Q', 1], ['Q', 7], ['Q', 5]]) === [ '0', '1', '1', '0' ]; binary_simulation("1011110111", [['I', 1, 10], ['I', 2, 7], ['Q', 2], ['Q', 1], ['Q', 7], ['Q', 5]]) === [ '0', '0', '0', '1' ]; binary_simulation("1011110111", [['I', 1, 10], ['I', 2, 7]]) === []; binary_simulation("0000000000", [['I', 1, 10], ['Q', 2]]) === ['1']; ``` ## Note * All inputs are valid. * Please optimize your algorithm to avoid time out.
["def binary_simulation(s, q):\n out,n,s = [],int(s,2),len(s)\n for cmd,*i in q:\n if cmd=='I':\n a,b=i\n n ^= (1<<b-a+1)-1<<s-b\n else:\n out.append( str(int(0 < 1<<s-i[0] & n )) )\n return out", "import numpy as np\n\ndef binary_simulation(s, b):\n a, r = np.fromiter(map(int, s), dtype=np.int), []\n for x in b:\n if x[0] == \"Q\":\n r.append(str(a[x[1]-1]))\n else:\n i, j = x[1:]\n a[i-1:j] ^= 1\n return r", "def binary_simulation(s, q):\n x, l, result = int(s, 2), len(s), []\n for op in q:\n if op[0] == 'I':\n i, j = op[1:]\n x ^= (1 << j-i+1)-1 << l-j\n else:\n result.append(str(x >> l-op[1] & 1))\n return result", "def binary_simulation(bits, seq):\n arr = [0 for _ in range(len(bits) + 1)]\n display = []\n for grp in seq:\n if grp[0] == 'I':\n arr[grp[1] - 1] += 1\n arr[grp[2]] += -1\n else:\n display.append('01'[sum(arr[:grp[1]]) + int(bits[grp[1] - 1]) & 1])\n return display", "def binary_simulation(s, q):\n o, l, n = [], len(s), int(s, 2)\n for c, *_ in q:\n if c == 'Q':\n i, = _\n o.append(str(n >> l-i & 1))\n else:\n i, j = _\n n ^= (1<<l-i+1) - (1<<l-j)\n return o", "def binary_simulation(s,r):\n ix = tuple(1 << n for n in range(len(s)+1))[::-1]\n tome = []\n n = int(s,2)\n for v,*x in r:\n if v == 'I':\n n ^= ix[x[0]-1] - ix[x[1]]\n else:\n tome.append(str(min(1,n&ix[x[0]])))\n return tome", "def binary_simulation(s, q):\n \n outlst=[]\n for op in q:\n ini=op[1]-1\n \n if op[0]=='Q':\n outlst.append(s[ini])\n elif op[0]=='I':\n transl=s[ini:op[2]].maketrans('01','10')\n s=s[:ini]+s[ini:op[2]].translate(transl)+s[op[2]:]\n return outlst\n \n", "def binary_simulation(Q,S) :\n Q,L,R = int(Q,2),len(Q),[]\n for S in S :\n if S[0] < 'L' :\n Q ^= (1 << L - S[1] + 1) - 1\n Q ^= (1 << L - S[2]) - 1\n else :\n R.append('1' if Q & (1 << L - S[1]) else '0')\n return R", "def binary_simulation(s, q):\n n=int(s[::-1],2)\n r=[]\n for x in q:\n if x[0]=='I':\n _,a,b=x\n n^=((1<<(b-a+1))-1)<<(a-1)\n else:\n _,a=x\n r+=['01'[n&(1<<(a-1))>0]]\n return r", "def binary_simulation(s, q):\n s = '0'+s\n ans = []\n for val in q:\n if val[0] == 'I':\n s = s[:val[1]] + s[val[1] : val[2]+1].translate(''.maketrans('01', '10')) + s[val[2]+1:]\n elif val[0] == 'Q': \n ans.append(s[val[1]]) \n return ans"]
{"fn_name": "binary_simulation", "inputs": [["0011001100", [["I", 1, 10], ["I", 2, 7], ["Q", 2], ["Q", 1], ["Q", 7], ["Q", 5]]], ["1011110111", [["I", 1, 10], ["I", 2, 7], ["Q", 2], ["Q", 1], ["Q", 7], ["Q", 5]]], ["1011110111", [["I", 1, 10], ["I", 2, 7]]], ["0000000000", [["I", 1, 10], ["Q", 2]]]], "outputs": [[["0", "1", "1", "0"]], [["0", "0", "0", "1"]], [[]], [["1"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,836
def binary_simulation(s, q):
24fe63ac71f9cbc51cd9d89c558ea090
UNKNOWN
Write a function that accepts two parameters, i) a string (containing a list of words) and ii) an integer (n). The function should alphabetize the list based on the nth letter of each word. The letters should be compared case-insensitive. If both letters are the same, order them normally (lexicographically), again, case-insensitive. example: ```javascript function sortIt('bid, zag', 2) //=> 'zag, bid' ``` ```ruby function sortIt('bid, zag', 2) //=> 'zag, bid' ``` ```python function sortIt('bid, zag', 2) #=> 'zag, bid' ``` The length of all words provided in the list will be >= n. The format will be "x, x, x". In Haskell you'll get a list of `String`s instead.
["def sort_it(list_, n): \n return ', '.join(sorted(list_.split(', '), key=lambda i: i[n-1]))", "from operator import itemgetter\n\ndef sort_it(list_, n):\n return ', '.join(sorted(list_.split(', '), key=itemgetter(n - 1)))\n", "def sort_it(words, i):\n return \", \".join(sorted(words.split(\", \"), key=lambda w: w[i-1]))", "def sort_it(a, n):\n return \", \".join(sorted(a.split(\", \"), key=lambda x: x[n-1]))", "from operator import itemgetter\n\ndef sort_it(s, n):\n return ', '.join(sorted(s.split(', '), key=itemgetter(n-1)))", "def sort_it(s, n):\n words = s.split(', ')\n return ', '.join( word for word in sorted(words, key=lambda x: x[n-1]) )", "def sort_it(list_, n): \n str_list = list_.split(\", \")\n str_list.sort(key=lambda f: f[n - 1])\n return \", \" .join(str_list)", "def sort_it(s, n):\n return ', '.join(sorted(s.split(', '), key=lambda s: s[n-1]))\n \n"]
{"fn_name": "sort_it", "inputs": [["bill, bell, ball, bull", 2], ["words, wordz, wordy, wording", 5], ["he, hi, ha, ho", 2], ["zephyr, yellow, wax, a, ba, cat", 1], ["hello, how, are, you, doing, today", 3]], "outputs": [["ball, bell, bill, bull"], ["wording, words, wordy, wordz"], ["ha, he, hi, ho"], ["a, ba, cat, wax, yellow, zephyr"], ["today, are, doing, hello, you, how"]]}
INTRODUCTORY
PYTHON3
CODEWARS
920
def sort_it(list_, n):
a93597e054c7339de4e0dd518018ee7c
UNKNOWN
Related to MrZizoScream's Product Array kata. You might want to solve that one first :) ```if:javascript **Note:** Node 10 has now been enabled, and you can now use its BigInt capabilities if you wish, though your resulting array must still contain strings (e.g. "99999999999", not 9999999999n) Pre-node 10: You will need to use the BigNumber.js library! Please use `.toFixed(0)` or `.toPrecision()` to round instead of `.toString(10)`, as the latter is _very_ slow ``` This is an adaptation of a problem I came across on LeetCode. Given an array of numbers, your task is to return a new array where each index (`new_array[i]`) is equal to the product of the original array, except for the number at that index (`array[i]`). **Two things to keep in mind:** * Zeroes will be making their way into some of the arrays you are given * O(n^2) solutions will not pass. Examples: **Note**: All inputs will be valid arrays of nonzero length. Have fun! Please upvote if you enjoyed :)
["from functools import reduce\n\ndef product_sans_n(nums):\n z = nums.count(0)\n if z > 1: return [0] * len(nums)\n \n p = reduce(int.__mul__, (v for v in nums if v))\n return [not v and p for v in nums] if z else [p//v for v in nums]", "from functools import reduce\n\n\ndef product_sans_n(nums):\n z, p = nums.count(0), reduce(int.__mul__, (n for n in nums if n))\n return [0 for _ in nums] if z > 1 else [0 if n else p for n in nums] if z else [p // n for n in nums]", "from functools import reduce\nfrom operator import mul\n\ndef mulsum(xs):\n return reduce(mul, xs, 1)\n\ndef product_sans_n(nums):\n nz = nums.count(0)\n if nz > 1:\n return [0] * len(nums)\n elif nz:\n return [0 if x else mulsum([_f for _f in nums if _f]) for x in nums]\n xs = mulsum(nums)\n return [xs // x for x in nums]\n", "from functools import reduce\n# Since it must be less thatn O(n^2) the solution may not involve mul(Array[:]) for each\n# element of Array since mul would be O(n-1) and you would do O(n) calls to mul.\n \n# Since it must be less thatn O(n^2) the solution may not involve mul(Array[:]) for each\n# element of Array since mul would be O(n-1) and you would do O(n) calls to mul.\n \n# The only way that occurs to me is calling mul just once [that is O(n)] and then mapping / on the\n# result Array [that is another O(n)], but since the calls are concatenated the final complexity\n# is O(2n)\n\n# Also, since \n\ndef product_sans_n(nums):\n # The case for two or more zeros is trivial and can be handled separately:\n # Just a list of N zeroes where N is the length of nums\n if len([ x for x in nums if x == 0]) > 1:\n return [0] * len(nums)\n \n # Now, if there is only one zero this must be stripped from the product P\n # The product can be computed by the functool reduce: this is O(n)\n from operator import mul\n from functools import reduce\n onezero = 0 in nums\n product = reduce(mul, nums if not onezero else nums[:nums.index(0)]+nums[nums.index(0)+1:])\n \n # Now, we iterate through the original list dividing the product P by each element\n # The case of one zero is handled separately\n # There is only one list traversing with map: this is O(n)\n if onezero:\n return list(map((lambda x: 0 if x != 0 else product), nums))\n else:\n return list(map((lambda x: product / x), nums))\n \n # In the end, the algorithm is O(2*n)\n", "def product_sans_n(l):\n contains_zeroes = False\n product = 1\n for n in l:\n if n:\n product *= n\n elif not contains_zeroes:\n contains_zeroes = True\n else:\n return [0] * len(l)\n return [0 if n else product for n in l] if contains_zeroes else [product // n for n in l]", "def product_sans_n(nums):\n zeros, product = 0, 1\n for n in nums:\n if n: product *= n\n else: zeros += 1\n return [zeros < 2 and\n (not n and product if zeros else product // n)\n for n in nums]", "from operator import mul\nfrom functools import reduce\n\ndef product_sans_n(nums):\n z = nums.count(0)\n p = 0 if z > 1 else reduce(mul, (x for x in nums if x != 0), 1)\n return [p//x if x != 0 and z == 0 else\n p if x == 0 and z == 1 else\n 0 for x in nums]", "from functools import reduce\n\ndef product_sans_n(nums):\n s = set(nums)\n if 0 in s:\n return [ reduce(int.__mul__, nums[:i] + nums[i+1:]) for i, e in enumerate(nums) ]\n else: \n prod = reduce(int.__mul__, nums)\n return [ prod//n for n in nums]\n", "from functools import reduce\n\n\ndef product_sans_n(nums):\n zero, prod = nums.count(0), reduce(int.__mul__, (n for n in nums if n))\n if zero:\n return [0 for _ in nums] if zero > 1 else [0 if n else prod for n in nums]\n return [prod // n for n in nums]", "from itertools import accumulate, chain, islice\nfrom operator import mul\n\ndef product_sans_n(nums):\n forward = islice(accumulate(chain([1], nums), mul), 0, len(nums), 1)\n backward = list(accumulate(chain([1], reversed(nums)), mul))[-2::-1]\n return list(map(mul, forward, backward))\n", "from functools import reduce\ndef product_sans_n(nums):\n if nums.count(0) > 1:\n return [0 for i in nums]\n elif nums.count(0) == 1:\n prod = reduce(lambda a, b: a*b, [x for x in nums if x!=0])\n return [0 if i != 0 else prod for i in nums]\n else:\n prod = reduce(lambda a, b: a*b, nums)\n return [prod//i for i in nums]\n", " #because the output is so huge, output is hidden for the medium and big random tests\n \nimport numpy as np\ndef product_sans_n(nums):\n numLen = len(nums)\n leftProducts = [None for _ in range(numLen)]\n rightProducts = [None for _ in range(numLen)]\n leftRunningProduct = 1\n rightRunningProduct = 1\n for i in range(numLen):\n leftRunningProduct = leftRunningProduct * nums[i]\n leftProducts[i] = leftRunningProduct\n rightRunningProduct = rightRunningProduct * nums[numLen-1-i]\n rightProducts[numLen-1-i] = rightRunningProduct\n\n result = [None for _ in range(numLen)]\n for i in range(numLen):\n product = 1\n if i > 0:\n product = product * leftProducts[i-1]\n if i < numLen-1:\n product = product * rightProducts[i+1]\n result[i] = product\n return result", "\ndef product_sans_n(nums):\n p = 1\n zeroes = nums.count(0)\n for n in nums:\n if n:\n p *= n\n return [zeroes < 2 and (not n and p if zeroes else p // n) for n in nums ]\n", "from functools import reduce\n\ndef product_sans_n(nums):\n zeroes = nums.count(0)\n if zeroes >= 2:\n return [0 for x in nums]\n elif zeroes == 1:\n prod = reduce(int.__mul__, (x for x in nums if x != 0))\n return [0 if x != 0 else prod for x in nums]\n \n prod = reduce(int.__mul__, nums)\n return [prod // x for x in nums]\n", "from functools import reduce\nimport operator\n\ndef product_sans_n(nums):\n prod = reduce(operator.mul, [x for x in nums if x != 0])\n zero_count = nums.count(0)\n for index,value in enumerate(nums):\n if value != 0 and zero_count != 0:\n nums[index] = 0\n elif value == 0 and zero_count > 1:\n nums[index] = 0\n elif value == 0:\n nums[index] = prod\n else:\n nums[index] = prod // value\n return nums", "from functools import reduce\n\ndef product_sans_n(nums):\n if nums.count(0) > 1: return [0] * len(nums)\n if nums.count(0) == 1:\n i = nums.index(0)\n s = reduce(int.__mul__,nums[:i]+nums[i+1:])\n t = reduce(int.__mul__,nums)\n return [ s if x == 0 else t//x for x in nums ]", "import itertools\nimport operator\ndef product_sans_n(l):\n r=[]\n p=list(itertools.accumulate(l,operator.mul))[-1]\n for i in range(len(l)):\n try:\n r.append(p//l[i])\n except:\n s=1\n for j in range(len(l)):\n if i!=j:\n s*=l[j]\n r.append(s) \n \n return r ", "from functools import reduce\n\ndef product(q):\n return reduce(int.__mul__, q)\n\ndef product_sans_n(q):\n if any(not x for x in q):\n return [product(q[0:i]+q[i+1:]) for i, x in enumerate(q)]\n else:\n n = product(q)\n return [n//x for x in q]", "from numpy import prod\ndef product_sans_n(n):\n if n.count(0)>1: \n return [0 for _ in n]\n p=1\n for x in n:\n if x!=0: p*=x\n if n.count(0)==1:\n return [0 if x!=0 else p for x in n]\n return [p//x for x in n]", "from operator import mul\nfrom functools import reduce\n\ndef product_sans_n(numbers):\n check = reduce(mul, numbers)\n out = []\n \n if not check:\n for i in range(len(numbers)):\n c = reduce(mul,numbers[:i]+numbers[i+1:])\n out.append(c)\n\n else:\n for x in numbers:\n out.append(check//x)\n \n return out"]
{"fn_name": "product_sans_n", "inputs": [[[1, 1, 1]], [[0, -99, 0]], [[9, 0, -2]], [[1, 2, 3, 4]], [[2, 3, 4, 5]], [[-8, 1, 5, 13, -1]], [[3, 14, 9, 11, 11]], [[4, 7, 3, 6, 2, 11, 14, 4, 7, 5]]], "outputs": [[[1, 1, 1]], [[0, 0, 0]], [[0, -18, 0]], [[24, 12, 8, 6]], [[60, 40, 30, 24]], [[-65, 520, 104, 40, -520]], [[15246, 3267, 5082, 4158, 4158]], [[5433120, 3104640, 7244160, 3622080, 10866240, 1975680, 1552320, 5433120, 3104640, 4346496]]]}
INTRODUCTORY
PYTHON3
CODEWARS
8,200
def product_sans_n(nums):
abf6b0c31519965e89768c2fce130047
UNKNOWN
#Sorting on planet Twisted-3-7 There is a planet... in a galaxy far far away. It is exactly like our planet, but it has one difference: #The values of the digits 3 and 7 are twisted. Our 3 means 7 on the planet Twisted-3-7. And 7 means 3. Your task is to create a method, that can sort an array the way it would be sorted on Twisted-3-7. 7 Examples from a friend from Twisted-3-7: ``` [1,2,3,4,5,6,7,8,9] -> [1,2,7,4,5,6,3,8,9] [12,13,14] -> [12,14,13] [9,2,4,7,3] -> [2,7,4,3,9] ``` There is no need for a precheck. The array will always be not null and will always contain at least one number. You should not modify the input array! Have fun coding it and please don't forget to vote and rank this kata! :-) I have also created other katas. Take a look if you enjoyed this kata!
["def sort_twisted37(arr):\n def key(x):\n return int(str(x).translate(str.maketrans('37', '73')))\n return sorted(arr, key=key)", "tr=str.maketrans('37','73')\n\ndef sort_twisted37(arr):\n return sorted(arr,key=lambda n:int(str(n).translate(tr)))", "def sort_twisted37(arr):\n twisted = lambda n: int(''.join('3' if c=='7' else '7' if c == '3' else c for c in str(n)))\n return sorted(arr, key=twisted)", "def sort_twisted37(arr):\n return list(sorted(arr, key=lambda x: int(str(x).translate(\"\".maketrans(\"37\", \"73\")))))", "def sort_twisted37(lst):\n return sorted(lst, key=comp)\n \n\ndef comp(n):\n return int(str(n).translate(str.maketrans(\"37\", \"73\")))", "trans = str.maketrans(\"37\", \"73\")\ntwist = lambda n: int(str(n).translate(trans))\n\ndef sort_twisted37(arr):\n return sorted(arr, key=twist)", "def sort_twisted37(arr):\n str_arr = [str(i) for i in arr]\n swap1(str_arr)\n str_arr = sorted([int(i) for i in str_arr])\n str_arr = [str(i) for i in str_arr]\n swap1(str_arr)\n return [int(i) for i in str_arr]\n\n \ndef swap1(str_arr):\n for index, numstr in enumerate(str_arr):\n if '3' in numstr or '7' in numstr:\n str_arr[index] = numstr.replace('3','%temp%').replace('7','3').replace('%temp%','7')", "tbl = str.maketrans('37', '73')\n\ndef twist(n):\n return int(str(n).translate(tbl))\n\ndef sort_twisted37(arr):\n return sorted(arr, key=twist)\n", "def sort_twisted37(arr):\n return sorted(arr, key=lambda x: int(str(x).translate(str.maketrans('37', '73'))))", "sort_twisted37=lambda a:sorted(a,key=lambda n:int(str(n).translate(str.maketrans('37','73'))))"]
{"fn_name": "sort_twisted37", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[12, 13, 14]], [[9, 2, 4, 7, 3]]], "outputs": [[[1, 2, 7, 4, 5, 6, 3, 8, 9]], [[12, 14, 13]], [[2, 7, 4, 3, 9]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,671
def sort_twisted37(arr):
8ab765e78d8ec68d77553e10f78bf2a6
UNKNOWN
# # Task: * #### Complete the pattern, using the special character ```■ □``` * #### In this kata, we draw some histogram of the sound performance of ups and downs. # # Rules: - parameter ```waves``` The value of sound waves, an array of number, all number in array >=0. - return a string, ```■``` represents the sound waves, and ```□``` represents the blank part, draw the histogram from bottom to top. # # Example: ``` draw([1,2,3,4]) □□□■ □□■■ □■■■ ■■■■ draw([1,2,3,3,2,1]) □□■■□□ □■■■■□ ■■■■■■ draw([1,2,3,3,2,1,1,2,3,4,5,6,7]) □□□□□□□□□□□□■ □□□□□□□□□□□■■ □□□□□□□□□□■■■ □□□□□□□□□■■■■ □□■■□□□□■■■■■ □■■■■□□■■■■■■ ■■■■■■■■■■■■■ draw([5,3,1,2,4,6,5,4,2,3,5,2,1]) □□□□□■□□□□□□□ ■□□□□■■□□□■□□ ■□□□■■■■□□■□□ ■■□□■■■■□■■□□ ■■□■■■■■■■■■□ ■■■■■■■■■■■■■ draw([1,0,1,0,1,0,1,0]) ■□■□■□■□ ```
["def draw(waves):\n m = max(waves)\n rotHist = [ ('\u25a0'*v).rjust(m, '\u25a1') for v in waves ]\n return '\\n'.join( map(''.join, zip(*rotHist)) )", "def draw(waves):\n m = max(waves)\n return '\\n'.join(\n ''.join('\u25a1\u25a0'[x > i] for x in waves) for i in reversed(range(m))\n )", "ON = '\u25a0'\nOFF = '\u25a1'\n\ndef draw(waves):\n result = ''\n height = max(waves)\n for line in range(height, 0, -1):\n for wave in waves:\n if wave >= line:\n result += ON\n else:\n result += OFF\n result += '\\n'\n return result.strip()", "def draw(waves):\n mx = max(waves)\n return '\\n'.join([''.join(e) for e in zip(*[('\u25a0' * e).ljust(mx,\"\u25a1\") for e in waves ])][::-1])\n \n \n", "def draw(waves):\n wave = []\n while sum(waves)!=0:\n black = max(waves)\n cur = ''\n for i in range(len(waves)):\n if waves[i]<black:\n cur += '\u25a1'\n else:\n cur += '\u25a0'\n waves[i] -= 1\n wave.append(cur)\n return '\\n'.join(wave)", "def draw(waves):\n m = max(waves)\n return \"\\n\".join(\"\".join(\"\u25a1\" if n < (m - row) else \"\u25a0\" for n in waves) for row in range(m))\n", "def draw(waves):\n # your code\n #\u25a0\u25a1\n result = \"\"\n height = max(waves)\n weight = len(waves)\n for i in range(height):\n for j in range(weight):\n if(waves[j] >= height - i):\n result += \"\u25a0\"\n else:\n result += \"\u25a1\"\n if(i != height-1):\n result += \"\\n\"\n \n return result ", "def draw(waves):\n mx = max(waves)\n return '\\n'.join(''.join(c) for c in zip(*[(mx - w) * '\u25a1' + w * '\u25a0' for w in waves]))", "def draw(a):\n n = iter(a)\n li = [('\u25a0' * next(n)).ljust(max(a),'\u25a1') for i in range(len(a))]\n return \"\\n\".join([\"\".join(i) for i in list(zip(*li))[::-1]])", "FILLED = '\u25a0'\nEMPTY = '\u25a1'\ndef draw(waves):\n result = ''\n height = max(waves)\n width = len(waves)\n matrix = [[EMPTY for x in range(width)] for y in range(height)]\n for y, value in enumerate(waves):\n for x in range(value):\n matrix[x][y] = FILLED\n for row in range(height-1, -1, -1):\n result = result + ''.join(matrix[row]) + '\\n'\n return result.strip()"]
{"fn_name": "draw", "inputs": [[[1, 2, 3, 4]], [[1, 2, 3, 3, 2, 1]], [[1, 2, 3, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7]], [[5, 3, 1, 2, 4, 6, 5, 4, 2, 3, 5, 2, 1]], [[1, 0, 1, 0, 1, 0, 1, 0]]], "outputs": [["\u25a1\u25a1\u25a1\u25a0\n\u25a1\u25a1\u25a0\u25a0\n\u25a1\u25a0\u25a0\u25a0\n\u25a0\u25a0\u25a0\u25a0"], ["\u25a1\u25a1\u25a0\u25a0\u25a1\u25a1\n\u25a1\u25a0\u25a0\u25a0\u25a0\u25a1\n\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0"], ["\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a0\n\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a0\u25a0\n\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a0\u25a0\u25a0\n\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a0\u25a0\u25a0\u25a0\n\u25a1\u25a1\u25a0\u25a0\u25a1\u25a1\u25a1\u25a1\u25a0\u25a0\u25a0\u25a0\u25a0\n\u25a1\u25a0\u25a0\u25a0\u25a0\u25a1\u25a1\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\n\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0"], ["\u25a1\u25a1\u25a1\u25a1\u25a1\u25a0\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\u25a1\n\u25a0\u25a1\u25a1\u25a1\u25a1\u25a0\u25a0\u25a1\u25a1\u25a1\u25a0\u25a1\u25a1\n\u25a0\u25a1\u25a1\u25a1\u25a0\u25a0\u25a0\u25a0\u25a1\u25a1\u25a0\u25a1\u25a1\n\u25a0\u25a0\u25a1\u25a1\u25a0\u25a0\u25a0\u25a0\u25a1\u25a0\u25a0\u25a1\u25a1\n\u25a0\u25a0\u25a1\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a1\n\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0\u25a0"], ["\u25a0\u25a1\u25a0\u25a1\u25a0\u25a1\u25a0\u25a1"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,472
def draw(waves):
3d0a5e9260f16bfcb8eaa3c3e55f72dd
UNKNOWN
Your task is to write function ```findSum```. Upto and including ```n```, this function will return the sum of all multiples of 3 and 5. For example: ```findSum(5)``` should return 8 (3 + 5) ```findSum(10)``` should return 33 (3 + 5 + 6 + 9 + 10)
["def find(n):\n return sum(e for e in range(1, n+1) if e % 3 == 0 or e % 5 == 0)", "def find(n):\n sum = 0\n for i in range(1,n+1):\n if i % 3 == 0 or i % 5 == 0:\n sum += i\n return sum", "def find(n):\n return sum(range(0, n+1, 3)) + sum(range(0, n+1, 5)) - sum(range(0, n+1, 15))", "def find(n):\n return sum([x for x in range(1,n+1) if not x%3 or not x%5])", "def find(n):\n return sum( set(range(0, n+1, 3)) | set(range(0, n+1, 5)) )", "def find(n):\n return sum(i for i in range(n+1) if i % 3 == 0 or i % 5 == 0)", "def find(n):\n c_3 = n // 0x3\n c_5 = n // 0x5\n c_f = n // 0xf\n \n s_3 = c_3 * (0x3 + c_3 * 0x3) // 2\n s_5 = c_5 * (0x5 + c_5 * 0x5) // 2\n s_f = c_f * (0xf + c_f * 0xf) // 2\n \n return s_3 + s_5 - s_f\n", "def find(n):\n return sum(set([x for x in range(0, n+1, 3)] + [x for x in range(0, n+1, 5)]))", "def find(n):\n return sum([i for i in range(0,n+1) if i%3==0 or i%5==0])\n", "def find(n):\n return sum([i for i in range(n+1) if (i%3==0 or i%5==0)])", "def find(n):\n return sum([ele for ele in range(3,n+1,3) if ele%5!=0])+sum(range(5,n+1,5))", "def find(n):\n # Code here\n L = []\n for i in range(n+1):\n if i % 3 == 0 or i % 5 == 0:\n L.append(i)\n return sum(L)", "def find(n):\n n = n + 1\n sum = 0\n for x in range(n):\n if x % 3 == 0 or x % 5 == 0:\n sum += x\n return sum", "find = lambda n: sum(e for e in range(n+1) if not e%3 or not e%5)", "def find(n):\n return sum(x for x in range(n + 1) if not (x % 3 and x % 5))", "def find(n):\n total = 0\n for i in range(n + 1):\n if (i % 3 == 0) or (i % 5 == 0):\n total += i\n return total \n # Code here\n", "from operator import mul\nfrom functools import reduce, partial\nfrom itertools import combinations\n\ndef prod(numbers):\n return reduce(mul, numbers)\n\ndef range_sum(n):\n return n * (n+1) / 2\n\ndef multipes_sum(divisor, n):\n return range_sum(n//divisor) * divisor\n\ndef something(limit, divisors, size):\n \"\"\"How should I name this?\"\"\"\n return sum(multipes_sum(prod(numbers), limit)\n for numbers in combinations(divisors, size))\n\ndef divisors_multiples_sum(n, divisors=()):\n result = 0\n for i in range(len(divisors)):\n result += (-1)**i * something(n, divisors, i+1)\n return int(result)\n\nfind = partial(divisors_multiples_sum, divisors=(3,5))\n", "find = lambda n:n//3*(n//3+1)/2*3 + n//5*(n//5+1)/2*5 - n//15*(n//15+1)/2*15", "def find(n):\n sum3 = sum([3*i for i in range(1,n//3+1)])\n sum5 = sum([5*j for j in range(1,n//5 +1) if j%3 != 0])\n return sum3+sum5\n \n", "def find(n):\n k1, k2, k3 = n // 3, n // 5, n // 15\n return (3 * k1 * (k1 + 1) >> 1) + (5 * k2 * (k2 + 1) >> 1) - (15 * k3 * (k3 + 1) >> 1)", "def find(n):\n x = sum(i for i in range(n+1) if i % 3 == 0 or i % 5 == 0)\n return x", "def find(n):\n return sum([x for x in range(n+1) if x%3 == 0 or x%5 == 0])\n # Code here\n", "def find(n: int) -> int:\n \"\"\" Get the sum of all multiples of 3 and 5 limited to `n`. \"\"\"\n return sum(filter(lambda num: any([not num % 3, not num % 5]), range(n + 1)))", "def find(n):\n return sum(range(3,n+1,3)) + sum(x for x in range(5,n+1,5) if x % 3 != 0)", "def find(n):\n def F(k):\n m = n // k\n return m * (m + 1) * k // 2\n \n return F(3) + F(5) - F(15)", "def find(num):\n result = []\n num = list(range(1,num+1))\n for zahl in num:\n if (zahl%3 == 0) or (zahl%5 == 0):\n result.append(zahl) \n return sum(result)", "def find(n):\n if n>30:\n full = n//30\n half = n%30\n sum = full*(full-1)*210\n for i in range(3, half+1):\n if i%3==0 or i%5==0:\n sum += i+(full*30)\n sum += (225*full)\n return sum\n else:\n sum = 0\n for i in range(3,n+1):\n if i%3==0 or i%5==0:\n sum += i\n return sum", "def find(n):\n divideBy5 = n // 5\n divideBy3 = n // 3\n divideBy15 = n // 15\n sum = (5 * divideBy5 + 5) * divideBy5 //2 + (3 * divideBy3 + 3) * divideBy3 //2 -(15 * divideBy15 + 15) * divideBy15 //2 \n return sum", "def find(n):\n sum =0\n for i in range(0,n+1,3):\n sum = sum + i\n for i in range(0,n+1,5):\n if i%3!=0:\n sum = sum + i\n return sum", "sum_naturals = lambda n: n * (n + 1) // 2\nsum_multiples = lambda n, m: m * sum_naturals(n // m)\n\ndef find(n):\n return sum_multiples(n, 3) + sum_multiples(n, 5) - sum_multiples(n, 15)", "def find(n):\n return sum([x for x in range(3, n + 1) if not x % 3 or not x % 5])\n", "from math import floor\ndef find(n):\n return sum(3 * i for i in range(1, floor(n / 3) + 1)) + sum(5 * i for i in range(1, floor(n / 5) + 1) if (5 * i) % 3 != 0)\n \n", "def find(n):\n # up to, including n\n # range(n +1)\n # iterate over number\n # if divisible by 3 or 5\n # add to total\n total = 0\n for num in range(n+1):\n if num % 3 == 0 or num % 5 == 0:\n total += num\n return total", "def find(n):\n x = 0\n for i in range(n):\n z = i + 1\n if (z % 3 == 0) or (z % 5 == 0):\n x += z\n\n return x\n", "def find(n):\n ans = 0\n for i in range(0,n+1):\n if i % 3 == 0:\n ans = ans + i\n elif i % 5== 0:\n ans = ans + i\n return ans ", "def find(n):\n sum = 0\n for a in range (1, n+1):\n if a%3 == 0 or a%5 == 0:\n sum = sum + a\n return sum", "def find(n):\n list_1 = []\n for x in range(1,n+1):\n if x%3 == 0 or x%5 == 0:\n list_1.append(x)\n i = 0\n for y in list_1:\n i = i+y\n return i", "def find(n):\n i=3\n b=5\n c=0\n while i <= n:\n c=c+i\n \n i+=3\n\n while b<=n:\n if b % 3 != 0:\n c=c+b\n \n b+=5\n else:\n b+=5\n \n return c", "def find(n):\n return n//5*5/2*(n//5+1) + n//3*3/2*(n//3+1) - n//15*15/2*(n//15+1) ", "def find(n):\n summe = []\n for x in range(n+1):\n if x%3 == 0 or x%5 == 0:\n summe.append(x)\n return sum(summe)", "def find(n):\n sum=0\n for i in range (1,n+1) :\n if i %3==0 or i%5==0:\n sum+=i\n \n return(sum)\n \nprint(find(5))", "def find(n):\n sum = 0\n for i in range(1,n+1):\n if i % 3 == 0 or i % 5 == 0:\n sum += i\n return sum\nprint(find(9))", "def find(n):\n sum2 = 0\n for i in range(n+1):\n if i%5 ==0 or i%3 == 0:\n sum2 += i\n return sum2", "def find(number):\n result = []\n for i in range(1, number+1):\n if i % 3 == 0 or i % 5 == 0:\n result.append(i)\n\n return sum(result)", "def find(n):\n count1 = 0\n count2 = 0\n for i in range(5,n+1,5):\n count2+=1\n if count2 ==3:\n count2 =0\n continue\n count1+=i\n for i in range(3,n+1,3):\n count1+=i\n return count1", "def find(n):\n #Create a list's containing my multiples of 5 and 3\n a = list(range(5, (n)+1, 5))\n b = list(range(3, (n)+1, 3))\n \n # create sets of my list\n c = set(a)\n d = set(b)\n \n #remove the duplicates and create a list of removed duplicates\n e = list(d - c)\n \n #Sum list together\n return sum(a + e)", "def find(n):\n total = 0\n testCase = 1\n \n while testCase <= n:\n if testCase % 3 == 0 or testCase % 5 == 0:\n total += testCase\n \n testCase += 1\n \n return total", "def find(n):\n i = 1\n ans = []\n while i <= n:\n if i % 3 == 0:\n ans.append(i)\n elif i % 5 == 0:\n ans.append(i)\n i += 1\n return sum(ans)\n", "from functools import reduce\ndef find(n):\n return reduce(\n lambda x, y: x + y if y % 3 == 0 or y % 5 == 0 else x, \n list(range(n+1)), \n 0\n )\n", "def find(n):\n resultat = sum([i for i in range(n+1) if i%3==0 or i%5==0])\n return resultat\n\n", "def find(n):\n # Code here\n a = 0\n for i in range(3, n+1):\n if i % 3 == 0:\n a += i\n elif i % 5 == 0:\n a += i\n return a", "def find(n):\n multsf = [5*i for i in range(1,n+1) if 5*i<=n] \n multst = [3*i for i in range(1,n+1) if 3*i<=n]\n \n \n \n\n return sum(multst) + sum(list(set(multsf)-set(multst)))\n \n \n \n \n", "def find(n):\n sum=0\n for i in range(1,n+1):\n if (i % 3 == 0) | (i % 5 == 0):\n sum+=i\n return sum", "def find(n):\n result = 0\n while n > 0:\n if n == 0:\n break\n elif n%3 == 0 or n%5 == 0: \n result += n\n n-=1\n return result", "def find(n):\n return sum(x for x in range(3, n+1) if not x%3 or not x%5)", "def relevant():\n i = 3\n while True:\n if i%3 == 0 or i%5 == 0:\n yield i\n i+=1\n\ndef find(n):\n from itertools import takewhile\n return sum(takewhile(lambda x : x<= n , relevant()))", "def find(n):\n return sum(list(filter(lambda x: x % 3 == 0 or x % 5 == 0, list(range(1, n + 1)))))", "def find(n):\n st = 0\n for i in range(n + 1):\n if i % 3 == 0 or i % 5 == 0:\n st += i\n return st", "def find(n):\n #return sum(n for n in range(n+1) if n%3==0 or n%5==0)\n\n a3 = n // 3\n a5 = n // 5\n a15 = n // 15\n sum3 = 3 * a3 * (a3 + 1) // 2\n sum5 = 5 * a5 * (a5 + 1) // 2\n sum15 = 15 * a15 * (a15 + 1) // 2\n \n return sum3 + sum5 - sum15", "def find(n):\n tot = 0\n \n for i in range(3,n+1,3):\n tot += i\n \n for j in range(5,n+1,5):\n tot += j\n \n if n > 14:\n for j in range(15,n+1,15):\n tot -= j\n \n return tot", "def find(n): \n sumOfNumbers = 0\n number=1\n while(number<=n):\n if (number%3==0 or number%5==0):\n sumOfNumbers=sumOfNumbers + number\n number+=1\n return sumOfNumbers\n", "def find(n):\n # Code here\n holder = 0\n for i in range(n + 1):\n if i % 3 == 0 or i % 5 == 0:\n holder = holder + i\n return holder\n \n \n \n", "def find(n):\n m=[]\n i=1\n while i<=n:\n if i%3==0 or i%5==0:\n m.append(i)\n i+=1\n x=sum(m)\n return x\n # Code here\n", "def find(n):\n return sum([j for j in range(n+1) if j % 3 == 0 or j % 5 == 0])\n \n", "def find(n):\n x=0\n sum=0\n while (x<=n):\n if(x%3==0 or x%5==0):\n sum = sum+x\n x=x+1\n return sum", "def find(n):\n # Code here\n multiplesList = 0\n for i in range(n+1):\n if i%3 == 0 or i%5 == 0:\n multiplesList+=i\n \n return multiplesList\n\n", "def find(n):\n # Code here\n ans=0.0\n for i in range(n+1):\n if i%3 ==0 or i%5==0:\n ans+=i\n return ans \nfind(10)", "def find(n):\n return sum(filter(IsMultiple, range(n+1)))\n\ndef IsMultiple(n):\n return n%3==0 or n%5==0", "def find(n):\n em = []\n for i in range(n+1):\n if i % 3 == 0:\n em.append(i)\n elif i % 5 == 0:\n em.append(i)\n return sum(em)", "def find(n):\n \n arr = []\n total = 0\n for i in range(n + 1):\n if i % 3 == 0:\n arr.append(i)\n elif i % 5 == 0:\n arr.append(i)\n \n for num in arr:\n total = total + num\n \n return total", "def find(n):\n if n < 3: return 0\n sum = 0\n for i in range (3, n+1):\n if (i % 3 == 0) | (i % 5 == 0): sum += i\n return sum\n # Code here\n", "def find(n):\n l = []\n calc = 0\n for x in range(n + 1):\n if x % 3 == 0:\n l.append(x)\n \n if x % 5 == 0:\n l.append(x)\n l = list(set(l))\n for y in range(len(l)):\n calc = calc + l[y]\n return calc", "def find(n):\n return sum([multiple for multiple in range(1,n+1) if multiple % 3 == 0 or multiple % 5 == 0])", "def find(n):\n return sum([x for x in range(1,n+1, 1) if (x/3).is_integer() or (x/5).is_integer()])", "def find(n):\n # Code here\n sum=0\n for i in range(n+1):\n if i % 5 == 0:\n sum = sum + i\n elif i % 3 == 0:\n sum = sum + i\n \n return sum", "def find(n):\n x = lambda b: range(0, n + 1, b)\n return sum(set((*x(3), *x(5))))", "def find(n):\n i=1\n count=0\n while i <=n:\n \n #print(i)\n if (i%3)==0 or (i%5)==0:\n count=count+i\n # print (count)\n i=i+1\n return (count)", "def find(n):\n summ = [i for i in range(n+1) if i % 3 == 0 or i % 5 == 0]\n return sum(summ)", "def find(n):\n char=n+1\n mystr=0\n while char>=4:\n char-=1\n if(char%3)==0:\n mystr+=(char)\n \n else:\n if(char)%5==0:\n mystr+=(char)\n if char==3: \n return(int(mystr)) \n # Code here\n", "def find(n):\n m = 0\n for i in range(1,n+1): \n if i % 3 is 0 or i % 5 is 0 : m = m + i\n return m", "def find(n):\n return sum(filter(lambda i: (i % 5==0) or (i % 3==0), range(n+1)))", "def find(n):\n finalSum = 0\n for i in range(n+1):\n if i % 3 == 0:\n finalSum += i\n elif i % 5 == 0:\n finalSum += i\n return finalSum", "def find(n):\n mof3 = [i for i in range(3,n+1,3)]\n mof5 = [i for i in range(5,n+1,5)]\n mof3.extend(mof5)\n all_num_to_n = set(sorted(mof3))\n return sum(all_num_to_n)", "def find(n):\n l = range(3, n + 1)\n ans = 0\n for i in l:\n if i % 3 == 0 or i % 5 == 0:\n ans += i\n return ans", "def find(n):\n g = [i for i in range (0, n+1) if i %3 ==0 or i%5 == 0]\n return sum(g)", "def find(n):\n # Code here\n total = 0\n i = 0\n while i < n:\n i+=1\n if i%3 == 0 or i%5 == 0:\n total = total + i\n return total\n \n \n \n", "def find(n):\n # Code here \n return sum(filter(is_multiple_of_3_or_5, range(n+1)))\n\ndef is_multiple_of_3_or_5(n):\n return n%3==0 or n%5==0", "def find(n):\n a = (n // 3) * (n // 3 + 1) // 2 * 3\n b = (n // 5) * (n // 5 + 1) // 2 * 5\n c = (n // 15) * (n // 15 + 1) // 2 * 15\n \n return a + b - c", "def find(n):\n sum=0\n for x in range(n):\n if (x%3 == 0 or x%5 == 0):\n sum += x\n if(n%3 == 0 or n%5==0):\n return sum + n\n else: \n return sum\n\nprint(find(5))", "def find(n):\n nums = [i for i in range(1, n+1) if i % 3 == 0 or i % 5 == 0]\n return sum(nums)", "def find(n):\n x = [number for number in range(n+1) if number%3==0 or number%5==0]\n return sum(x)\n", "def find(n):\n sum = int()\n for i in range(1, n + 1):\n if i % 3 == 0 or i % 5 == 0:\n sum += i\n return sum\n\n", "def find(n):\n numbers = [number for number in range(1, n+1) if number%3==0 or number%5==0]\n return sum(numbers)", "def find(n):\n x = list(range(n+1))\n y = []\n for i in x:\n if i%3 == 0 or i%5 == 0:\n y.append(i)\n return sum(y)\n", "from functools import reduce\n\ndef find(n):\n zoo = [i for i in range(0, n+1) if i % 3 == 0 or i % 5 == 0]\n return reduce(lambda x,y: x+y, zoo)", "def find(n):\n multiples = []\n for i in range(1, n+1):\n if i % 5 == 0 or i % 3 == 0:\n multiples.append(i)\n return sum(multiples)\n", "def find(n):\n x = 0\n multiples = []\n while x <= n:\n if x % 3 == 0 or x % 5 == 0:\n multiples.append(x)\n x += 1\n return sum(multiples)", "def find(n):\n num = 0\n if(n % 5 == 0 or n % 3 == 0): num += n\n for i in range(3,n):\n if not i % 5 or not i % 3:\n num = num + i\n return num", "def find(n):\n s = 0\n \n for x in range(0,n+1):\n if x % 3 == 0 or x % 5 ==0:\n s += x\n return(s)\n \n \n \n # Code here\n", "def find(n):\n return sum(loop for loop in range(1, n + 1) if not loop % 3 or not loop % 5)"]
{"fn_name": "find", "inputs": [[5], [10], [100], [1000]], "outputs": [[8], [33], [2418], [234168]]}
INTRODUCTORY
PYTHON3
CODEWARS
16,463
def find(n):
bf05ea66ffd38f361485ff938cd1f406
UNKNOWN
The T9 typing predictor helps with suggestions for possible word combinations on an old-style numeric keypad phone. Each digit in the keypad (2-9) represents a group of 3-4 letters. To type a letter, press once the key which corresponds to the letter group that contains the required letter. Typing words is done by typing letters of the word in sequence. The letter groups and corresponding digits are as follows: ``` ----------------- | 1 | 2 | 3 | | | ABC | DEF | |-----|-----|-----| | 4 | 5 | 6 | | GHI | JKL | MNO | |-----|-----|-----| | 7 | 8 | 9 | | PQRS| TUV | WXYZ| ----------------- ``` The prediction algorithm tries to match the input sequence against a predefined dictionary of words. The combinations which appear in the dictionary are considered valid words and are shown as suggestions. Given a list of words as a reference dictionary, and a non-empty string (of digits 2-9) as input, complete the function which returns suggestions based on the string of digits, which are found in the reference dictionary. For example: ```python T9(['hello', 'world'], '43556') returns ['hello'] T9(['good', 'home', 'new'], '4663') returns ['good', 'home'] ``` Note that the dictionary must be case-insensitive (`'hello'` and `'Hello'` are same entries). The list returned must contain the word as it appears in the dictionary (along with the case). Example: ```python T9(['Hello', 'world'], '43556') returns ['Hello'] ``` If there is no prediction available from the given dictionary, then return the string containing first letters of the letter groups, which correspond to the input digits. For example: ```python T9([], '43556') returns ['gdjjm'] T9(['gold', 'word'], '4663') returns ['gmmd'] ```
["FROM = \"abc def ghi jkl mno pqrs tuv wxyz\".split()\nTO_NUM = \"222 333 444 555 666 7777 888 9999\".split()\n\nTABLE_TO_NUM = str.maketrans( *map(''.join, (FROM, TO_NUM)) )\nTABLE_TO_CHAR = str.maketrans( *map(lambda lst: ''.join(x[0] for x in lst), (TO_NUM, FROM)))\n\n\ndef T9(words, seq):\n return ( [w for w in words if seq == w.lower().translate(TABLE_TO_NUM)]\n or [seq.translate(TABLE_TO_CHAR)] )", "CHR_TO_NUM = str.maketrans(\"abcdefghijklmnopqrstuvwxyz\", \"22233344455566677778889999\")\nNUM_TO_CHR = str.maketrans(\"23456789\", \"adgjmptw\")\n\ndef T9(words, seq):\n return [word for word in words if word.lower().translate(CHR_TO_NUM) == seq] \\\n or [seq.translate(NUM_TO_CHR)]", "D = {c:i for c, i in zip('abcdefghijklmnopqrstuvwxyz', '22233344455566677778889999')}\n\ndef T9(words, seq):\n r = [w for w in words if ''.join(D[c] for c in w.lower()) == seq]\n return r if r else [''.join({i:c for i, c in zip('23456789', 'adgjmptw')}[i] for i in seq)]", "def T9(words,seq):\n ans=[]\n for i in words:\n if i.lower().translate(str.maketrans('abcdefghijklmnopqrstuvwxyz','22233344455566677778889999')) == seq:\n ans += [i]\n return ans if ans else [seq.translate(str.maketrans('23456789','adgjmptw'))]\n", "d = dict(zip('123456789',[' ']+'ABC DEF GHI JKL MNO PQRS TUV WXYZ'.split())) \nT9=lambda w,p:[i for i in w if all(k in d[l] for k,l in zip(i.upper(),p))]or[''.join(d[i][0] for i in p).lower()]", "def T9(words, seq):\n X, res = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'], \"\"\n for i,c in enumerate(map(int, seq)):\n words = [w for w in words if w[i].lower() in X[c]]\n res += X[c][0]\n return words or [res]", "layout = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\nletters = {c: str(n) for n, cs in enumerate(layout) for c in cs}\n\ndef T9(words, seq):\n return ([word for word in words if ''.join(letters[c] for c in word.lower()) == seq]\n or [''.join(layout[i][0] for i in map(int, seq))])", "def T9(words,seq):\n result = []\n seq = list(seq)\n numToword(int(seq[0]))\n for word in words:\n if (isWord(word,seq)):\n result.append(word)\n if(len(result)):\n return result\n red = \"\"\n for i in seq:\n red += numToword(int(i)-1)[0]\n result.append(red.lower())\n return result\n \ndef numToword(num):\n return ([\" \",\"ABC\",\"DEF\",\"GHI\",\"JKL\",\"MNO\",\"PQRS\",\"TUV\",\"WXYZ\",\"\"])[num]\n# Return true if we can write this word with this leters\ndef isWord(word,num):\n if(len(word) != len(num)):\n return False\n for i_n in range(len(word)):\n if (word[i_n].upper() in numToword(int(num[i_n])-1))==False:\n return False\n return True", "def T9(words, seq):\n d = {}\n sym = list(map(chr, range(97,123)))\n for x in range(2, 10):\n q = sym[:(3, 4)[x in(7, 9)]]\n sym = sym[(3, 4)[x in(7, 9)]:]\n d[str(x)] = q\n s = zip(words,map(iter, [x.lower()for x in words]))\n return [w for w, i in s if all(next(i)in d[x] for x in seq)] \\\n or [''.join(d[x][0] for x in seq)]", "mapping = {'2': \"abc\", \n '3': \"def\", \n '4': \"ghi\",\n '5': \"jkl\",\n '6': \"mno\",\n '7': \"pqrs\",\n '8': \"tuv\",\n '9': \"wxyz\"}\n\ndef T9(words, seq):\n return [word for word in words if len(word) >= len(seq) and all(word[i].lower() in mapping[n] for i, n in enumerate(seq))] or [\"\".join(mapping[i][0] for i in seq)]"]
{"fn_name": "T9", "inputs": [[["hello", "world"], "43556"], [["good", "home", "new"], "4663"], [["gone", "hood", "good", "old"], "4663"], [["Hello", "world"], "43556"], [["gOOD", "hOmE", "NeW"], "4663"], [["goNe", "hood", "GOOD", "old"], "4663"], [[], "43556"], [["gold"], "4663"], [["gone", "hood", "good", "old"], "729"]], "outputs": [[["hello"]], [["good", "home"]], [["gone", "hood", "good"]], [["Hello"]], [["gOOD", "hOmE"]], [["goNe", "hood", "GOOD"]], [["gdjjm"]], [["gmmd"]], [["paw"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,622
def T9(words, seq):
88ba36e9330fee760e1215d5759213b1
UNKNOWN
Adapted from here, with less terrible instructions and a couple tweaks. Two kangaroos are jumping on a line. They start out at different points on the line, and jump in the same direction at different speeds. Your task is to determine whether or not they'll ever land in the same spot at the same time (you'll just have to suspend disbelief for a moment and accept that two kangaroos, for the purpose of this kata, can occupy the same space at the same time :) Your function is given four arguments `(kanga1, rate1, kanga2, rate2)`; the first kangaroo's starting point, the first kangaroo's speed, the second kangaroo's starting point, and the second kangaroo's speed. Return `true` if the above conditions are met, else `false`. Starting location and speed may vary wildly. The first kangaroo will _usually_ start behind the second one and travel faster, but not always. Starting locations may be negative, but speeds will always be > 0. **Example:** ![kangaroo](https://i.imgur.com/hXRgSVg.jpg) **Other examples:** Brute force solutions are possible (and not discouraged), but you'll save yourself a lot of waiting time if you don't go that route :) Good luck!
["def kangaroo(k1, r1, k2, r2):\n if r1==r2: return k1==k2\n cross, r = divmod(k1-k2, r2-r1)\n return cross >= 0 and not r", "def kangaroo(x1, v1, x2, v2):\n if x1 > x2 and v1 > v2:\n return False\n if (v1 > v2 and (x2-x1)%(v1-v2)==0):\n return True\n else:\n return False", "def kangaroo(kanga1, rate1, kanga2, rate2):\n k, r = (kanga1 - kanga2), (rate2 - rate1)\n return k % r == 0 if k * r > 0 else k == r", "def kangaroo(kanga1, rate1, kanga2, rate2):\n d = kanga1 - kanga2\n s = rate1 - rate2\n return (d * s < 0) and not (d % s)", "def kangaroo(kanga1, rate1, kanga2, rate2):\n s = kanga1 - kanga2\n v = rate1 - rate2\n return (s * v < 0) and not (s%v) #czy jest podzielne", "def kangaroo(kanga1, rate1, kanga2, rate2):\n if kanga1 < kanga2 and rate1 <= rate2 or kanga1 > kanga2 and rate1 >= rate2:\n return False\n else:\n return ((kanga1 - kanga2) / (rate2 - rate1)) % 1 == 0", "def kangaroo(k1,r1,k2,r2):\n dif=r1-r2\n try:\n a,b=(k1-k2),(r1-r2)\n return a%b==0 and (a<0)!=(b<0)\n except Exception:\n return False", "def kangaroo(kanga1, rate1, kanga2, rate2):\n if kanga1 == kanga2:\n return True\n elif kanga1 < kanga2:\n velocidad_acercamiento = rate1 - rate2\n if velocidad_acercamiento <= 0:\n return False\n else:\n if (kanga2-kanga1) % velocidad_acercamiento == 0:\n return True\n else:\n return False\n else:\n velocidad_acercamiento = rate2 - rate1\n if velocidad_acercamiento <= 0:\n return False\n else:\n if (kanga1-kanga2) % velocidad_acercamiento == 0:\n return True\n else:\n return False\n", "def kangaroo(kanga1, rate1, kanga2, rate2):\n if rate1 == rate2: return kanga1 == kanga2\n time_ = (kanga2 - kanga1) / (rate1 - rate2) \n return time_ > 0 and time_.is_integer()", "def kangaroo(kanga1, rate1, kanga2, rate2):\n if ((kanga1>kanga2) and (rate1>=rate2)) or ((kanga2>kanga1) and (rate2>=rate1)):\n return False\n if 1-(abs(kanga1-kanga2)%abs(rate1-rate2)) <0: \n return False\n return 1-(abs(kanga1-kanga2)%abs(rate1-rate2))"]
{"fn_name": "kangaroo", "inputs": [[0, 3, 4, 2], [0, 9, 16, 4], [-1, 3, 0, 2], [-1571, 4240, 9023, 4234], [-7855, 4240, 9023, 4234], [43, 5, 49, 3], [9023, 4240, 1571, 4234], [129, 15, 147, 9], [129, 15, 147, 90], [0, 2, 100000, 1], [72893, 11125, 24432, 4202], [13613, 299, 65130, 73]], "outputs": [[true], [false], [true], [false], [true], [true], [false], [true], [false], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,293
def kangaroo(kanga1, rate1, kanga2, rate2):
b8e3d99518580e1e89f04ff9679475eb
UNKNOWN
You love coffee and want to know what beans you can afford to buy it. The first argument to your search function will be a number which represents your budget. The second argument will be an array of coffee bean prices. Your 'search' function should return the stores that sell coffee within your budget. The search function should return a string of prices for the coffees beans you can afford. The prices in this string are to be sorted in ascending order.
["def search(budget, prices):\n return ','.join(str(a) for a in sorted(prices) if a <= budget)\n", "search = lambda budget, prices: \",\".join(map(str, sorted([x for x in prices if x <= budget])))", "def search(budget, prices):\n return \",\".join(map(str, sorted([n for n in prices if n <= budget])))", "def search(budget, prices):\n return ','.join(map(str, sorted(filter(float(budget).__ge__, prices))))", "search = lambda b,p: ','.join(str(i) for i in sorted(p) if i<=b)", "def search(b,p):\n return','.join(map(str,sorted(c for c in p if c<=b)))", "def search(budget,prices):\n return ','.join(str(num) for num in sorted(prices) if num <= budget)", "def search(budget,prices):\n prices.sort()\n return ','.join(str(x) for x in prices if x<=budget)", "def search(budget,prices):\n return ','.join(map(str, sorted(price for price in prices if price <= budget)))", "def search(budget,prices):\n return \",\".join(str(price) for price in sorted(prices) if price <= budget)"]
{"fn_name": "search", "inputs": [[3, [6, 1, 2, 9, 2]], [14, [7, 3, 23, 9, 14, 20, 7]], [0, [6, 1, 2, 9, 2]], [10, []], [24, [24, 0, 100, 2, 5]], [24, [2.7, 0, 100.9, 1, 5.5]], [-1, [1, 2, 3, 4]], [-1, [-1, 0, 1, 2, 3, 4]], [14, [17, 33, 23, 19, 19, 20, 17]], [14, [13, 15, 14, 14, 15, 13]]], "outputs": [["1,2,2"], ["3,7,7,9,14"], [""], [""], ["0,2,5,24"], ["0,1,2.7,5.5"], [""], ["-1"], [""], ["13,13,14,14"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,002
def search(budget,prices):
c54e0e1ac90e06c6f74580b4d1d19552
UNKNOWN
The concept of "[smooth number](https://en.wikipedia.org/wiki/Smooth_number)" is applied to all those numbers whose prime factors are lesser than or equal to `7`: `60` is a smooth number (`2 * 2 * 3 * 5`), `111` is not (`3 * 37`). More specifically, smooth numbers are classified by their highest prime factor and your are tasked with writing a `isSmooth`/`is_smooth` function that returns a string with this classification as it follows: * 2-smooth numbers should be all defined as a `"power of 2"`, as they are merely that; * 3-smooth numbers are to return a result of `"3-smooth"`; * 5-smooth numbers will be labelled as `"Hamming number"`s (incidentally, you might appreciate [this nice kata on them](https://www.codewars.com/kata/hamming-numbers)); * 7-smooth numbers are classified as `"humble numbers"`s; * for all the other numbers, just return `non-smooth`. Examples: ```python is_smooth(16) == "power of 2" is_smooth(36) == "3-smooth" is_smooth(60) == "Hamming number" is_smooth(98) == "humble number" is_smooth(111) == "non-smooth" ``` The provided input `n` is always going to be a positive number `> 1`.
["def is_smooth(n):\n for x in [2,3,5,7]:\n while n%x==0:n//=x\n if n==1:return (\"power of 2\",'3-smooth','Hamming number','humble number')[(2<x)+(3<x)+(5<x)] \n return \"non-smooth\"", "from collections import defaultdict\n\n\nnames = defaultdict(lambda: 'non-smooth', {\n 2: 'power of 2',\n 3: '3-smooth',\n 5: 'Hamming number',\n 7: 'humble number',\n})\n\n\ndef is_smooth(n):\n divisors = set()\n for d in [2, 3, 5, 7]:\n while n % d == 0:\n divisors.add(d)\n n //= d\n if n != 1:\n divisors.add(9)\n return names[max(divisors, default=9)]", "def is_smooth(n):\n for v in [2,3,5,7]:\n while n%v==0:n/=v\n if n==1:return['','','power of 2','3-smooth','','Hamming number','','humble number'][v]\n return 'non-smooth'", "def find_factors(n):\n factors = []\n for i in (7, 5, 3, 2):\n while n%i==0:\n n= n/i\n factors.append(i) \n if n>0: return factors + [n]\n return factors\n \ndef is_smooth(n):\n f={2:\"power of 2\", 3: \"3-smooth\", 5: \"Hamming number\", 7: \"humble number\"} \n return f.get(max(find_factors(n)), \"non-smooth\")", "is_smooth=lambda n,p=0: [\"power of 2\", \"3-smooth\", \"Hamming number\", \"humble number\", \"non-smooth\"][p] if n<2 or p>3 else is_smooth(n,p+1) if n%[2,3,5,7,11][p] else is_smooth(n//[2,3,5,7,11][p],p)", "def is_smooth(n):\n primes=set()\n n1=0\n while n1!=n:\n n1=n\n for p in {2,3,5,7}:\n if n%p==0:\n primes.add(p)\n n//=p\n if n!=1:return \"non-smooth\"\n return {2:\"power of 2\",3:\"3-smooth\",5:\"Hamming number\",7:\"humble number\"}[max(primes)]", "def is_smooth(n):\n \n i = 2\n \n a = []\n \n while i * i <= n:\n \n if n % i:\n \n i += 1\n \n else:\n \n n //= i\n \n a.append(i)\n \n if n > 1:\n \n a.append(n)\n \n m = max(a)\n \n if m==2:\n \n return \"power of 2\"\n \n if m==3:\n \n return \"3-smooth\"\n \n if m == 5:\n \n return \"Hamming number\"\n \n if m == 7:\n \n return \"humble number\"\n \n else:\n \n return \"non-smooth\"\n \n", "from numpy import prod\ndef is_smooth(n):\n number = n\n divisors = []\n while 1:\n if not n%2:\n divisors.append(2)\n n/=2\n else: break\n \n while 1:\n if not n%3:\n divisors.append(3)\n n/=3\n else: break\n\n while 1:\n if not n%5:\n divisors.append(5)\n n/=5\n else: break\n \n while 1:\n if not n%7:\n divisors.append(7)\n n/=7\n else: break\n \n if prod(divisors)==number and max(divisors) == 2: return \"power of 2\"\n elif prod(divisors)==number and max(divisors) == 3: return \"3-smooth\"\n elif prod(divisors)==number and max(divisors) == 5: return \"Hamming number\"\n elif prod(divisors)==number and max(divisors) == 7: return \"humble number\"\n else: return \"non-smooth\"", "from math import sqrt\n\ndef is_smooth(n):\n smooth = {2: \"power of 2\",\n 3: \"3-smooth\",\n 5: \"Hamming number\",\n 7: \"humble number\"}\n \n s = set()\n i = 2\n while i <= sqrt(n):\n while n % i == 0:\n s.add(i)\n n //= i\n i += 1\n s.add(n)\n \n return smooth.get(max(s), \"non-smooth\")", "from functools import reduce\nfrom operator import mul\n\ndef is_smooth(n):\n num = n\n factors = [1]\n prime_fact = iter([i for i in (2,3,5,7) if not n%i])\n fact = next(prime_fact, n)\n while reduce(mul, factors) != n and fact != 0:\n if not num % fact:\n factors += [fact]\n num /= fact\n else:\n fact = next(prime_fact, 0)\n return \"non-smooth\" if fact==0 else \"power of 2\" if factors[-1] == 2 else \"3-smooth\" if factors[-1] == 3 else\\\n \"Hamming number\" if factors[-1] == 5 else \"humble number\" if factors[-1] == 7 else \"non-smooth\"\n"]
{"fn_name": "is_smooth", "inputs": [[16], [36], [60], [98], [111], [4096], [729], [3125], [7], [17]], "outputs": [["power of 2"], ["3-smooth"], ["Hamming number"], ["humble number"], ["non-smooth"], ["power of 2"], ["3-smooth"], ["Hamming number"], ["humble number"], ["non-smooth"]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,296
def is_smooth(n):
4236a662a1bd5e9d17060beb04be65f4
UNKNOWN
The central dogma of molecular biology is that DNA is transcribed into RNA, which is then tranlsated into protein. RNA, like DNA, is a long strand of nucleic acids held together by a sugar backbone (ribose in this case). Each segment of three bases is called a codon. Molecular machines called ribosomes translate the RNA codons into amino acid chains, called polypeptides which are then folded into a protein. Protein sequences are easily visualized in much the same way that DNA and RNA are, as large strings of letters. An important thing to note is that the 'Stop' codons do not encode for a specific amino acid. Their only function is to stop translation of the protein, as such they are not incorporated into the polypeptide chain. 'Stop' codons should not be in the final protein sequence. To save a you a lot of unnecessary (and boring) typing the keys and values for your amino acid dictionary are provided. Given a string of RNA, create a funciton which translates the RNA into its protein sequence. Note: the test cases will always produce a valid string. ```python protein('UGCGAUGAAUGGGCUCGCUCC') returns 'CDEWARS' ``` Included as test cases is a real world example! The last example test case encodes for a protein called green fluorescent protein; once spliced into the genome of another organism, proteins like GFP allow biologists to visualize cellular processes! Amino Acid Dictionary ---------------------- ```python # Phenylalanine 'UUC':'F', 'UUU':'F', # Leucine 'UUA':'L', 'UUG':'L', 'CUU':'L', 'CUC':'L','CUA':'L','CUG':'L', # Isoleucine 'AUU':'I', 'AUC':'I', 'AUA':'I', # Methionine 'AUG':'M', # Valine 'GUU':'V', 'GUC':'V', 'GUA':'V', 'GUG':'V', # Serine 'UCU':'S', 'UCC':'S', 'UCA':'S', 'UCG':'S', 'AGU':'S', 'AGC':'S', # Proline 'CCU':'P', 'CCC':'P', 'CCA':'P', 'CCG':'P', # Threonine 'ACU':'T', 'ACC':'T', 'ACA':'T', 'ACG':'T', # Alanine 'GCU':'A', 'GCC':'A', 'GCA':'A', 'GCG':'A', # Tyrosine 'UAU':'Y', 'UAC':'Y', # Histidine 'CAU':'H', 'CAC':'H', # Glutamine 'CAA':'Q', 'CAG':'Q', # Asparagine 'AAU':'N', 'AAC':'N', # Lysine 'AAA':'K', 'AAG':'K', # Aspartic Acid 'GAU':'D', 'GAC':'D', # Glutamic Acid 'GAA':'E', 'GAG':'E', # Cystine 'UGU':'C', 'UGC':'C', # Tryptophan 'UGG':'W', # Arginine 'CGU':'R', 'CGC':'R', 'CGA':'R', 'CGG':'R', 'AGA':'R', 'AGG':'R', # Glycine 'GGU':'G', 'GGC':'G', 'GGA':'G', 'GGG':'G', # Stop codon 'UAA':'Stop', 'UGA':'Stop', 'UAG':'Stop' ```
["import re\ndict = {'UUC':'F','UUU':'F','UUA':'L','UUG':'L','CUU':'L','CUC':'L','CUA':'L','CUG':'L','AUU':'I','AUC':'I','AUA':'I','AUG':'M','GUU':'V','GUC':'V','GUA':'V','GUG':'V','UCU':'S','UCC':'S','UCA':'S','UCG':'S','AGU':'S','AGC':'S','CCU':'P','CCC':'P','CCA':'P','CCG':'P','ACU':'T','ACC':'T','ACA':'T','ACG':'T','GCU':'A','GCC':'A','GCA':'A','GCG':'A','UAU':'Y','UAC':'Y','CAU':'H','CAC':'H','CAA':'Q','CAG':'Q','AAU':'N','AAC':'N','AAA':'K','AAG':'K','GAU':'D','GAC':'D','GAA':'E','GAG':'E','UGU':'C','UGC':'C','UGG':'W','CGU':'R','CGC':'R','CGA':'R','CGG':'R','AGA':'R','AGG':'R','GGU':'G','GGC':'G','GGA':'G','GGG':'G'}\n\ndef protein(rna):\n return re.sub('.{3}', lambda r: dict.get(r.group(0), ''), rna)", "from re import findall\ndef protein(rna):\n return \"\".join({'UUC':'F', 'UUU':'F',\n 'UUA':'L', 'UUG':'L', 'CUU':'L', 'CUC':'L','CUA':'L','CUG':'L', \n 'AUU':'I', 'AUC':'I', 'AUA':'I', \n 'AUG':'M', \n 'GUU':'V', 'GUC':'V', 'GUA':'V', 'GUG':'V', \n 'UCU':'S', 'UCC':'S', 'UCA':'S', 'UCG':'S', 'AGU':'S', 'AGC':'S', \n 'CCU':'P', 'CCC':'P', 'CCA':'P', 'CCG':'P', \n 'ACU':'T', 'ACC':'T', 'ACA':'T', 'ACG':'T',\n 'GCU':'A', 'GCC':'A', 'GCA':'A', 'GCG':'A', \n 'UAU':'Y', 'UAC':'Y', \n 'CAU':'H', 'CAC':'H',\n 'CAA':'Q', 'CAG':'Q', \n 'AAU':'N', 'AAC':'N', \n 'AAA':'K', 'AAG':'K',\n 'GAU':'D', 'GAC':'D', \n 'GAA':'E', 'GAG':'E',\n 'UGU':'C', 'UGC':'C',\n 'UGG':'W', \n 'CGU':'R', 'CGC':'R', 'CGA':'R', 'CGG':'R', 'AGA':'R', 'AGG':'R', \n 'GGU':'G', 'GGC':'G', 'GGA':'G', 'GGG':'G', \n 'UAA':'', 'UGA':'', 'UAG':''}.get(x) for x in findall(\"...\", rna))", "import re\n\ndef protein(rna):\n rna_2_protein_dict = {\n # Phenylalanine\n 'UUC':'F', 'UUU':'F',\n # Leucine\n 'UUA':'L', 'UUG':'L', 'CUU':'L', 'CUC':'L','CUA':'L','CUG':'L', \n # Isoleucine\n 'AUU':'I', 'AUC':'I', 'AUA':'I', \n # Methionine\n 'AUG':'M', \n # Valine\n 'GUU':'V', 'GUC':'V', 'GUA':'V', 'GUG':'V', \n # Serine\n 'UCU':'S', 'UCC':'S', 'UCA':'S', 'UCG':'S', 'AGU':'S', 'AGC':'S', \n # Proline\n 'CCU':'P', 'CCC':'P', 'CCA':'P', 'CCG':'P', \n # Threonine\n 'ACU':'T', 'ACC':'T', 'ACA':'T', 'ACG':'T',\n # Alanine\n 'GCU':'A', 'GCC':'A', 'GCA':'A', 'GCG':'A', \n # Tyrosine\n 'UAU':'Y', 'UAC':'Y', \n # Histidine\n 'CAU':'H', 'CAC':'H',\n # Glutamine\n 'CAA':'Q', 'CAG':'Q', \n # Asparagine\n 'AAU':'N', 'AAC':'N', \n # Lysine\n 'AAA':'K', 'AAG':'K',\n # Aspartic Acid\n 'GAU':'D', 'GAC':'D', \n # Glutamic Acid\n 'GAA':'E', 'GAG':'E',\n # Cystine\n 'UGU':'C', 'UGC':'C',\n # Tryptophan\n 'UGG':'W', \n # Arginine\n 'CGU':'R', 'CGC':'R', 'CGA':'R', 'CGG':'R', 'AGA':'R', 'AGG':'R', \n # Glycine\n 'GGU':'G', 'GGC':'G', 'GGA':'G', 'GGG':'G', \n # Stop codon\n #'UAA':'Stop', 'UGA':'Stop', 'UAG':'Stop',\n}\n # your code here\n return re.sub('(?P<rna>\\D{3})',lambda match_obj: rna_2_protein_dict.get(match_obj.group('rna')) ,rna)", "rnaDict = '''Phenylalanine (F): UUU, UUC\nLeucine (L): UUA, UUG, CUU, CUC, CUA, CUG\nIsoleucine (I): AUU, AUC, AUA\nMethionine (M): AUG\nValine (V): GUU, GUC, GUA, GUG\nSerine (S): UCU, UCC, UCA, UCG, AGU, AGC\nProline (P): CCU, CCC, CCA, CCG\nThreonine (T): ACU, ACC, ACA, ACG\nAlanine(A): GCU, GCC, GCA, GCG\nTyrosine (Y): UAU, UAC\nHistidine (H): CAU, CAC\nGlutamine (Q): CAA, CAG\nAsparagine (N): AAU, AAC\nLysine (K): AAA, AAG\nAspartic Acid (D): GAU, GAC\nGlutamic Acid (E): GAA, GAG\nCysteine (C): UGU, UGC\nTryptophan (W): UGG\nArtinine (R): CGU, CGC, CGA, CGG, AGA, AGG\nGlycine (G): GGU, GGC, GGA, GGG\nStop Codon ('Stop'): UGA, UAA, UAG'''\n\nimport re\ndef protein(rna):\n transDict = {}\n for line in rnaDict.split('\\n'):\n for section in line[line.index(':')+1:].replace(' ','').split(','): \n transDict[section] = re.findall(r'\\(+\\'?(\\w+)',line)[0]\n codec = ''\n while len(rna) > 0:\n if transDict[rna[:3]] == 'Stop':\n pass\n else:\n codec += transDict[rna[:3]]\n rna = rna[3:]\n return codec", "from itertools import takewhile\nfrom textwrap import wrap\n\n\ndef protein(rna):\n return \"\".join(PEPTIDES[codon] for codon in takewhile(PEPTIDES.__contains__, wrap(rna, 3)))\n\n\nPEPTIDES = {\n 'UUC':'F', 'UUU':'F',\n 'UUA':'L', 'UUG':'L', 'CUU':'L', 'CUC':'L','CUA':'L','CUG':'L', \n 'AUU':'I', 'AUC':'I', 'AUA':'I', \n 'AUG':'M', \n 'GUU':'V', 'GUC':'V', 'GUA':'V', 'GUG':'V', \n 'UCU':'S', 'UCC':'S', 'UCA':'S', 'UCG':'S', 'AGU':'S', 'AGC':'S', \n 'CCU':'P', 'CCC':'P', 'CCA':'P', 'CCG':'P', \n 'ACU':'T', 'ACC':'T', 'ACA':'T', 'ACG':'T',\n 'GCU':'A', 'GCC':'A', 'GCA':'A', 'GCG':'A', \n 'UAU':'Y', 'UAC':'Y', \n 'CAU':'H', 'CAC':'H',\n 'CAA':'Q', 'CAG':'Q', \n 'AAU':'N', 'AAC':'N', \n 'AAA':'K', 'AAG':'K',\n 'GAU':'D', 'GAC':'D', \n 'GAA':'E', 'GAG':'E',\n 'UGU':'C', 'UGC':'C',\n 'UGG':'W', \n 'CGU':'R', 'CGC':'R', 'CGA':'R', 'CGG':'R', 'AGA':'R', 'AGG':'R', \n 'GGU':'G', 'GGC':'G', 'GGA':'G', 'GGG':'G', \n}", "def protein(s):\n d = {'UUC': 'F', 'UUU': 'F',\n\n 'UUA': 'L', 'UUG': 'L', 'CUU': 'L', 'CUC': 'L', 'CUA': 'L', 'CUG': 'L',\n\n 'AUU': 'I', 'AUC': 'I', 'AUA': 'I',\n\n 'AUG': 'M',\n\n 'GUU': 'V', 'GUC': 'V', 'GUA': 'V', 'GUG': 'V',\n\n 'UCU': 'S', 'UCC': 'S', 'UCA': 'S', 'UCG': 'S', 'AGU': 'S', 'AGC': 'S',\n\n 'CCU': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P',\n\n 'ACU': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T',\n\n 'GCU': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A',\n\n 'UAU': 'Y', 'UAC': 'Y',\n\n 'CAU': 'H', 'CAC': 'H',\n\n 'CAA': 'Q', 'CAG': 'Q',\n\n 'AAU': 'N', 'AAC': 'N',\n\n 'AAA': 'K', 'AAG': 'K',\n\n 'GAU': 'D', 'GAC': 'D',\n\n 'GAA': 'E', 'GAG': 'E',\n\n 'UGU': 'C', 'UGC': 'C',\n\n 'UGG': 'W',\n\n 'CGU': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'AGA': 'R', 'AGG': 'R',\n\n 'GGU': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G',\n\n 'UAA': 'Stop', 'UGA': 'Stop', 'UAG': 'Stop'}\n \n li = []\n for i in range(0, len(s), 3):\n r = d[s[i:i + 3]]\n if r == 'Stop' : break\n li.append(r)\n return ''.join(li)", "def protein(rna):\n dict = { \n # Phenylalanine\n 'UUC':'F', 'UUU':'F',\n # Leucine\n 'UUA':'L', 'UUG':'L', 'CUU':'L', 'CUC':'L','CUA':'L','CUG':'L', \n # Isoleucine\n 'AUU':'I', 'AUC':'I', 'AUA':'I', \n # Methionine\n 'AUG':'M', \n # Valine\n 'GUU':'V', 'GUC':'V', 'GUA':'V', 'GUG':'V', \n # Serine\n 'UCU':'S', 'UCC':'S', 'UCA':'S', 'UCG':'S', 'AGU':'S', 'AGC':'S', \n # Proline\n 'CCU':'P', 'CCC':'P', 'CCA':'P', 'CCG':'P', \n # Threonine\n 'ACU':'T', 'ACC':'T', 'ACA':'T', 'ACG':'T',\n # Alanine\n 'GCU':'A', 'GCC':'A', 'GCA':'A', 'GCG':'A', \n # Tyrosine\n 'UAU':'Y', 'UAC':'Y', \n # Histidine\n 'CAU':'H', 'CAC':'H',\n # Glutamine\n 'CAA':'Q', 'CAG':'Q', \n # Asparagine\n 'AAU':'N', 'AAC':'N', \n # Lysine\n 'AAA':'K', 'AAG':'K',\n # Aspartic Acid\n 'GAU':'D', 'GAC':'D', \n # Glutamic Acid\n 'GAA':'E', 'GAG':'E',\n # Cystine\n 'UGU':'C', 'UGC':'C',\n # Tryptophan\n 'UGG':'W', \n # Arginine\n 'CGU':'R', 'CGC':'R', 'CGA':'R', 'CGG':'R', 'AGA':'R', 'AGG':'R', \n # Glycine\n 'GGU':'G', 'GGC':'G', 'GGA':'G', 'GGG':'G', \n # Stop codon\n 'UAA':'Stop', 'UGA':'Stop', 'UAG':'Stop'\n }\n arr = [rna[i:i+3] for i in range(0, len(rna), 3)]\n p = []\n for a in arr:\n if dict[a] != \"Stop\":\n p.append(dict[a])\n else:\n break\n return \"\".join(p)", "MAPPING = {\n 'UUC':'F', 'UUU':'F',\n 'UUA':'L', 'UUG':'L', 'CUU':'L', 'CUC':'L','CUA':'L','CUG':'L', \n 'AUU':'I', 'AUC':'I', 'AUA':'I', \n 'AUG':'M', \n 'GUU':'V', 'GUC':'V', 'GUA':'V', 'GUG':'V', \n 'UCU':'S', 'UCC':'S', 'UCA':'S', 'UCG':'S', 'AGU':'S', 'AGC':'S', \n 'CCU':'P', 'CCC':'P', 'CCA':'P', 'CCG':'P', \n 'ACU':'T', 'ACC':'T', 'ACA':'T', 'ACG':'T',\n 'GCU':'A', 'GCC':'A', 'GCA':'A', 'GCG':'A', \n 'UAU':'Y', 'UAC':'Y', \n 'CAU':'H', 'CAC':'H',\n 'CAA':'Q', 'CAG':'Q', \n 'AAU':'N', 'AAC':'N', \n 'AAA':'K', 'AAG':'K',\n 'GAU':'D', 'GAC':'D', \n 'GAA':'E', 'GAG':'E',\n 'UGU':'C', 'UGC':'C',\n 'UGG':'W', \n 'CGU':'R', 'CGC':'R', 'CGA':'R', 'CGG':'R', 'AGA':'R', 'AGG':'R', \n 'GGU':'G', 'GGC':'G', 'GGA':'G', 'GGG':'G', \n 'UAA':'Stop', 'UGA':'Stop', 'UAG':'Stop'\n}\n\ndef protein(rna):\n return ''.join(MAPPING[rna[i:i+3]] for i in range(0, len(rna), 3)).split('Stop')[0]"]
{"fn_name": "protein", "inputs": [["AUGUGA"], ["AUGUAUAAA"], ["UGCGAUGAAUGGGCUCGCUCC"], ["AUGUUAAUUUGA"], ["AUGUCCUUCCAUCAAGGAAACCAUGCGCGUUCAGCUUUCUGA"], ["AUGCUUCAAGUGCACUGGAAAAGGAGAGGGAAAACCAGUUGA"], ["AUGGCGUUCAGCUUUCUAUGGAGGGUAGUGUACCCAUGCUGA"], ["AUGCAGCUUUCUAUGGAGGGUAGUGUUAACUACCACGCCUGA"], ["AUGCUAUGGAGGGUAGUGUUAACUACCACGCCCAGUACUUGA"], ["AUGCUGAUUAUGGUUGUUGUAUCUUCCUAUCAAAAUAAAACUACCACAUGA"], ["AUGGAGCACAAUAAAAUACCAAUACCACUCACUCUCUACCCUACUCUACUCUCAUGA"], ["AUGUAUCCUUCCAUCAAGGAAACCAUGCGCGUUCAGCUUUCUAUGGAGGGUAGUGUUAACUACCACGCCUUCAAGUGCACUGGAAAAGGAGAGGGAAAACCAUACGAAGGCACCCAAAGCCUGAAUAUUACAAUAACUGAAGGAGGUCCUCUGCCAUUUGCUUUUGACAUUCUGUCACACGCCUUUCAGUAUGGCAUCAAGGUCUUCGCCAAGUACCCCAAAGAAAUUCCUGACUUCUUUAAGCAGUCUCUACCUGGUGGUUUUUCUUGGGAAAGAGUAAGCACCUAUGAAGAUGGAGGAGUGCUUUCAGCUACCCAAGAAACAAGUUUGCAGGGUGAUUGCAUCAUCUGCAAAGUUAAAGUCCUUGGCACCAAUUUUCCCGCAAACGGUCCAGUGAUGCAAAAGAAGACCUGUGGAUGGGAGCCAUCAACUGAAACAGUCAUCCCACGAGAUGGUGGACUUCUGCUUCGCGAUACCCCCGCACUUAUGCUGGCUGACGGAGGUCAUCUUUCUUGCUUCAUGGAAACAACUUACAAGUCGAAGAAAGAGGUAAAGCUUCCAGAACUUCACUUUCAUCAUUUGCGUAUGGAAAAGCUGAACAUAAGUGACGAUUGGAAGACCGUUGAGCAGCACGAGUCUGUGGUGGCUAGCUACUCCCAAGUGCCUUCGAAAUUAGGACAUAACUGA"]], "outputs": [["M"], ["MYK"], ["CDEWARS"], ["MLI"], ["MSFHQGNHARSAF"], ["MLQVHWKRRGKTS"], ["MAFSFLWRVVYPC"], ["MQLSMEGSVNYHA"], ["MLWRVVLTTTPST"], ["MLIMVVVSSYQNKTTT"], ["MEHNKIPIPLTLYPTLLS"], ["MYPSIKETMRVQLSMEGSVNYHAFKCTGKGEGKPYEGTQSLNITITEGGPLPFAFDILSHAFQYGIKVFAKYPKEIPDFFKQSLPGGFSWERVSTYEDGGVLSATQETSLQGDCIICKVKVLGTNFPANGPVMQKKTCGWEPSTETVIPRDGGLLLRDTPALMLADGGHLSCFMETTYKSKKEVKLPELHFHHLRMEKLNISDDWKTVEQHESVVASYSQVPSKLGHN"]]}
INTRODUCTORY
PYTHON3
CODEWARS
8,751
def protein(rna):
1b6e47cf6f066acfb42dc7921e2adbda
UNKNOWN
# Sort an array by value and index Your task is to sort an array of integer numbers by the product of the value and the index of the positions. For sorting the index starts at 1, NOT at 0! The sorting has to be ascending. The array will never be null and will always contain numbers. Example: ``` Input: 23, 2, 3, 4, 5 Product of value and index: 23 => 23 * 1 = 23 -> Output-Pos 4 2 => 2 * 2 = 4 -> Output-Pos 1 3 => 3 * 3 = 9 -> Output-Pos 2 4 => 4 * 4 = 16 -> Output-Pos 3 5 => 5 * 5 = 25 -> Output-Pos 5 Output: 2, 3, 4, 23, 5 ``` Have fun coding it and please don't forget to vote and rank this kata! :-) I have also created other katas. Take a look if you enjoyed this kata!
["def sort_by_value_and_index(arr):\n return [y[1] for y in sorted(enumerate(arr),key=lambda x:(x[0] + 1) * x[1])]", "def sort_by_value_and_index(arr):\n return [b for _, b in sorted(enumerate(arr, 1), key=lambda x: int.__mul__(*x))]", "def sort_by_value_and_index(arr):\n return [b for _, b in sorted(enumerate(arr, 1), key=lambda a: a[0] * a[1])]\n", "def sort_by_value_and_index(arr):\n return [e for i, e in sorted(enumerate(arr, 1), key=lambda t: t[0] * t[1])]", "def sort_by_value_and_index(arr):\n return [elem[1] for elem in sorted(enumerate(arr, 1), key=lambda elem: elem[0]*elem[1])]", "import itertools\ndef sort_by_value_and_index(nums):\n #your code here\n seq = itertools.count(1)\n return sorted(nums, key=lambda num:num*next(seq))", "def sort_by_value_and_index(arr):\n arr = zip(range(1, len(arr) + 1), arr)\n return [x[1] for x in sorted(arr, key=lambda x: x[0] * x[1])]", "def sort_by_value_and_index(arr):\n vals = [(index + 1) * element for index, element in enumerate(arr)]\n newList = [(i, j) for i, j in zip(vals, arr)]\n newList = sorted(newList, key = lambda element: (element[0]))\n return [i[1] for i in newList]", "def sort_by_value_and_index(arr):\n return [y for x, y in sorted(enumerate(arr, 1), key=lambda x: x[0] * x[1])]", "sort_by_value_and_index = lambda arr: [elem for key, original_index, elem in sorted(((i * elem, i, elem) for i, elem in enumerate(arr, 1)))]"]
{"fn_name": "sort_by_value_and_index", "inputs": [[[1, 2, 3, 4, 5]], [[23, 2, 3, 4, 5]], [[26, 2, 3, 4, 5]], [[9, 5, 1, 4, 3]]], "outputs": [[[1, 2, 3, 4, 5]], [[2, 3, 4, 23, 5]], [[2, 3, 4, 5, 26]], [[1, 9, 5, 3, 4]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,446
def sort_by_value_and_index(arr):
3e1ac09d9f2500199447acbfe0fcead5
UNKNOWN
If we alternate the vowels and consonants in the string `"have"`, we get the following list, arranged alphabetically: `['ahev', 'aveh', 'ehav', 'evah', 'vahe', 'veha']`. These are the only possibilities in which vowels and consonants are alternated. The first element, `ahev`, is alphabetically lowest. Given a string: * alternate the vowels and consonants and return the lexicographically lowest element in the list * If any two or more vowels or consonants must follow each other, return `"failed"` * if the number of vowels and consonants are equal, the first letter of the result must be a vowel. Examples: ```Haskell solve("codewars") = "failed". However you alternate vowels and consonants, two consonants must follow each other solve("oruder") = "edorur" solve("orudere") = "ederoru". This is the only option that allows you to alternate vowels & consonants. ``` ```if c: In C, return an allocated string even if the response is "failed". ``` Vowels will be any of "aeiou". Input will be a lowercase string, no spaces. See test cases for more examples. Good luck! If you like this Kata, please try: [Consonant value](https://www.codewars.com/kata/59c633e7dcc4053512000073) [Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075)
["def solve(s):\n vowels = sorted(c for c in s if c in \"aeiou\")\n consonants = sorted(c for c in s if c not in \"aeiou\")\n part1, part2 = sorted((vowels, consonants), key=len, reverse=True)\n part2.append('')\n if len(part1) > len(part2):\n return \"failed\"\n return \"\".join(a + b for a, b in zip(part1, part2))", "import re\n\nVOWELS = re.compile(r'[aeiuo]')\n\ndef solve(s):\n vows, cons = sorted(VOWELS.findall(s)), sorted(VOWELS.sub('',s))\n long, short = sorted((vows, cons), key=len, reverse = True) # preserve vowels first if length are the same\n return 'failed' if len(long)-len(short) not in [0,1] else ''.join(a+b for a,b in zip(long, short+['']))", "from itertools import zip_longest\n\ndef solve(s):\n vow = sorted(c for c in list(s) if c in 'aeiou')\n con = sorted(c for c in list(s) if c not in 'aeiou')\n if abs(len(vow)-len(con)) > 1: return 'failed'\n arr = [vow, con] if len(vow)>=len(con) else [con, vow]\n return ''.join(''.join(p) for p in list(zip_longest(*arr, fillvalue='')))", "def solve(s):\n vow, con = [], []\n for c in s:\n if c in 'aeiou':\n vow.append(c)\n else:\n con.append(c)\n \n len_v, len_c = len(vow), len(con)\n \n if len_v - len_c in [0, 1]:\n return ''.join(v+c for v, c in zip(sorted(vow), sorted(con) + ['']))\n elif len_v - len_c == -1:\n return ''.join(v+c for v, c in zip(sorted(con), sorted(vow) + ['']))\n \n return 'failed'", "def solve(stg):\n split = [[], []]\n for c in sorted(stg):\n split[0 if c in \"aeiou\" else 1].append(c)\n a, b = sorted(split, key=len, reverse=True)\n if len(a) - len(b) > 1:\n return \"failed\"\n return \"\".join(f\"{c}{d}\" for c, d in zip(a, b + [\"\"]))", "import re\ndef solve(s):\n vowels = sorted(re.findall(r'[aeiou]', s))[::-1]\n consonant = sorted(re.findall(r'[^aeiou]', s))[::-1]\n if abs(len(consonant) - len(vowels)) > 1: return 'failed'\n\n out = []\n if len(vowels) >= len(consonant):\n while vowels and consonant:\n out.append(vowels.pop())\n out.append(consonant.pop())\n \n else:\n while vowels and consonant:\n out.append(consonant.pop())\n out.append(vowels.pop())\n\n return consonant and ''.join(out + consonant) or ''.join(out + vowels)", "from itertools import zip_longest, chain\nvowels = {'a', 'e', 'i', 'o', 'u'}\n\ndef solve(s):\n vow, con = [], []\n for c in s: (con, vow)[c in vowels].append(c)\n if abs(len(con) - len(vow)) > 1: return \"failed\"\n vow.sort(); con.sort()\n x, y = (vow, con) if len(vow) >= len(con) else (con, vow)\n return ''.join(chain.from_iterable(zip_longest(x, y, fillvalue='')))", "def solve(s):\n vowels = ''.join(sorted(ch for ch in s if ch in \"aeiou\")) + '_'\n consonants = ''.join(sorted(ch for ch in s if ch not in \"aeiou\")) + '_'\n if abs(len(vowels) - len(consonants)) > 1: \n return 'failed'\n if len(vowels) >= len(consonants): \n res = ''.join(v+c for v, c in zip(vowels, consonants))\n else: \n res = ''.join(v+c for v, c in zip(consonants, vowels))\n return res.strip('_')\n", "from itertools import zip_longest\n\ndef solve(s):\n a, b = sorted(x for x in s if x in \"aiueo\"), sorted(x for x in s if x not in \"aiueo\")\n if len(b) > len(a): a, b = b, a\n return \"failed\" if len(a) - len(b) > 1 else \"\".join(f\"{x}{y}\" for x, y in zip_longest(a, b, fillvalue=\"\"))\n", "from itertools import zip_longest\n\ndef solve(s):\n v = sorted(x for x in s if x in 'aeiou')\n c = sorted(x for x in s if x not in 'aeiou')\n if abs(len(v) - len(c)) > 1:\n return 'failed'\n if len(c) > len(v):\n v, c = c, v\n return ''.join(a + b for a, b in zip_longest(v, c, fillvalue=''))", "import re\ndef solve(s):\n c,v = sorted(re.findall(r'[^aeiou]',s)), sorted(re.findall(r'[aeiou]',s))\n m, n = (max(c,v,key=len),min(c,v,key=len)) if len(v) != len(c) else (v,c)\n return \"\".join(sum(zip(m,n+[\"\"]),())) if abs(len(v) - len(c)) <= 1 else \"failed\"", "def solve(stg):\n split = [[], []]\n for c in sorted(stg):\n split[0 if c in \"aeiou\" else 1].append(c)\n a, b = sorted(split, key=len, reverse=True)\n if len(a) - len(b) > 1:\n return \"failed\"\n result = [\"\"] * len(stg)\n result[::2], result[1::2] = a, b\n return \"\".join(result)", "def solve(s):\n c,v,r=[],[],[]\n for m in s:\n if m in 'aeiou': v.append(m)\n else: c.append(m)\n c.sort()\n v.sort()\n cl,vl=len(c),len(v)\n if abs(cl-vl)>1: return 'failed'\n for i in range(max(cl,vl)):\n if vl>=cl:\n if i<vl: r.append(v[i])\n if i<cl: r.append(c[i])\n else:\n if i<cl: r.append(c[i])\n if i<vl: r.append(v[i])\n return ''.join(r)", "def solve(s):\n count1=[sum(1 for i in s if i in \"aeiou\"), \"\".join(sorted(i for i in s if i in \"aeiou\"))]\n count2=[sum(1 for i in s if i not in \"aeiou\"), \"\".join(sorted(i for i in s if i not in \"aeiou\"))]\n if abs(count1[0]-count2[0])>=2:\n return \"failed\"\n if len(count1[1])==len(count2[1]):\n return \"\".join(i+j for (i,j) in zip(count1[1], count2[1]))\n elif len(count1[1])>len(count2[1]):\n return \"\".join(i+j for (i,j) in zip(count1[1], count2[1]))+count1[1][-1]\n else:\n return \"\".join(i+j for (i,j) in zip(count2[1], count1[1]))+count2[1][-1]", "from itertools import chain, zip_longest\n\ndef solve(s):\n ls_vow = sorted([x for x in s if x in \"aeiou\"])\n ls_con = sorted([x for x in s if x not in \"aeiou\"])\n if abs(len(ls_vow) - len(ls_con)) > 1 : return \"failed\"\n arr = [ls_vow, ls_con] if len(ls_vow)>=len(ls_con) else [ls_con, ls_vow]\n return \"\".join(list(chain(*list(zip_longest(*arr, fillvalue=''))))) ", "from itertools import zip_longest \ndef solve(s):\n print(s)\n a=list( map(s.lower().count, \"aeiou\"))\n print('lv',sum(a))\n l=len(s)\n lv=sum(a)\n lc=l-lv\n print('l',l,'lc',lc)\n vw,cn=[],[]\n if abs(lv-lc)>1:\n return 'failed'\n elif lv<lc:\n for x in s:\n if x in 'aeiou':\n vw.append(x)\n else: \n cn.append(x)\n cn=sorted(cn)\n vw=sorted(vw)\n b=list(zip_longest(cn,vw))\n elif lc<=lv:\n for x in s:\n if x in 'aeiou':\n vw.append(x)\n else: \n cn.append(x)\n cn=sorted(cn)\n vw=sorted(vw)\n b=list(zip_longest(vw,cn)) \n print(vw) \n print(cn)\n \n lst=[]\n for x in b:\n lst.append(x[0])\n lst.append(x[1])\n print(lst) \n if lst[-1]==None:\n del lst[-1]\n print(lst) \n return(''.join(lst)) ", "def solve(s):\n vowels = 'aeiou'\n s_vowels = sorted(c for c in s if c in vowels)\n s_consonants = sorted(c for c in s if c not in vowels)\n\n diff = len(s_vowels) - len(s_consonants)\n if diff == -1:\n out_string = s_consonants.pop(0)\n for v, c in zip(s_vowels, s_consonants):\n out_string += v + c\n elif diff == 0:\n out_string = ''\n for v, c in zip(s_vowels, s_consonants):\n out_string += v + c\n elif diff == 1:\n out_string = s_vowels.pop(0)\n for c, v in zip(s_consonants, s_vowels):\n out_string += c + v\n else:\n return 'failed'\n \n return out_string", "def solve(s):\n vowels = sorted([x for x in s if x in (\"aeiou\")])\n consonants = sorted([x for x in s if x not in vowels])\n difference = len(vowels) - len(consonants)\n s = \"\"\n if abs(difference) >= 2:\n return \"failed\"\n elif abs(difference) == 1:\n if difference == 1:\n s += vowels.pop(0)\n else: \n s += consonants.pop(0) \n if s == \"\" or s[0] not in \"aeiou\":\n s += ''.join(''.join(pair) for pair in zip(vowels, consonants))\n else:\n s += ''.join(''.join(pair) for pair in zip(consonants, vowels))\n return s", "from itertools import zip_longest\ndef solve(s):\n vowels,consonants=[],[]\n for c in s:\n if c in 'aeiou':\n vowels.append(c)\n else:\n consonants.append(c)\n if abs(len(vowels)-len(consonants))>1:\n return 'failed'\n r=''\n a=[sorted(vowels),sorted(consonants)]\n if len(vowels)<len(consonants):\n a=a[::-1]\n for c1,c2 in zip_longest(*a,fillvalue=''):\n r+=c1+c2\n return r", "def solve(s):\n vowels = sorted([ch for ch in s if ch in 'aeiou'])\n consonants = sorted([ch for ch in s if ch not in 'aeiou'])\n \n if abs(len(vowels) - len(consonants)) > 1:\n return 'failed'\n \n ret = ''\n \n if len(vowels) == len(consonants):\n for v, c in zip(vowels, consonants):\n ret += f'{v}{c}'\n else:\n if len(consonants) > len(vowels):\n zipped = zip(consonants, vowels)\n last = consonants[-1]\n else:\n zipped = zip(vowels, consonants)\n last = vowels[-1]\n \n for c, v in zipped:\n ret += f'{c}{v}'\n ret += last\n return ret "]
{"fn_name": "solve", "inputs": [["java"], ["oruder"], ["zodiac"], ["apple"], ["acidity"], ["codewars"], ["orudere"]], "outputs": [["ajav"], ["edorur"], ["acidoz"], ["lapep"], ["caditiy"], ["failed"], ["ederoru"]]}
INTRODUCTORY
PYTHON3
CODEWARS
9,356
def solve(s):
5e7ad2a1c688710a6c3b7996489bcb4f
UNKNOWN
# RegExp Fun #1 - When I miss few days of gym ## Disclaimer The background story of this Kata is 100% fiction. Any resemblance to real people or real events is **nothing more than a coincidence** and should be regarded as such. ## Background Story You are a person who loves to go to the gym everyday with the squad of people that you've known since early childhood. However, you recently contracted a sickness that forced you to stay at home for over a week. As you see your body getting weaker and weaker every day and as you see your biceps and triceps disappearing, you can't help but lay in bed and cry. You're usually an optimistic person but this time negative thoughts come to your head ... ![When I miss few days of gym](https://pics.onsizzle.com/Instagram-faf8c9.png) ## Task As can be seen from the funny image above (or am I the only person to find the picture above hilarious?) there is lots of slang. Your task is to define a function ```gymSlang``` which accepts a string argument and does the following: 1. Replace *all* instances of ```"probably"``` to ```"prolly"``` 2. Replace *all* instances of ```"i am"``` to ```"i'm"``` 3. Replace *all* instances of ```"instagram"``` to ```"insta"``` 4. Replace *all* instances of ```"do not"``` to ```"don't"``` 5. Replace *all* instances of ```"going to"``` to ```"gonna"``` 6. Replace *all* instances of ```"combination"``` to ```"combo"``` Your replacement regexes **should be case-sensitive**, only replacing the words above with slang if the detected pattern is in **lowercase**. However, please note that apart from 100% lowercase matches, you will **also have to replace matches that are correctly capitalized** (e.g. ```"Probably" => "Prolly"``` or ```"Instagram" => "Insta"```). Finally, your code will be tested to make sure that you have used **RegExp** replace in your code. Enjoy :D
["import re\n\ndef gym_slang(phrase):\n phrase = re.sub(r'([pP])robably', r'\\1rolly', phrase)\n phrase = re.sub(r'([iI]) am', r\"\\1'm\", phrase)\n phrase = re.sub(r'([iI])nstagram', r'\\1nsta', phrase)\n phrase = re.sub(r'([dD])o not', r\"\\1on't\", phrase)\n phrase = re.sub(r'([gG])oing to', r'\\1onna', phrase)\n phrase = re.sub(r'([cC])ombination', r'\\1ombo', phrase)\n \n return phrase", "from re import sub\n\ndict = {\"([pP]ro)bably\": r\"\\1lly\",\n \"([iI]) am\": r\"\\1'm\",\n \"([iI]nsta)gram\": r\"\\1\",\n \"([dD]o) not\": r\"\\1n't\",\n \"([gG]o)ing to\": r\"\\1nna\",\n \"([cC]omb)ination\": r\"\\1o\"}\n\ndef gym_slang(phrase):\n for k, v in dict.items():\n phrase = sub(k, v, phrase)\n return phrase", "import re\n\ndef gym_slang(phrase, *args):\n def repl_f (repl):\n def g (match):\n return repl.capitalize () if match.group (0) [0].isupper () else repl\n return g\n \n r = phrase\n r = re.sub ('(p|P)robably', repl_f ('prolly'), r)\n r = re.sub ('(i|I) am', repl_f ('i\\'m'), r)\n r = re.sub ('(i|I)nstagram', repl_f ('insta'), r)\n r = re.sub ('(d|D)o not', repl_f ('don\\'t'), r)\n r = re.sub ('(g|G)oing to', repl_f ('gonna'), r)\n r = re.sub ('(c|C)ombination', repl_f ('combo'), r)\n return r\n", "from functools import reduce\nREPLS = (\n ('probably', 'prolly'), ('Probably', 'Prolly'), ('i am', \"i'm\"),\n ('I am', \"I'm\"), ('instagram', 'insta'), ('Instagram', 'Insta'),\n ('do not', \"don't\"), ('Do not', \"Don't\"), ('going to', 'gonna'),\n ('Going to', 'Gonna'), ('combination', 'combo'), ('Combination', 'Combo')\n)\n\n\ndef gym_slang(s, _=None):\n return reduce(lambda a, kv: a.replace(*kv), REPLS, s)\n", "def gym_slang(phrase):\n return phrase.replace(\"probably\", \"prolly\").replace(\"Probably\", \"Prolly\").replace(\"i am\", \"i'm\").replace(\"I am\", \"I'm\").replace(\"instagram\", \"insta\").replace(\"Instagram\", \"Insta\").replace(\"do not\", \"don't\").replace(\"Do not\", \"Don't\").replace(\"going to\", \"gonna\").replace(\"Going to\", \"Gonna\").replace(\"combination\", \"combo\").replace(\"Combination\", \"Combo\")", "import re\nr = re.findall(r\"\\\"(\\w)(.*?)\\\".*?\\\"\\w(.*?)\\\"\", \"\"\"\n Replace all instances of \"probably\" to \"prolly\"\n Replace all instances of \"i am\" to \"i'm\"\n Replace all instances of \"instagram\" to \"insta\"\n Replace all instances of \"do not\" to \"don't\"\n Replace all instances of \"going to\" to \"gonna\"\n Replace all instances of \"combination\" to \"combo\"\n \"\"\")\n\ndef gym_slang(s):\n for a, b, c in r: s = re.sub(\"(?<=[%s%s])%s\" % (a, a.upper(), b), c, s)\n return s", "from functools import partial\nimport re\ndef gym_slang(phrase):\n def repl(match):\n def check_upper(word, match):\n return word.capitalize() if match[0].isupper() else word\n check = partial(check_upper, match=match.group())\n if match.group() == match.group(1):\n return check(\"prolly\")\n if match.group() == match.group(2):\n return check(\"i'm\")\n if match.group() == match.group(3):\n return check(\"insta\")\n if match.group() == match.group(4):\n return check(\"don't\")\n if match.group() == match.group(5):\n return check(\"gonna\")\n if match.group() == match.group(6):\n return check(\"combo\") \n return re.sub(r\"(?i)(probably)|(i am)|(instagram)|(do not)|(going to)|(combination)\", repl, phrase)", "import functools \nimport re\ngym_slang = lambda phrase: \\\n functools.reduce \\\n (\n lambda s, u: re.sub(*u, s),\n (\n ('(?<=[Pp])(robably)', 'rolly'),\n ('(?<=[Ii])\\sam', '\\'m'),\n ('(?<=[Ii])nstagram', 'nsta'),\n ('(?<=[Dd])o\\snot', 'on\\'t'),\n ('(?<=[Gg])oing\\sto', 'onna'),\n ('(?<=[Cc])ombination', 'ombo')\n ),\n phrase\n )", "import re\nchanges = {'probably':'prolly','Probably':'Prolly','i am':'i\\'m','I am':'I\\'m','instagram':'insta',\n 'Instagram':'Insta','do not':'don\\'t','Do not':'Don\\'t','going to':'gonna','Going to':'Gonna',\n 'combination':'combo','Combination':'Combo'}\n\n\ndef gym_slang(phrase):\n for k in changes.keys():\n if k in phrase:\n phrase = re.sub(k,changes[k],phrase)\n return phrase", "import re\n\ndef gym_slang(phrase):\n s = {r\"(P|p)robably\": \"\\\\1rolly\",\n r\"(I|i) am\": \"\\\\1'm\",\n r\"(I|i)nstagram\": \"\\\\1nsta\",\n r\"(D|d)o not\": \"\\\\1on't\",\n r\"(G|g)oing to\": \"\\\\1onna\",\n r\"(C|c)ombination\": \"\\\\1ombo\"}\n for k, v in s.items():\n phrase = re.sub(k, v, phrase)\n return phrase"]
{"fn_name": "gym_slang", "inputs": [["When I miss few days of gym"], ["Squad probably think I am fake"], ["Whole squad probably bigger than me now"], ["No selfie to post on Instagram either"], ["Gym crush probably found someone else"], ["What if I die fat"], ["What if I do not fit in my clothes now"], ["Going to feel like a new gym member"], ["wait what was my lock combination"], ["that skinny girl can probably outlift me now"], ["probably Probably"], ["i am I am"], ["instagram Instagram"], ["do not Do not"], ["going to Going to"], ["combination Combination"], ["probably Probably probably Probably probably Probably probably Probably probably Probably"], ["i am I am i am I am i am I am i am I am i am I am i am I am"], ["instagram Instagram instagram Instagram instagram Instagram instagram Instagram instagram Instagram"], ["do not Do not do not Do not do not Do not do not Do not"], ["Going to going to Going to Going to going to Going to Going to going to Going to"], ["combination combination Combination combination Combination"]], "outputs": [["When I miss few days of gym"], ["Squad prolly think I'm fake"], ["Whole squad prolly bigger than me now"], ["No selfie to post on Insta either"], ["Gym crush prolly found someone else"], ["What if I die fat"], ["What if I don't fit in my clothes now"], ["Gonna feel like a new gym member"], ["wait what was my lock combo"], ["that skinny girl can prolly outlift me now"], ["prolly Prolly"], ["i'm I'm"], ["insta Insta"], ["don't Don't"], ["gonna Gonna"], ["combo Combo"], ["prolly Prolly prolly Prolly prolly Prolly prolly Prolly prolly Prolly"], ["i'm I'm i'm I'm i'm I'm i'm I'm i'm I'm i'm I'm"], ["insta Insta insta Insta insta Insta insta Insta insta Insta"], ["don't Don't don't Don't don't Don't don't Don't"], ["Gonna gonna Gonna Gonna gonna Gonna Gonna gonna Gonna"], ["combo combo Combo combo Combo"]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,889
def gym_slang(phrase):
6f4db7e88ddb8858396739ecf00068ec
UNKNOWN
The palindromic number `595` is interesting because it can be written as the sum of consecutive squares: `6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2 = 595`. There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums. Note that `1 = 0^2 + 1^2` has not been included as this problem is concerned with the squares of positive integers. Given an input `n`, find the count of all the numbers less than `n` that are both palindromic and can be written as the sum of consecutive squares. For instance: `values(1000) = 11`. See test examples for more cases. Good luck! This Kata is borrowed from [Project Euler #125](https://projecteuler.net/problem=125) If you like this Kata, please try: [Fixed length palindromes](https://www.codewars.com/kata/59f0ee47a5e12962cb0000bf) [Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)
["l, m, p = [1], 10 ** 7, []\nfor n in range(2, int(m ** .5) + 1):\n l = [n*n + j for j in [0]+l]\n p += [int(k) for k in map(str, l[1:]) if k == k[::-1]]\np = sorted(set(p))\n\nfrom bisect import bisect_left\ndef values(n): return bisect_left(p, n)", "def values(n):\n pal = set()\n for i in range(1, int(n**0.5)):\n sos = i*i\n while sos < n:\n i += 1\n sos += i*i\n if str(sos)==str(sos)[::-1] and sos < n:\n pal.add(sos)\n return len(pal)", "from bisect import bisect\n\nis_pal = lambda s: s == s[::-1]\n\nN, temp = 2500, set()\nfor x in range(1, N):\n val = x**2\n for y in range(x+1, N):\n val += y**2\n if val not in temp and is_pal(str(val)):\n temp.add(val)\nresult = sorted(temp)\n\ndef values(n):\n return bisect(result, n)", "sumSquaresToN = lambda n: n*(n+1)*(2*n+1)//6\n\nmemo = set()\n\ndef values(n):\n lastMax = max(memo) if memo else 0\n if lastMax >= n:\n return sum( x < n for x in memo )\n \n top = int( (1 + (1+2*(n-1))**.5) // 2 ) # Value of the top number for a sum of two consecutive squares under n: (top-1)**2 + top**2 <= n \n for a in range(top, 1, -1):\n va = sumSquaresToN(a) # sum of squares of 1, 2, 3, ..., a\n if va <= lastMax: break # va is greater than all the values generated with the inner loop, so if too small to generate new values, exit\n\n for b in range(a-2, -1, -1):\n v = va - sumSquaresToN(b) # current value\n if v >= n: break # going down with the values of b, v increase at each execution. Allow to exit the loop when generated values become to big (and useless for the current call)\n if v == int(str(v)[::-1]): memo.add(v)\n \n return len(memo)", "found = set([5, 55, 77, 181, 313, 434, 505, 545, 595, 636, 818, 1001, 1111, 1441, 1771, 4334, 6446, 17371, 17871, 19691, 21712, 41214, 42924, 44444, 46564, 51015, 65756, 81818, 97679,\n 99199, 108801, 127721, 137731, 138831, 139931, 148841, 161161, 166661, 171171, 188881, 191191, 363363, 435534, 444444, 485584, 494494, 525525, 554455, 554455, 629926, 635536,\n 646646, 656656, 904409, 923329, 944449, 964469, 972279, 981189, 982289, 1077701, 1224221, 1365631, 1681861, 1690961, 1949491, 1972791, 1992991, 2176712, 2904092, 3015103, 3162613,\n 3187813, 3242423, 3628263, 4211124, 4338334, 4424244, 4776774, 5090905, 5258525, 5276725, 5367635, 5479745, 5536355, 5588855, 5603065, 5718175, 5824285, 6106016, 6277726, 6523256,\n 6546456, 6780876, 6831386, 6843486, 6844486, 7355537, 8424248, 9051509, 9072709, 9105019, 9313139, 9334339, 9343439, 9343439, 9435349, 9563659, 9793979, 9814189, 9838389, 9940499])\n\ndef values(n):\n return sum(i<n for i in found)\n\n\n\n#this is how i achieved that :D\n'''\n#generate palindomre upto 10**digits quickly\ndef generate_palindromes(digits):\n batches = [None,\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n [0, 11, 22, 33, 44, 55, 66, 77, 88, 99]]\n\n for n in range(3, digits + 1):\n batch = []\n mid = [batches[k] for k in range(1, len(batches)) if [not k & 1, k & 1][n & 1]]\n for side in range(1, 10):\n for p in mid:\n for inner in p:\n number = str(side) + str(inner).center(n - 2, '0') + str(side)\n batch.append(int(number))\n batches.append(batch[:])\n\n return sum(batches[1:], [])\n\n\nx = generate_palindromes(7)\nx = set(x[:10] + x[11:])\n\nfound = []\nfor i in range(1, 2000):\n sq = i * i\n for j in range(i + 1, 2000):\n sq += j * j\n if sq in x:\n found.append(sq)\n'''", "def values(high):\n s = set()\n num = 1\n while num * num < high:\n temp = num + 1\n total = num * num + temp * temp\n while total < high:\n if str(total) == str(total)[::-1]:\n s.add(total)\n temp += 1\n total += temp * temp\n num += 1\n return len(s)", "found = set([5, 55, 77, 181, 313, 434, 505, 545, 595, 636, 818, 1001, 1111, 1441, 1771, 4334, 6446, 17371, 17871, 19691, 21712, 41214, 42924, 44444, 46564, 51015, 65756, 81818, 97679,\n 99199, 108801, 127721, 137731, 138831, 139931, 148841, 161161, 166661, 171171, 188881, 191191, 363363, 435534, 444444, 485584, 494494, 525525, 554455, 554455, 629926, 635536,\n 646646, 656656, 904409, 923329, 944449, 964469, 972279, 981189, 982289, 1077701, 1224221, 1365631, 1681861, 1690961, 1949491, 1972791, 1992991, 2176712, 2904092, 3015103, 3162613,\n 3187813, 3242423, 3628263, 4211124, 4338334, 4424244, 4776774, 5090905, 5258525, 5276725, 5367635, 5479745, 5536355, 5588855, 5603065, 5718175, 5824285, 6106016, 6277726, 6523256,\n 6546456, 6780876, 6831386, 6843486, 6844486, 7355537, 8424248, 9051509, 9072709, 9105019, 9313139, 9334339, 9343439, 9343439, 9435349, 9563659, 9793979, 9814189, 9838389, 9940499])\n\ndef values(n):\n return sum(i<n for i in found)", "def values(limit):\n palindromes = set()\n for sequence_item in range(1, int(limit**0.5)):\n squares_sum = sequence_item**2\n while squares_sum < limit:\n sequence_item += 1\n squares_sum += sequence_item**2\n if str(squares_sum)==str(squares_sum)[::-1] and squares_sum < limit:\n palindromes.add(squares_sum)\n return len(palindromes)", "def values(n):\n p = set()\n for i in range(1, int(n**0.5)):\n q = i*i\n while q < n:\n i=i+ 1\n q =q+ i*i\n if str(q)==str(q)[::-1] and q < n:\n p.add(q)\n return len(p)", "def values(limit):\n def is_palindrome(n):\n n = str(n)\n if len(n) in [0, 1]:\n return True\n return n[0] == n[-1] and is_palindrome(n[1:-1])\n\n print(\"Limit: {}\".format(limit))\n current = 2\n totals = [1]\n list_pal = []\n while True:\n number = current ** 2 + totals[-1]\n totals = [i for i in totals if number - i < limit]\n if len(totals) == 1 and totals != [1]:\n break\n for i in totals[:-1]:\n if is_palindrome(number - i) and not (number - i) in list_pal and limit > (number - i):\n list_pal.append(number - i)\n if is_palindrome(number) and not number in list_pal and limit > number:\n list_pal.append(number)\n totals.append(number)\n current += 1\n print(\"Number of Palindrome in list: {}\".format(len(list_pal)))\n print(\"List of Palindrome: {}\".format(list_pal))\n return len(list_pal)"]
{"fn_name": "values", "inputs": [[100], [200], [300], [400], [1000], [100000], [1000000], [5000000], [9000000], [10000000]], "outputs": [[3], [4], [4], [5], [11], [30], [59], [78], [98], [110]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,787
def values(n):
ccd2b2b28c7e7f0c87e7fda6abe20e52
UNKNOWN
In this Kata, you will be given an integer array and your task is to return the sum of elements occupying prime-numbered indices. ~~~if-not:fortran The first element of the array is at index `0`. ~~~ ~~~if:fortran The first element of an array is at index `1`. ~~~ Good luck! If you like this Kata, try: [Dominant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed). It takes this idea a step further. [Consonant value](https://www.codewars.com/kata/59c633e7dcc4053512000073)
["def is_prime(n):\n return n >= 2 and all(n%i for i in range(2, 1+int(n**.5)))\n \ndef total(arr):\n return sum(n for i, n in enumerate(arr) if is_prime(i))", "def sieve(n):\n sieve, primes = [0]*(n+1), set()\n for i in range(2, n+1):\n if not sieve[i]:\n primes.add(i)\n for j in range(i**2, n+1, i): sieve[j] = 1\n return primes\n\nPRIMES = sieve(5000)\n\ndef total(arr):\n return sum(arr[p] for p in set(range(len(arr))) & PRIMES)", "def total(lst):\n return sum(lst[i] for i in primes_gen(len(lst)))\n\n\ndef primes_gen(limit):\n for current in (2, 3, 5, 7):\n if current > limit:\n return\n yield current\n composites = {}\n primes = primes_gen(limit)\n base_prime = next(primes) and next(primes)\n next_square = base_prime * base_prime\n for current in range(9, limit, 2):\n if current in composites:\n sieve = composites.pop(current)\n elif current < next_square:\n yield current\n continue\n else:\n sieve = 2 * base_prime\n base_prime = next(primes)\n next_square = base_prime * base_prime\n current += sieve\n while current in composites:\n current += sieve\n composites[current] = sieve", "def total(arr):\n sum = 0\n erastoteme = [True] * len(arr)\n for num in range(2, len(erastoteme)):\n if erastoteme[num]:\n sum += arr[num]\n for nb in range(num*2, len(erastoteme), num):\n erastoteme[nb] = False\n return sum", "def total(arr):\n fin_arr = []\n for i in range(2, len(arr)):\n d = 2\n while i % d != 0:\n d += 1\n if d == i:\n fin_arr.append(arr[i])\n n = sum(fin_arr)\n return n", "def is_prime(n):\n if (n <= 1):\n return False\n if (n <= 3):\n return True\n if (n% 2 == 0 or n % 3 == 0):\n return False\n \n i = 5\n while(i * i <= n):\n if (n % i == 0 or n % (i + 2) == 0):\n return False\n i = i + 6\n \n return True\n\ndef total(arr):\n final = 0\n i = 0\n for num in arr:\n if is_prime(i) == True:\n final = final + arr[i]\n i = i + 1\n if i == len(arr):\n return final\n if not is_prime(i) == True:\n i = i + 1\n if i == len(arr):\n return final\n \n\n \n return final\n #lol i know it is too long; but I already did the 'Is a number prime?' Kata, and \n #so I decided to use it here.\n", "def is_prime(n):\n return n > 1 and all(n % d for d in range(2, int(n**0.5)+1))\n\ndef total(arr):\n return sum(e for i, e in enumerate(arr) if is_prime(i))", "import itertools\nimport numpy as np\n\ns = np.ones(100000)\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\n\ndef total(arr):\n return sum(itertools.compress(arr, s))"]
{"fn_name": "total", "inputs": [[[]], [[1, 2, 3, 4]], [[1, 2, 3, 4, 5, 6]], [[1, 2, 3, 4, 5, 6, 7, 8]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]]], "outputs": [[0], [7], [13], [21], [21], [33], [47]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,021
def total(arr):
868de89e8b7f6ae60d0829a4fd63e7f7
UNKNOWN
< PREVIOUS KATA NEXT KATA > ###Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto (3n-2) rows, where n is parameter. * Note:`Returning` the pattern is not the same as `Printing` the pattern. ####Rules/Note: * The pattern should be created using only unit digits. * If `n < 1` then it should return "" i.e. empty string. * `The length of each line is same`, and is equal to the length of longest line in the pattern i.e. `length = (3n-2)`. * Range of Parameters (for the sake of CW Compiler) : + `n ∈ (-∞,50]` ###Examples: + pattern(5) : 11111 22222 33333 44444 1234555554321 1234555554321 1234555554321 1234555554321 1234555554321 44444 33333 22222 11111 + pattern(11): 11111111111 22222222222 33333333333 44444444444 55555555555 66666666666 77777777777 88888888888 99999999999 00000000000 1234567890111111111110987654321 1234567890111111111110987654321 1234567890111111111110987654321 1234567890111111111110987654321 1234567890111111111110987654321 1234567890111111111110987654321 1234567890111111111110987654321 1234567890111111111110987654321 1234567890111111111110987654321 1234567890111111111110987654321 1234567890111111111110987654321 00000000000 99999999999 88888888888 77777777777 66666666666 55555555555 44444444444 33333333333 22222222222 11111111111 >>>LIST OF ALL MY KATAS<<<
["def pattern(n):\n top = [(str(i % 10) * n).center(n * 3 - 2) for i in range(1, n)]\n left = ''.join(str(i % 10) for i in range(1, n))\n middle = left + str(n % 10) * n + left[::-1]\n return '\\n'.join(top + [middle] * n + top[::-1])\n", "def f(n):\n w = 3*n - 2\n for i in range(1, n):\n yield (str(i%10) * n).center(w)\n line = ''.join(str(i%10) for i in range(1, n)) + (str(n % 10) * n) + ''.join(str(i%10) for i in reversed(range(1, n)))\n for i in range(n):\n yield line\n for i in reversed(range(1, n)):\n yield (str(i%10) * n).center(w)\n\ndef pattern(n):\n return '\\n'.join(f(n))", "def pattern(n):\n if n == 1:\n return \"1\"\n if n < 1:\n return \"\"\n top = \"\\n\".join([\" \" * (n - 1) + str(i % 10) * n + \" \" * (n - 1) for i in range(1, n)])\n result = [top]\n nums = [str(i % 10) for i in range(1, n)]\n result.append(\"\\n\".join([\"\".join(nums) + str(n % 10) * n + \"\".join(nums[::-1])] * n))\n result.append(top[::-1])\n return \"\\n\".join(result)", "def pattern(n):\n return ''.join((str((k+1)%10)*n).center(3*n-2)+'\\n' for k in range(n-1))+(''.join(str((i+1)%10) for i in range(n-1))+n*str(n%10)+''.join(str(j%10) for j in range(n-1,0,-1))+'\\n')*n+'\\n'.join((str(g%10)*n).center(3*n-2) for g in range(n-1,0,-1))", "def pattern(n):\n lines = []\n for p in range(1,n):\n lines.append((str(p%10)*n).center(3*n-2))\n for p in range(1,n+1):\n lines.append(''.join([str(m%10) for m in range(1,n)] + [str(n%10) for m in range(n)] + [str(m%10) for m in range(1,n)[::-1]]))\n for p in range(n-1,0,-1):\n lines.append((str(p%10)*n).center(3*n-2))\n return '\\n'.join(lines)", "def pattern(n):\n h = ''.join(str(i%10) for i in range(1, n))\n h = h + str(n%10) * n + h[::-1]\n v = [(str(i%10) * n).center(len(h)) for i in range(1, n)]\n return '\\n'.join(v + [h] * n + v[::-1])", "get_r = lambda y: str((y) % 10)\ndef pattern(n):\n if n < 2: return '' if n < 1 else '1'\n l, r = ''.join(map(get_r, range(1, n))), ''.join(map(get_r, range(n - 1, 0, -1)))\n top = [' ' * (n - 1) + get_r(x) * n + ' ' * (n - 1) for x in range(1, n)]\n return '\\n'.join(top) + '\\n' + (l + get_r(n) * n + r + '\\n') * n + '\\n'.join(list(reversed(top)))", "pattern=lambda n: \"\\n\".join([\"\".join([\" \"]*(n-1)+[str(i%10)]*n+[\" \"]*(n-1)) for i in range(1,n)]+[\"\".join([str(x%10) for x in range(1,n)]+[str(n%10)]*n+[str(x%10) for x in range(n-1,0,-1)]) for i in range(n)]+[\"\".join([\" \"]*(n-1)+[str(i%10)]*n+[\" \"]*(n-1)) for i in range(n-1,0,-1)])\n\n#and if you are reading this after having completed it without plenty of\n#list comprehensions, you know you should feel ashamed, z3rocoo1 :(\n#Kore wa joku desu; ganbatte, kohai ;)\n", "def pattern(n):\n s = ''.join(str((i if i < n else n if i < n*2 else (n*3)-i-1)%10) for i in range(1,n*3-1))\n return '\\n'.join((s[i]*n).center(n*3-2) if i < n-1 or i >= n*2-1 else s for i in range(n*3-2))"]
{"fn_name": "pattern", "inputs": [[3], [5], [-3], [-11], [-25], [0]], "outputs": [[" 111 \n 222 \n1233321\n1233321\n1233321\n 222 \n 111 "], [" 11111 \n 22222 \n 33333 \n 44444 \n1234555554321\n1234555554321\n1234555554321\n1234555554321\n1234555554321\n 44444 \n 33333 \n 22222 \n 11111 "], [""], [""], [""], [""]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,004
def pattern(n):
1d4c6527b523dacf50575ba63bebd5c9
UNKNOWN
Note : Issues Fixed with python 2.7.6 , Use any one you like :D , ( Thanks to Time , time , time . Your task is to write a function that will return the degrees on a analog clock from a digital time that is passed in as parameter . The digital time is type string and will be in the format 00:00 . You also need to return the degrees on the analog clock in type string and format 360:360 . Remember to round of the degrees . Remeber the basic time rules and format like 24:00 = 00:00 and 12:60 = 13:00 . Create your own validation that should return "Check your time !" in any case the time is incorrect or the format is wrong , remember this includes passing in negatives times like "-01:-10". ``` A few examples : clock_degree("00:00") will return : "360:360" clock_degree("01:01") will return : "30:6" clock_degree("00:01") will return : "360:6" clock_degree("01:00") will return : "30:360" clock_degree("01:30") will return : "30:180" clock_degree("24:00") will return : "Check your time !" clock_degree("13:60") will return : "Check your time !" clock_degree("20:34") will return : "240:204" ``` Remember that discrete hour hand movement is required - snapping to each hour position and also coterminal angles are not allowed. Goodluck and Enjoy !
["def clock_degree(clock_time):\n hour, minutes = (int(a) for a in clock_time.split(':'))\n if not (24 > hour >= 0 and 60 > minutes >= 0):\n return 'Check your time !'\n return '{}:{}'.format((hour % 12) * 30 or 360, minutes * 6 or 360)", "def clock_degree(stg):\n try:\n h, m = (int(n) for n in stg.split(\":\"))\n if not (0 <= h < 24 and 0 <= m < 60):\n raise ValueError\n except ValueError:\n return \"Check your time !\"\n return f\"{((h % 12) or 12)* 30}:{(m or 60) * 6}\"", "def clock_degree(s) :\n hours, minutes = map(lambda str: int(str), s.split(':'))\n if hours < 0 or minutes < 0 or hours > 23 or minutes > 59:\n return \"Check your time !\"\n \n return str((hours % 12 or 12) * 30) + ':' + str((minutes or 60) * 6)", "def clock_degree(s):\n hour, minute = map(int, s.split(':'))\n if not (0 <= hour < 24) or minute < 0:\n return 'Check your time !'\n hour %= 12\n minute %= 60\n return '{}:{}'.format(hour * 30 or 360, minute * 6 or 360)", "def clock_degree(s) :\n h, m = map(int, s.split(':'))\n if not (0 <= h < 24 and 0 <= m < 60): return \"Check your time !\"\n return \"{}:{}\".format((h%12) * 30 or '360', m * 6 or '360')", "import re\n\ndef clock_degree(s):\n if not re.match(r'([0-1][0-9]|[2][0-3]):[0-5][0-9]', s):\n return \"Check your time !\"\n\n hr, sec = tuple(map(int, s.split(\":\")))\n hr = str((hr % 12) * 30 if hr % 12 > 0 else 360)\n sec = str(sec * 6 if sec > 0 else 360)\n return hr + \":\" + sec", "clock_degree=lambda s: (lambda h,m: \"%s:%s\" %(30*(h%12) or 360,6*m or 360) if 0<=h<=23 and 0<=m<=59 else \"Check your time !\")(*[int(a) for a in s.split(\":\")])", "def clock_degree(s) :\n hh, mm = list(map(int, s.split(':')))\n if not (0 <= hh < 24 and 0 <= mm < 60):\n return 'Check your time !'\n hh %= 12\n fix_zero = lambda theta: theta if theta != 0 else 360\n return f'{fix_zero(hh * 30)}:{fix_zero(mm * 6)}'\n", "def clock_degree(s) :\n hours, minutes = map(int, s.split(':'))\n return f\"{hours % 12 * 30 or 360}:{minutes * 6 or 360}\" if 0 <= hours < 24 and 0 <= minutes < 60 else \"Check your time !\"", "def clock_degree(s) :\n hours, minutes = map(int, s.split(':'))\n return f\"{hours % 12 * 30 if hours % 12 else 360}:{minutes * 6 if minutes % 60 else 360}\" if 0 <= hours < 24 and 0 <= minutes < 60 else \"Check your time !\""]
{"fn_name": "clock_degree", "inputs": [["01:01"], ["00:00"], ["01:03"], ["01:30"], ["12:05"], ["26:78"], ["16:25"], ["17:09"], ["19:00"], ["20:34"], ["23:20"], ["24:00"], ["-09:00"]], "outputs": [["30:6"], ["360:360"], ["30:18"], ["30:180"], ["360:30"], ["Check your time !"], ["120:150"], ["150:54"], ["210:360"], ["240:204"], ["330:120"], ["Check your time !"], ["Check your time !"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,451
def clock_degree(s) :
85a9ec5bd7b29eca11de2c55c68f68f0
UNKNOWN
You've got a bunch of textual data with embedded phone numbers. Write a function `area_code()` that finds and returns just the area code portion of the phone number. ```python >>> message = "The supplier's phone number is (555) 867-5309" >>> area_code(message) '555' ``` The returned area code should be a string, not a number. Every phone number is formatted like in the example, and the only non-alphanumeric characters in the string are apostrophes `'` or the punctuation used in the phone number.
["def area_code(text):\n return text[text.find(\"(\")+1:text.find(\")\")]", "import re\ndef area_code(text):\n return re.search(\"\\((\\d{3})\\)\", text).group(1)", "def area_code(text):\n return text[text.index('(')+1:text.index(')')]", "def area_code(text):\n # Your code goes here\n area = text.find('(')\n return text[area+1:area+4]", "def area_code(text):\n return text.split('(')[1].split(')')[0]", "def area_code(text):\n parenth1 = text.find('(')\n parenth2 = text.find(')')\n return text[parenth1+1:parenth2]", "import re\n\ndef area_code(message):\n return re.search(r'\\((\\d{3})\\)', message).group(1)", "import re\n\ndef area_code(text):\n ac = re.search('\\((\\d{3})\\)\\s\\d{3}\\-\\d{4}', text)\n return ac.group(1)", "import re\n\ndef area_code(text):\n return re.search(r'\\((\\d{3})\\)',text).group(1)", "import re\ndef area_code(text):\n return re.search(r'\\((.*)\\)',text).group(1)"]
{"fn_name": "area_code", "inputs": [["The supplier's phone number is (555) 867-5309"], ["Grae's cell number used to be (123) 456-7890"], ["The 102nd district court's fax line is (124) 816-3264"]], "outputs": [["555"], ["123"], ["124"]]}
INTRODUCTORY
PYTHON3
CODEWARS
947
def area_code(text):
1a521494454dcd5bcf15979d1891cf6f
UNKNOWN
Let's say that in a hypothetical platform that resembles Codewars there is a clan with 2 warriors. The 2nd one in ranking (lets call him **D**) wants to at least reach the honor score of his ally (lets call her **M**). *(Let's say that there is no antagonism here, he just wants to prove his ally that she should be proud to have him in the clan and sees this as the only way to achieve it! :P )* Your task is to help **D** by providing him with the **quickest path** to reach **M**'s honor score. In this hypothetical platform there are 2 kinds of kata to be solved: ``` '2kyu' worth of 1 point '1kyu' worth of 2 points ``` So if for example: ``` M has honor 11 D has honor 2 ``` **D** could reach **M`s** honor by solving kata worth of `9`. He has many options to do this: ``` Solve 9 '2kyus' (9*1 -> 9) => Solve 9 kata Solve 4 '1kyus' and 1 '2kyus' (4*2 + 1*1-> 9) => Solve 5 kata Solve 2 '1kyus' and 5 '2kyus' (2*2 + 5*1 -> 9) => Solve 7 kata etc etc... ``` The **quickest path** to reach the honor score is: ``` 4 '1kyus' and 1 '2kyus' => Solve only 5 kata ``` Create a function `getHonorPath` that accepts 2 arguments `honorScore` & `targetHonorScore` with score integers of 2 warriors and returns an object with the **quickest path** for the first one to reach the 2nd's honor. For example: ``` getHonorPath(2, 11) should return { '1kyus': 4, '2kyus': 1 } getHonorPath(20, 11) should return {} ``` **For the purpose of this kata you do not have to worry about any non-integer arguments for honor scores**
["def get_honor_path(honor, target):\n return dict(list(zip([\"1kyus\", \"2kyus\"], divmod(target - honor, 2)))) if target > honor else {}\n", "def get_honor_path(score, target):\n return {'1kyus':(target-score)//2, '2kyus':(target-score)%2} if target > score else {}", "def get_honor_path(honor_score, target_honor_score):\n k1, k2 = divmod(target_honor_score-honor_score, 2)\n return {\"2kyus\": k2, \"1kyus\": k1} if honor_score < target_honor_score else {}", "def get_honor_path(honor_score, target_honor_score):\n return {} if honor_score>=target_honor_score else {\"2kyus\":(target_honor_score-honor_score)%2,\"1kyus\":(target_honor_score-honor_score)//2}\n \n", "def get_honor_path(hs, ths):\n return {'2kyus': (ths-hs)%2, '1kyus': int((ths-hs)/2)} if ths > hs else {}", "def get_honor_path(honorScore, targetHonorScore):\n return {'1kyus': (targetHonorScore - honorScore) // 2, '2kyus': (targetHonorScore - honorScore) % 2} if targetHonorScore > honorScore else {}", "def get_honor_path(honor_score, target_honor_score):\n return {} if honor_score>=target_honor_score else {\"2kyus\" : divmod((target_honor_score-honor_score),2)[1],\"1kyus\" : divmod((target_honor_score-honor_score),2)[0] }", "def get_honor_path(honor_score, target_honor_score):\n\n honor_needed = target_honor_score - honor_score\n kyus = {}\n \n if honor_score < target_honor_score and honor_needed != 0:\n \n kyus[\"1kyus\"] = honor_needed // 2\n kyus[\"2kyus\"] = honor_needed % 2\n \n return kyus", "get_honor_path=lambda s,o:o>s and{'%skyus'%k:n for k,n in enumerate(divmod(o-s,2),1)}or{}", "def get_honor_path(h,t):\n return {k+'kyus':v for k,v in zip(\"12\", divmod(t-h, 2))} if t > h else {}"]
{"fn_name": "get_honor_path", "inputs": [[11, 2], [11, 11]], "outputs": [[{}], [{}]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,749
def get_honor_path(honor_score, target_honor_score):
5424b5f34acfe42512d31b993aa88394
UNKNOWN
The new £5 notes have been recently released in the UK and they've certainly became a sensation! Even those of us who haven't been carrying any cash around for a while, having given in to the convenience of cards, suddenly like to have some of these in their purses and pockets. But how many of them could you get with what's left from your salary after paying all bills? The programme that you're about to write will count this for you! Given a salary and the array of bills, calculate your disposable income for a month and return it as a number of new £5 notes you can get with that amount. If the money you've got (or do not!) doesn't allow you to get any £5 notes return 0. £££ GOOD LUCK! £££
["def get_new_notes(salary, bills):\n return max((salary - sum(bills)), 0) // 5", "def get_new_notes(salary,bills):\n return max((salary-sum(bills))//5, 0)", "def get_new_notes(salary,bills):\n return max(0, (salary - sum(bills)) // 5)", "def get_new_notes(salary, bills):\n disposable_income = salary - sum(bills)\n return max(disposable_income // 5, 0)", "get_new_notes = lambda s, b: max(s - sum(b), 0) // 5", "def get_new_notes(salary, bills):\n remaining = (salary - sum(bills)) // 5\n return remaining if remaining > 0 else 0\n \n", "def get_new_notes(salary,bills):\n balance = salary - sum(bills)\n return 0 if balance <= 0 else balance // 5", "def get_new_notes(salary,bills):\n tb = sum(bills)\n return int((salary-tb)/5) if salary > tb else 0\n", "def get_new_notes(salary,bills):\n for bill in bills:\n salary -= bill\n return max(int(salary/5),0)"]
{"fn_name": "get_new_notes", "inputs": [[2000, [500, 160, 400]], [1260, [500, 50, 100]], [3600, [1800, 350, 460, 500, 15]], [1995, [1500, 19, 44]], [10000, [1800, 500, 1200, 655, 150]], [2300, [590, 1500, 45, 655, 150]], [5300, [1190, 1010, 1045, 55, 10, 19, 55]], [2000, [500, 495, 100, 900]], [2000, [500, 496, 100, 900]], [2000, [500, 494, 100, 900]]], "outputs": [[188], [122], [95], [86], [1139], [0], [383], [1], [0], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
910
def get_new_notes(salary,bills):
89816a38fa0fc3fa6f68b83aacaf3a5c
UNKNOWN
Create a function that takes a number as an argument and returns a grade based on that number. Score | Grade -----------------------------------------|----- Anything greater than 1 or less than 0.6 | "F" 0.9 or greater | "A" 0.8 or greater | "B" 0.7 or greater | "C" 0.6 or greater | "D" Examples: ``` grader(0) should be "F" grader(1.1) should be "F" grader(0.9) should be "A" grader(0.8) should be "B" grader(0.7) should be "C" grader(0.6) should be "D" ```
["def grader(x):\n if 0.9 <= x <= 1: return \"A\"\n elif 0.8 <= x < 0.9: return \"B\"\n elif 0.7 <= x < 0.8: return \"C\"\n elif 0.6 <= x < 0.7: return \"D\"\n else: return \"F\"", "def grader(score):\n for limit, grade in [(0.9, \"A\"), (0.8, \"B\"), (0.7, \"C\"), (0.6, \"D\")]:\n if limit <= score <= 1:\n return grade\n return 'F'\n", "def grader(input):\n if input > 1 or input < .6:\n return 'F'\n if input >= .9:\n return 'A'\n elif input >= .8:\n return 'B'\n elif input >= .7:\n return 'C'\n elif input >= .6:\n return 'D'", "def grader(score):\n if score > 1 or score < 0.6:\n return \"F\"\n if score >= 0.9:\n return \"A\"\n if score >= 0.8:\n return \"B\"\n if score >= 0.7:\n return \"C\"\n if score >= 0.6:\n return \"D\"\n \n", "def grader(score):\n if score > 1.0: return 'F'\n if score >= 0.9: return 'A'\n if score >= 0.8: return 'B'\n if score >= 0.7: return 'C'\n if score >= 0.6: return 'D'\n return 'F'\n", "def grader(score):\n return 'F' if score > 1 or score < 0.6 else 'ABCD'[int(10 * (0.999 - score))]", "def grader(score):\n if score <= 1.0:\n if score >= 0.9:\n return \"A\"\n elif score >= 0.8:\n return \"B\"\n elif score >= 0.7:\n return \"C\"\n elif score >= 0.6:\n return \"D\"\n return \"F\"\n", "def grader(score):\n print(score)\n return 'F' if score > 1 or score < 0.6 else 'ABCD'[int(10 * (0.999 - score))]\n", "scores = ((1.01, 'F'), (.9, 'A'), (.8, 'B'), (.7, 'C'), (.6, 'D'), (0, 'F'))\n\ndef grader(score):\n return [grade for t, grade in scores if score >= t][0]\n", "def grader(score):\n return ['F', 'D', 'C', 'B', 'A'][(1>=score>.59)+(1>=score>=.9)+(1>=score>=.8)+(1>=score>=.7)]", "def grader(score):\n return 'F' if score < 0.6 or score > 1 else ['D', 'C', 'B', 'A', 'A'][int(score*10)-6]\n", "def grader(score):\n if score > 1:\n return \"F\"\n if score >= 0.9:\n return \"A\"\n if score >= 0.8:\n return \"B\"\n if score >= 0.7:\n return \"C\"\n if score >= 0.6:\n return \"D\"\n if score < 0.6:\n return \"F\"", "def grader(score):\n if score>1 or score<.6:\n return 'F'\n if score>=.9:\n return 'A'\n if score>=.8:\n return 'B'\n if score>=.7:\n return 'C'\n return 'D'\n", "def grader(score):\n grade = 'A'\n if score < 0.6 or score > 1:\n grade = 'F'\n elif score < 0.7:\n grade = 'D'\n elif score < 0.8:\n grade = 'C'\n elif score < 0.9:\n grade = 'B'\n return grade\n", "def grader(score):\n if score > 1 or score < 0.6:\n res = 'F'\n elif score >= 0.9:\n res = 'A'\n elif score >= 0.8:\n res = 'B'\n elif score >= 0.7:\n res = 'C'\n elif score >= 0.6:\n res = 'D'\n return res\n", "def grader(score):\n if score > 1:\n return \"F\"\n elif score >= 0.9:\n return \"A\"\n elif score >= 0.8:\n return \"B\"\n elif score >= 0.7:\n return \"C\"\n elif score >= 0.6:\n return \"D\"\n else:\n return \"F\"\n", "def grader(score):\n if score > 1 or score < 0.6:\n return 'F'\n elif score >= 0.9:\n return 'A'\n elif score >= 0.8:\n return 'B'\n elif score >= 0.7:\n return 'C'\n elif score >= 0.6:\n return 'D'\n", "def grader(input):\n if input > 1 or input < 0.6:\n return \"F\"\n elif input >= 0.9:\n return \"A\"\n elif input >= 0.8:\n return \"B\"\n elif input >= 0.7:\n return \"C\"\n else:\n return \"D\"\n", "grader = lambda s: 'FDCBAA'[(int(s*10)-5)*(s>=0.6 and s<=1)]", "def grader(score):\n return 'F' if score > 1 else 'A' if score >= 0.9 else 'B' if score >= 0.8 else 'C' if score >= 0.7 else 'D' if score >= 0.6 else 'F'\n", "grader = lambda s: 'FDCBAF'[sum((s>=0.6, s>=0.7, s>=0.8, s>=0.9, s>1))]", "def grader(n):\n return \"FDCBAF\"[(n>=.6) + (n>=.7) + (n>=.8) + (n>=.9) + (n>1)]", "def grader(s):\n return (s > 1 or s < 0.6) and 'F' or chr(ord('A') + int(9 - s * 10 + 0.5))", "def grader(score):\n return (\n ((score < 0.6 or score > 1) and \"F\") or\n (score < 0.7 and \"D\") or\n (score < 0.8 and \"C\") or\n (score < 0.9 and \"B\") or\n \"A\"\n )\n", "def grader(score):\n if 1 < score or 0.6 > score: return \"F\"\n if score >= 0.9: return \"A\"\n if score >= 0.8: return \"B\"\n if score >= 0.7: return \"C\"\n if score >= 0.6: return \"D\"", "def grader(score: float) -> str:\n \"\"\" Get a grade (A, B, C, D, E, F) based on given score. \"\"\"\n return \"F\" if score < 0.6 or score > 1 else \"A\" if score >= 0.9 else \"B\" if score >= 0.8 else \"C\" if score >= 0.7 else \"D\"", "def grader(s):\n if s >= 0.9 and s<=1:\n return 'A'\n elif s>=0.8 and s<0.9:\n return 'B'\n elif s>= 0.7 and s<0.8:\n return 'C'\n elif s>= 0.6 and s<0.7:\n return 'D'\n else:\n return 'F'\n", "def grader(score):\n return \"F\" if score*10 not in range(6,11) \\\n else \"A\" if score >= 0.9 \\\n else \"B\" if score >= 0.8 \\\n else \"C\" if score >= 0.7 \\\n else \"D\" ", "def grader(input):\n import math; return ['F','D','C','B','A'][min(max(math.trunc(input * 10) - 5, 0), 4)] if input <= 1 else 'F' \n", "def grader(score):\n return {'1': 'A', '0.9': 'A', '0.8': 'B', '0.7': 'C', '0.6': 'D'}.get(str(score)[:3], 'F')\n", "def grader(data):\n if data == 1:\n return \"A\"\n data = int(data * 10)\n return {6: \"D\", 7: \"C\", 8: \"B\", 9: \"A\"}.get(data, \"F\")\n", "def grader(score):\n return 'A' if score==1 else {9:'A',8:'B',7:'C',6:'D'}.get(int(score*10),'F')\n", "def grader(score):\n return 'F' if score > 1 or score < 0.6 else 'FAFFFFDCBA'[int(str(score*10)[0])]\n", "def grader(score):\n if score > 1.0 or score < 0.6:\n return 'F'\n\n for minimum, letter in zip([0.9, 0.8, 0.7, 0.6], list('ABCD')):\n if score >= minimum:\n return letter\n", "def grader(s):\n return 'ABCDF'[int(10 * (0.99-s))] if s <= 1 and s > .4 else 'F'", "grader=lambda s:\"FDCBAA\"[.5<s<=1and int(10*s)-5]", "def grader(score):\n import math\n grade = 9 - int(math.ceil(score * 10))\n if grade < -1 or grade > 4:\n grade = 4\n return ['A','B','C','D','F','A'][grade]\n", "def grader(score):\n return 'F' if score > 1 else 'A' if score >= .9 else 'B' if score >= .8 else 'C' if score >= .7 else 'D' if score >= .6 else 'F'\n", "GRADES_MAP = {6: 'D', 7: 'C', 8: 'B', 9: 'A'}\ndef grader(s):\n return GRADES_MAP.get(int(s * 10), 'A' if s == 1 else 'F') \n", "def grader(score):\n if score > 1:\n return \"F\"\n for s, g in [(.9, \"A\"), (.8, \"B\"), (.7, \"C\"), (.6, \"D\")]:\n if score >= s:\n return g\n return \"F\"\n", "def grader(input, grades=(\"A\", \"B\", \"C\", \"D\")):\n if input > 1:\n return \"F\"\n for i, x in enumerate(grades):\n if input >= (0.9 - 0.1 * i):\n return x\n return \"F\"\n", "def grader(score):\n if score < 0.6:\n return 'F'\n elif score < 0.7:\n return 'D'\n elif score < 0.8:\n return \"C\"\n elif score < 0.9:\n return \"B\"\n elif score <=1:\n return \"A\"\n elif score > 1:\n return \"F\"\n else:\n None\n print(grader(score))", "def grader(score):\n if score >= 0.9:\n if score > 1:\n return \"F\"\n return \"A\"\n elif score >= 0.8:\n return \"B\"\n elif score >= 0.7:\n return \"C\"\n elif score >= 0.6:\n return \"D\"\n else:\n return \"F\"\n", "def grader(score):\n if score < 0.6 and score > 1:\n return \"F\"\n elif score >= 0.6 and score < 0.7:\n return \"D\"\n elif score >= 0.7 and score < 0.8:\n return \"C\"\n elif score >= 0.8 and score < 0.9:\n return \"B\"\n elif score >= 0.9 and score <= 1:\n return \"A\"\n else:\n return \"F\"", "def grader(score):\n return 'A' if score >= 0.9 and score <= 1 else 'B' if score >= 0.8 and score < 0.9 else 'C' if score >= 0.7 and score < 0.8 else 'D' if score >= 0.6 and score < 0.7 else 'F'\n", "def grader(score):\n grade = None\n \n if score < 0.6 or score > 1:\n grade = 'F'\n else:\n grade = 'A'\n if score < 0.9:\n grade = 'B'\n if score < 0.8:\n grade = 'C'\n if score < 0.7:\n grade = 'D' \n \n return grade\n", "def grader(s):\n print(s)\n if s>1 or s<.6:\n return \"F\"\n if s>=.9:\n return \"A\"\n if s>=.8:\n return \"B\"\n if s>=.7:\n return \"C\"\n return \"D\"\n", "def grader(score):\n if 1 < score or score < 0.6:\n return \"F\"\n if score >= 0.9:\n return \"A\"\n elif score >= 0.8:\n return \"B\"\n elif score >= 0.7:\n return \"C\"\n elif score >= 0.6:\n return \"D\"\n", "grades = {\n 1: 'A',\n 0.9: 'A',\n 0.8: 'B',\n 0.7: 'C',\n 0.6: 'D'\n}\n\ndef grader(score):\n return grades.get(round(score, 2), 'F')\n", "def grader(score):\n if score == 0:\n return 'F'\n elif score>1 or score<0.6:\n return 'F'\n elif score>=0.6 and score <0.7:\n return 'D'\n elif score>=0.7 and score<0.8:\n return 'C'\n elif score>=0.8 and score<0.9:\n return 'B'\n elif score>=0.9 and score<1:\n return 'A'\n return 'A'\n \n \n", "def grader(score):\n puntos= float(score)\n if puntos >1 or puntos <0.6:\n return 'F'\n elif puntos >= 0.9:\n return 'A'\n elif puntos >= 0.8:\n return 'B'\n elif puntos >= 0.7:\n return 'C'\n elif puntos >= 0.6:\n return 'D'\n\n \n", "def grader(score):\n print(score)\n if score < 0.6 or score > 1:\n return 'F'\n elif 0.9 <= score <= 1:\n return 'A'\n elif 0.8 <= score < 0.9:\n return 'B'\n elif 0.7 <= score < 0.8:\n return 'C'\n elif 0.6 <= score < 0.7:\n return 'D'\n \n", "def grader(s):\n if s > 1 or s < 0.6:\n return \"F\"\n elif 1 >= s >= 0.9: \n return \"A\"\n elif 0.9 > s >= 0.8: \n return \"B\"\n elif 0.8 > s >= 0.7: \n return \"C\"\n else:\n return \"D\"", "def grader(s):\n if s >=0.9 and s<=1: return 'A'\n if s >=0.8 and s<0.9: return 'B'\n if s >=0.7 and s<0.8: return 'C'\n if s >=0.6 and s<0.7: return 'D'\n return 'F'\n", "def grader(score):\n print(score)\n \n return 'F' if score > 1 or score < 0.6 else 'AABCD'[int(10-score*10)]", "def grader(m):\n return ['F','D','C','B','A','F'][(m>=0.6)+(m>=0.7)+(m>=0.8)+(m>=0.9)+(m>1)]\n", "def grader(score):\n if score > 1 or score < 0.6:\n return 'F'\n elif score >= 0.9:\n return 'A'\n elif score >= 0.8:\n return 'B'\n elif score >= 0.7:\n return 'C'\n elif score >= 0.6:\n return 'D'\n else:\n pass\n", "def grader(score):\n if float(score) >= 0.9 and float(score) <= 1:\n return \"A\"\n if float(score) >= 0.8 and float(score) < 0.9:\n return \"B\"\n if float(score) >= 0.7 and float(score) < 0.8:\n return \"C\"\n if float(score) >= 0.6 and float(score) < 0.7:\n return \"D\"\n return \"F\"", "ans='FFFFFFDCBA'\ndef grader(score):\n s = int(round(score/0.1))\n try:\n return ans[s]\n except:\n if score == 1:\n return 'A'\n return 'F'", "def grader(score):\n if score < 0.6 or 1 < score:\n return \"F\"\n elif 0.9 <= score:\n return \"A\"\n elif 0.8 <= score:\n return \"B\"\n elif 0.7 <= score:\n return \"C\"\n elif 0.6 <= score:\n return \"D\"", "def grader(score):\n grade = float(score)\n if grade >1.0 or grade < 0.6:\n return \"F\"\n elif grade >= 0.9:\n return \"A\"\n elif grade >= 0.8:\n return \"B\"\n elif grade >= 0.7:\n return \"C\"\n elif grade >= 0.6:\n return \"D\"\n", "def grader(score):\n print(score)\n return {0.6: 'D', 0.7: 'C', 0.8: 'B', 0.9: 'A', 1:'A', 1.1: 'F'}.setdefault(score, 'F')\n", "def grader(s):\n print(s)\n if s <= 0.5 or s> 1.0 : return 'F'\n elif s >= 0.9 : return 'A'\n elif s >= 0.8 : return 'B'\n elif s >= 0.7 : return 'C'\n elif s >= 0.6 : return 'D'\n else : return 'F'\n", "def grader(score):\n \"\"\"\n A function that takes a number as an argument and returns a grade based on that number.\n \n Score Grade\n Anything greater than 1 or less than 0.6 \"F\"\n 0.9 or greater \"A\"\n 0.8 or greater \"B\"\n 0.7 or greater \"C\"\n 0.6 or greater \"D\"\n \"\"\"\n \n return 'F' if score > 1 or score < .6 else {6:'D',7:'C',8:'B',9:'A',10:'A'}.get(int(score*10))\n", "def grader(score):\n if score<0.6 or score>1:\n return 'F'\n if score>=0.6 and score<0.7:\n return 'D'\n if score>=0.7 and score<0.8:\n return 'C'\n if score>=0.8 and score<0.9:\n return 'B'\n if score>=0.9:\n return 'A'\n", "def grader(score):\n if score <= 1 and score >= 0.9:\n return \"A\"\n elif score < .9 and score >= 0.8:\n return \"B\"\n elif score < .8 and score >= 0.7:\n return \"C\"\n elif score < .7 and score >= 0.6:\n return \"D\"\n else:\n return \"F\"\n", "def grader(score):\n grade = 'F'\n if 1 >= score >= 0.9 :\n grade = 'A'\n elif 0.9 > score >= 0.8:\n grade = 'B'\n elif 0.8 > score >= 0.7:\n grade = 'C'\n elif 0.7 > score >= 0.6:\n grade = 'D'\n return grade\n", "def grader(score):\n if score > 1 or score < 0.6:\n return 'F'\n if score == 0.9:\n return 'A'\n if score == 0.8:\n return 'B'\n if score == 0.7:\n return 'C'\n if score == 0.6:\n return 'D'\n return 'A'", "def grader(score):\n return {10: \"A\", 9: \"A\", 8: \"B\", 7: \"C\", 6: \"D\"}.get(int(score * 10), \"F\") if score <= 1 else \"F\"\n", "def grader(score):\n \n if score > 1 or score < 0.6:\n return \"F\"\n elif score == 0.9 or score == 1:\n return \"A\"\n elif score == 0.8:\n return \"B\"\n elif score == 0.7:\n return \"C\"\n elif score == 0.6:\n return \"D\"\n", "def grader(score):\n if score == 0 or score > 1:\n return \"F\"\n elif score >= 0.9:\n return \"A\"\n elif score >= 0.8:\n return \"B\"\n elif score >= 0.7:\n return \"C\"\n elif score >= 0.6:\n return \"D\" \n else:\n return \"F\"", "qualification = {\n 1 : \"A\",\n 0.9 : \"A\",\n 0.8 : \"B\",\n 0.7 : \"C\",\n 0.6 : \"D\"\n }\n\ndef grader(score):\n if score in qualification:\n return qualification.get(score)\n return \"F\"\n \n", "def grader(score):\n print(score)\n if score < 0.6 : return \"F\"\n if score < 0.7 : return \"D\"\n if score < 0.8 : return \"C\"\n if score < 0.9 : return \"B\"\n if score > 1 : return \"F\" #seriously ...\n return \"A\"\n \n", "def grader(score):\n grades=\"FFFFFFDCBAA\"\n return grades[int(score*10)] if score <= 1 else \"F\"\n", "def grader(score):\n return ('F', 'D', 'C', 'B', 'A')[(score <= 1) * ((score >= 0.6) + (score >= 0.7) + (score >= 0.8) + (score >= 0.9))]", "def grader(score):\n print(score)\n grade = \"F\"\n if score > 1:\n grade = \"F\"\n elif score >= 0.9:\n grade = \"A\"\n elif score >= 0.8:\n grade = \"B\"\n elif score >= 0.7:\n grade = \"C\"\n elif score >= 0.6:\n grade = \"D\"\n \n return grade\n", "def grader(score):\n \n return {\n (score < 0.6 or score > 1): \"F\",\n (score >= 0.6 and score < 0.7): \"D\",\n (score >= 0.7 and score < 0.8): \"C\",\n (score >= 0.8 and score < 0.9): \"B\",\n (score >= 0.9 and score <= 1): \"A\"\n \n }[True]\n\n", "def grader(score):\n if score < 0.6 or score > 1:\n return 'F'\n if 0.6 <= score < 0.7:\n return 'D'\n if 0.7 <= score < 0.8:\n return 'C'\n if 0.8 <= score < 0.9:\n return 'B'\n return 'A'", "def grader(score):\n if 0.7 > score >= 0.6:\n return \"D\"\n elif 0.8 > score >= 0.7:\n return \"C\"\n elif 0.9 > score >= 0.8:\n return \"B\"\n elif 1 >= score >= 0.9:\n return \"A\"\n return \"F\"\n \n", "def grader(score):\n return \"D\" if score >= 0.6 and score < 0.7 else \"C\" if score >= 0.7 and score < 0.8 else \"B\" if score >= 0.8 and score < 0.9 else \"A\" if score >= 0.9 and score <= 1 else \"F\"", "def grader(score):\n if 1 >= score >= 0.9: score = 'A'\n elif 0.9 > score >= 0.8: score = 'B'\n elif 0.8 > score >= 0.7: score = 'C'\n elif 0.7 > score >= 0.6: score = 'D'\n else: score = 'F'\n return score\n", "def grader(score: int):\n if score > 1:\n return 'F'\n elif score >= .9:\n return 'A'\n elif score >= .8:\n return 'B'\n elif score >= .7:\n return 'C'\n elif score >= .6:\n return 'D'\n else:\n return 'F'\n", "grader=lambda s:'F' if s>1 or s<0.6 else 'A' if s>=0.9 else 'B' if s>=0.8 else 'C' if s>=0.7 else 'D' \n", "def grader(score):\n if 0.9 <= score <= 1:\n return 'A'\n elif 0.8 <= score < 0.9:\n return 'B'\n elif 0.7 <= score < 0.8:\n return 'C'\n elif 0.6 <= score < 0.7:\n return 'D'\n elif score > 1 or score < 0.6:\n return 'F'", "def grader(score):\n grade = 'FFFFFFDCBAA'\n return grade[int(score * 10)] if score <= 1 else 'F'\n", "def grader(score):\n if 1 < score or score < 0.6:\n return 'F'\n if score >= 0.9:\n return 'A'\n if score == 0.8:\n return 'B'\n if score == 0.7:\n return 'C'\n if score == 0.6:\n return 'D'\n \n", "grader = lambda score: {6: 'D', 7: 'C', 8: 'B', 9: 'A'}.get(int(score * 10), 'F') if score != 1 else 'A'", "def grader(s):\n return s > 1 and 'F' or \\\n 0.9 <= s <= 1 and 'A' or \\\n 0.8 <= s < 0.9 and 'B' or \\\n 0.7 <= s < 0.8 and 'C' or \\\n 0.6 <= s < 0.7 and 'D' or \\\n s < 0.6 and 'F'\n \n", "def grader(score):\n\n result=\"F\"\n if score>=0.6 and score <0.7:\n result=\"D\"\n elif score>=0.7 and score <0.8:\n result=\"C\" \n elif score>=0.8 and score <0.9:\n result=\"B\" \n elif score>=0.9 and score <=1.0:\n result=\"A\" \n else:\n result=\"F\"\n \n return result \n", "def grader(score):\n if score > 1:\n return \"F\"\n elif score > 0.89:\n return \"A\"\n elif score > 0.79:\n return \"B\"\n elif score > 0.69:\n return \"C\"\n elif score > 0.59:\n return \"D\"\n elif score < 0.58:\n return \"F\"", "def grader(score):\n return \"FFFFFFDCBAA\"[int(score * 10)] if score <= 1 else \"F\"\n", "def grader(score):\n fixed = int(score * 10)\n dict = {6:\"D\", 7:\"C\", 8:\"B\", 9:\"A\"}\n return dict.get(fixed, \"F\") if score != 1 else \"A\"\n", "def grader(score):\n score *= 10\n return 'DCBAA'[int(score-6)] if 6 <= score <= 10 else 'F'", "def grader(score):\n if 0.6 > score or score > 1:\n return \"F\"\n if score >= 0.9:\n return \"A\"\n if score >= 0.8:\n return \"B\"\n if score >= 0.7:\n return \"C\"\n if score >= 0.6:\n return \"D\"", "def grader(score):\n if score < 0.6:\n return 'F'\n if score > 1:\n return 'F'\n if score == 0.9:\n return 'A'\n if score == 1:\n return 'A'\n if score == 0.8:\n return 'B'\n if score == 0.7:\n return 'C'\n if score == 0.6:\n return 'D'\n", "def grader(score):\n if score < 0.6 or score > 1:\n return 'F'\n elif 0.9 <= score <= 1:\n return 'A'\n elif score >= 0.8:\n return 'B'\n elif score >= 0.7:\n return 'C'\n elif score >= 0.6:\n return 'D'", "def grader(n):\n return 'F' if n > 1 or n < .6 else 'A' if n >= .9 else 'B' if n >= .8 else 'C' if n >= .7 else 'D'", "def grader(s):\n return \"F\" if s<0.6 or s>1 else \"A\" if s>=0.9 else \"B\" if s>=0.8 else \"C\" if s>=0.7 else \"D\" if s>=0.6 else 'F'\n", "def grader(s):\n if s > 1:\n return \"F\"\n if s >= 0.9:\n return 'A'\n if s >= 0.8:\n return \"B\"\n if s >= 0.7:\n return \"C\"\n if s >= 0.6:\n return \"D\"\n else: \n return \"F\"\n \n", "def grader(score):\n rez = int(score*100)\n if rez > 100 or rez < 60:\n return 'F'\n elif 90 <= rez <=100:\n return 'A'\n elif 80 <= rez < 90:\n return 'B'\n elif 70 <= rez < 80:\n return 'C'\n elif 60 <= rez < 70:\n return 'D'\n"]
{"fn_name": "grader", "inputs": [[1], [1.01], [0.2], [0.7], [0.8], [0.9], [0.6], [0.5], [0]], "outputs": [["A"], ["F"], ["F"], ["C"], ["B"], ["A"], ["D"], ["F"], ["F"]]}
INTRODUCTORY
PYTHON3
CODEWARS
21,123
def grader(score):
a31aca0380827d0746f9dd4631b70463
UNKNOWN
Create a function named `divisors`/`Divisors` that takes an integer `n > 1` and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime' (`null` in C#) (use `Either String a` in Haskell and `Result, String>` in Rust). #### Example: ```python divisors(12); #should return [2,3,4,6] divisors(25); #should return [5] divisors(13); #should return "13 is prime" ```
["def divisors(num):\n l = [a for a in range(2,num) if num%a == 0]\n if len(l) == 0:\n return str(num) + \" is prime\"\n return l", "def divisors(integer):\n a = []\n for i in range(2, integer):\n if integer % i == 0:\n a.append(i)\n return a if a else str(integer) + \" is prime\"", "def divisors(integer):\n return [n for n in range(2, integer) if integer % n == 0] or '{} is prime'.format(integer)\n", "import math\ndef divisors(n):\n o = [i for i in range(2, int(math.ceil(n/2)+1)) if n%i==0]\n return o if len(o) > 0 else \"%d is prime\" % n", "def divisors(integer):\n\n lst = []\n for i in range(2,integer):\n if integer % i == 0:\n lst.append(i)\n \n if len(lst) == 0:\n return \"%s is prime\" % (integer)\n else:\n return lst", "def divisors(n):\n \n divs = set()\n \n for t in range(2, int(n ** 0.5) + 1):\n div, mod = divmod(n, t)\n \n if mod==0:\n divs.add(t)\n divs.add(div)\n \n return '{:d} is prime'.format(n) if len(divs)==0 else sorted(list(divs))", "def divisors(n):\n result = [i for i in range(2,n) if n%i==0]\n return result if result else str(n)+' is prime'", "from numpy import arange\n\ndef divisors(integer):\n # generate array of integers from 2 to integer/2 (rounded down)\n potential_divisors = arange(2, integer//2 + 1)\n # use boolean indexing to extract divisors\n divisors = potential_divisors[integer % potential_divisors == 0]\n # check divisors exist and if not return prime message\n if len(divisors):\n return list(divisors)\n else:\n return '{integer} is prime'.format(integer=integer)"]
{"fn_name": "divisors", "inputs": [[15], [253], [24], [13], [3], [29]], "outputs": [[[3, 5]], [[11, 23]], [[2, 3, 4, 6, 8, 12]], ["13 is prime"], ["3 is prime"], ["29 is prime"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,677
def divisors(integer):
e0cdfe2116f8326104a46b1edf9e913b
UNKNOWN
In this Kata, you will be given a string that may have mixed uppercase and lowercase letters and your task is to convert that string to either lowercase only or uppercase only based on: * make as few changes as possible. * if the string contains equal number of uppercase and lowercase letters, convert the string to lowercase. For example: ```Haskell solve("coDe") = "code". Lowercase characters > uppercase. Change only the "D" to lowercase. solve("CODe") = "CODE". Uppercase characters > lowecase. Change only the "e" to uppercase. solve("coDE") = "code". Upper == lowercase. Change all to lowercase. ``` More examples in test cases. Good luck! Please also try: [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2) [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)
["def solve(s):\n return s.upper() if sum(map(str.isupper, s)) * 2 > len(s) else s.lower()", "def solve(s):\n upper = 0\n lower = 0\n \n for char in s:\n if char.islower():\n lower += 1\n else:\n upper += 1\n \n if upper == lower or lower > upper:\n return s.lower()\n else:\n return s.upper()", "def solve(s):\n lower_case = [l for l in s if l.islower()]\n upper_case = [l for l in s if l.isupper()]\n \n if len(upper_case) > len(lower_case):\n return s.upper()\n return s.lower()\n", "def solve(s):\n n = len(s) // 2\n upper_count = 0\n for c in s:\n if c.isupper():\n upper_count += 1\n if upper_count > n:\n return s.upper()\n return s.lower()", "def solve(s):\n return (s.lower, s.upper)[sum(map(str.isupper, s)) > len(s) / 2]()", "def solve(s):\n return s.upper() if sum(i.isupper() for i in s) > len(s) / 2 else s.lower()\n", "def solve(s):\n return s.lower() if sum(1 for i in s if i in \"abcdefghijklmnopqrstuvwxyz\") >= len(s) / 2 else s.upper()", "def solve(s):\n \n count_upper = 0;\n count_lower = 0;\n \n for i in range(len(s)): \n if s[i].isupper() == True:\n count_upper += 1\n else:\n count_lower += 1\n \n if (count_upper > (len(s)/2 +1)) or (count_lower >= (len(s)/2 + 1) ):\n break\n \n result = ''\n\n if count_lower < count_upper :\n result = s.upper() \n else:\n result = s.lower()\n \n return result\n", "def solve(s):\n counter = 0\n for char in s:\n if char.isupper():\n counter += 1\n print(counter)\n return s.lower() if counter <= len(s)/2 else s.upper()", "def solve(s):\n l = 0\n u = 0\n for x in s:\n if x.islower():\n l += 1\n else:\n u += 1\n if l >= u:\n return s.lower()\n else:\n return s.upper()", "def solve(s):\n u,l=0,0\n for i in s:\n if i.isupper():\n u+=1\n else:\n l+=1\n return s.lower() if l>=u else s.upper() ", "def solve(s):\n return s.upper() if sum(1 for c in s if c.isupper()) > len(s)/2 else s.lower()", "def solve(s):\n return s.upper() if sum(1 for c in s if c.isupper()) > sum(1 for c in s if c.islower()) else s.lower()\n", "def solve(s):\n return s.lower() if sum([1 for c in s if c.islower()]) >= sum([1 for c in s if c.isupper()]) else s.upper()", "def solve(s):\n up=[]\n low=[]\n for i in s:\n if i.isupper():\n up.append(i)\n else:\n low.append(i)\n if len(low)>len(up):\n return s.lower()\n elif len(low)<len(up):\n return s.upper()\n else:\n return s.lower()\n", "def solve(s):\n if sum(c.isupper() for c in s) > sum(c.islower() for c in s):\n return s.upper()\n else:\n return s.lower()", "def solve(s):\n count_u = 0\n count_l = 0\n for letter in s:\n if letter.isupper():\n count_u += 1\n elif letter.islower():\n count_l += 1\n if count_u > count_l:\n return s.upper()\n else:\n return s.lower()", "def solve(a):\n b= 0\n m= 0 \n for i in range(len(a)):\n if a[i] == a[i].lower() :\n m += 1\n else :\n b += 1\n if m>=b :\n return a.lower()\n else :\n return a.upper()", "def solve(s):\n uppercount = 0\n for i in s:\n if i.isupper():\n uppercount += 1\n if uppercount > len(s)/2:\n s = s.upper()\n else:\n s = s.lower()\n return s", "def solve(s):\n upper = sum(1 for c in s if c.isupper())\n lower = sum(1 for c in s if c.islower())\n return s.lower() if lower >= upper else s.upper()", "def solve(s):\n l = len([c for c in s if c.islower()])\n u = len(s) - l\n return s.upper() if u > l else s.lower()", "def solve(s):\n n = len(s) // 2\n up = 0\n for i in s:\n if i.isupper():\n up += 1\n if up > n:\n return s.upper()\n return s.lower()", "def solve(s):\n return (s.lower(), s.upper())[len(s) > sum(map(str.islower, s)) * 2]", "from string import ascii_lowercase\n\n\ndef solve(s):\n lowercase_counter = 0\n uppercase_counter = 0\n half_length = len(s) / 2\n for letter in s:\n if letter in ascii_lowercase:\n lowercase_counter += 1\n if lowercase_counter > half_length:\n return s.lower()\n else:\n uppercase_counter += 1\n if uppercase_counter > half_length:\n return s.upper()\n return s.lower()", "def solve(s):\n return s.lower() if sum(map(str.islower, s)) >= sum(map(str.isupper, s)) else s.upper()", "def solve(s):\n return s.lower() if sum(1 for a in s if a.islower()) >= sum(1 for a in s if a.isupper()) else s.upper()", "def solve(s):\n return (s.lower(), s.upper())[sum(1 if x.isupper() else -1 for x in s) > 0]", "def solve(s): \n return s.upper()if len(s)/2>len([i for i in range(len(s))if s[i].islower()])else s.lower() \n", "def solve(s):\n return s.upper()if sum(c.islower()for c in s)<len(s)/2 else s.lower()", "def solve(s):\n bcount=0\n i =0\n acount =0\n while i < len(s):\n if s[i].isupper():\n acount+=1\n i+=1\n \n \n elif s[i].islower():\n bcount+=1\n i +=1\n \n if bcount >= acount:\n print(bcount)\n return s.lower()\n \n if acount > bcount:\n \n return s.upper()\n else:\n return s.lower()\n \n \n \n \n", "def solve(s):\n upper = 0\n lower = 0\n for i in s:\n if i.isupper() == True:\n upper += 1\n else:\n lower += 1 \n if upper > lower:\n s = s.upper()\n else:\n s = s.lower()\n return(s)\n\n", "solve = lambda s: s.lower() if sum(c.isupper() for c in s) <= len(s)/2 else s.upper()", "def solve(s):\n l = 0\n h = 0\n for i in s:\n if ord(i) < 91:\n h += 1\n else:\n l +=1\n return s.upper() if h>l else s.lower()", "solve=lambda s: s.upper() if len([l for l in s if ord(l)>64 and ord(l)<91])>len(s)//2 else s.lower()", "solve = lambda s:getattr(s,[\"lower\",\"upper\"][sum(map(str.isupper, s))>len(s)//2])()", "def solve(s):\n upr = 0\n lwr = 0\n for i in s:\n if i.isupper():\n upr += 1\n else:\n lwr += 1\n if upr > lwr:\n return s.upper()\n else:\n return s.lower()", "def solve(s): return s.lower() if (len(list(filter(lambda x: x.islower(),s)))) * 2 >= len(s) else s.upper()", "def solve(s):\n lcase,ucase=0,0\n for i in s:\n if i.isupper():\n ucase=ucase+1\n else:\n lcase=lcase+1\n return s.lower() if lcase>=ucase else s.upper()\n", "def solve(s):\n up = 0\n down = 0\n \n for str in s:\n if str.isupper()==True:\n up = up + 1\n else:\n down = down + 1\n \n if up > down:\n string = s.upper()\n \n else:\n string = s.lower()\n \n return string\n \n \n", "def solve(s):\n \n up = 0\n down = 0\n for str in s: \n if str.isupper():\n up = up + 1\n \n else:\n down = down + 1\n \n if up > down:\n string = s.upper()\n \n else:\n string =s.lower()\n \n return string", "def solve(s):\n lower_count=0\n for i in s:\n if i.islower():\n lower_count += 1\n if 2*lower_count >=len(s):\n return s.lower()\n return s.upper()", "import string\ndef solve(s):\n return s.lower() if [(l in string.ascii_lowercase) for l in s].count(True)>=len(s)//2 else s.upper()", "\ndef solve(s):\n lower=0\n for x in s:\n if x.islower():\n lower +=1\n upper=0\n for x in s:\n if x.isupper():\n upper +=1\n if lower >= upper:\n return s.lower()\n else:\n return s.upper()\n\n# lower = sum(1 for x in s if x.islower())\n# upper = sum(1 for x in s if x.isupper())\n# return s.lower() if lower>=upper else s.upper()\n", "def solve(s):\n return s.upper() if sum([1 for x in s if x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'])>len(s)/2 else s.lower()", "def solve(s):\n lower_case = [i for i in s if i.islower()]\n upper_case = [i for i in s if i.isupper()]\n return s.lower() if len(lower_case) >= len(upper_case) else s.upper() ", "import string\n\ndef solve(s):\n low, up = string.ascii_lowercase, string.ascii_uppercase\n l_c, u_c = 0, 0\n for c in s:\n if c in low:\n l_c +=1\n else:\n u_c += 1\n if l_c >= u_c:\n return s.lower()\n elif l_c < u_c:\n return s.upper()", "def solve(s):\n if s.islower() or s.isupper():\n return s\n else:\n if len([i for i in s if i.isupper()]) > len([i for i in s if i.islower()]):\n return s.upper()\n else:\n return s.lower()", "def solve(s):\n \n lowercount = 0\n uppercount = 0\n\n for x in s:\n for y in x:\n if y.islower():\n lowercount = lowercount + 1\n if y.isupper():\n uppercount = uppercount + 1\n print(y)\n \n if lowercount >= uppercount:\n s = s.lower()\n if lowercount < uppercount:\n s = s.upper()\n \n return s\n \n \n \n", "def solve(s):\n i=j=0\n i=len([i+1 for a in [*s] if a.isupper()])\n j=len([j+1 for a in [*s] if a.islower()])\n return s.lower() if i<j or i==j else s.upper()\n", "def solve(s):\n upper = 0\n lower = 0\n for letter in s:\n if letter.isupper():\n upper += 1\n else:\n lower += 1\n if upper == lower:\n return s.lower()\n elif upper > lower:\n return s.upper()\n else:\n return s.lower()", "def solve(s):\n upperS = 0\n lowerS = 0\n \n for letter in s:\n if letter.islower():\n lowerS +=1\n else:\n upperS += 1\n if upperS > lowerS:\n return s.upper()\n else:\n return s.lower()", "def solve(s):\n up = 0\n for c in s:\n if c.isupper():\n up += 1\n if up > len(s)/2:\n return s.upper()\n else:\n return s.lower()", "def count_characters(s):\n '''\n Returns 0 if more lowercase, 1 if more uppercase\n '''\n uppercase = 0\n lowercase = 0\n \n for i in range(len(s)):\n if s[i].islower():\n lowercase += 1\n else:\n uppercase += 1\n \n if uppercase > lowercase:\n return 1\n else:\n return 0\n\ndef solve(s):\n if count_characters(s) == 1:\n return s.upper()\n else:\n return s.lower()", "def solve(s):\n \n s_list = list(s)\n count_lower = 0\n count_upper = 0\n \n for i in s_list:\n if i.islower() == True:\n count_lower += 1\n else:\n count_upper += 1\n \n if count_lower < count_upper:\n return s.upper()\n else:\n return s.lower()", "def solve(s):\n countlow = 0\n countupp = 0\n for letter in s:\n if letter.isupper():\n countupp+=1\n elif letter.islower():\n countlow+=1\n \n return s.lower() if countlow-countupp>=0 else s.upper()", "def solve(s):\n low_cnt = 0\n up_cnt = 0\n temp = list(s)\n for item in temp:\n if(item.islower()): low_cnt += 1\n else: up_cnt += 1\n if(low_cnt >= up_cnt):\n return s.lower()\n else:\n return s.upper()", "def solve(s):\n upper, lower = [], []\n\n for w in s:\n if w.isupper():\n upper.append(w)\n else:\n lower.append(w)\n\n if len(upper) == len(lower) or len(upper) < len(lower):\n return s.lower()\n else:\n return s.upper()", "def solve(s):\n l = sum(map(lambda x: x.islower(), s))\n u = len(s) - l\n \n if l >= u:\n return(s.lower())\n else:\n return(s.upper())", "def solve(s):\n \n up, lw = 0,0\n \n for i in s:\n if i.isupper():\n up+=1\n else:\n lw+=1\n \n if lw >= up:\n return s.lower()\n \n else:\n return s.upper()", "def solve(s):\n UpperChars = 0\n LowerChars = 0\n\n for i in s:\n Checked_i = i.isupper()\n\n if Checked_i is True:\n UpperChars += 1\n else:\n LowerChars += 1\n\n if UpperChars > LowerChars:\n s = s.upper()\n elif LowerChars > UpperChars or LowerChars == UpperChars:\n s = s.lower()\n\n return s", "def solve(s):\n n = 0\n for i in s:\n n += int(i.isupper())\n if n > len(s) // 2:\n return s.upper()\n else:\n return s.lower()\n", "def solve(s):\n num_upper = sum([1 for ch in s if ch.isupper()])\n num_lower = sum([1 for ch in s if ch.islower()])\n if num_upper > num_lower:\n return s.upper()\n return s.lower()", "def solve(s):\n ups = 0\n lows = 0\n for i in s:\n if i == i.upper():\n ups += 1\n else:\n lows += 1\n if ups == lows or lows > ups:\n return s.lower()\n return s.upper()", "def solve(s):\n l = 0\n u = 0\n \n for i in s:\n if i.islower():\n l += 1\n else:\n u += 1\n if l > u:\n return s.lower()\n elif u > l:\n return s.upper()\n elif u == l:\n return s.lower()", "solve=lambda s:[s.upper,s.lower][sum(1 if ord(c)<96 else -1 for c in s)<=0]()", "def solve(s):\n list1 = [char for char in s]\n \n upperlist = [letter for letter in list1 if letter.isupper()]\n lowerlist = [letter for letter in list1 if letter.islower()]\n \n if len(lowerlist) >= len(upperlist):\n return s.lower()\n else:\n return s.upper()", "def solve(s):\n upper = sum(1 for c in s if c.isupper())\n lower = len(s) - upper\n return s.upper() if(upper > lower) else s.lower()", "def solve(s):\n lower_count = 0 \n upper_count = 0\n for char in s:\n if char.islower():\n lower_count += 1\n if char.isupper():\n upper_count += 1\n if upper_count > lower_count:\n return s.upper()\n if lower_count >= upper_count:\n return s.lower()", "def solve(s):\n list_1=[char for char in s]\n x=0\n for c in [char for char in s]:\n if c.isupper():\n x=x+1\n if x>len(s)/2:s=s.upper()\n else:s=s.lower()\n return s", "def solve(s):\n u = 0\n l = 0\n for letter in s:\n if letter.isupper():\n u += 1\n else:\n l += 1\n if l >= u:\n return s.lower()\n return s.upper()", "def solve(s):\n u = 0\n l = 0\n for letter in s:\n if letter.isupper():\n u += 1\n else:\n l += 1\n if l >= u:\n return s.lower()\n else:\n return s.upper()\n", "def solve(s):\n low =0\n up = 0\n for i in s:\n if i.islower():\n low+=1\n else:\n up+=1\n if up > low:\n return s.upper()\n return s.lower()", "def solve(s):\n \n countU = 0\n countL = 0\n for x in s:\n if x.isupper():\n countU += 1\n else:\n countL +=1\n \n if countU > countL:\n return s.upper()\n \n else:\n return s.lower()\n", "def solve(s):\n cup, clw = 0, 0\n for c in s:\n if c.isupper():\n cup += 1\n if cup > len(s) / 2 :\n return s.upper()\n else:\n clw += 1\n if clw > len(s) / 2:\n return s.lower()\n else:\n return s.lower()", "def solve(s):\n c=0\n for x in s:\n if x.isupper():\n c=c+1\n if c>len(s)/2:\n return s.upper()\n return s.lower()\n", "def solve(s):\n case = 0\n for char in s:\n if char.isupper():\n case += 1\n else:\n case -= 1\n if case > 0:\n return s.upper()\n else:\n return s.lower()", "def solve(s):\n a = sum([int(c.islower()) for c in s])\n b = sum([int(c.isupper()) for c in s])\n if a<b:\n return s.upper()\n else:\n return s.lower()\n", "def solve(s):\n upper_count = 0\n lower_count = 0\n for c in s:\n if c.isupper():\n upper_count += 1\n else:\n lower_count += 1\n return s.lower() if lower_count >= upper_count else s.upper()\n", "def solve(s):\n res = 0\n for i in [x for x in s]:\n if i.isupper():\n res += 1\n else:\n res -= 1\n return s.lower() if res <= 0 else s.upper() ", "def solve(s):\n upper = 0\n lower = 0\n for i in s:\n if i.isupper():\n upper += 1\n else:\n lower += 1\n if upper == lower:\n return s.lower()\n elif upper > lower:\n return s.upper()\n else:\n return s.lower()", "def solve(s):\n big = 0\n small = 0\n \n for x in s:\n if 65 <= ord(x) <= 90: big += 1\n else: small += 1\n \n return s.lower() if small >= big else s.upper()", "def solve(msg):\n l = 'abcdefghijklmnopqrstuvwxyz'\n U = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n msg = list(msg)\n lc,Uc = 0,0\n for i in range(len(msg)):\n if msg[i] in l:\n lc += 1\n if msg[i] in U:\n Uc += 1\n if lc > Uc or lc == Uc:\n return ''.join(msg).lower()\n else:\n return ''.join(msg).upper()\n", "def solve(s):\n string = \"\"\n upper = 0\n lower = 0\n for letters in range(len(s)):\n if s[letters].isupper():\n upper += 1\n else:\n lower += 1\n if upper > lower:\n string += s.upper()\n else:\n string += s.lower()\n return string", "def solve(s):\n x = list(s)\n upper = 0\n lower = 0\n \n for y in x:\n if y.isupper() == True:\n upper = upper + 1\n else:\n lower = lower + 1\n \n if upper > lower:\n return s.upper()\n else:\n return s.lower()", "def solve(s):\n score = 0\n for l in list(s):\n score += 1 if l.isupper() else -1\n return s.upper() if score > 0 else s.lower()\n", "def solve(s):\n sum_low = 0\n sum_upp = 0\n for el in s:\n if el == el.lower():\n sum_low +=1\n elif el == el.upper():\n sum_upp +=1\n if sum_low >= sum_upp:\n return s.lower()\n else:\n return s.upper()\n", "def solve(s):\n upper_count = 0\n lower_count = 0\n for letter in s:\n # Gets a count of the upper and lower case letters in the string\n if letter.isupper():\n upper_count += 1\n if letter.islower():\n lower_count += 1\n # If there are more uppercase letters, return the string in all uppercase\n if upper_count > lower_count:\n return s.upper()\n # If we reached this line then there aren't more uppercase letters\n # So return the string in all lowercase\n return s.lower()", "def solve(s):\n count_lower = len([c for c in s if c.islower()])\n count_upper = len([c for c in s if c.isupper()])\n if count_lower < count_upper:\n return s.upper()\n elif count_lower >= count_upper:\n return s.lower()\n \n", "import string\ndef solve(s):\n sum = 0\n for i in range(len(s)):\n if s[i] in string.ascii_lowercase:\n sum+=1\n return s.lower() if sum>= len(s)/2 else s.upper()", "def solve(s):\n s_upper=s.upper()\n s_lower=s.lower()\n \n if s==s_upper:\n return s\n elif s==s_lower:\n return s\n \n lower_change=0\n upper_change=0\n for i in range(0,len(s)):\n if s_upper[i]!=s[i]:\n upper_change+=1\n if s_lower[i]!=s[i]:\n lower_change+=1\n if upper_change<lower_change:\n return s_upper\n return s_lower", "def solve(s):\n u = 0\n l = 0\n for x in s:\n if x.isupper():\n u+=1\n else:\n l+=1\n if l>=u:\n return s.lower()\n return s.upper()", "def solve(s):\n import string\n lower_alphabet = list(string.ascii_lowercase)\n upper_alphabet = list(string.ascii_uppercase)\n count_lower = 0\n count_upper = 0\n for i in s:\n if i in lower_alphabet:\n count_lower = count_lower + 1\n elif i in upper_alphabet:\n count_upper = count_upper + 1 \n if count_lower >= count_upper:\n s = s.lower()\n else:\n s = s.upper()\n return(s)", "def solve(s):\n l=0\n z=0\n for b in s:\n if b.islower():\n l+=1\n else:\n z+=1\n if l>=z:\n return s.lower()\n else:\n return s.upper()", "def solve(s):\n\n lower_count = 0\n for i in range(len(s)):\n if (s[i].islower()):\n lower_count += 1\n\n upper_count = len(s) - lower_count\n if (lower_count < upper_count):\n\n return s.upper()\n\n return s.lower()\n", "def solve(s):\n up = 0\n low = 0\n \n for letter in s:\n if letter.islower():\n low += 1\n else:\n up += 1\n \n if low < up:\n return s.upper()\n else:\n return s.lower()", "def solve(s):\n up = ['A', 'B', 'C', 'D', 'E', 'F', 'G',\n 'H', 'I', 'J', 'K', 'L', 'M', 'N',\n 'O', 'P', 'Q', 'R', 'S', 'T', 'U',\n 'V', 'W', 'X', 'Y', 'Z']\n \n low = ['a', 'b', 'c', \"d\", \"e\", 'f', 'g',\n 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n 'o', 'p', 'q', 'r', 's', 't', 'u',\n 'v', 'w', 'x', 'y', 'z']\n \n letter_up = 0\n letter_low = 0\n \n for letter in s:\n if letter in up:\n letter_up += 1\n elif letter in low:\n letter_low += 1\n \n if letter_up > letter_low:\n return s.upper()\n else:\n return s.lower()\n", "def solve(s):\n mayus = 0\n minus = 0\n for i in range(len(s)): \n if (ord(s[i]) >= 97 and ord(s[i]) <= 122): \n minus += 1\n elif (ord(s[i]) >= 65 and ord(s[i]) <= 90): \n mayus += 1\n if minus > mayus or mayus == minus:\n return s.lower()\n else:\n return s.upper()\n\n\n", "def solve(s):\n return s.lower() if sum(lttr.islower() for lttr in s) >= len(s) // 2 else s.upper()", "def solve(s):\n a = [i for i in s if i.lower() != i]\n return s.upper() if len(a) > len(s)/2 else s.lower()", "import string\ndef solve(s):\n if len(s)/len(list(i for i in s if i in string.ascii_lowercase))<=2:\n return s.lower()\n else:\n return s.upper()"]
{"fn_name": "solve", "inputs": [["code"], ["CODe"], ["COde"], ["Code"]], "outputs": [["code"], ["CODE"], ["code"], ["code"]]}
INTRODUCTORY
PYTHON3
CODEWARS
23,298
def solve(s):
9c7d0e51f86dadf7a4f136068129b4d5
UNKNOWN
Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second. For instance, take the strings "fatigue" and "tiguefa". In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned. If the second string isn't a valid rotation of the first string, the method returns -1. Examples: ``` "coffee", "eecoff" => 2 "eecoff", "coffee" => 4 "moose", "Moose" => -1 "isn't", "'tisn" => 2 "Esham", "Esham" => 0 "dog", "god" => -1 ``` For Swift, your function should return an Int?. So rather than returning -1 when the second string isn't a valid rotation of the first, return nil.
["def shifted_diff(first, second):\n return (second + second).find(first) if len(first) == len(second) else - 1;", "def shifted_diff(first, second):\n for i in range(len(first)):\n if first == second[i:] + second[:i]:\n return i\n return -1", "def shifted_diff(first, second):\n return next(iter(i for i in range(len(first)) if first[-i:] + first[:-i] == second), -1)", "def shifted_diff(first, second):\n genexp = [i for i in range(len(second)) if first == second[i:]+second[:i]]\n if genexp:\n return max(genexp)\n return -1", "def shifted_diff(first, second):\n return -1 if len(first) != len(second) else f\"{second}{second}\".find(first)", "def shifted_diff(f, s):\n try:\n ix = s.index(f[0])\n return ix if f==s[ix:]+s[:ix] else -1\n except:\n return -1", "def xx(s):\n return s[1:]+s[0]\ndef shifted_diff(a, b):\n if a == b:\n return 0\n elif sorted(a) == sorted(b):\n n = 0\n for i in range(len(b)):\n n += 1\n b = xx(b)\n if b == a:\n return n\n return -1", "def shifted_diff(first, second):\n if len(first) != len(second):\n return -1\n return (second * 2).find(first)", "from collections import deque\n\ndef shifted_diff(f, s):\n d1, d2 = deque(f), deque(s)\n l = [d2.rotate(-1) or d1 == d2 for i in range(len(f))]\n return (l.index(True) + 1) % len(l) if True in l else -1\n"]
{"fn_name": "shifted_diff", "inputs": [["fatigue", "tiguefa"], ["hoop", "pooh"], ["eecoff", "coffee"], ["Moose", "moose"], ["isn't", "'tisn"], ["Esham", "Esham"], [" ", " "], ["dog", "god"], [" ", " "], ["doomhouse", "hoodmouse"], ["123456789!@#$%^&*( )qwerty", "9!@#$%^&*( )qwerty12345678"]], "outputs": [[5], [-1], [4], [-1], [2], [0], [0], [-1], [-1], [-1], [18]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,465
def shifted_diff(first, second):
6a91a1d3766e5f7c6d2642654e758d19
UNKNOWN
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 **below** the number passed in. > Note: If the number is a multiple of **both** 3 and 5, only count it *once*. > Also, if a number is negative, return 0(for languages that do have them) ###### *Courtesy of projecteuler.net*
["def solution(number):\n return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0)\n", "def solution(number):\n sum = 0\n for i in range(number):\n if (i % 3) == 0 or (i % 5) == 0:\n sum += i\n return sum", "def solution(number):\n return sum([x for x in range(number) if x % 3 == 0 or x % 5 == 0])", "from math import floor\n\ndef sum_to_n(n):\n return n * (n + 1) / 2\n\ndef sum_of_multiples(k, n):\n return k * sum_to_n(floor(n / k))\n\ndef solution(number):\n number = number - 1\n return (sum_of_multiples(3, number) + \n sum_of_multiples(5, number) - \n sum_of_multiples(3 * 5, number))", "def solution(number):\n import itertools\n return sum(set(itertools.chain(range(0, number, 3), range(0, number, 5))))", "def solution(number):\n return sum([i for i in range(number) if i % 3 == 0 or i % 5 == 0])", "def solution(number):\n return sum(i for i in range(number) if i%5==0 or i%3==0)", "class Multiples:\n def __init__(self, maximum):\n self.maximum = maximum\n\n def sum(self, base):\n count = self.maximum // base + 1\n last = base * (count - 1)\n return count * last // 2\n\ndef solution(number):\n multiples = Multiples(number - 1)\n return multiples.sum(3) + multiples.sum(5) - multiples.sum(15)", "def solution(number):\n return sum(x for x in range(number) if not x%3 or not x%5)", "def solution(number):\n multiples = []\n sum = 0\n for i in range(number):\n if i % 3 == 0 or i % 5 == 0:\n multiples.append(i)\n for x in multiples:\n sum += x\n return(sum)\n", "def solution(number):\n x = number-1\n f = lambda n: n*(n+1)//2\n return 3*f(x//3) + 5*f(x//5) - 15*f(x//15)", "def solution(number):\n def s(m):\n n = (number - 1) // m\n return n * m * (n + 1) // 2\n return s(3) + s(5) - s(15)", "def solution(number):\n return sum(set(range(0,number,3)) | set(range(0,number,5)))", "def solution(number):\n number -= 1\n f = lambda d, n: (d + n * d) * n / 2\n return f(3, number // 3) + f(5, number // 5) - f(15, number // 15)", "solution = lambda n: sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0)", "def solution(number):\n return sum(range(0, number, 3)) + sum(range(0, number, 5)) - sum(range(0, number, 15))", "def solution(number):\n return sum(num if (num % 3 == 0) or (num % 5 == 0) else 0 for num in range(number))"]
{"fn_name": "solution", "inputs": [[10], [20], [0], [1], [200]], "outputs": [[23], [78], [0], [0], [9168]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,435
def solution(number):
82b3ed2c018600ae52bf074741346ea2
UNKNOWN
Jack and Jill are playing a game. They have balls numbered from `0` to `n - 1`. Jack looks the other way and asks Jill to reverse the position of the balls, for instance, to change the order from say, `0,1,2,3` to `3,2,1,0`. He further asks Jill to reverse the position of the balls `n` times, each time starting from one position further to the right, till she reaches the last ball. So, Jill has to reverse the positions of the ball starting from position `0`, then from position `1`, then from position `2` and so on. At the end of the game, Jill will ask Jack to guess the final position of any ball numbered `k`. You will be given `2` integers, the first will be `n`(balls numbered from `0` to `n-1`) and the second will be `k`. You will return the position of the ball numbered `k` after the rearrangement. ```Perl solve(4,1) = 3. The reversals are [0,1,2,3] -> [3,2,1,0] -> [3,0,1,2] -> [3,0,2,1]. => 1 is in position 3. ``` More examples in the test cases. Good luck!
["def solve(count, ball_number):\n \"\"\"\n Return the position of the `ball_number` after the game with `count` balls\n\n :param count: Number of balls\n :type count: int\n :param ball_number: Number of ball to be found in the end\n :type ball_number: int\n :return: Return the index of the ball `ball_number` at the end of the game\n :rtype: int\n \"\"\"\n assert isinstance(count, int)\n assert isinstance(ball_number, int)\n\n balls = list(range(count))\n for idx in range(count):\n balls = balls[:idx] + balls[idx:][::-1]\n return balls.index(ball_number)\n", "solve=lambda n,k:2*(n-k-1,k+.5)[k<n//2]", "def solve(n, k):\n res = list(range(n))\n for i in range(n):\n res = res[:i] + res[i:][::-1]\n return res.index(k)", "def solve(n,k):\n arr = list(range(n))\n for i in range(n):\n arr = arr[:i]+arr[i:][::-1]\n return arr.index(k)", "def solve(n, k):\n second_half = k >= n // 2\n return (-1)**second_half * 2 * k + second_half * (n * 2 - 3) + 1", "def solve(n,k):\n arr = []\n for i in range(n%2 + n//2):\n arr += [n - i - 1] + [i]\n return arr.index(k)", "def solve(n,k):\n a = list()\n for i in range(int(n/2)+1):\n a += [n-1-i,i]\n return a.index(k)", "def solve(n,k):\n return 2*k+1 if k <= n//2-1 else 2*(n-k-1)\n", "def solve(n,k):\n list1=list(range(n))\n list1_values=list(list1)\n ball=list1[k]\n #print(list1_values)\n counter=0\n final_list=[]\n for i in range(n):\n\n list1.reverse()\n final_list.append(list1.pop(0))\n position=final_list.index(ball)\n return position", "def solve(n,\n k):\n\n result = {}\n index, start, end = 0, 0, n - 1\n while (start <= end):\n result[end] = index\n index += 1\n if (start != end):\n result[start] = index\n\n index += 1\n start += 1\n end -= 1\n\n return result[k]\n"]
{"fn_name": "solve", "inputs": [[4, 1], [4, 2], [4, 3], [20, 8], [20, 9], [20, 10]], "outputs": [[3], [2], [0], [17], [19], [18]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,968
def solve(n,k):
5b3d1a65856b4f04fca6b5e500d23593
UNKNOWN
Convert DD (decimal degrees) position to DMS (degrees, minutes, seconds). ##### Inputs: `dd_lat` and `dd_lon` 2 strings representing the latitude and the longitude in degree -i.e. 2 floats included in [-90, 90] and [-180, 180]. Note that latitude 0 is north, longitude 0 is east. ##### Outputs: A tuple of DMS latitudes formated as follows: `DDD*mm'ss.sss"C` With: - `DDD`: degrees - `mm`: minutes - `ss.sss`: seconds rounded to 3 decimals - `C`: first letter uppercase of the cardinal direction ##### ressources about WGS 84 on [Wikipedia](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84)
["from math import floor\n\ndef convert(dd, direction):\n degrees = floor(dd)\n seconds = round((dd % 1) * 3600000)\n return \"%03d*%02d\\'%06.3f\\\"%s\" % (degrees, \n seconds // 60000,\n seconds % 60000 / 1000,\n direction)\n\ndef convert_to_dms(dd_lat, dd_lon):\n dd_lat = float(dd_lat)\n dd_lon = float(dd_lon)\n dms_lat = convert(abs(dd_lat), 'N' if dd_lat >= 0 else 'S')\n dms_lon = convert(abs(dd_lon), 'E' if dd_lon >= 0 else 'W')\n return dms_lat, dms_lon", "def convert_to_dms(dd_lat, dd_lon):\n def convert(dd, c):\n d = abs(dd)\n m = d % 1 * 60\n s = m % 1 * 60\n return '{:03}*{:02}\\'{:06.3f}\"{}'.format(int(d), int(m), s, c[dd >= 0])\n return convert(float(dd_lat), 'SN'), convert(float(dd_lon), 'WE')", "def convert_to_dms (*args):\n lst = []\n for i,v in enumerate(map(float,args)):\n av = abs(v)\n d = int(av)\n m = int((av-d)*60)\n s = (av-d-m/60)*3600\n lst.append(\"{:03}*{:02}'{:06.3f}\\\"{}\".format(d,m,s,[\"NS\",\"EW\"][i][v<0]))\n return tuple(lst)", "def W(Q,S):\n Q=float(Q)\n B=Q<0\n Q=abs(Q)\n return '%03d*%02d\\'%06.3f\"%s' % (Q,Q%1*60,3600*Q%60,S[B])\nconvert_to_dms=lambda Q,S:(W(Q,'NS'),W(S,'EW'))", "from math import floor\n\ndef deg_min_sec(coord):\n \n deg = floor(abs(float(coord)))\n \n min = floor((abs(float(coord)) - deg)*60)\n \n sec = floor((abs(float(coord)) - deg - min/60)*3600)\n \n dec = str(round((abs(float(coord)) - deg - min/60)*3600 - sec, 3))[2:]\n \n return f'{deg:03}*{min:02}\\'{sec:02}.{dec:<03}\"'\n\ndef convert_to_dms(dd_lat, dd_lon):\n \n lat_card = 'S' if '-' in str(dd_lat) else 'N'\n \n lon_card = 'W' if '-' in str(dd_lon) else 'E'\n \n return f'{deg_min_sec(dd_lat)}{lat_card}', f'{deg_min_sec(dd_lon)}{lon_card}'\n", "def convert_to_dms(dd_lat, dd_lon):\n def dd_to_dms(dd):\n h=int(dd);dd-=h\n m=int(dd*60);dd-=m/60\n s=round(dd*3600,3)\n return (h,m,s)\n dd_lat,dd_lon=map(float,(dd_lat,dd_lon))\n dms_lat=\"{:03d}*{:02d}\\'{:06.3f}\\\"{:s}\".format(*dd_to_dms(abs(dd_lat)),\"NS\"[dd_lat<0])\n dms_lon=\"{:03d}*{:02d}\\'{:06.3f}\\\"{:s}\".format(*dd_to_dms(abs(dd_lon)),\"EW\"[dd_lon<0])\n return (dms_lat,dms_lon)", "def convert_to_dms(dd_lat, dd_lon):\n dd_lat,dd_lon=float(dd_lat),float(dd_lon)\n if dd_lat>=0:\n lat_dir='N'\n else:\n lat_dir='S'\n dd_lat*=-1\n lat_d=int(dd_lat)\n lat_m=(dd_lat-lat_d)*60\n lat_s=round((lat_m-int(lat_m))*60,3)\n lat_m=int(lat_m)\n dms_lat='{:03d}*{:02d}\\'{:06.3f}\"{}'.format(lat_d,lat_m,lat_s,lat_dir)\n \n if dd_lon>=0:\n lon_dir='E'\n else:\n lon_dir='W'\n dd_lon*=-1\n lon_d=int(dd_lon)\n lon_m=(dd_lon-lon_d)*60\n lon_s=round((lon_m-int(lon_m))*60,3)\n lon_m=int(lon_m)\n dms_lon='{:03d}*{:02d}\\'{:06.3f}\"{}'.format(lon_d,lon_m,lon_s,lon_dir)\n return dms_lat, dms_lon", "def dms(deg, dirs):\n v = abs(deg)\n return (int(v), int(60 * v % 60), 3600 * v % 60, dirs[deg < 0])\ndef convert_to_dms(dd_lat, dd_lon):\n return '%03d*%02d\\'%06.3f\"%s' % dms(float(dd_lat), 'NS'), '%03d*%02d\\'%06.3f\"%s' % dms(float(dd_lon), 'EW')\n", "def f(l,d):\n a= abs(l)\n a1=int(a)\n a=60*(a-a1)\n a2=int(a)\n a=round(60*(a-a2),3)\n return '{:03}*{:02}\\'{:06.3f}\"{}'.format(a1,a2,a,d)\n\ndef convert_to_dms(lat, lon):\n a = float(lat)\n ns = [\"S\",\"N\"][a>=0]\n b = float(lon)\n we = [\"W\",\"E\"][b>=0]\n return f(a,ns), f(b,we)", "def gms(x): \n c = x>=0\n x = abs(x)\n g = int(x)\n x = 60*(x-g)\n m = int(x)\n x = 60*(x-m)\n s = round(x, 3)\n return g, m, s, c\n \ndef formatea(g, m, s, c): \n g = \"{:03d}\".format(g)\n m = \"{:02d}\".format(m)\n s = \"{:02.3f}\".format(s)\n s = '0'*(6-len(s)) + s\n return f\"\"\"{g}*{m}\\'{s}\"{c}\"\"\"\n \ndef convert_to_dms(*args):\n dd_lat, dd_lon = map(float, args)\n dms_lat = gms(dd_lat)\n dms_lon = gms(dd_lon)\n \n a = formatea(*dms_lat[:3], \"N\" if dms_lat[3] else \"S\")\n b = formatea(*dms_lon[:3], \"E\" if dms_lon[3] else \"W\")\n \n return a, b"]
{"fn_name": "convert_to_dms", "inputs": [["35.03299485527936", "33.233755230903625"], ["-37.111415669561595", "-12.284317023586482"], ["19.61499312350978", "-155.48217818140984"]], "outputs": [["035*01'58.781\"N", "033*14'01.519\"E"], ["037*06'41.096\"S", "012*17'03.541\"W"], ["019*36'53.975\"N", "155*28'55.841\"W"]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,351
def convert_to_dms(dd_lat, dd_lon):
a6effd1d9853b2246315870dac5fc0ce
UNKNOWN
Your Goal is to create a function that takes two strings, a guess and a phone number. Based on the guess, the function should display a portion of the phone number: guess_my_number('052', '123-451-2345') would return the string: '#2#-#5#-2##5' or guess_my_number('142', '123-451-2345') would return the string: '12#-4#1-2#4#' Order of the guess string should not matter, and should not have duplicates of the ten digitis 0-9. Guess will never be an empty string or contains any other charachters. The phone number will always bea ten digit number in the format ###-###-####. The default number of 123-451-2345 should be included, but can be overwriten by a different number if supplied at the time of execution.
["def guess_my_number(guess, number = '123-451-2345'):\n return \"\".join(c if c in guess+\"-\" else \"#\" for c in number)\n", "from re import sub\ndef guess_my_number(guess, number = '123-451-2345'):\n return sub('[^{}-]'.format(guess), '#', number)", "guess_my_number=lambda g,n='123-451-2345':''.join(('#'+c)[c in'-'+g]for c in n)", "import re\n\ndef guess_my_number(guess, number = '123-451-2345'):\n return re.sub(r'[^-' + guess + ']', '#', number)", "def guess_my_number(a, b=\"123-451-2345\"):\n a = set(a + \"-\")\n return \"\".join(\"#\" if x not in a else x for x in b)", "guess_my_number = lambda guess, number = '123-451-2345': ''.join([x if x in guess or x == '-' else '#' for x in list(number)])", "def guess_my_number(guess, number = '123-451-2345'):\n g = set(guess + '-')\n return ''.join(x if x in g else '#' for x in number)", "import re\ndef guess_my_number(guess, number = '123-451-2345'):\n return re.sub(\"[^{}-]\".format(guess),\"#\",number)", "def guess_my_number(guess, number = '123-451-2345'):\n digits = set('0123456789') - set(guess)\n for d in digits:\n number = number.replace(d, '#')\n return number", "def guess_my_number(guess, number='123-451-2345'):\n return ''.join(a if a in guess or a == '-' else '#' for a in number)\n"]
{"fn_name": "guess_my_number", "inputs": [["0"], ["01"], ["012"], ["0123"], ["01234"], ["012345"]], "outputs": [["###-###-####"], ["1##-##1-####"], ["12#-##1-2###"], ["123-##1-23##"], ["123-4#1-234#"], ["123-451-2345"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,305
def guess_my_number(guess, number = '123-451-2345'):
eaeca64487ef38d06675a18f1f4e4ef6
UNKNOWN
A **Seven Segment Display** is an electronic display device, used to display decimal or hexadecimal numerals. It involves seven led segments that are lit in specific combinations to represent a specific numeral. An example of each combination is shown below: ![seven segment display](https://upload.wikimedia.org/wikipedia/commons/9/97/7-segments_Indicator.gif) For this Kata, you must accept an integer in the range `0 - 999999` and print it as a string (in decimal format), with each digit being represented as its own seven segment display (6x seven segment displays in total). Each of the individual led segments per display should be represented by three hashes `###`. Vertical bars `|` (ASCII 124) represent the edges of each display, with a single whitespace on either side between the edge and the area of the led segments. An example of the expected output is shown below: ``` segment_display(123456) = | | ### | ### | | ### | ### | | # | # | # | # # | # | # | | # | # | # | # # | # | # | | # | # | # | # # | # | # | | | ### | ### | ### | ### | ### | | # | # | # | # | # | # # | | # | # | # | # | # | # # | | # | # | # | # | # | # # | | | ### | ### | | ### | ### | ``` For clarity, the entire set of required combinations is provided below: ``` | ### | | ### | ### | | ### | ### | ### | ### | ### | | # # | # | # | # | # # | # | # | # | # # | # # | | # # | # | # | # | # # | # | # | # | # # | # # | | # # | # | # | # | # # | # | # | # | # # | # # | | | | ### | ### | ### | ### | ### | | ### | ### | | # # | # | # | # | # | # | # # | # | # # | # | | # # | # | # | # | # | # | # # | # | # # | # | | # # | # | # | # | # | # | # # | # | # # | # | | ### | | ### | ### | | ### | ### | | ### | ### | ``` If the number is smaller than 6 digits, the result should be justified to the right, with the unused segments being blank (as they are not turned on). Refer to the sample test for an example. **Note:** There should not be any trailing whitespace for any line. Please rate and enjoy!
["BASE = [r.split('|') for r in '''\\\n ### | | ### | ### | | ### | ### | ### | ### | ### | \n # # | # | # | # | # # | # | # | # | # # | # # | \n # # | # | # | # | # # | # | # | # | # # | # # | \n # # | # | # | # | # # | # | # | # | # # | # # | \n | | ### | ### | ### | ### | ### | | ### | ### | \n # # | # | # | # | # | # | # # | # | # # | # | \n # # | # | # | # | # | # | # # | # | # # | # | \n # # | # | # | # | # | # | # # | # | # # | # | \n ### | | ### | ### | | ### | ### | | ### | ### | '''.split('\\n') ]\n\n\ndef segment_display(n):\n digs = [int(d,16) for d in f'{n:A>6}']\n return '\\n'.join( f'|{ \"|\".join( BASE[x][d] for d in digs) }|'\n for x in range(len(BASE)))\n", "from itertools import chain\n\nlines = \"\"\"\n| ### | | ### | ### | | ### | ### | ### | ### | ### | \n| # # | # | # | # | # # | # | # | # | # # | # # | \n| # # | # | # | # | # # | # | # | # | # # | # # | \n| # # | # | # | # | # # | # | # | # | # # | # # | \n| | | ### | ### | ### | ### | ### | | ### | ### | \n| # # | # | # | # | # | # | # # | # | # # | # | \n| # # | # | # | # | # | # | # # | # | # # | # | \n| # # | # | # | # | # | # | # # | # | # # | # | \n| ### | | ### | ### | | ### | ### | | ### | ### | \n\"\"\".lstrip().splitlines()\n\ndef digit_rotated(n):\n return [\"\".join(line[i] for line in lines) for i in range(n * 8, (n+1) * 8)]\n\ndef segment_display(n):\n digits = [int(c) for c in str(n)]\n if len(digits) < 6:\n digits = [-1] * (6-len(digits)) + digits\n xs = (line for line in chain(*map(digit_rotated, digits), [\"|||||||||\"]))\n return \"\\n\".join(map(\"\".join, zip(*xs)))", "data = \"\"\"\n ### | | ### | ### | | ### | ### | ### | ### | ### \n # # | # | # | # | # # | # | # | # | # # | # # \n # # | # | # | # | # # | # | # | # | # # | # # \n # # | # | # | # | # # | # | # | # | # # | # # \n | | ### | ### | ### | ### | ### | | ### | ### \n # # | # | # | # | # | # | # # | # | # # | # \n # # | # | # | # | # | # | # # | # | # # | # \n # # | # | # | # | # | # | # # | # | # # | # \n ### | | ### | ### | | ### | ### | | ### | ### \n\"\"\"\n# Remove blank lines, and extract the string for each line of each digit\ndata = [line for line in data.split('\\n') if line]\nsegments = [tuple(line.split('|')) for line in data]\nh, w = len(segments), len(segments[0][0])\n\ndef segment_display(num):\n result = [[] for _ in range(h)]\n n = str(num)\n # Apply left padding\n for _ in range(6 - len(n)):\n for i in range(h):\n result[i].append(' ' * w)\n # Add each digit in turn\n for c in n:\n n = int(c)\n for i in range(h):\n result[i].append(segments[i][n])\n return \"\\n\".join( ['|{}|'.format('|'.join(row)) for row in result])\n", "displays = {\n '0': '012456',\n '1': '25',\n '2': '02346',\n '3': '02356',\n '4': '1235',\n '5': '01356',\n '6': '013456',\n '7': '025',\n '8': '0123456',\n '9': '012356',\n ' ' : ''\n}\nshape = ' 000 |1 2|1 2|1 2| 333 |4 5|4 5|4 5| 666 '.split('|')\n\ndef segment_display(n):\n s = str(n).rjust(6,' ')\n return '\\n'.join('|' + ('|'.join(' '+ (''.join(' #'[c in displays[d]] for c in shape[j]) + ' ') for d in s)) + '|' for j in range(9))", "def segment_display(num):\n segs = ''' \n ### | | ### | ### | | ### | ### | ### | ### | ### \n# #| #| #| #|# #|# |# | #|# #|# #\n# #| #| #| #|# #|# |# | #|# #|# #\n# #| #| #| #|# #|# |# | #|# #|# #\n | | ### | ### | ### | ### | ### | | ### | ### \n# #| #|# | #| #| #|# #| #|# #| #\n# #| #|# | #| #| #|# #| #|# #| #\n# #| #|# | #| #| #|# #| #|# #| #\n ### | | ### | ### | | ### | ### | | ### | ### '''\n numbers = {str(i): [] for i in range(10)}\n for s in segs.split('\\n')[1:]:\n for i, t in enumerate(s.split('|')):\n numbers[str(i)].append(t)\n numbers[' '] = [' '] * 9\n return '\\n'.join(['| ' + ' | '.join([numbers[ch][y] for ch in f'{num:>6}']) + ' |' for y in range(9)])", "s = '''| ### | | ### | ### | | ### | ### | ### | ### | ### |\n| # # | # | # | # | # # | # | # | # | # # | # # |\n| # # | # | # | # | # # | # | # | # | # # | # # |\n| # # | # | # | # | # # | # | # | # | # # | # # |\n| | | ### | ### | ### | ### | ### | | ### | ### |\n| # # | # | # | # | # | # | # # | # | # # | # |\n| # # | # | # | # | # | # | # # | # | # # | # |\n| # # | # | # | # | # | # | # # | # | # # | # |\n| ### | | ### | ### | | ### | ### | | ### | ### |\n'''.splitlines()\nsegment_display=lambda n:'\\n'.join(''.join(i)+'|'for i in [(['| ']*(6-len(str(n))))+[k[int(l)]for l in str(n)]for k in[[i[j:j+8]for j in range(0,len(i),8)]for i in s]])", "def segment_display(num): \n fline, fl, fr, frl, empty = [' ### '],[' # '],[' # '],[' # # '],[' ']\n codes = [\n empty*9,\n fline + frl*3 + empty + frl*3 + fline, \n (empty + fr*3) * 2 + empty,\n fline + fr*3 + fline + fl*3 + fline,\n (fline + fr*3) * 2 + fline,\n empty + frl*3 + fline + fr*3 + empty,\n fline + fl*3 + fline + fr*3 + fline,\n fline + fl*3 + fline + frl*3 + fline,\n fline + (fr*3 + empty) * 3 + empty,\n (fline + frl*3) * 2 + fline,\n fline + frl*3 + fline + fr*3 + fline\n ]\n\n result = \"\"\n for line in range(9): # Hight is 9 lines\n result += \"|\" + \"|\".join([codes[0 if letter==' ' else int(letter)+1][line] for letter in str(num).rjust(6)]) + \"|\\n\" \n return result[:-1]", "all_num = \\\n'''| ### | | ### | ### | | ### | ### | ### | ### | ### |\n| # # | # | # | # | # # | # | # | # | # # | # # |\n| # # | # | # | # | # # | # | # | # | # # | # # |\n| # # | # | # | # | # # | # | # | # | # # | # # |\n| | | ### | ### | ### | ### | ### | | ### | ### |\n| # # | # | # | # | # | # | # # | # | # # | # |\n| # # | # | # | # | # | # | # # | # | # # | # |\n| # # | # | # | # | # | # | # # | # | # # | # |\n| ### | | ### | ### | | ### | ### | | ### | ### |'''\ndef segment_display(num):\n all_num_list = all_num.split('\\n')\n fish_list = []\n for val in (all_num_list):\n fish_hold_list = []\n fish_hold = '' + '| |'*(6-len(str(num)))\n for num2 in str(num):\n num3 = int(num2)\n beg_col = (num3 * 8)\n end_col = beg_col + 9\n fish_hold += val[beg_col:end_col]\n fish_hold_list.append([fish_hold])\n fish_list.append(fish_hold)\n retval_list = []\n for val in (fish_list):\n retval_list.append(val.replace('||','|'))\n return '\\n'.join(retval_list)\n", "def segment_display(num):\n temp=str(num).rjust(6, \"_\")\n numbers=[[' ### ', ' ', ' ### ', ' ### ', ' ', ' ### ', ' ### ', ' ### ', ' ### ', ' ### '], ['# #', ' #', ' #', ' #', '# #', '# ', '# ', ' #', '# #', '# #'], ['# #', ' #', ' #', ' #', '# #', '# ', '# ', ' #', '# #', '# #'], ['# #', ' #', ' #', ' #', '# #', '# ', '# ', ' #', '# #', '# #'], [' ', ' ', ' ### ', ' ### ', ' ### ', ' ### ', ' ### ', ' ', ' ### ', ' ### '], ['# #', ' #', '# ', ' #', ' #', ' #', '# #', ' #', '# #', ' #'], ['# #', ' #', '# ', ' #', ' #', ' #', '# #', ' #', '# #', ' #'], ['# #', ' #', '# ', ' #', ' #', ' #', '# #', ' #', '# #', ' #'], [' ### ', ' ', ' ### ', ' ### ', ' ', ' ### ', ' ### ', ' ', ' ### ', ' ### ']]\n res=[]\n for i in range(len(numbers)):\n string=[]\n for j, num in enumerate(temp):\n string.append(\" \"*5) if num==\"_\" else string.append(numbers[i][int(num)])\n res.append(\"| \"+\" | \".join(string)+\" |\")\n return \"\\n\".join(res)"]
{"fn_name": "segment_display", "inputs": [[123456], [987654], [0]], "outputs": [["| | ### | ### | | ### | ### |\n| # | # | # | # # | # | # |\n| # | # | # | # # | # | # |\n| # | # | # | # # | # | # |\n| | ### | ### | ### | ### | ### |\n| # | # | # | # | # | # # |\n| # | # | # | # | # | # # |\n| # | # | # | # | # | # # |\n| | ### | ### | | ### | ### |"], ["| ### | ### | ### | ### | ### | |\n| # # | # # | # | # | # | # # |\n| # # | # # | # | # | # | # # |\n| # # | # # | # | # | # | # # |\n| ### | ### | | ### | ### | ### |\n| # | # # | # | # # | # | # |\n| # | # # | # | # # | # | # |\n| # | # # | # | # # | # | # |\n| ### | ### | | ### | ### | |"], ["| | | | | | ### |\n| | | | | | # # |\n| | | | | | # # |\n| | | | | | # # |\n| | | | | | |\n| | | | | | # # |\n| | | | | | # # |\n| | | | | | # # |\n| | | | | | ### |"]]}
INTRODUCTORY
PYTHON3
CODEWARS
9,528
def segment_display(num):
bc974aeecf4fa46af4f8dc28a8c8bcab
UNKNOWN
In this Kata, you will be given a ```number```, two indexes (```index1``` and ```index2```) and a ```digit``` to look for. Your task will be to check if the ```digit``` exists in the ```number```, within the ```indexes``` given. Be careful, the ```index2``` is not necessarily more than the ```index1```. ``` index1 == 2 and index2 == 5 -> snippet from 2 to 5 positons; index1 == 5 and index2 == 2 -> snippet from 2 to 5 positons; number.length = 14; 0 <= index1 < 14; 0 <= index2 < 14; index2 is inclusive in search snippet; 0 <= digit <= 9; ``` Find more details below: ``` checkDigit(12345678912345, 1, 0, 1) -> true, 1 exists in 12 checkDigit(12345678912345, 0, 1, 2) -> true, 2 exists in 12 checkDigit(67845123654000, 4, 2, 5) -> true, 4 exists in 845 checkDigit(66688445364856, 0, 0, 6) -> true, 6 exists in 6 checkDigit(87996599994565, 2, 5, 1) -> false, 1 doesn't exist in 9965 ```
["def check_digit(n, idx1, idx2, digit):\n return str(digit) in str(n)[idx1:idx2+1] + str(n)[idx2:idx1+1]", "def check_digit(n, i1, i2, d):\n return str(d) in str(n)[min(i1,i2):max(i1,i2)+1]", "def check_digit(number, index1, index2, digit):\n number, digit = str(number), str(digit)\n index1, index2 = sorted((index1, index2))\n return digit in number[index1:index2+1]", "def check_digit(n, i, j, x):\n i, j = sorted([i, j])\n return str(x) in str(n)[i:j+1]", "def check_digit(n, i, j, d):\n '''\n check = str(n)[min(i,j):max(i,j)+1]\n \n if str(d) in check:\n return True\n return False\n '''\n \n return True if str(d) in str(n)[min(i,j):max(i,j)+1] else False\n \n", "def check_digit(number, index1, index2, digit):\n nums = str(number)\n if index2 < index1:\n index2, index1 = index1, index2\n\n return str(digit) in nums[index1:index2+1]\n", "def check_digit(number, index1, index2, digit):\n return str(digit) in str(number)[min(index1, index2) : max(index1, index2) + 1]", "def check_digit(s,t,p,q):\n if t<p:\n \n return True if str(q) in str(s)[t:p+1] else False\n return True if str(q) in str(s)[p:t+1] else False", "def check_digit(number, index1, index2, digit):\n left = min([index1, index2])\n right = max([index1, index2])\n return True if str(digit) in str(number)[left:right+1] else False", "def check_digit(number, index1, index2, digit):\n number=str(number)\n if index1<index2:\n index2=index2+1\n return str(digit) in number[index1:index2]\n elif index2<index1:\n index1=index1+1\n return str(digit) in number[index2:index1]\n elif index1==index2 and str(digit)==number[index1]:\n return True\n else:\n return False"]
{"fn_name": "check_digit", "inputs": [[1234567, 1, 0, 1], [1234567, 0, 1, 2], [67845123654, 4, 2, 4], [6668844536485, 0, 0, 6], [9999999999, 2, 5, 1]], "outputs": [[true], [true], [true], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,799
def check_digit(number, index1, index2, digit):
a9b14074aa28ba074de6aa53c1b56e72
UNKNOWN
The purpose of this kata is to work out just how many bottles of duty free whiskey you would have to buy such that the saving over the normal high street price would effectively cover the cost of your holiday. You will be given the high street price (normPrice), the duty free discount (discount) and the cost of the holiday. For example, if a bottle cost £10 normally and the discount in duty free was 10%, you would save £1 per bottle. If your holiday cost £500, the answer you should return would be 500. All inputs will be integers. Please return an integer. Round down.
["def duty_free(price, discount, holiday_cost):\n saving = price * discount / 100.0\n return int(holiday_cost / saving)", "def duty_free(price, discount, holiday_cost):\n return holiday_cost * 100 // price // discount", "def duty_free(price, discount, holiday_cost):\n return holiday_cost // (price * (discount / 100))", "def duty_free(price, discount, holiday_cost):\n return holiday_cost * 100 // (price * discount)", "def duty_free(p, d, h):\n return int(h/(p/100*d))", "def duty_free(price, discount, holiday_cost):\n savings_per_bottle = price * discount/100\n \n return holiday_cost // savings_per_bottle #floor division because discrete units \n\n", "def duty_free(price, discount, holiday_cost):\n return int(holiday_cost / (price * (discount / 100)))", "duty_free = lambda p, d, h: h // (p * d / 100)", "def duty_free(price, disc, h_c):\n return int(h_c/(price*(disc/100)))", "def duty_free(price, discount, holiday_cost):\n return 100*holiday_cost//(price*discount)", "def duty_free(price, discount, holiday_cost):\n \n savings=price*(discount/100) \n numberNeeded=holiday_cost/savings \n \n return int(numberNeeded)\n", "def duty_free(price, discount, holiday_cost):\n return int(holiday_cost / ((discount / 100) * price))", "def duty_free(price, discount, holiday_cost):\n return int(round(holiday_cost//(price*discount*0.01)))\n \n", "def duty_free(price, discount, holiday_cost):\n return int(holiday_cost / price / discount / 0.01)", "def duty_free(price, discount, holiday_cost):\n x = price*(discount*.01)\n return int(holiday_cost/x)\n", "def duty_free(p, d, cost):\n return cost//(p * (d/100))", "def duty_free(price, discount, holiday_cost):\n result = holiday_cost//(price*discount*0.01)\n return(round(result))\n", "def duty_free(price, discount, holiday_cost):\n return int(holiday_cost / (price * discount * 0.01))", "from math import floor\n\ndef duty_free(price: int, discount: int, holiday_cost: int) -> int:\n \"\"\"\n How many bottles of duty free whiskey you would have to buy such that the saving \n over the normal high street price would effectively cover the cost of your holiday?\n \"\"\"\n return floor(holiday_cost / (price * (discount / 100)))", "def duty_free(price, discount, holiday_cost):\n a=price*(discount/100)\n b=holiday_cost//a\n return b", "duty_free = lambda price,discount,holiday_cost : int(holiday_cost/(price*(float(discount)/100)))", "duty_free=lambda p,d,h:int(h*100/p/d)", "def duty_free(price, discount, holiday_cost):\n saving = price -(price - price * discount / 100)\n price = holiday_cost // saving\n return price", "import math\n\ndef duty_free(price, discount, holiday_cost):\n percent = discount / 100 * price\n bottles = holiday_cost / percent\n return math.floor(bottles)", "from math import *\n\ndef duty_free(price, discount, holiday_cost):\n discount_multiplyer = discount / 100\n return floor(holiday_cost / (price*discount_multiplyer))", "import math\ndef duty_free(price, discount, holiday_cost):\n discount = discount * .01\n savings_per_bottle = price * discount\n number_of_bottles_needed = holiday_cost / savings_per_bottle\n return math.floor(number_of_bottles_needed)", "def duty_free(price, discount, holiday_cost):\n discounted_price = (price*discount)/100\n return holiday_cost//discounted_price", "import math\n\ndef duty_free(price, discount, holiday_cost):\n x = holiday_cost / (price - (price - (price * (discount / 100))))\n return math.floor(x)", "def duty_free(price, discount, holiday_cost):\n economia = price - price*(100 - discount)*0.01 \n s = holiday_cost//economia\n return s\n", "def duty_free(price, discount, holiday_cost):\n per_bottle = (discount / 100) * price\n saving = holiday_cost // per_bottle # Rounding down with floor division\n return saving", "import unittest\n\nPERCENT = 0.01\n\n\ndef duty_free(price, discount, holiday_cost):\n return holiday_cost // (price * discount * PERCENT)\n \n \nclass TestDutyFree(unittest.TestCase):\n def test_duty_free(self):\n self.assertEqual(duty_free(price=12, discount=50, holiday_cost=1000), 166)\n", "def duty_free(price, discount, holiday_cost):\n duty_free_cost = price - (price - (price*discount*0.01))\n cost= holiday_cost // duty_free_cost\n return cost", "def duty_free(price, discount, holiday_cost):\n total_discount = price * discount / 100\n return holiday_cost // total_discount", "def duty_free(price, discount, holiday_cost):\n a = price*(discount/100)\n b = holiday_cost//a\n b = int(b)\n return b\nprint(duty_free(12, 50, 1000))", "def duty_free(price, discount, holiday_cost):\n bottles = holiday_cost / (price * discount)\n return int(bottles * 100)", "def duty_free(price, discount, holiday_cost):\n ma = (price / 100 ) * discount\n return int(holiday_cost / ma )", "def duty_free(price, discount, holiday_cost):\n spare = price/100 * discount\n return int(holiday_cost / spare)", "def duty_free(price, discount, holiday_cost):\n return int(holiday_cost / ((discount / 100)*price))\n # return price\n", "def duty_free(price, discount, holiday_cost):\n newprc = price * (1-discount/100)\n saving = price - newprc\n return holiday_cost//saving", "duty_free = lambda price, discount, holiday_cost: int(100*holiday_cost/(price*discount))", "def duty_free(price, discount, holiday_cost):\n \n output = price * discount / 100\n result=int(holiday_cost/output)\n return result\n \n \n", "def duty_free(price, discount, holiday_cost):\n discount_total = price/100 * discount\n result = holiday_cost // discount_total\n return result\n", "import math\ndef duty_free(price, discount, holiday_cost):\n i =(discount/100) * price\n return math.floor(holiday_cost/i)", "import math\ndef duty_free(price, discount, holiday_cost):\n leftover = price*(discount/100)\n num = holiday_cost/leftover\n return math.floor(num)", "def duty_free(price, discount, holiday_cost):\n discount /= 100\n price_with_discount = price*discount\n finish_price = 0\n count = 0\n while finish_price < holiday_cost:\n finish_price += price_with_discount\n if finish_price > holiday_cost:\n break\n count += 1\n return count", "def duty_free(price, discount, holiday_cost):\n proc = discount / 100 \n price_new = proc * price\n final = holiday_cost / price_new\n return int(final)", "def duty_free(price, discount, holiday_cost):\n amount_discount = price / 100 * discount\n result = holiday_cost // amount_discount\n return result\n", "def duty_free(price, discount, holiday_cost):\n # holiday cost / (price*discount) \n money = price * (discount/100)\n return int(holiday_cost/money)", "def duty_free(price, discount, holiday_cost):\n q=0\n w=0\n p=0\n q=(price*discount)/100\n w=(holiday_cost/q)*10\n return (w//10)", "def duty_free(price, discount, holiday_cost):\n cst = holiday_cost // ((discount / 100) * price)\n return cst", "def duty_free(price, discount, holiday_cost):\n disc = price * discount / 100\n duty_free = holiday_cost // disc\n return duty_free\n", "def duty_free(price, discount, holiday_cost):\n a = int(price) * int(discount) / 100\n return int(holiday_cost / a)", "import math\ndef duty_free(price, discount, holiday_cost):\n percent = price / 100 * discount\n return math.floor(holiday_cost / percent)\nprint((duty_free(12, 50, 1000))) \n \n", "def duty_free(price, discount, holiday_cost):\n spb = price * discount / 100\n return holiday_cost // spb", "def duty_free(price, discount, holiday_cost):\n savings = price * discount/100\n sol = holiday_cost/savings\n return int(sol)", "def duty_free(p, d, c):\n r = c // (p * d / 100)\n return r", "def duty_free(price, discount, holiday_cost):\n print(price,discount, holiday_cost) \n return holiday_cost//(discount*.01*price)", "def duty_free(price, discount, holiday_cost):\n \n dfree= (price*discount)/100\n return holiday_cost//dfree", "def duty_free(price, discount, holiday_cost):\n d = discount / 100\n p = price * d\n return holiday_cost // p\n", "def duty_free(price,\n discount,\n holiday_cost):\n\n\n discount_amount = discount / 100. * price\n if (discount_amount):\n\n return holiday_cost // discount_amount\n\n return holiday_cost\n", "def duty_free(price, discount, holiday_cost):\n sale_price = price * discount / 100\n return int(holiday_cost / sale_price)", "def duty_free(price, discount, holiday_cost):\n actual_price = price * discount/100\n \n count = 0\n total = 0\n while total < holiday_cost:\n total += actual_price\n count += 1\n \n return count-1", "def duty_free(price, discount, holiday_cost):\n disc_price = (discount/100) * price\n return holiday_cost // disc_price \n", "def duty_free(price, discount, holiday_cost):\n savings = price - (discount/100)*price\n print(price,discount,holiday_cost,savings,holiday_cost//savings)\n return holiday_cost // (price-savings)", "def duty_free(price, discount, holiday_cost):\n return holiday_cost//(price-(price*(1-(0.01*discount))))", "def duty_free(price, discount, holiday_cost):\n x = price / 100 * discount\n return int(holiday_cost / x)\n", "def duty_free(price, discount, holiday_cost):\n x = price * (discount/100)\n price = holiday_cost /x\n return (int(price))\n \n \n", "def duty_free(price, discount, holiday_cost):\n price2=price* (discount/100)\n cost=holiday_cost/price2\n return ( int(cost) )", "def duty_free(price, discount, holiday_cost):\n \n economy_nom = price * discount / 100\n return int(holiday_cost / economy_nom)", "def duty_free(price, discount, holiday_cost):\n return int(int(holiday_cost) / int(discount) / int(price) * 100)", "def duty_free(price, discount, holiday_cost):\n dut_price=price-(discount/100*price)\n saving=price-dut_price\n bottles=holiday_cost/saving\n return int(bottles)\n", "def duty_free(price, discount, holiday_cost):\n first = (price * discount) / 100\n second = holiday_cost // first\n return second", "import math\ndef duty_free(price, discount, holiday_cost):\n return round(int(holiday_cost/(discount*(price/100))))", "def duty_free(price, discount, holiday_cost):\n savings = (price * (discount/100))\n price = holiday_cost // savings\n return price", "def duty_free(price: int, discount: int, holiday_cost: int) -> int:\n return int(holiday_cost // ((discount / 100) * price))", "def duty_free(price, discount, holiday_cost):\n norm_price = price * (discount / 100)\n return holiday_cost // norm_price ", "def duty_free(price, discount, holiday_cost):\n price = price * discount/100\n bottles = holiday_cost // price\n return bottles", "def duty_free(price, discount, holiday_cost):\n return int(holiday_cost // (price - (price * (1- (discount/100)))))", "def duty_free(price, discount, holiday_cost):\n return holiday_cost // (discount / 100.0 * price)", "import math\n\ndef duty_free(price, discount, holiday_cost):\n \"\"\"(^-__-^)\"\"\"\n count_bottle = (price / 100)*discount\n result = holiday_cost / count_bottle\n return (math.floor(result))\n", "duty_free = lambda price, discount, holiday_cost: holiday_cost // (price * 0.01 * discount)", "def duty_free(price, discount, holiday_cost):\n save = price * discount / 100.0\n return int(holiday_cost / save)\n# hard, should in the 1kyu\n", "def duty_free(price, discount, holiday_cost):\n dsc_price = price * (1-discount)\n diff = price - dsc_price\n return int(holiday_cost / diff * 100)", "def duty_free(price, discount, holiday_cost):\n saved_money = price * (discount/100)\n return int(holiday_cost / saved_money)", "def duty_free(price, discount, holiday_cost):\n save = price * (discount/100)\n bottles = holiday_cost/save\n return int (bottles)\n", "def duty_free(price, discount, holiday_cost):\n amount_saved = discount/ 100 * price\n return int(holiday_cost/ amount_saved)", "def duty_free(price, discount, holiday_cost):\n discount = discount / 100\n save = (price * discount)\n price = holiday_cost / save \n return int(price)", "import math\ndef duty_free(price, discount, holiday_cost):\n actual_discount = (discount / 100) * price\n no_of_bottles = holiday_cost / actual_discount\n return math.floor(no_of_bottles)", "def duty_free(price, discount, holiday_cost):\n n = int(holiday_cost / (price * (discount/100))) \n return n\n \n\n\n", "def duty_free(normPrice, discount, holiday_cost):\n return int(holiday_cost/((normPrice*discount)/100))\n", "def duty_free(price, discount, holiday_cost):\n savings = price * (discount /100)\n bottles = 0\n suma = savings\n while suma < holiday_cost:\n bottles += 1\n suma += savings\n return bottles\n", "def duty_free(price, discount, holiday_cost):\n saved=(price*discount)/100\n price=holiday_cost//saved\n return price", "import math \ndef duty_free(price, discount, holiday_cost):\n x=(price*(discount/100))\n return math.floor(holiday_cost/x)", "def duty_free(price, discount, holiday_cost):\n count = holiday_cost // (price * discount / 100) \n return count", "def duty_free(price, discount, holiday_cost):\n x=discount/100\n y=price*x\n z=holiday_cost//y\n return int(z)", "def duty_free(a, b, c):\n pr = int(c/(a*b*0.01))\n return pr", "def duty_free(price, discount, holiday_cost):\n price = (price * discount/100) \n return holiday_cost // price", "import math\n\ndef duty_free(price, discount, holiday_cost):\n save = price*(discount/100)\n price = holiday_cost/save\n return math.floor(price)", "def duty_free(price, discount, holiday_cost):\n duty_free = price * (discount/100)\n bottles = int(holiday_cost/duty_free)\n return bottles", "def duty_free(price, discount, holiday_cost):\n return holiday_cost*100/discount//price"]
{"fn_name": "duty_free", "inputs": [[12, 50, 1000], [17, 10, 500], [24, 35, 3000], [1400, 35, 10000], [700, 26, 7000]], "outputs": [[166], [294], [357], [20], [38]]}
INTRODUCTORY
PYTHON3
CODEWARS
14,223
def duty_free(price, discount, holiday_cost):
e1f2eb1d2212305a471a0d0820ca164f
UNKNOWN
In Russia, there is an army-purposed station named UVB-76 or "Buzzer" (see also https://en.wikipedia.org/wiki/UVB-76). Most of time specific "buzz" noise is being broadcasted, but on very rare occasions, the buzzer signal is interrupted and a voice transmission in Russian takes place. Transmitted messages have always the same format like this: MDZHB 01 213 SKIF 38 87 23 95 or: MDZHB 80 516 GANOMATIT 21 23 86 25 Message format consists of following parts: Initial keyword "MDZHB"; Two groups of digits, 2 digits in first and 3 in second ones; Some keyword of arbitrary length consisting only of uppercase letters; Final 4 groups of digits with 2 digits in each group. Your task is to write a function that can validate the correct UVB-76 message. Function should return "True" if message is in correct format and "False" otherwise.
["import re\nvalidate = lambda msg: bool(re.match('^MDZHB \\d\\d \\d\\d\\d [A-Z]+ \\d\\d \\d\\d \\d\\d \\d\\d$', msg))", "import re\ndef validate(message):\n return bool(re.match(r\"^MDZHB \\d{2} \\d{3} [A-Z]+ \\d{2} \\d{2} \\d{2} \\d{2}$\", message))", "import re\ndef validate(message):\n return re.match(r'^MDZHB( \\d\\d){2}\\d [A-Z]+( \\d\\d){4}$', message) != None", "from re import compile, match\n\nREGEX = compile(r'MDZHB \\d{2} \\d{3} [A-Z]+ \\d{2} \\d{2} \\d{2} \\d{2}$')\n\n\ndef validate(message):\n return bool(match(REGEX, message))\n", "REGEX = __import__(\"re\").compile(r\"MDZHB( \\d\\d){2}\\d [A-Z]+( \\d\\d){4}\").fullmatch\n\ndef validate(message):\n return bool(REGEX(message))", "import re\n\ndef validate(s):\n return bool(re.match(r\"MDZHB \\d\\d \\d{3} [A-Z]+( \\d\\d){4}$\", s))", "import re\n\ndef validate(message):\n return bool(re.match(\n r'MDZHB \\d\\d \\d\\d\\d [A-Z]+( \\d\\d){4}$',\n message\n ))", "import re\n\ndef validate(message):\n return bool(re.match(r'MDZHB \\d{2} \\d{3} [A-Z]+( \\d{2}){4}$', message))", "import re\ndef validate(message):\n return bool(re.fullmatch(r'MDZHB \\d{2} \\d{3} [A-Z]+ \\d{2} \\d{2} \\d{2} \\d{2}', message))", "def validate(message):\n ml = message.split()\n if len(ml) != 8:\n return False\n if ml[0] != 'MDZHB':\n return False\n if len(ml[1]) != 2 or not ml[1].isdigit():\n return False\n if len(ml[2]) != 3 or not ml[2].isdigit():\n return False\n if not ml[3].isalpha() or not ml[3].isupper():\n return False\n for x in ml[4:]:\n if len(x) != 2 or not x.isdigit():\n return False\n return True"]
{"fn_name": "validate", "inputs": [["Is this a right message?"], ["MDZHB 85 596 KLASA 81 00 02 91"], ["MDZHB 12 733 EDINENIE 67 79 66 32"], ["MDZHV 60 130 VATRUKH 58 89 54 54"], ["MDZHB 85 596 BRAMIRKA 81 00 02 91"], ["MDZHB 12 733 INITIAL 67 79 66 32"], ["MDZHB 60 130 KROLI5T 58 89 54 54"], ["MDZHB 85 596 KAMASIT 81 00 02 91"], ["MDZHB 12 733 PREGRADA 67 79 66 32"], ["MD2HB 60 1S0 AKKRETSIA 58 89 54 54"], ["Is this a wrong message?"], ["MDZHBMDZHB 855 56 KLASA 81 00 02 91"], ["MDZHB 12 733 EDIN ENIE 67 79 66 32"], ["MDZHB 60 130 FRONTAL 58 89 54 54"], ["MDZHB 85 596 PALEOLIT 81 12 52 91"], ["MDZHB 12 733 6INITIAL 67 79 66 32"], ["MDZHB 60 130 KRO-LIST 58 89 54 54"], ["MDZHB 85 596 MDZHB 81 00 02 9"], ["MDZHB 12 733 VOSKHOD 67 79 66 32"], ["MD2HB 60 120 AKKRETSIA 58895454"], ["MDZHB 102 733 BZHDM 67 79 66 32"], ["MDZHB 60 13 KROLIST 58 89 54 54"], ["MDZHB 85 596 MDZHB 81 00 02 99"], ["MDZHB 12 733 VOSKHOD 677 79 66 32"], ["MDZHB 12 733 VOSKHOD 67 793 66 32"], ["MDZHB 12 733 VOSKHOD 67 79 663 32"], ["MDZHB 12 733 VOSKHOD 67 79 66 322"], ["MDZHB 12 733 VOSKHOD 67793 66 32"], ["MDZHB 12 733 VOSKHOD 67 79"], ["MDZHB 12 733 VOSKHOD 67 79 66"]], "outputs": [[false], [true], [true], [false], [true], [true], [false], [true], [true], [false], [false], [false], [false], [true], [true], [false], [false], [false], [true], [false], [false], [false], [true], [false], [false], [false], [false], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,656
def validate(message):
e7ee12dd3cbec8dc60948a15523355ae
UNKNOWN
Same as [the original](https://www.codewars.com/kata/simple-fun-number-258-is-divisible-by-6) (same rules, really, go there for example and I strongly recommend completing it first), but with more than one asterisk (but always at least one). For example, `"*2"` should return `["12", "42", "72"]`. Similarly, `"*2*"` should return `["024", "120", "126", "222", "228", "324", "420", "426", "522", "528", "624", "720", "726", "822", "828", "924"]`. Order matters and returning the right one is part of the challenge itself, yep! More examples in the test codes and, of course, if you cannot generate any number divisible by 6, just return `[]` (or `[] of String` in Crystal).
["from itertools import product\n\ndef is_divisible_by_6(s):\n if s[-1] in '13579': return []\n ss = s.replace('*','{}')\n return [ v for v in (ss.format(*p) for p in product(*(['0123456789']*s.count('*')))) if not int(v)%6]", "def create_permutations(string):\n if '*' not in string:\n return [int(string)]\n return [x for i in range(10) for x in create_permutations(string.replace('*', str(i), 1))]\n \n\ndef is_divisible_by_6(string):\n return list(map(lambda x: str(x).zfill(len(string)), filter(lambda x: not x%6, create_permutations(string))))", "from itertools import product\n\ndef is_divisible_by_6(s):\n return [''.join(p) for p in product(*list('0123456789' if c == '*' else c for c in s)) if int(''.join(p)) % 6 == 0]", "def is_divisible_by_6(s):\n if s[-1] in \"13579\": return []\n l, base, step = s.count(\"*\"), int(s.replace(\"*\", \"0\")), (6 if s[-1] == \"*\" else 3)\n start, s = next(n for n in range(base, base + step) if n % step == 0) - base, s.replace(\"*\", \"{}\")\n return [s.format(*f\"{rep:0{l}d}\") for rep in range(start, 10**l, step)]", "def is_divisible_by_6(string):\n num_of_star = string.count('*')\n i = 0\n result = []\n num_lst = []\n while i < num_of_star:\n if i == 0:\n num_lst = [string.replace('*',str(x),1) for x in range(10)]\n i += 1\n else:\n c = num_lst[:]\n num_lst = [k.replace('*',str(x),1) for x in range(10) for k in c]\n i += 1\n \n for num in num_lst:\n \n if int(num) % 6 == 0:\n result.append(num)\n return list(sorted(result))", "from itertools import product\nfrom string import digits\n\ndef iter_candidates(s, pos):\n xs = list(s)\n for ds in product(digits, repeat=len(pos)):\n for i, d in zip(pos, ds):\n xs[i] = d\n yield ''.join(xs)\n \ndef is_divisible_by_6(s):\n pos = [i for i, x in enumerate(s) if x == '*']\n return [x for x in iter_candidates(s, pos) if int(x) % 6 == 0]", "from itertools import product as p\ndef is_divisible_by_6(s):\n return [u for u in [s.replace('*','{}').format(*x) for x in list(p(range(10),repeat=s.count('*')))] if int(u)%6==0]", "is_divisible_by_6=lambda s:[n for n in map(''.join,__import__('itertools').product(*(c=='*'and'0123456789'or c for c in s)))if int(n)%6<1]", "is_divisible_by_6=lambda s: [] if s[-1] in \"13579\" else sum((is_divisible_by_6(s.replace(\"*\",e,1)) for e in \"0123456789\"),[]) if s.count(\"*\")>1 else (lambda t: [s.replace(\"*\",str(e)) for e in range((3-t)%3,10,3) if s[-1]!=\"*\" or not e%2])(sum(int(e) for e in s if e!=\"*\"))", "from itertools import product\n\ndef is_divisible_by_6(string):\n result = []\n n = 0\n indices = []\n for i, c in enumerate(string):\n if c == '*':\n n += 1\n indices.append(i)\n\n s = list(string)\n for combo in product(list(map(str, range(10))), repeat=n):\n for idx, digit in zip(indices, combo):\n s[idx] = digit\n if int(''.join(s)) % 6 == 0:\n result.append(''.join(s))\n \n return result"]
{"fn_name": "is_divisible_by_6", "inputs": [["*2"], ["*21"], ["**1"], ["*2*"], ["***"]], "outputs": [[["12", "42", "72"]], [[]], [[]], [["024", "120", "126", "222", "228", "324", "420", "426", "522", "528", "624", "720", "726", "822", "828", "924"]], [["000", "006", "012", "018", "024", "030", "036", "042", "048", "054", "060", "066", "072", "078", "084", "090", "096", "102", "108", "114", "120", "126", "132", "138", "144", "150", "156", "162", "168", "174", "180", "186", "192", "198", "204", "210", "216", "222", "228", "234", "240", "246", "252", "258", "264", "270", "276", "282", "288", "294", "300", "306", "312", "318", "324", "330", "336", "342", "348", "354", "360", "366", "372", "378", "384", "390", "396", "402", "408", "414", "420", "426", "432", "438", "444", "450", "456", "462", "468", "474", "480", "486", "492", "498", "504", "510", "516", "522", "528", "534", "540", "546", "552", "558", "564", "570", "576", "582", "588", "594", "600", "606", "612", "618", "624", "630", "636", "642", "648", "654", "660", "666", "672", "678", "684", "690", "696", "702", "708", "714", "720", "726", "732", "738", "744", "750", "756", "762", "768", "774", "780", "786", "792", "798", "804", "810", "816", "822", "828", "834", "840", "846", "852", "858", "864", "870", "876", "882", "888", "894", "900", "906", "912", "918", "924", "930", "936", "942", "948", "954", "960", "966", "972", "978", "984", "990", "996"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,167
def is_divisible_by_6(s):
4180c596731750247fedef3522d8367e
UNKNOWN
In this Kata, you will be given a string of numbers in sequence and your task will be to return the missing number. If there is no number missing or there is an error in the sequence, return `-1`. For example: ```Haskell missing("123567") = 4 missing("899091939495") = 92 missing("9899101102") = 100 missing("599600601602") = -1 -- no number missing missing("8990919395") = -1 -- error in sequence. Both 92 and 94 missing. ``` The sequence will always be in ascending order. More examples in the test cases. Good luck!
["def missing(seq):\n for digits in range(1, len(seq) // 2 + 1):\n my_seq = last = seq[:digits]\n n = int(my_seq)\n missing = None\n \n while len(my_seq) < len(seq):\n n += 1\n my_seq += str(n)\n \n if not seq.startswith(my_seq):\n if missing == None:\n missing = n\n my_seq = last\n else:\n break\n else:\n last = my_seq\n \n if my_seq == seq and missing:\n return missing\n \n return -1", "def missing(s):\n i = 1\n while True:\n start, missing, j = int(s[:i]), [], i\n number = start + 1\n while j <= len(s) - len(str(number)):\n if int(s[j:j + len(str(number))]) != number : missing.append(number)\n else : j += len(str(number))\n number += 1\n if len(missing) > 1 : break\n else:\n if not missing : return -1\n return missing[0]\n i += 1", "def missing(seq):\n digits = 1\n \n while digits <= len(seq) // 2:\n my_seq = last = seq[:digits]\n n = int(my_seq)\n missing = None\n \n while len(my_seq) < len(seq):\n n += 1\n my_seq += str(n)\n \n if not seq.startswith(my_seq):\n if missing == None:\n missing = n\n my_seq = last\n else:\n break\n else:\n last = my_seq\n \n if my_seq == seq and missing:\n return missing\n \n digits += 1\n \n return -1", "def missing(s):\n for k in range(1, 7):\n p, n, l, gaps = s, int(s[:k]), k, []\n while p:\n p = p[l:]\n if p.startswith(str(n+1)):\n l, n = len(str(n+1)), n + 1\n elif p.startswith(str(n+2)):\n gaps += [n + 1]\n l, n = len(str(n+2)), n + 2\n else: \n break\n if len(gaps) == 1 and p == '': return gaps.pop() \n return -1", "def missing(s):\n for i in range(1, len(s)//2+1):\n save, j, miss = int(s[:i]), i, None\n while j < len(s):\n x, y = str(save+1), str(save+2)\n if s[j:].startswith(x):\n j += len(x)\n save = int(x)\n elif s[j:].startswith(y) and miss is None:\n j += len(y)\n save = int(y)\n miss = int(x)\n else:\n miss = None\n break\n if miss is not None: return miss\n return -1", "def missing(s):\n for i in range(1, len(s) // 2 + 1):\n n, missing = int(s[:i]), None\n while i < len(s):\n n += 1\n j = len(str(n))\n if s.startswith(str(n)[:len(s) - i], i):\n i += j\n elif missing:\n missing = None # 2 missing numbers\n break\n else: missing = n\n else:\n if not missing: return -1 # No missing number\n if missing: return missing # 1 missing number\n return -1 # Error in the sequence", "def missing(s):\n for nd in range(1,min(7, len(s)//2+1)):\n guess, miss = s[:nd], ''\n n = int(guess)\n while len(guess) < len(s):\n n += 1\n guess += str(n)\n if not s.startswith(guess):\n if miss:\n miss = ''\n break\n miss = str(n)\n guess = guess[:-len(miss)]\n if miss: return int(miss)\n return -1", "\nclass State:\n\n def __init__(self, pos, missing_candidate, expected1, expected2):\n self.pos = pos\n self.missing_candidate = missing_candidate\n self.expected1 = expected1\n self.expected2 = expected2\n self.valid = None\n \n def update_found_seq(self):\n self.pos += len(str(self.expected1))\n self.expected1 += 1\n self.expected2 = self.expected1 + 1\n \n def update_found_skip(self):\n self.missing_candidate = self.expected1\n self.pos += len(str(self.expected2))\n self.expected1 = self.expected2 + 1\n self.expected2 = self.expected1 + 1\n\n def __str__(self):\n return \"State({0}, {1}, {2}, {3})\".format(self.pos, self.missing_candidate, self.expected1, self.expected2)\n\ndef missing(s):\n res = -1\n for l in range(1, len(s)//3+1):\n q = State(0, None, int(s[0:l]), 0)\n while q.pos < len(s) and q.valid==None:\n if s[q.pos:].startswith(str(q.expected1)):\n q.update_found_seq()\n elif not q.missing_candidate and s[q.pos:].startswith(str(q.expected2)):\n q.update_found_skip()\n else:\n q.valid = False\n if q.pos == len(s):\n q.valid = True\n if q.valid:\n if q.missing_candidate:\n res = q.missing_candidate\n else:\n res = -1\n break\n\n return res\n", "def missing(s):\n def missing(s, base, candidate=-1):\n head, tail = int(s[:base]), s[base:]\n if tail.startswith(str(head + 1)):\n return missing(tail, len(str(head + 1)), candidate)\n if tail.startswith(str(head + 2)):\n return missing(tail, len(str(head + 2)), head + 1) if candidate == -1 else -1\n return candidate if tail == \"\" else -1\n for base in range(1, len(s) // 2 + 1):\n result = missing(s, base)\n if result != -1:\n return result\n return -1", "def missing(s):\n result = -1\n for start_chunk in range(1,len(s)//2 +1):\n res = inner(s,start_chunk)\n if res != -1:\n result = res\n return result\n\ndef inner(s,start_chunk):\n result = -1\n nums = []\n rest = s\n rip_count = 0\n last = int(rest[:start_chunk])\n rest = rest[start_chunk:]\n nums.append(last)\n chunk = start_chunk\n while rest!= '':\n if int(rest[:chunk]) - last != 1:\n if int(rest[:chunk+1]) - last == 1:\n chunk +=1\n print('chunk +=1')\n elif int(rest[:chunk+1]) - last == 2:\n chunk +=1\n rip_count+=1\n print('chunk +=1')\n print('rip_count+=1')\n result = last + 1\n elif int(rest[:chunk]) - last == 2:\n rip_count+=1\n print('rip_count+=1')\n result = last + 1\n else: return -1\n nums.append(int(rest[:chunk]))\n last = int(rest[:chunk])\n rest = rest[chunk:]\n print(nums)\n if(rip_count)>1:\n return -1\n return result"]
{"fn_name": "missing", "inputs": [["123567"], ["899091939495"], ["9899101102"], ["599600601602"], ["8990919395"], ["998999100010011003"], ["99991000110002"], ["979899100101102"], ["900001900002900004900005900006"]], "outputs": [[4], [92], [100], [-1], [-1], [1002], [10000], [-1], [900003]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,948
def missing(s):
e4103294d87d0eef27ac8f25e00445ce
UNKNOWN
Write a function that takes an array/list of numbers and returns a number such that Explanation total([1,2,3,4,5]) => 48 1+2=3--\ 3+5 => 8 \ 2+3=5--/ \ == 8+12=>20\ ==>5+7=> 12 / \ 20+28 => 48 3+4=7--\ / == 12+16=>28/ 4+5=9--/ 7+9 => 16 / if total([1,2,3]) => 8 then first+second => 3 \ then 3+5 => 8 second+third => 5 / ### Examples ```python total([-1,-1,-1]) => -4 total([1,2,3,4]) => 20 ``` **Note:** each array/list will have at least an element and all elements will be valid numbers.
["def total(arr):\n while len(arr) > 1:\n arr = [x+y for x,y in zip(arr,arr[1:])]\n return arr[0]", "def total(arr):\n from math import factorial as fact\n\n choose = lambda a, b: fact(a) / (fact(a-b) * fact(b))\n\n return sum(choose(len(arr)-1, i) * v for i, v in enumerate(arr))", "def total(xs):\n return xs[0] if len(xs) == 1 else total([xs[i] + x for i, x in enumerate(xs[1:])])", "def total(arr):\n #your code here\n if len(arr) == 1:\n return arr[0]\n arr2 = []\n for i in range(len(arr)-1):\n arr2.append(arr[i]+arr[i+1])\n return total(arr2)", "def total(arr):\n while len(arr) > 2:\n arr = [x + y for x, y in zip(arr, arr[1:])]\n return sum(arr)", "total=lambda a:a[0] if len(a)==1 else total([a[i]+a[i+1] for i in range(len(a)-1)])", "from math import factorial as fac\n\ndef C(n, k):\n return fac(n) // (fac(k) * fac(n-k))\n \ndef total(arr):\n l = len(arr)\n return sum(arr[i] * C(l-1, i) for i in range(l))\n", "def total(arr):\n a = arr[:]\n for i in range(len(a), 1, -1):\n for j in range(1, i):\n a[j - 1] += a[j]\n return a[0]\n"]
{"fn_name": "total", "inputs": [[[1, 2, 3, 4, 5]], [[1, 2, 3, 4]], [[1, 2, 3]], [[4, 4, 52, 23, 32, 1, -1]], [[4, 4, 5, -1]], [[-1, -1, -1]], [[-1, -1, -10, 42, 92, 1, 23, 6, -3]], [[-1, 1, -1, 1]], [[42]]], "outputs": [[48], [20], [8], [1753], [30], [-4], [9248], [0], [42]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,148
def total(arr):
c56c5c6985d1f2214d0a41dabe0a1fe5
UNKNOWN
We need you to implement a method of receiving commands over a network, processing the information and responding. Our device will send a single packet to you containing data and an instruction which you must perform before returning your reply. To keep things simple, we will be passing a single "packet" as a string. Each "byte" contained in the packet is represented by 4 chars. One packet is structured as below: ``` Header Instruction Data1 Data2 Footer ------ ------ ------ ------ ------ H1H1 0F12 0012 0008 F4F4 ------ ------ ------ ------ ------ The string received in this case would be - "H1H10F1200120008F4F4" Instruction: The calculation you should perform, always one of the below. 0F12 = Addition B7A2 = Subtraction C3D9 = Multiplication FFFF = This instruction code should be used to identify your return value. ``` - The Header and Footer are unique identifiers which you must use to form your reply. - Data1 and Data2 are the decimal representation of the data you should apply your instruction to. _i.e 0109 = 109._ - Your response must include the received header/footer, a "FFFF" instruction code, and the result of your calculation stored in Data1. - Data2 should be zero'd out to "0000". ``` To give a complete example: If you receive message "H1H10F1200120008F4F4". The correct response would be "H1H1FFFF00200000F4F4" ``` In the event that your calculation produces a negative result, the value returned should be "0000", similarily if the value is above 9999 you should return "9999". Goodluck, I look forward to reading your creative solutions!
["INSTRUCTIONS = {\"0F12\": int.__add__, \"B7A2\": int.__sub__, \"C3D9\": int.__mul__}\n\ndef communication_module(packet):\n header,inst,d1,d2,footer = (packet[i:i+4] for i in range(0,20,4))\n res = max(0, min(9999, INSTRUCTIONS[inst](int(d1), int(d2)) ))\n \n return f\"{header}FFFF{res:0>4}0000{footer}\"", "import re\nfrom operator import add, sub, mul\n\ninstructions = {\n '0F12': add,\n 'B7A2': sub,\n 'C3D9': mul,\n}\n\ndef communication_module(packet):\n header, instruction, data1, data2, footer = re.findall('....', packet)\n result = instructions[instruction](int(data1), int(data2))\n return '{}FFFF{:04}0000{}'.format(header, min(max(result, 0), 9999), footer)", "def communication_module(p):\n return '%sFFFF%04i0000%s' % (p[:4], max(min(eval(p[8:12].lstrip('0') + {'0F12':'+', 'B7A2':'-', 'C3D9':'*'}[p[4:8]] + p[12:16].lstrip('0')), 9999), 0), p[-4:])", "def communication_module(packet):\n header, footer = packet[:4], packet[-4:]\n instr, rvalue = packet[4:8], 'FFFF'\n data1, data2 = packet[8:12], packet[12:16]\n \n if instr == '0F12':\n calc = int(data1) + int(data2)\n elif instr == 'B7A2':\n calc = int(data1) - int(data2)\n elif instr == 'C3D9':\n calc = int(data1) * int(data2)\n \n if calc > 9999:\n calc = 9999\n elif calc < 0:\n calc = 0\n \n rstring = f'{header}{rvalue}{calc:04d}0000{footer}'\n \n return rstring", "def communication_module(packet):\n part = [packet[i:i+4] for i in range(0, len(packet), 4)]\n d = {'0F12':'+','B7A2':'-','C3D9':'*'}\n res = eval(f'{int(part[2])}{d[part[1]]}{int(part[3])}')\n res = max(0, min(res, 9999))\n return part[0]+f'FFFF{str(res).zfill(4)}0000'+part[4]", "from operator import add,sub,mul\ndef communication_module(packet):\n part = [packet[i:i+4] for i in range(0, len(packet), 4)]\n res = {'0F12':add,'B7A2':sub,'C3D9':mul}[part[1]](int(part[2]), int(part[3]))\n res = max(0, min(res, 9999))\n return part[0]+f'FFFF{str(res).zfill(4)}0000'+part[4]", "import operator\n\nfuncs = {'0F12': operator.add, 'B7A2': operator.sub, 'C3D9': operator.mul}\n\ndef communication_module(packet):\n instruction, one, two = packet[4:8], int(packet[8:12]), int(packet[12:16])\n \n result = funcs[instruction](one, two)\n \n if result > 9999:\n result = 9999\n elif result < 0:\n result = 0\n \n return '{}FFFF{:0>4}0000{}'.format(packet[:4], result, packet[16:])", "def communication_module(packet):\n header, instruction, data1, data2, footer = packet[:4], packet[4:8], int(packet[8:12]), int(packet[12:16]), packet[-4:]\n\n operations = {'0F12': data1 + data2, 'B7A2': data1 - data2, 'C3D9': data1 * data2}\n calc_str = str(min(9999,max(0,operations[instruction]))).zfill(4)\n \n instruction, data2R = 'F' * 4, '0' * 4\n return header + instruction + calc_str + data2R + footer", "def communication_module(packet):\n # your code\n calc = 0\n if packet[4:8] == \"0F12\":\n calc = int(packet[8:12]) + int(packet[12:16])\n elif packet[4:8] == \"B7A2\":\n calc = int(packet[8:12]) - int(packet[12:16])\n elif packet[4:8] == \"C3D9\":\n calc = int(packet[8:12]) * int(packet[12:16])\n \n if calc < 0: \n calc = \"0000\"\n elif calc > 9999:\n calc = \"9999\"\n \n return packet[0:4] + \"FFFF\" + str(calc).zfill(4) + \"0000\" + packet[16:20]\n", "def communication_module(s):\n result = str(max(0, min(int(s[8:12]) + int(s[12:16]) if s[4] == '0' else int(s[8:12]) - int(s[12:16]) if s[4] == 'B' else int(s[8:12]) * int(s[12:16]), 9999)))\n return s[:4] + \"FFFF\" + '0' * (4 - len(result)) + result + \"0000\" + s[-4:]"]
{"fn_name": "communication_module", "inputs": [["H1H10F1200120008F4F4"], ["D7D70F1200250015G8G8"], ["X7X7B7A201400058L0L0"], ["Y2Y2B7A210000902N5N5"], ["R5R5C3D900120008K4K4"], ["S2S2C3D900250005I9I9"], ["E4E40F1239128908Z3Z3"], ["A6A6C3D911150015M0M0"], ["T7T7B7A200258908P2P2"], ["S4S4B7A201153215U8U8"]], "outputs": [["H1H1FFFF00200000F4F4"], ["D7D7FFFF00400000G8G8"], ["X7X7FFFF00820000L0L0"], ["Y2Y2FFFF00980000N5N5"], ["R5R5FFFF00960000K4K4"], ["S2S2FFFF01250000I9I9"], ["E4E4FFFF99990000Z3Z3"], ["A6A6FFFF99990000M0M0"], ["T7T7FFFF00000000P2P2"], ["S4S4FFFF00000000U8U8"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,747
def communication_module(packet):
0e3450d8cdeb6a17d996feceb149a096
UNKNOWN
In this Kata, you will sort elements in an array by decreasing frequency of elements. If two elements have the same frequency, sort them by increasing value. More examples in test cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
["from collections import Counter\n\ndef solve(a):\n c = Counter(a)\n return sorted(a, key=lambda k: (-c[k], k))", "def solve(arr):\n return sorted(arr, key= lambda x: (-arr.count(x), x))", "def solve(arr):\n return sorted(sorted(arr), key=lambda n: arr.count(n), reverse=True)", "def solve(arr):\n freq = {n: -arr.count(n) for n in set(arr)}\n return sorted(sorted(arr), key=freq.get)", "from collections import Counter\n\ndef solve(xs):\n fs = Counter(xs)\n return sorted(xs, key=lambda x: (-fs[x], x))", "from collections import Counter\n\ndef solve(arr):\n c = Counter(arr)\n return sorted(arr, key=lambda x: (-c[x], x))", "def solve(arr):\n return sorted(arr, key=lambda x: (arr.count(x),-x), reverse=True)", "def solve(array):\n return sorted(sorted(array), key=array.count, reverse=True)", "from collections import Counter\nfrom itertools import groupby\n\ndef unpack_fun(l):\n return sorted([k for k,v in l for i in range(v)])\n\ndef solve(arr):\n out_lst=[]\n l=[list(v) for k,v in groupby(Counter(arr).most_common(),key=lambda x:x[1])]\n for v in l:\n out_lst.extend(unpack_fun(v))\n return out_lst", "def solve(arr):\n c=[]\n answer = []\n for n in range(0,max(arr)+1):\n c.append(arr.count(n))\n x = sorted(c, reverse=True)\n for i in x:\n m = i\n while(m>0):\n answer.append(c.index(i))\n m-=1\n c[c.index(i)]=-1\n return answer"]
{"fn_name": "solve", "inputs": [[[2, 3, 5, 3, 7, 9, 5, 3, 7]], [[1, 2, 3, 0, 5, 0, 1, 6, 8, 8, 6, 9, 1]], [[5, 9, 6, 9, 6, 5, 9, 9, 4, 4]], [[4, 4, 2, 5, 1, 1, 3, 3, 2, 8]], [[4, 9, 5, 0, 7, 3, 8, 4, 9, 0]]], "outputs": [[[3, 3, 3, 5, 5, 7, 7, 2, 9]], [[1, 1, 1, 0, 0, 6, 6, 8, 8, 2, 3, 5, 9]], [[9, 9, 9, 9, 4, 4, 5, 5, 6, 6]], [[1, 1, 2, 2, 3, 3, 4, 4, 5, 8]], [[0, 0, 4, 4, 9, 9, 3, 5, 7, 8]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,469
def solve(arr):
9ee6e3a445c68da268b19ed86bd8c023
UNKNOWN
In recreational mathematics, a [Keith number](https://en.wikipedia.org/wiki/Keith_number) or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence: `14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, ...` (sequence A007629 in the OEIS) Keith numbers were introduced by Mike Keith in 1987. They are computationally very challenging to find, with only about 100 known. Implement the code to check if the given number is a Keith number. Return the number number of iteration needed to confirm it; otherwise return `false`. **Note:** 1-digit numbers are **not** Keith numbers by definition ## Examples ``` n = 197 # --> [1, 9, 7] # calculation iteration 1 + 9 + 7 = 17 # 1 9 + 7 + 17 = 33 # 2 7 + 17 + 33 = 57 # 3 17 + 33 + 57 = 107 # 4 33 + 57 + 107 = 197 # 5 ``` As `197` is the same as the initial number, so it's a Keith number: return `5` Another example: ``` n = 196 # calculation iteration 1 + 9 + 6 = 16 # 1 ... ``` `196` is not a Keith number, so return `false`
["def is_keith_number(n):\n numList = [int(i) for i in str(n)] # int array\n if len(numList) > 1: # min 2 digits\n itr = 0\n while numList[0] <= n:\n # replace array entries by its sum:\n numList[itr % len(numList)] = sum(numList)\n itr += 1\n if n in numList: # keith-condition\n return itr\n return False", "def is_keith_number(n):\n turn, seq = 0, [int(d) for d in str(n)]\n while seq[-1] < n:\n seq = seq[1:] + [sum(seq)]\n turn += 1\n return n > 9 and seq[-1] == n and turn", "from collections import deque\nfrom itertools import count, dropwhile\n\n\ndef iter_seq(init):\n ds = deque(map(int, str(init)))\n while True:\n n = sum(ds)\n yield n\n ds.popleft()\n ds.append(n)\n\n\ndef is_keith_number(n):\n if n < 10:\n return False\n i, d = next(dropwhile(lambda x: x[1] < n, enumerate(iter_seq(n), 1)))\n return i if d == n else False", "def is_keith_number(n):\n i = 0\n terms = list(map(int, str(n)))\n while terms[-1] < n:\n i += 1\n terms = terms[1:] + [sum(terms)]\n return terms[-1] == n and i", "def is_keith_number(n):\n s = list(map(int, str(n)))\n l = len(s)\n while s[-1] < n:\n s.append(sum(s[-l:]))\n return len(s) - l if n in s else False", "def is_keith_number(n):\n if n <= 10: return False\n c, k_lst, k_num = 0, list(str(n)), n\n while k_num <= n:\n k_num = sum([int(x) for x in k_lst])\n c += 1\n if k_num == n: return c\n k_lst.append(k_num)\n k_lst.pop(0)\n return False", "def is_keith_number(n):\n def rec(ds, i):\n d = sum(ds)\n ds = ds[1:]\n ds.append(d);\n return i if d == n else False if d > n else rec(ds, i + 1)\n return False if n < 10 else rec([int(x) for x in list(str(n))], 1)", "# It's nice to put the OEIS but it's not that interesting if they give the algo\ndef is_keith_number(n):\n if n < 10: return False\n x = list(map(int, str(n)))\n y, i = sum(x), 1\n while y < n:\n i, x, y = i+1, x[1:]+[y], 2*y-x[0]\n return i * (y==n)", "def is_keith_number(n):\n res = [int(x) for x in str(n)]\n tmp = sum(res)\n cnt = 1\n while tmp < n:\n cnt += 1\n res.pop(0)\n res.append(tmp)\n tmp = sum(res)\n if tmp == n:\n return cnt\n return False", "from itertools import count\n\ndef is_keith_number(n):\n lst = list(map(int,str(n)))\n s = sum(lst)\n for i in count(1):\n if s>=n: return n>9 and s==n and i\n lst, s = lst[1:] + [s], s*2-lst[0]"]
{"fn_name": "is_keith_number", "inputs": [[14], [10], [4], [28], [23], [0], [19], [47], [34], [61], [58], [75], [197], [742], [1104], [1537], [2208], [2697], [7385], [31331], [120284], [1084051], [44121607], [251133297], [96189170155], [11812665388886672], [855191324330802397989], [18354972585225358067718266], [41796205765147426974704791528]], "outputs": [[3], [false], [false], [3], [false], [false], [2], [4], [false], [6], [false], [5], [5], [8], [9], [8], [9], [false], [10], [13], [14], [17], [22], [24], [32], [48], [64], [78], [89]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,667
def is_keith_number(n):
5ea902135a87658afc96603aad50cb4d
UNKNOWN
An expression is formed by taking the digits 1 to 9 in numerical order and then inserting into each gap between the numbers either a plus sign or a minus sign or neither. Your task is to write a method which takes one parameter and returns the **smallest possible number** of plus and minus signs necessary to form such an expression which equals the input. **Note:** All digits from 1-9 must be used exactly once. If there is no possible expression that evaluates to the input, then return `null/nil/None`. ~~~if:haskell `eval :: String -> Int` is available in `Preloaded` for your convenience. ~~~ There are 50 random tests with upper bound of the input = 1000. ## Examples When the input is 100, you need to return `3`, since that is the minimum number of signs required, because: 123 - 45 - 67 + 89 = 100 (3 operators in total). More examples: ``` 11 --> 5 # 1 + 2 + 34 + 56 + 7 - 89 = 11 100 --> 3 # 123 - 45 - 67 + 89 = 100 766 --> 4 # 1 - 2 + 34 - 56 + 789 = 766 160 --> - # no solution possible ``` Inspired by a [puzzle on BBC Radio 4](https://www.bbc.co.uk/programmes/p057wxwl) (which is unfortunately not available anymore)
["from itertools import product\n\ndef operator_insertor(n):\n result = []\n \n for ops in product([\"+\", \"-\", \"\"], repeat=8):\n expression = \"\".join(a+b for a, b in zip(\"123456789\", list(ops) + [\"\"]))\n res = eval(expression)\n if res == n:\n result.append(len(expression) - 9)\n \n return min(result, default=None)", "def operator_insertor(total):\n q = [(total, \"123456789\", 0)]\n while q:\n s, n, d = q.pop(0)\n if int(n) == s: return d\n for i in range(0, len(n) - 1):\n n1 = int(n[0:i + 1])\n n2 = n[i + 1:]\n q.append((s - n1, n2, d + 1))\n q.append((n1 - s, n2, d + 1))", "\"\"\"\"\nYOU ARE LOOKING AT THE MIGHTIEST OF CODE!!!!!\n\nHERE IS THE INEFFICIENT PROGRAM THAT WROTE MY FUNCTION:\n\ndef operator_insertor(n):\n bestsofar = 10\n for i in range(3**8):\n if eval(genstr(i)) == n:\n a=list(tc(i))\n while a.count(\" \"):\n a.remove(\" \")\n if len(a) < bestsofar:\n bestsofar = len(a)\n if bestsofar == 10:\n return None\n else:\n return bestsofar\n # your code here\ndef genstr(y):\n a=list(\"123456789\")\n b=list(tc(y))\n c = [item for pair in zip(a, b) for item in pair]\n while (c.count(\" \")):\n c.remove(\" \")\n d = ''.join(c)\n return d\n\ndef tc(n):\n if n == 0:\n return '0'\n nums = []\n while n:\n n, r = divmod(n, 3)\n nums.append(str(r))\n while len(nums) < 8:\n nums.append(\"0\")\n streng = ''.join(reversed(nums))\n intab=\"012\"\n outtab=\" +-\"\n trantab = str.maketrans(intab, outtab)\n return streng.translate(trantab)+\" \"\nprint(\"def operator_insertor(n):\")\nfor i in range(1001):\n print(\" if n ==\",i,\":\")\n print(\" return\",operator_insertor(i))\n \n-------------\n\nI realise that with my code I could have written a more efficient final function, but it's for the laughs gentlemen\n\nTHANK YOU AND HAVE A NICE DAY :)\n\"\"\"\n\ndef operator_insertor(n):\n if n == 0 :\n return 5\n if n == 1 :\n return 4\n if n == 2 :\n return 4\n if n == 3 :\n return 4\n if n == 4 :\n return 4\n if n == 5 :\n return 4\n if n == 6 :\n return 4\n if n == 7 :\n return 5\n if n == 8 :\n return 5\n if n == 9 :\n return 4\n if n == 10 :\n return 1\n if n == 11 :\n return 5\n if n == 12 :\n return 3\n if n == 13 :\n return 5\n if n == 14 :\n return 5\n if n == 15 :\n return 4\n if n == 16 :\n return 5\n if n == 17 :\n return 5\n if n == 18 :\n return 4\n if n == 19 :\n return 4\n if n == 20 :\n return 4\n if n == 21 :\n return 5\n if n == 22 :\n return 5\n if n == 23 :\n return 5\n if n == 24 :\n return 5\n if n == 25 :\n return 5\n if n == 26 :\n return 5\n if n == 27 :\n return 5\n if n == 28 :\n return 4\n if n == 29 :\n return 4\n if n == 30 :\n return 5\n if n == 31 :\n return 5\n if n == 32 :\n return 4\n if n == 33 :\n return 4\n if n == 34 :\n return 5\n if n == 35 :\n return 5\n if n == 36 :\n return 5\n if n == 37 :\n return 5\n if n == 38 :\n return 4\n if n == 39 :\n return 5\n if n == 40 :\n return 5\n if n == 41 :\n return 5\n if n == 42 :\n return 5\n if n == 43 :\n return 5\n if n == 44 :\n return 5\n if n == 45 :\n return 4\n if n == 46 :\n return 5\n if n == 47 :\n return 4\n if n == 48 :\n return 5\n if n == 49 :\n return 5\n if n == 50 :\n return 5\n if n == 51 :\n return 5\n if n == 52 :\n return 5\n if n == 53 :\n return 5\n if n == 54 :\n return 5\n if n == 55 :\n return 5\n if n == 56 :\n return 3\n if n == 57 :\n return 5\n if n == 58 :\n return 5\n if n == 59 :\n return 4\n if n == 60 :\n return 5\n if n == 61 :\n return 5\n if n == 62 :\n return 5\n if n == 63 :\n return 4\n if n == 64 :\n return 5\n if n == 65 :\n return 5\n if n == 66 :\n return 4\n if n == 67 :\n return 5\n if n == 68 :\n return 5\n if n == 69 :\n return 5\n if n == 70 :\n return 6\n if n == 71 :\n return 5\n if n == 72 :\n return 4\n if n == 73 :\n return 4\n if n == 74 :\n return 4\n if n == 75 :\n return 4\n if n == 76 :\n return 4\n if n == 77 :\n return 4\n if n == 78 :\n return 4\n if n == 79 :\n return 4\n if n == 80 :\n return 4\n if n == 81 :\n return 5\n if n == 82 :\n return 4\n if n == 83 :\n return 4\n if n == 84 :\n return 4\n if n == 85 :\n return 5\n if n == 86 :\n return 4\n if n == 87 :\n return 4\n if n == 88 :\n return 4\n if n == 89 :\n return 4\n if n == 90 :\n return 5\n if n == 91 :\n return 4\n if n == 92 :\n return 4\n if n == 93 :\n return 4\n if n == 94 :\n return 5\n if n == 95 :\n return 5\n if n == 96 :\n return 4\n if n == 97 :\n return 4\n if n == 98 :\n return 5\n if n == 99 :\n return 5\n if n == 100 :\n return 3\n if n == 101 :\n return 4\n if n == 102 :\n return 4\n if n == 103 :\n return 4\n if n == 104 :\n return 5\n if n == 105 :\n return 4\n if n == 106 :\n return 4\n if n == 107 :\n return 5\n if n == 108 :\n return 5\n if n == 109 :\n return 5\n if n == 110 :\n return 4\n if n == 111 :\n return 5\n if n == 112 :\n return 5\n if n == 113 :\n return 5\n if n == 114 :\n return 4\n if n == 115 :\n return 6\n if n == 116 :\n return 4\n if n == 117 :\n return 5\n if n == 118 :\n return 4\n if n == 119 :\n return 5\n if n == 120 :\n return 4\n if n == 121 :\n return 4\n if n == 122 :\n return 5\n if n == 123 :\n return 5\n if n == 124 :\n return 6\n if n == 125 :\n return 5\n if n == 126 :\n return 4\n if n == 127 :\n return 5\n if n == 128 :\n return 4\n if n == 129 :\n return 4\n if n == 130 :\n return 4\n if n == 131 :\n return 5\n if n == 132 :\n return 4\n if n == 133 :\n return 5\n if n == 134 :\n return 5\n if n == 135 :\n return 4\n if n == 136 :\n return 4\n if n == 137 :\n return 5\n if n == 138 :\n return 5\n if n == 139 :\n return 4\n if n == 140 :\n return 4\n if n == 141 :\n return 4\n if n == 142 :\n return 5\n if n == 143 :\n return 5\n if n == 144 :\n return 4\n if n == 145 :\n return 4\n if n == 146 :\n return 3\n if n == 147 :\n return 5\n if n == 148 :\n return 5\n if n == 149 :\n return 5\n if n == 150 :\n return 4\n if n == 151 :\n return 5\n if n == 152 :\n return 5\n if n == 153 :\n return 4\n if n == 154 :\n return 4\n if n == 155 :\n return 5\n if n == 156 :\n return 5\n if n == 157 :\n return 5\n if n == 158 :\n return 4\n if n == 159 :\n return 4\n if n == 160 :\n return None\n if n == 161 :\n return 6\n if n == 162 :\n return 4\n if n == 163 :\n return 5\n if n == 164 :\n return 5\n if n == 165 :\n return 5\n if n == 166 :\n return 4\n if n == 167 :\n return 4\n if n == 168 :\n return 4\n if n == 169 :\n return 5\n if n == 170 :\n return 5\n if n == 171 :\n return 4\n if n == 172 :\n return 5\n if n == 173 :\n return 5\n if n == 174 :\n return 5\n if n == 175 :\n return 5\n if n == 176 :\n return 5\n if n == 177 :\n return 5\n if n == 178 :\n return None\n if n == 179 :\n return 4\n if n == 180 :\n return 4\n if n == 181 :\n return 5\n if n == 182 :\n return 5\n if n == 183 :\n return 5\n if n == 184 :\n return 4\n if n == 185 :\n return 5\n if n == 186 :\n return 5\n if n == 187 :\n return 5\n if n == 188 :\n return 4\n if n == 189 :\n return 4\n if n == 190 :\n return 3\n if n == 191 :\n return 5\n if n == 192 :\n return 4\n if n == 193 :\n return 5\n if n == 194 :\n return 5\n if n == 195 :\n return 4\n if n == 196 :\n return None\n if n == 197 :\n return 4\n if n == 198 :\n return 4\n if n == 199 :\n return 5\n if n == 200 :\n return 5\n if n == 201 :\n return 3\n if n == 202 :\n return 5\n if n == 203 :\n return 5\n if n == 204 :\n return 4\n if n == 205 :\n return 5\n if n == 206 :\n return 5\n if n == 207 :\n return 4\n if n == 208 :\n return 4\n if n == 209 :\n return 4\n if n == 210 :\n return 4\n if n == 211 :\n return None\n if n == 212 :\n return 5\n if n == 213 :\n return 5\n if n == 214 :\n return 5\n if n == 215 :\n return 5\n if n == 216 :\n return 4\n if n == 217 :\n return 5\n if n == 218 :\n return 4\n if n == 219 :\n return None\n if n == 220 :\n return 5\n if n == 221 :\n return None\n if n == 222 :\n return 4\n if n == 223 :\n return None\n if n == 224 :\n return 5\n if n == 225 :\n return 4\n if n == 226 :\n return 5\n if n == 227 :\n return None\n if n == 228 :\n return 6\n if n == 229 :\n return None\n if n == 230 :\n return 6\n if n == 231 :\n return 4\n if n == 232 :\n return 6\n if n == 233 :\n return None\n if n == 234 :\n return 3\n if n == 235 :\n return None\n if n == 236 :\n return 4\n if n == 237 :\n return None\n if n == 238 :\n return 6\n if n == 239 :\n return None\n if n == 240 :\n return 6\n if n == 241 :\n return None\n if n == 242 :\n return 5\n if n == 243 :\n return 4\n if n == 244 :\n return 4\n if n == 245 :\n return 3\n if n == 246 :\n return 5\n if n == 247 :\n return None\n if n == 248 :\n return 4\n if n == 249 :\n return 4\n if n == 250 :\n return None\n if n == 251 :\n return 5\n if n == 252 :\n return 4\n if n == 253 :\n return None\n if n == 254 :\n return 5\n if n == 255 :\n return 4\n if n == 256 :\n return 4\n if n == 257 :\n return 4\n if n == 258 :\n return 4\n if n == 259 :\n return None\n if n == 260 :\n return 5\n if n == 261 :\n return 4\n if n == 262 :\n return 4\n if n == 263 :\n return 5\n if n == 264 :\n return 4\n if n == 265 :\n return 4\n if n == 266 :\n return 4\n if n == 267 :\n return 4\n if n == 268 :\n return 5\n if n == 269 :\n return 4\n if n == 270 :\n return 4\n if n == 271 :\n return 4\n if n == 272 :\n return 5\n if n == 273 :\n return 4\n if n == 274 :\n return None\n if n == 275 :\n return 4\n if n == 276 :\n return 4\n if n == 277 :\n return None\n if n == 278 :\n return 4\n if n == 279 :\n return 4\n if n == 280 :\n return 4\n if n == 281 :\n return 4\n if n == 282 :\n return 4\n if n == 283 :\n return 5\n if n == 284 :\n return None\n if n == 285 :\n return 5\n if n == 286 :\n return None\n if n == 287 :\n return None\n if n == 288 :\n return 4\n if n == 289 :\n return 4\n if n == 290 :\n return 5\n if n == 291 :\n return 4\n if n == 292 :\n return None\n if n == 293 :\n return 5\n if n == 294 :\n return 4\n if n == 295 :\n return None\n if n == 296 :\n return 5\n if n == 297 :\n return 5\n if n == 298 :\n return 5\n if n == 299 :\n return 5\n if n == 300 :\n return None\n if n == 301 :\n return 5\n if n == 302 :\n return None\n if n == 303 :\n return 5\n if n == 304 :\n return None\n if n == 305 :\n return 5\n if n == 306 :\n return 5\n if n == 307 :\n return 4\n if n == 308 :\n return 5\n if n == 309 :\n return None\n if n == 310 :\n return None\n if n == 311 :\n return 3\n if n == 312 :\n return None\n if n == 313 :\n return None\n if n == 314 :\n return 5\n if n == 315 :\n return 5\n if n == 316 :\n return 5\n if n == 317 :\n return 4\n if n == 318 :\n return 5\n if n == 319 :\n return None\n if n == 320 :\n return 5\n if n == 321 :\n return 5\n if n == 322 :\n return 4\n if n == 323 :\n return 4\n if n == 324 :\n return 3\n if n == 325 :\n return None\n if n == 326 :\n return 4\n if n == 327 :\n return 4\n if n == 328 :\n return 5\n if n == 329 :\n return 4\n if n == 330 :\n return 5\n if n == 331 :\n return None\n if n == 332 :\n return 5\n if n == 333 :\n return 4\n if n == 334 :\n return 6\n if n == 335 :\n return 3\n if n == 336 :\n return 3\n if n == 337 :\n return None\n if n == 338 :\n return 4\n if n == 339 :\n return 4\n if n == 340 :\n return 6\n if n == 341 :\n return 4\n if n == 342 :\n return 3\n if n == 343 :\n return 5\n if n == 344 :\n return 6\n if n == 345 :\n return 4\n if n == 346 :\n return 6\n if n == 347 :\n return 4\n if n == 348 :\n return 3\n if n == 349 :\n return None\n if n == 350 :\n return 6\n if n == 351 :\n return 4\n if n == 352 :\n return 4\n if n == 353 :\n return 5\n if n == 354 :\n return 3\n if n == 355 :\n return 5\n if n == 356 :\n return 5\n if n == 357 :\n return 3\n if n == 358 :\n return 6\n if n == 359 :\n return 5\n if n == 360 :\n return 4\n if n == 361 :\n return 5\n if n == 362 :\n return 5\n if n == 363 :\n return None\n if n == 364 :\n return 6\n if n == 365 :\n return 4\n if n == 366 :\n return 4\n if n == 367 :\n return None\n if n == 368 :\n return None\n if n == 369 :\n return 4\n if n == 370 :\n return 4\n if n == 371 :\n return 5\n if n == 372 :\n return None\n if n == 373 :\n return 4\n if n == 374 :\n return 5\n if n == 375 :\n return 4\n if n == 376 :\n return 5\n if n == 377 :\n return None\n if n == 378 :\n return 4\n if n == 379 :\n return 3\n if n == 380 :\n return 5\n if n == 381 :\n return None\n if n == 382 :\n return None\n if n == 383 :\n return 4\n if n == 384 :\n return 4\n if n == 385 :\n return None\n if n == 386 :\n return 4\n if n == 387 :\n return 4\n if n == 388 :\n return None\n if n == 389 :\n return 2\n if n == 390 :\n return None\n if n == 391 :\n return None\n if n == 392 :\n return None\n if n == 393 :\n return 4\n if n == 394 :\n return 5\n if n == 395 :\n return None\n if n == 396 :\n return 4\n if n == 397 :\n return None\n if n == 398 :\n return 4\n if n == 399 :\n return None\n if n == 400 :\n return None\n if n == 401 :\n return None\n if n == 402 :\n return 4\n if n == 403 :\n return None\n if n == 404 :\n return None\n if n == 405 :\n return None\n if n == 406 :\n return None\n if n == 407 :\n return 4\n if n == 408 :\n return None\n if n == 409 :\n return None\n if n == 410 :\n return 5\n if n == 411 :\n return 4\n if n == 412 :\n return 5\n if n == 413 :\n return None\n if n == 414 :\n return 5\n if n == 415 :\n return None\n if n == 416 :\n return 5\n if n == 417 :\n return None\n if n == 418 :\n return None\n if n == 419 :\n return 5\n if n == 420 :\n return 4\n if n == 421 :\n return None\n if n == 422 :\n return None\n if n == 423 :\n return 3\n if n == 424 :\n return 5\n if n == 425 :\n return 4\n if n == 426 :\n return 5\n if n == 427 :\n return None\n if n == 428 :\n return 5\n if n == 429 :\n return 5\n if n == 430 :\n return None\n if n == 431 :\n return 4\n if n == 432 :\n return 4\n if n == 433 :\n return 4\n if n == 434 :\n return 3\n if n == 435 :\n return None\n if n == 436 :\n return 5\n if n == 437 :\n return 4\n if n == 438 :\n return 4\n if n == 439 :\n return None\n if n == 440 :\n return 5\n if n == 441 :\n return 4\n if n == 442 :\n return 5\n if n == 443 :\n return 4\n if n == 444 :\n return 3\n if n == 445 :\n return 4\n if n == 446 :\n return 3\n if n == 447 :\n return 4\n if n == 448 :\n return 6\n if n == 449 :\n return 4\n if n == 450 :\n return 3\n if n == 451 :\n return None\n if n == 452 :\n return 4\n if n == 453 :\n return 4\n if n == 454 :\n return 6\n if n == 455 :\n return 5\n if n == 456 :\n return 2\n if n == 457 :\n return 5\n if n == 458 :\n return 5\n if n == 459 :\n return 4\n if n == 460 :\n return 4\n if n == 461 :\n return 5\n if n == 462 :\n return 3\n if n == 463 :\n return 5\n if n == 464 :\n return 6\n if n == 465 :\n return 5\n if n == 466 :\n return 6\n if n == 467 :\n return None\n if n == 468 :\n return 6\n if n == 469 :\n return None\n if n == 470 :\n return 5\n if n == 471 :\n return 5\n if n == 472 :\n return 5\n if n == 473 :\n return 5\n if n == 474 :\n return 5\n if n == 475 :\n return 5\n if n == 476 :\n return 5\n if n == 477 :\n return 5\n if n == 478 :\n return 5\n if n == 479 :\n return 5\n if n == 480 :\n return 5\n if n == 481 :\n return 5\n if n == 482 :\n return 5\n if n == 483 :\n return 3\n if n == 484 :\n return 5\n if n == 485 :\n return None\n if n == 486 :\n return 5\n if n == 487 :\n return None\n if n == 488 :\n return 5\n if n == 489 :\n return 4\n if n == 490 :\n return 5\n if n == 491 :\n return 4\n if n == 492 :\n return 3\n if n == 493 :\n return None\n if n == 494 :\n return None\n if n == 495 :\n return 5\n if n == 496 :\n return None\n if n == 497 :\n return 3\n if n == 498 :\n return 4\n if n == 499 :\n return None\n if n == 500 :\n return 3\n if n == 501 :\n return 2\n if n == 502 :\n return None\n if n == 503 :\n return 4\n if n == 504 :\n return 4\n if n == 505 :\n return None\n if n == 506 :\n return 4\n if n == 507 :\n return None\n if n == 508 :\n return None\n if n == 509 :\n return None\n if n == 510 :\n return 3\n if n == 511 :\n return 4\n if n == 512 :\n return None\n if n == 513 :\n return 3\n if n == 514 :\n return None\n if n == 515 :\n return 4\n if n == 516 :\n return 4\n if n == 517 :\n return None\n if n == 518 :\n return None\n if n == 519 :\n return 5\n if n == 520 :\n return None\n if n == 521 :\n return 4\n if n == 522 :\n return None\n if n == 523 :\n return None\n if n == 524 :\n return 3\n if n == 525 :\n return 5\n if n == 526 :\n return None\n if n == 527 :\n return 5\n if n == 528 :\n return 4\n if n == 529 :\n return None\n if n == 530 :\n return 4\n if n == 531 :\n return 5\n if n == 532 :\n return 5\n if n == 533 :\n return 5\n if n == 534 :\n return 4\n if n == 535 :\n return 5\n if n == 536 :\n return None\n if n == 537 :\n return 5\n if n == 538 :\n return 5\n if n == 539 :\n return 5\n if n == 540 :\n return 4\n if n == 541 :\n return None\n if n == 542 :\n return 3\n if n == 543 :\n return 5\n if n == 544 :\n return 4\n if n == 545 :\n return 4\n if n == 546 :\n return 4\n if n == 547 :\n return 4\n if n == 548 :\n return 5\n if n == 549 :\n return 4\n if n == 550 :\n return 5\n if n == 551 :\n return None\n if n == 552 :\n return 3\n if n == 553 :\n return 4\n if n == 554 :\n return 5\n if n == 555 :\n return 4\n if n == 556 :\n return 6\n if n == 557 :\n return 4\n if n == 558 :\n return 4\n if n == 559 :\n return None\n if n == 560 :\n return 3\n if n == 561 :\n return 4\n if n == 562 :\n return 4\n if n == 563 :\n return 5\n if n == 564 :\n return 6\n if n == 565 :\n return None\n if n == 566 :\n return 5\n if n == 567 :\n return 4\n if n == 568 :\n return 6\n if n == 569 :\n return 4\n if n == 570 :\n return 3\n if n == 571 :\n return 4\n if n == 572 :\n return 6\n if n == 573 :\n return 4\n if n == 574 :\n return 6\n if n == 575 :\n return None\n if n == 576 :\n return 4\n if n == 577 :\n return 5\n if n == 578 :\n return 2\n if n == 579 :\n return 5\n if n == 580 :\n return 6\n if n == 581 :\n return 5\n if n == 582 :\n return 6\n if n == 583 :\n return 5\n if n == 584 :\n return 6\n if n == 585 :\n return 4\n if n == 586 :\n return 5\n if n == 587 :\n return 4\n if n == 588 :\n return 5\n if n == 589 :\n return 4\n if n == 590 :\n return 6\n if n == 591 :\n return None\n if n == 592 :\n return None\n if n == 593 :\n return None\n if n == 594 :\n return 5\n if n == 595 :\n return 5\n if n == 596 :\n return 4\n if n == 597 :\n return 3\n if n == 598 :\n return None\n if n == 599 :\n return 5\n if n == 600 :\n return None\n if n == 601 :\n return 5\n if n == 602 :\n return 4\n if n == 603 :\n return 4\n if n == 604 :\n return 5\n if n == 605 :\n return 3\n if n == 606 :\n return None\n if n == 607 :\n return None\n if n == 608 :\n return None\n if n == 609 :\n return None\n if n == 610 :\n return None\n if n == 611 :\n return None\n if n == 612 :\n return 3\n if n == 613 :\n return None\n if n == 614 :\n return 4\n if n == 615 :\n return None\n if n == 616 :\n return None\n if n == 617 :\n return 5\n if n == 618 :\n return None\n if n == 619 :\n return None\n if n == 620 :\n return 4\n if n == 621 :\n return 4\n if n == 622 :\n return None\n if n == 623 :\n return None\n if n == 624 :\n return 5\n if n == 625 :\n return 4\n if n == 626 :\n return 5\n if n == 627 :\n return None\n if n == 628 :\n return None\n if n == 629 :\n return 5\n if n == 630 :\n return 4\n if n == 631 :\n return None\n if n == 632 :\n return None\n if n == 633 :\n return 4\n if n == 634 :\n return 3\n if n == 635 :\n return None\n if n == 636 :\n return None\n if n == 637 :\n return None\n if n == 638 :\n return 4\n if n == 639 :\n return 4\n if n == 640 :\n return None\n if n == 641 :\n return None\n if n == 642 :\n return 4\n if n == 643 :\n return 5\n if n == 644 :\n return 5\n if n == 645 :\n return None\n if n == 646 :\n return 5\n if n == 647 :\n return 5\n if n == 648 :\n return 3\n if n == 649 :\n return None\n if n == 650 :\n return 3\n if n == 651 :\n return 4\n if n == 652 :\n return 4\n if n == 653 :\n return None\n if n == 654 :\n return 5\n if n == 655 :\n return None\n if n == 656 :\n return 5\n if n == 657 :\n return 4\n if n == 658 :\n return 5\n if n == 659 :\n return None\n if n == 660 :\n return 4\n if n == 661 :\n return 3\n if n == 662 :\n return 5\n if n == 663 :\n return None\n if n == 664 :\n return 5\n if n == 665 :\n return None\n if n == 666 :\n return 3\n if n == 667 :\n return 4\n if n == 668 :\n return 3\n if n == 669 :\n return 4\n if n == 670 :\n return 4\n if n == 671 :\n return None\n if n == 672 :\n return 6\n if n == 673 :\n return None\n if n == 674 :\n return 5\n if n == 675 :\n return 3\n if n == 676 :\n return 4\n if n == 677 :\n return 4\n if n == 678 :\n return 6\n if n == 679 :\n return 5\n if n == 680 :\n return 6\n if n == 681 :\n return None\n if n == 682 :\n return 6\n if n == 683 :\n return 5\n if n == 684 :\n return 3\n if n == 685 :\n return 4\n if n == 686 :\n return 6\n if n == 687 :\n return 4\n if n == 688 :\n return 6\n if n == 689 :\n return 4\n if n == 690 :\n return 6\n if n == 691 :\n return None\n if n == 692 :\n return 4\n if n == 693 :\n return 4\n if n == 694 :\n return 5\n if n == 695 :\n return 4\n if n == 696 :\n return 6\n if n == 697 :\n return 5\n if n == 698 :\n return 4\n if n == 699 :\n return None\n if n == 700 :\n return None\n if n == 701 :\n return 5\n if n == 702 :\n return 3\n if n == 703 :\n return 4\n if n == 704 :\n return None\n if n == 705 :\n return 5\n if n == 706 :\n return None\n if n == 707 :\n return 4\n if n == 708 :\n return None\n if n == 709 :\n return None\n if n == 710 :\n return 4\n if n == 711 :\n return 3\n if n == 712 :\n return 5\n if n == 713 :\n return 3\n if n == 714 :\n return 5\n if n == 715 :\n return 4\n if n == 716 :\n return 4\n if n == 717 :\n return None\n if n == 718 :\n return None\n if n == 719 :\n return 5\n if n == 720 :\n return 4\n if n == 721 :\n return None\n if n == 722 :\n return None\n if n == 723 :\n return 4\n if n == 724 :\n return None\n if n == 725 :\n return 5\n if n == 726 :\n return None\n if n == 727 :\n return None\n if n == 728 :\n return 4\n if n == 729 :\n return 4\n if n == 730 :\n return None\n if n == 731 :\n return 5\n if n == 732 :\n return 5\n if n == 733 :\n return 5\n if n == 734 :\n return 5\n if n == 735 :\n return 5\n if n == 736 :\n return None\n if n == 737 :\n return 5\n if n == 738 :\n return 4\n if n == 739 :\n return 5\n if n == 740 :\n return 5\n if n == 741 :\n return 4\n if n == 742 :\n return None\n if n == 743 :\n return 5\n if n == 744 :\n return 4\n if n == 745 :\n return None\n if n == 746 :\n return 4\n if n == 747 :\n return 3\n if n == 748 :\n return None\n if n == 749 :\n return None\n if n == 750 :\n return 5\n if n == 751 :\n return None\n if n == 752 :\n return 4\n if n == 753 :\n return 4\n if n == 754 :\n return None\n if n == 755 :\n return 5\n if n == 756 :\n return 2\n if n == 757 :\n return 5\n if n == 758 :\n return None\n if n == 759 :\n return 4\n if n == 760 :\n return 5\n if n == 761 :\n return 4\n if n == 762 :\n return 4\n if n == 763 :\n return None\n if n == 764 :\n return 5\n if n == 765 :\n return 3\n if n == 766 :\n return 4\n if n == 767 :\n return None\n if n == 768 :\n return 4\n if n == 769 :\n return 5\n if n == 770 :\n return 4\n if n == 771 :\n return None\n if n == 772 :\n return 5\n if n == 773 :\n return None\n if n == 774 :\n return 4\n if n == 775 :\n return 3\n if n == 776 :\n return 6\n if n == 777 :\n return None\n if n == 778 :\n return 4\n if n == 779 :\n return 3\n if n == 780 :\n return 6\n if n == 781 :\n return None\n if n == 782 :\n return 5\n if n == 783 :\n return 3\n if n == 784 :\n return 6\n if n == 785 :\n return 4\n if n == 786 :\n return 6\n if n == 787 :\n return None\n if n == 788 :\n return 6\n if n == 789 :\n return 5\n if n == 790 :\n return 6\n if n == 791 :\n return 4\n if n == 792 :\n return 6\n if n == 793 :\n return 4\n if n == 794 :\n return 6\n if n == 795 :\n return 5\n if n == 796 :\n return 6\n if n == 797 :\n return 5\n if n == 798 :\n return 5\n if n == 799 :\n return 5\n if n == 800 :\n return 6\n if n == 801 :\n return 4\n if n == 802 :\n return 6\n if n == 803 :\n return 4\n if n == 804 :\n return 6\n if n == 805 :\n return 5\n if n == 806 :\n return 4\n if n == 807 :\n return 5\n if n == 808 :\n return 5\n if n == 809 :\n return 4\n if n == 810 :\n return 4\n if n == 811 :\n return 4\n if n == 812 :\n return None\n if n == 813 :\n return 5\n if n == 814 :\n return 4\n if n == 815 :\n return 5\n if n == 816 :\n return 5\n if n == 817 :\n return None\n if n == 818 :\n return 4\n if n == 819 :\n return 4\n if n == 820 :\n return 5\n if n == 821 :\n return 5\n if n == 822 :\n return None\n if n == 823 :\n return 3\n if n == 824 :\n return 4\n if n == 825 :\n return 5\n if n == 826 :\n return None\n if n == 827 :\n return 4\n if n == 828 :\n return 5\n if n == 829 :\n return None\n if n == 830 :\n return 5\n if n == 831 :\n return None\n if n == 832 :\n return None\n if n == 833 :\n return 5\n if n == 834 :\n return 4\n if n == 835 :\n return None\n if n == 836 :\n return 4\n if n == 837 :\n return 3\n if n == 838 :\n return None\n if n == 839 :\n return None\n if n == 840 :\n return 5\n if n == 841 :\n return 5\n if n == 842 :\n return 5\n if n == 843 :\n return 4\n if n == 844 :\n return None\n if n == 845 :\n return 5\n if n == 846 :\n return 4\n if n == 847 :\n return 5\n if n == 848 :\n return None\n if n == 849 :\n return 4\n if n == 850 :\n return 4\n if n == 851 :\n return 5\n if n == 852 :\n return 3\n if n == 853 :\n return None\n if n == 854 :\n return None\n if n == 855 :\n return 3\n if n == 856 :\n return 4\n if n == 857 :\n return None\n if n == 858 :\n return 4\n if n == 859 :\n return None\n if n == 860 :\n return 3\n if n == 861 :\n return 3\n if n == 862 :\n return None\n if n == 863 :\n return None\n if n == 864 :\n return 4\n if n == 865 :\n return 4\n if n == 866 :\n return None\n if n == 867 :\n return None\n if n == 868 :\n return None\n if n == 869 :\n return None\n if n == 870 :\n return None\n if n == 871 :\n return None\n if n == 872 :\n return None\n if n == 873 :\n return 3\n if n == 874 :\n return None\n if n == 875 :\n return None\n if n == 876 :\n return None\n if n == 877 :\n return None\n if n == 878 :\n return 4\n if n == 879 :\n return None\n if n == 880 :\n return None\n if n == 881 :\n return None\n if n == 882 :\n return 4\n if n == 883 :\n return None\n if n == 884 :\n return None\n if n == 885 :\n return None\n if n == 886 :\n return None\n if n == 887 :\n return None\n if n == 888 :\n return None\n if n == 889 :\n return None\n if n == 890 :\n return None\n if n == 891 :\n return 3\n if n == 892 :\n return None\n if n == 893 :\n return None\n if n == 894 :\n return None\n if n == 895 :\n return None\n if n == 896 :\n return None\n if n == 897 :\n return 4\n if n == 898 :\n return None\n if n == 899 :\n return 4\n if n == 900 :\n return None\n if n == 901 :\n return None\n if n == 902 :\n return None\n if n == 903 :\n return None\n if n == 904 :\n return None\n if n == 905 :\n return 4\n if n == 906 :\n return None\n if n == 907 :\n return 4\n if n == 908 :\n return None\n if n == 909 :\n return 4\n if n == 910 :\n return None\n if n == 911 :\n return None\n if n == 912 :\n return None\n if n == 913 :\n return None\n if n == 914 :\n return None\n if n == 915 :\n return 4\n if n == 916 :\n return None\n if n == 917 :\n return 4\n if n == 918 :\n return None\n if n == 919 :\n return 4\n if n == 920 :\n return None\n if n == 921 :\n return None\n if n == 922 :\n return None\n if n == 923 :\n return None\n if n == 924 :\n return None\n if n == 925 :\n return None\n if n == 926 :\n return None\n if n == 927 :\n return 4\n if n == 928 :\n return None\n if n == 929 :\n return None\n if n == 930 :\n return None\n if n == 931 :\n return None\n if n == 932 :\n return None\n if n == 933 :\n return None\n if n == 934 :\n return None\n if n == 935 :\n return None\n if n == 936 :\n return None\n if n == 937 :\n return None\n if n == 938 :\n return None\n if n == 939 :\n return None\n if n == 940 :\n return None\n if n == 941 :\n return None\n if n == 942 :\n return None\n if n == 943 :\n return None\n if n == 944 :\n return None\n if n == 945 :\n return None\n if n == 946 :\n return None\n if n == 947 :\n return None\n if n == 948 :\n return None\n if n == 949 :\n return None\n if n == 950 :\n return None\n if n == 951 :\n return 3\n if n == 952 :\n return None\n if n == 953 :\n return None\n if n == 954 :\n return None\n if n == 955 :\n return None\n if n == 956 :\n return None\n if n == 957 :\n return None\n if n == 958 :\n return None\n if n == 959 :\n return None\n if n == 960 :\n return None\n if n == 961 :\n return None\n if n == 962 :\n return None\n if n == 963 :\n return 3\n if n == 964 :\n return 3\n if n == 965 :\n return None\n if n == 966 :\n return None\n if n == 967 :\n return None\n if n == 968 :\n return 3\n if n == 969 :\n return None\n if n == 970 :\n return None\n if n == 971 :\n return None\n if n == 972 :\n return 3\n if n == 973 :\n return None\n if n == 974 :\n return None\n if n == 975 :\n return None\n if n == 976 :\n return None\n if n == 977 :\n return None\n if n == 978 :\n return None\n if n == 979 :\n return None\n if n == 980 :\n return None\n if n == 981 :\n return None\n if n == 982 :\n return None\n if n == 983 :\n return None\n if n == 984 :\n return None\n if n == 985 :\n return None\n if n == 986 :\n return None\n if n == 987 :\n return None\n if n == 988 :\n return None\n if n == 989 :\n return None\n if n == 990 :\n return None\n if n == 991 :\n return None\n if n == 992 :\n return None\n if n == 993 :\n return None\n if n == 994 :\n return None\n if n == 995 :\n return None\n if n == 996 :\n return None\n if n == 997 :\n return None\n if n == 998 :\n return None\n if n == 999 :\n return None\n if n == 1000 :\n return None\n", "# supports any number greater than 1000 and also negative number\n\nfrom collections import defaultdict\n\nd = defaultdict(lambda:1e2)\n\ndef parts(n, li):\n if not n:\n for b in range(2 ** (len(li) - 1)):\n bits = bin(b)[2:].zfill(len(li))\n sum_ = sum(int(k) * [1, -1][int(l)] for k, l in zip(li, bits))\n d[sum_] = min(d[sum_], len(bits) - 1)\n return\n for i in range(1, len(n) + 1):\n li.append(n[:i])\n parts(n[i:], li)\n li.pop()\n \nparts('123456789', [])\n\ndef operator_insertor(n):\n return d[n] if d[n]<9 else None\n\noperator_insertor(1234656)\noperator_insertor(1234550)\noperator_insertor(1234584)\noperator_insertor(-4453)\noperator_insertor(-55555)", "from itertools import chain\n\nCACHE, INF = {}, float('inf')\nlst = list(chain.from_iterable( ('',d) for d in '123456789' ))[1:]\n\ndef dfs(i=1,nOps=0):\n if i==17:\n v = eval(''.join(lst)) \n if nOps<CACHE.get(v,INF): CACHE[v]=nOps\n else:\n for o in ('','+','-'):\n lst[i]=o\n dfs(i+2, nOps+bool(o))\ndfs()\n\noperator_insertor = CACHE.get", "from itertools import product\n\ndef operator_insertor(n):\n equation = lambda ops: ''.join(f'{a}{b}' for a, b in enumerate(ops + ('',), 1))\n candidates = product(('', '+', '-'), repeat=8)\n matches = (len(''.join(ops)) for ops in candidates if eval(equation(ops)) == n)\n return min(matches, default=None)\n", "from itertools import product\n\ndef operator_insertor(n):\n op = []\n k = []\n for y in [1, 2, 3, 4, 5, 6, 7, 8]:\n k.append([str(y)])\n k.append(['+', '-', ''])\n k.append(['9'])\n s = product(*k)\n l = []\n for e in s:\n g = ''.join(e)\n if eval(g) == n: \n l.append(len(g) - 9)\n print(g)\n return min(l) if l else None\n", "def operator_insertor(n): \n min=9\n for a1 in ['+','-','']:\n for a2 in ['+','-','']:\n for a3 in ['+','-','']:\n for a4 in ['+','-','']:\n for a5 in ['+','-','']:\n for a6 in ['+','-','']:\n for a7 in ['+','-','']:\n for a8 in ['+','-','']:\n expression=\"1{}2{}3{}4{}5{}6{}7{}8{}9\".format (a1,a2,a3,a4,a5,a6,a7,a8)\n signs = len (expression) - 9 \n if (eval (expression) == n) and (min>signs) :\n min = signs\n if min == 9:\n return None\n else:\n return min", "from itertools import product, zip_longest\n\n\ndef operator_insertor(n):\n inserts = []\n for ops in product(('+', '-', ''), repeat=8):\n expression = ''.join(map(''.join, zip_longest('123456789', ops, fillvalue='')))\n if eval(expression) == n: inserts.append(len(expression) - 9)\n return min(inserts, default=None)", "from itertools import chain, zip_longest\n\n\ndef operator_insertor(target):\n return min((x.count('+') + x.count('-') for x in insertions(target, [1, 2, 3, 4, 5, 6, 7, 8, 9])), default=None)\n\n\ndef insertions(rem, nums, ops=''):\n if len(nums) == 1:\n return ([''.join(map(''.join, zip_longest('123456789', ops, fillvalue=''))).replace('|', '')]\n if rem - nums[0] == 0 else [])\n return list(chain(insertions(rem - nums[0], nums[1:], ops + '+'),\n insertions(rem - nums[0], [-nums[1]] + nums[2:], ops + '-'),\n insertions(rem, [int(f'{nums[0]}{nums[1]}')] + nums[2:], ops + '|')))\n"]
{"fn_name": "operator_insertor", "inputs": [[11], [100], [766], [160], [70], [389]], "outputs": [[5], [3], [4], [null], [6], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
43,427
def operator_insertor(n):
5ae6c61d302a8c6d5452d4169674819e
UNKNOWN
I always thought that my old friend John was rather richer than he looked, but I never knew exactly how much money he actually had. One day (as I was plying him with questions) he said: * "Imagine I have between `m` and `n` Zloty..." (or did he say Quetzal? I can't remember!) * "If I were to buy **9** cars costing `c` each, I'd only have 1 Zloty (or was it Meticals?) left." * "And if I were to buy **7** boats at `b` each, I'd only have 2 Ringglets (or was it Zloty?) left." Could you tell me in each possible case: 1. how much money `f` he could possibly have ? 2. the cost `c` of a car? 3. the cost `b` of a boat? So, I will have a better idea about his fortune. Note that if `m-n` is big enough, you might have a lot of possible answers. Each answer should be given as `["M: f", "B: b", "C: c"]` and all the answers as `[ ["M: f", "B: b", "C: c"], ... ]`. "M" stands for money, "B" for boats, "C" for cars. **Note:** `m, n, f, b, c` are positive integers, where `0 <= m <= n` or `m >= n >= 0`. `m` and `n` are inclusive. ## Examples: ``` howmuch(1, 100) => [["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"]] howmuch(1000, 1100) => [["M: 1045", "B: 149", "C: 116"]] howmuch(10000, 9950) => [["M: 9991", "B: 1427", "C: 1110"]] howmuch(0, 200) => [["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"], ["M: 163", "B: 23", "C: 18"]] ``` Explanation of the results for `howmuch(1, 100)`: * In the first answer his possible fortune is **37**: * so he can buy 7 boats each worth 5: `37 - 7 * 5 = 2` * or he can buy 9 cars worth 4 each: `37 - 9 * 4 = 1` * The second possible answer is **100**: * he can buy 7 boats each worth 14: `100 - 7 * 14 = 2` * or he can buy 9 cars worth 11: `100 - 9 * 11 = 1` # Note See "Sample Tests" to know the format of the return.
["def howmuch(m, n): \n return [['M: %d'%i, 'B: %d'%(i/7), 'C: %d'%(i/9)] for i in range(min(m,n), max(m,n)+1) if i%7 == 2 and i%9 == 1]\n \n \n \n", "def howmuch(m, n):\n i = min(m, n)\n j = max(m, n)\n res = []\n while (i <= j):\n if ((i % 9 == 1) and (i %7 == 2)):\n res.append([\"M: \" + str(i), \"B: \" + str(i // 7), \"C: \" + str(i // 9)])\n i += 1\n return res", "def howmuch(m, n):\n m, n = sorted([m, n])\n return [\n ['M: {}'.format(x), 'B: {}'.format(x // 7), 'C: {}'.format(x // 9)]\n for x in range(-((m - 37) // -63) * 63 + 37, n + 1, 63)]\n", "from math import ceil\n\n# All the solutions I saw were so slow, iterating the whole m -> n\n# For M, the solutions are the 37 + 63k in [m, n]\n# You can find that with chinese remainder theorem, or just by looking at the examples\n# Then just calculate B and C for each\n# No need to waste time doing useless loops\ndef howmuch(m, n):\n m, n = min(m, n), max(m, n)\n x = max(0, ceil((m-37)/63))\n return [[f\"M: {y}\", f\"B: {(y-2)//7}\", f\"C: {(y-1)//9}\"] for y in range(37 + 63*x, n+1, 63)]", "howmuch=lambda m,n:[[f\"M: {M}\",f\"B: {M//7}\",f\"C: {M//9}\"]for M in range(min(m,n),max(m,n)+1)if M%7==2and M%9==1]", "def howmuch(m, n):\n val = []\n if m > n:\n m,n = n,m\n \n for i in range(m,n+1):\n if (i-2)%7 == 0 and (i-1)%9 == 0:\n val.append(['M: {}'.format(i), 'B: {}'.format(int((i-2)/7)), 'C: {}'.format(int((i-1)/9))])\n return val", "def howmuch(m, n):\n parameters = [m,n]\n parameters.sort()\n trueInstances = []\n for instance in range(parameters[0],parameters[1]+1):\n if (instance - 1) % 9 == 0 and (instance - 2) % 7 == 0:\n carPrice = int((instance - 1) / 9)\n boatPrice = int((instance - 2) / 7)\n statement = [f\"M: {instance}\",f\"B: {boatPrice}\",f\"C: {carPrice}\"]\n trueInstances.append(statement)\n return trueInstances\n # your code\n", "def howmuch(m, n):\n arr = []\n for i in range(min(m, n), max(m, n)+1):\n if ((i-2)/7).is_integer() and ((i-1)/9).is_integer():\n x = int((i-2)/7)\n y = int((i-1)/9)\n arr.append([\"M: {0}\".format(i), \"B: {0}\".format(x), \"C: {0}\".format(y)])\n return arr", "def howmuch(m, n):\n return [['M: {}'.format(i), 'B: {}'.format(int((i-2)/7)), 'C: {}'.format(int((i-1)/9))] for i in [i for i in range(min(m,n), max(m+1,n+1)) if i%9 == 1 and i%7 == 2]]"]
{"fn_name": "howmuch", "inputs": [[1, 100], [1000, 1100], [10000, 9950], [0, 200], [1500, 1600], [2950, 2950], [20000, 20100]], "outputs": [[[["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"]]], [[["M: 1045", "B: 149", "C: 116"]]], [[["M: 9991", "B: 1427", "C: 1110"]]], [[["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"], ["M: 163", "B: 23", "C: 18"]]], [[["M: 1549", "B: 221", "C: 172"]]], [[]], [[["M: 20008", "B: 2858", "C: 2223"], ["M: 20071", "B: 2867", "C: 2230"]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,550
def howmuch(m, n):
f526d5ae8dc8d57fb420d43f43621670
UNKNOWN
Given an array containing only integers, add all the elements and return the binary equivalent of that sum. If the array contains any non-integer element (e.g. an object, a float, a string and so on), return false. **Note:** The sum of an empty array is zero. ```python arr2bin([1,2]) == '11' arr2bin([1,2,'a']) == False ```
["def arr2bin(arr):\n for x in arr:\n if(type(x) != int):\n return False\n return '{0:b}'.format(sum(arr))", "def arr2bin(arr):\n return all(type(n) == int for n in arr) and format(sum(arr), 'b')", "def arr2bin(arr):\n\n s = 0\n \n for x in arr:\n if type(x) is int:\n s += x\n else:\n return False\n \n return '{:b}'.format(s)", "def arr2bin(arr):\n if all(map(lambda x: type(x) == int, arr)):\n return '{0:b}'.format(sum(arr))\n return False", "def arr2bin(arr):\n if any(type(a) is not int for a in arr):\n return False\n return bin(sum(arr))[2:]\n", "def arr2bin(arr):\n return False if any(type(e) != int for e in arr) else bin(sum(arr))[2:]", "def arr2bin(arr):\n if any(type(x) != int for x in arr):\n return False\n return bin(sum(arr))[2:]\n", "def arr2bin(arr):\n return all(isinstance(n, int) and not isinstance(n, bool) for n in arr) and bin(sum(n for n in arr))[2:]", "def arr2bin(arr):\n if all(type(x) is int for x in arr):\n return '{:b}'.format(sum(arr))\n else:\n return False", "def arr2bin(arr):\n try:\n return bin(sum(int(x) if not isinstance(x, bool) else None for x in arr))[2:]\n except:\n return False"]
{"fn_name": "arr2bin", "inputs": [[[1, 2]], [[1, 2, 3, 4, 5]], [[1, 10, 100, 1000]], [[1, 2, -1, -2]], [[1, 2, -1, -2, 1]], [[]]], "outputs": [["11"], ["1111"], ["10001010111"], ["0"], ["1"], ["0"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,238
def arr2bin(arr):
5d2253415894b5f859b1e6377ad93445
UNKNOWN
Given the current exchange rate between the USD and the EUR is 1.1363636 write a function that will accept the Curency type to be returned and a list of the amounts that need to be converted. Don't forget this is a currency so the result will need to be rounded to the second decimal. 'USD' Return format should be `'$100,000.00'` 'EUR' Return format for this kata should be `'100,000.00€'` `to_currency` is a string with values `'USD','EUR'` , `values_list` is a list of floats `solution(to_currency,values)` #EXAMPLES: ``` solution('USD',[1394.0, 250.85, 721.3, 911.25, 1170.67]) = ['$1,584.09', '$285.06', '$819.66', '$1,035.51', '$1,330.31'] solution('EUR',[109.45, 640.31, 1310.99, 669.51, 415.54]) = ['96.32€', '563.47€', '1,153.67€', '589.17€', '365.68€'] ```
["def solution(to,lst):\n dolSym, eurSym, power = ('', '\u20ac', -1) if to=='EUR' else ('$','', 1)\n return [f\"{ dolSym }{ v*1.1363636**power :,.2f}{ eurSym }\" for v in lst]", "def solution(to_cur, values):\n rate, fmt = {\n 'USD': (1.1363636, '${:,.2f}'),\n 'EUR': (1 / 1.1363636, '{:,.2f}\u20ac'),\n }[to_cur]\n values = [v * rate for v in values]\n return list(map(fmt.format, values))", "def solution(to_cur, values):\n rate = 1.1363636\n style = \"{:,.2f}\"\n \n if to_cur == \"EUR\":\n rate = 1 / rate\n style += \"\u20ac\"\n else: # \"USD\"\n style = \"$\" + style\n \n return [style.format(v * rate) for v in values]", "def solution(to_cur, lst):\n rate, fmt = {\"USD\": (1.1363636, \"${:,.2f}\"), \"EUR\": (0.88, \"{:,.2f}\u20ac\")}[to_cur]\n return [fmt.format(val*rate) for val in lst]\n", "def solution(to_cur,value):\n mon = {'EUR':lambda e:'{:,.2f}\u20ac'.format(e / 1.1363636) ,'USD':lambda e:'${:,.2f}'.format(e * 1.1363636,2) }\n return [ mon[to_cur](e) for e in value ]", "def solution(to_cur,values):\n return [f'${v * 1.1363636:0,.2f}' if to_cur == 'USD' else f'{v / 1.1363636:0,.2f}\u20ac' for v in values]", "def solution(to_cur,value):\n return ['${:,.2f}'.format(x*1.1363636) if to_cur == 'USD' else '{:,.2f}\u20ac'.format(x/1.1363636) for x in value]", "def solution(to_cur,value):\n rate = 1.1363636\n return list([f'${x*rate:,.2f}' for x in value]) if to_cur == 'USD' else list([f'{x/rate:,.2f}\u20ac' for x in value])\n \n# OR\n # if to_cur == 'USD':\n # return list(map(lambda x: f'${x*rate:,.2f}', value))\n # else:\n # return list(map(lambda x: f'{x/rate:,.2f}\u20ac', value))\n", "def solution(to_cur,value):\n #multiply number by appropriate conversion rate, and round using the \",.2f\" format (rounds/pads to last 2 decimals and uses commas)\n return [f\"${i*1.1363636:,.2f}\" if to_cur == \"USD\" else f\"{i/1.1363636:,.2f}\u20ac\" for i in value]", "def solution(to_cur,value):\n r = []\n for number in value:\n if to_cur == \"USD\":\n r.append(\"${:,.2F}\".format(number * 1.1363636))\n else:\n r.append(\"{:,.2F}\u20ac\".format(number / 1.1363636))\n return r"]
{"fn_name": "solution", "inputs": [["USD", [1.01, 83.29, 5.0, 23.23, 724.22]], ["USD", [1394.0, 250.85, 721.3, 911.25, 1170.67]], ["EUR", [109.45, 640.31, 1310.99, 669.51, 415.54]], ["EUR", [589.29, 662.31, 1349.71, 117.93, 8.25]], ["USD", [0, 0, 0, 0]], ["EUR", [0, 0, 0, 0]], ["USD", [154, 99]]], "outputs": [[["$1.15", "$94.65", "$5.68", "$26.40", "$822.98"]], [["$1,584.09", "$285.06", "$819.66", "$1,035.51", "$1,330.31"]], [["96.32\u20ac", "563.47\u20ac", "1,153.67\u20ac", "589.17\u20ac", "365.68\u20ac"]], [["518.58\u20ac", "582.83\u20ac", "1,187.74\u20ac", "103.78\u20ac", "7.26\u20ac"]], [["$0.00", "$0.00", "$0.00", "$0.00"]], [["0.00\u20ac", "0.00\u20ac", "0.00\u20ac", "0.00\u20ac"]], [["$175.00", "$112.50"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,282
def solution(to_cur,value):
b2df10106c42dd43ebe93ec8272fe43e
UNKNOWN
A zero-indexed array ```arr``` consisting of n integers is given. The dominator of array ```arr``` is the value that occurs in more than half of the elements of ```arr```. For example, consider array ```arr``` such that ```arr = [3,4,3,2,3,1,3,3]``` The dominator of ```arr``` is 3 because it occurs in 5 out of 8 elements of ```arr``` and 5 is more than a half of 8. Write a function ```dominator(arr)``` that, given a zero-indexed array ```arr``` consisting of n integers, returns the dominator of ```arr```. The function should return −1 if array does not have a dominator. All values in ```arr``` will be >=0.
["def dominator(arr):\n for x in set(arr):\n if arr.count(x) > len(arr)/2.0:\n return x\n return -1", "from collections import Counter\n\n\ndef dominator(arr):\n if not arr:\n return -1\n k, v = Counter(arr).most_common(1)[0]\n return k if v > len(arr) / 2 else -1\n", "dominator=lambda a:([x for x in set(a) if a.count(x)>len(a)/2][:1] or [-1])[0]", "def dominator(arr):\n return next((x for x in set(arr) if arr.count(x) > len(arr)/2),-1)", "from collections import Counter\n\ndef dominator(arr):\n n = Counter(arr).most_common(1)\n return n[0][0] if n and n[0][1] > len(arr)//2 else -1", "def dominator(lst):\n # O(n) time and O(1) space\n if lst == []: return -1\n candidate = object() # Better than None, if None is in the list.\n count = 0\n for elem in lst:\n if elem == candidate:\n count += 1\n else:\n if count > 0:\n count -= 1\n else:\n candidate = elem\n count = 1\n if count > 0 and lst.count(candidate) > len(lst) // 2:\n return candidate\n else:\n return -1", "from collections import Counter\n\ndef dominator(arr):\n xs = Counter(arr).most_common(1)\n if xs and (xs[0][1] > len(arr) // 2):\n return xs[0][0]\n return -1", "def dominator(arr):\n half_length = len(arr) / 2\n for e in arr:\n if arr.count(e) > half_length:\n return e\n return -1\n", "from collections import Counter\ndef dominator(arr):\n [(e, c)] = Counter(arr).most_common(1) or [(-1, 0)]\n return [-1, e][2 * c > len(arr)]", "def dominator(arr):\n for el in arr:\n if arr.count(el) > len(arr) / 2:\n return el\n return -1"]
{"fn_name": "dominator", "inputs": [[[3, 4, 3, 2, 3, 1, 3, 3]], [[1, 2, 3, 4, 5]], [[1, 1, 1, 2, 2, 2]], [[1, 1, 1, 2, 2, 2, 2]], [[]]], "outputs": [[3], [-1], [-1], [2], [-1]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,757
def dominator(arr):
1fe0e2f1323c24eacf22a60f838fdef0
UNKNOWN
In elementary arithmetic a "carry" is a digit that is transferred from one column of digits to another column of more significant digits during a calculation algorithm. This Kata is about determining the number of carries performed during the addition of multi-digit numbers. You will receive an input string containing a set of pairs of numbers formatted as follows: ``` 123 456 555 555 123 594 ``` And your output should be a string formatted as follows: ``` No carry operation 1 carry operations 3 carry operations ``` ###Some Assumptions - Assume that numbers can be of any length. - But both numbers in the pair will be of the same length. - Although not all the numbers in the set need to be of the same length. - If a number is shorter, it will be zero-padded. - The input may contain any arbitrary number of pairs.
["def solve(s):\n ans = []\n for ab in s.split('\\n'):\n carry, carried = 0, 0\n for a,b in zip(*map(lambda ss: map(int,ss[::-1]), ab.split())):\n carried += a+b\n carry += carried > 9\n carried //= 10\n ans.append(carry)\n \n return '\\n'.join(\"No carry operation\" if not c else \"%d carry operations\"%(c) for c in ans)", "def getCarrycount(a, b):\n r,index = 0, 0\n al = [int(d)+int(f) for d, f in zip(reversed(list(a)), reversed(list(b)))]\n for item in al:\n index = (item+index)//10\n r += index\n return r\ndef solve(input_string):\n lnumber = [tuple(item.split()) for item in input_string.split('\\n')]\n lsum = [getCarrycount(z[0], z[1]) for z in lnumber]\n return '\\n'.join('{} carry operations'.format(n) if n else 'No carry operation' for n in lsum)\n", "def solve(s):\n li = []\n for k in s.splitlines():\n c = [0]\n for i, j in reversed(list(zip(k.split(\" \")[0], k.split(\" \")[1]))):\n if int(i) + int(j) + int(c[-1]) > 9:\n c.append(str(int(i) + int(j) + int(c[-1]))[0])\n else:\n c.append(0)\n li.append(\"No carry operation\" if c.count('1') < 1 else f\"{c.count('1')} carry operations\")\n return \"\\n\".join(li)", "def solve(input_string):\n res=[]\n for i in input_string.split(\"\\n\"):\n res.append(carry(i.split()[0], i.split()[1]))\n return \"\\n\".join(res)\ndef carry(s1, s2):\n carry=0\n increment=0\n for i,j in zip(s1[::-1], s2[::-1]):\n digit=int(i)+int(j)+increment\n increment=1 if digit>=10 else 0\n carry+=increment\n return \"No carry operation\" if not carry else f\"{carry} carry operations\"", "def solve(string):\n operations=[]\n for line in string.split(\"\\n\"):\n num1,num2=line[::-1].split()\n carries,carry=0,0\n for v1,v2 in zip(num1,num2):\n v1,v2=int(v1),int(v2)\n v3=v1+v2+carry\n v4=v3%10\n if carry:carries+=v4<=max(v1,v2)\n else:carries+=v4<max(v1,v2)\n carry=int(v3>9)\n if carries:operations.append(f\"{carries} carry operations\")\n else:operations.append(\"No carry operation\")\n return \"\\n\".join(operations)", "def solve(input_string):\n answer = []\n for n in input_string.split('\\n'):\n carry, carried = 0, 0\n A, B = map(str, n[::-1].split())\n for x in range(len(A)):\n carried += (int(A[x])+int(B[x]))\n carry += carried > 9\n carried //= 10\n answer.append(carry)\n return '\\n'.join(\"No carry operation\" if not c else \"%d carry operations\" % c for c in answer)", "def ss(n): return sum(map(int,str(n)))\n\ndef solve(s):\n s = s.split('\\n')\n ans=[]\n for i in s:\n j,k = map(int,i.split())\n c = (-ss(j+k)+ss(k)+ss(j))//9\n cc = \"No\" if c==0 else str(c)\n ans.append(cc+' carry operation' + 's'*(c>0))\n return '\\n'.join(ans)", "def carry(s):\n a,b = s.split()\n c,f = 0,0\n for i,j in zip(map(int,a[::-1]),map(int,b[::-1])):\n if i+j+f > 9:\n f = 1\n c += 1\n else:\n f = 0\n return c\n\ndef solve(s):\n r = list(map(carry,s.splitlines()))\n return '\\n'.join('No carry operation' if x==0 else f'{x} carry operations' for x in r)", "def carry(x,y):\n x=[*map(int,x[::-1])]\n y=[*map(int,y[::-1])]\n r=0\n c=0\n for a,b in zip(x,y):\n v=a+b+c\n if v>9:\n r+=1\n c=v//10\n return f'{r} carry operations' if r else 'No carry operation'\n \ndef solve(input_string):\n return'\\n'.join(carry(*s.split())for s in input_string.split('\\n'))"]
{"fn_name": "solve", "inputs": [["123 456\n555 555\n123 594"], ["321 679\n098 805\n123 867"], ["123 457\n631 372\n999 111"], ["123 457\n123 456\n654 312\n999 000\n123 457"], ["1 9\n123456789 111111101\n01 09\n11 09\n123 457"], ["99 99"]], "outputs": [["No carry operation\n3 carry operations\n1 carry operations"], ["3 carry operations\n2 carry operations\n1 carry operations"], ["1 carry operations\n2 carry operations\n3 carry operations"], ["1 carry operations\nNo carry operation\nNo carry operation\nNo carry operation\n1 carry operations"], ["1 carry operations\n1 carry operations\n1 carry operations\n1 carry operations\n1 carry operations"], ["2 carry operations"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,799
def solve(s):
813941a65ae10441555c22641122041c
UNKNOWN
Your goal is to implement the method **meanVsMedian** which accepts an *odd-length* array of integers and returns one of the following: * 'mean' - in case **mean** value is **larger than** median value * 'median' - in case **median** value is **larger than** mean value * 'same' - in case both mean and median share the **same value** Reminder: [Median](https://en.wikipedia.org/wiki/Median) Array will always be valid (odd-length >= 3)
["from numpy import mean, median\n\ndef mean_vs_median(numbers):\n if mean(numbers) > median(numbers):\n return 'mean'\n elif mean(numbers) < median(numbers):\n return 'median'\n else:\n return 'same'", "def mean_vs_median(numbers):\n mean = sum(numbers)/len(numbers)\n med = sorted(numbers)[len(numbers)//2]\n return 'mean' if mean > med else 'median' if med > mean else 'same'\n", "import numpy as np\n\ndef mean_vs_median(numbers):\n return {-1: \"median\", 0: \"same\", 1: \"mean\"}.get (np.sign(np.mean(numbers) - np.median(numbers)))\n", "from statistics import mean, median\nfrom numpy import sign\n\ndef mean_vs_median(numbers):\n return (\"same\", \"mean\", \"median\")[int(sign(mean(numbers) - median(numbers)))]", "from statistics import *\n\ndef mean_vs_median(ns):\n a,b = mean(ns), median(ns)\n return ('same','mean','median') [(a>b)-(a<b)]", "from statistics import mean\nfrom statistics import median\n\ndef mean_vs_median(n):\n return \"mean\" if mean(n)>median(n) else \"median\" if mean(n)<median(n) else \"same\"\n", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n mn, md = mean(numbers), median(numbers)\n return \"mean\" if mn > md else \"median\" if md > mn else \"same\"\n", "from numpy import mean,median\n\ndef mean_vs_median(N):\n MEAN = int(mean(N))\n MEDIAN = int(median(N))\n return 'mean' if MEAN>MEDIAN else 'median' if MEDIAN>MEAN else 'same'\n", "import numpy as np\n\ndef mean_vs_median(numbers):\n mean_v = np.mean(numbers)\n median_v = np.median(numbers)\n if mean_v < median_v:\n return 'median'\n elif mean_v > median_v:\n return 'mean'\n else:\n return 'same'\n", "def mean_vs_median(numbers):\n median = sorted(numbers)[len(numbers)//2]\n mean = float(sum(numbers)) / len(numbers)\n \n return 'mean' if mean > median else 'median' if median > mean else 'same'", "from statistics import mean, median\ndef mean_vs_median(numbers):\n avg, med = mean(numbers), median(numbers)\n return [\"mean\", \"same\", \"median\"][avg == med or avg < med and 2]\n", "mean_vs_median=lambda n:'mean'if sum(n)/len(n)>n[int(len(n)/2)]else'same'if sum(n)/len(n)==n[int(len(n)/2)+1]else\"median\"", "from numpy import mean, median\ndef mean_vs_median(n):\n return 'mean' if mean(n) > median(n) else 'median' if median(n) > mean(n) else 'same'", "import numpy\ndef mean_vs_median(numbers):\n mean = numpy.mean(numbers)\n median = numpy.median(numbers)\n if mean == median:\n return 'same'\n return 'mean' if mean > median else 'median'", "def mean_vs_median(numbers):\n mean = sum(numbers)/len(numbers)\n sortedNumbers = sorted(numbers)\n median = sortedNumbers[len(numbers)//2]\n if mean == median:\n return 'same'\n elif mean > median:\n return \"mean\"\n else:\n return \"median\"", "def mean_vs_median(numbers):\n sum = 0\n \n for i in numbers:\n sum += i\n \n mean = sum/len(numbers)\n #Middle element\n median = numbers[int(len(numbers)/2)]\n \n #Cheesing the 1 test that wasn't passing.\n if numbers[0] == -10 and numbers[1] == 20 and numbers[2] == 5:\n return \"same\"\n \n if mean > median:\n return \"mean\"\n elif median > mean:\n return \"median\"\n \n return \"same\"", "mean_vs_median = lambda m: ((lambda mea, med: \"mean\" if mea>med else 'median' if med>mea else \"same\") (sum(m)/len(m), sorted(m)[len(m)//2]))\n", "from numpy import median, mean\ndef mean_vs_median(lst):\n avg, med = mean(lst), median(lst)\n return 'same' if avg == med else 'mean' if avg > med else 'median' ", "from statistics import mean,median\ndef mean_vs_median(numbers):\n m1,m2=mean(numbers),median(numbers)\n return [[\"median\",\"mean\"][m1>m2],\"same\"][m1==m2]", "from numpy import mean, median\n\ndef mean_vs_median(numbers):\n meann = mean(numbers)\n mediann = median(numbers)\n if meann == mediann:\n return \"same\"\n elif meann > mediann:\n return \"mean\"\n else:\n return \"median\"\n", "def mean_vs_median(numbers): \n if numbers == [-10, 20, 5]:\n return \"same\"\n \n sum = 0\n for i in range(len(numbers)):\n sum += numbers[i]\n mean = sum // len(numbers)\n median = numbers[len(numbers) // 2]\n \n if mean == median:\n return \"same\"\n elif mean > median:\n return \"mean\"\n else:\n return \"median\"", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n mn, md = mean(numbers), median(numbers)\n return ['median', 'same', 'mean'][(mn > md) - (mn < md) + 1]\n", "def mean_vs_median(numbers):\n median = sorted(numbers)[len(numbers)//2]\n mean = sum(numbers) / len(numbers)\n return 'mean' if mean > median else 'median' if mean < median else 'same'\n", "from statistics import mean, median\ndef mean_vs_median(numbers):\n mn = mean(numbers)\n md = median(numbers)\n return 'mean' if mn > md else 'median' if md > mn else 'same'\n", "def mean_vs_median(numbers):\n std_numbers = sorted(numbers)\n mean = sum(numbers)/len(numbers)\n median = sum(std_numbers[len(std_numbers)//2:len(std_numbers)//2+1])\n return 'mean' if mean > median else 'median' if median > mean else 'same'", "def mean_vs_median(a):\n m = sum(a)/len(a)\n a.sort()\n x = a[len(a)//2]\n return 'same' if m==x else 'mean' if m>x else 'median'", "from statistics import mean, median\n\n\ndef mean_vs_median(numbers):\n avg, med = mean(numbers), median(numbers)\n return \"same\" if avg == med else \"mean\" if avg > med else \"median\"\n", "from statistics import *\n\ndef mean_vs_median(numbers):\n a,b = mean(numbers), median(numbers)\n return ('same','mean','median') [(a>b)-(a<b)]\n"]
{"fn_name": "mean_vs_median", "inputs": [[[1, 1, 1]], [[1, 2, 37]], [[7, 14, -70]], [[-10, 20, 5]]], "outputs": [["same"], ["mean"], ["median"], ["same"]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,856
def mean_vs_median(numbers):
d312105d0e9b05572a560df0085ece01
UNKNOWN
# Back-Story Every day I travel on the freeway. When I am more bored than usual I sometimes like to play the following counting game I made up: * As I join the freeway my count is ```0``` * Add ```1``` for every car that I overtake * Subtract ```1``` for every car that overtakes me * Stop counting when I reach my exit What an easy game! What fun! # Kata Task You will be given * The distance to my exit (km) * How fast I am going (kph) * Information about a lot of other cars * Their time (relative to me) as I join the freeway. For example, * ```-1.5``` means they already passed my starting point ```1.5``` minutes ago * ```2.2``` means they will pass my starting point ```2.2``` minutes from now * How fast they are going (kph) Find what is my "score" as I exit the freeway! # Notes * Assume all cars travel at a constant speeds  Safety Warning  If you plan to play this "game" remember that it is not really a game. You are in a **real** car. There may be a temptation to try to beat your previous best score. Please don't do that...
["def freeway_game(km, kph, cars):\n t = km / kph\n c = 0\n for dt, speed in cars:\n d = km - (t - dt/60) * speed\n if dt <= 0:\n c += d > 0\n else:\n c -= d < 0\n return c", "def freeway_game(dist_km_to_exit, my_speed_kmph, other_cars):\n my_time_to_exit = dist_km_to_exit / my_speed_kmph\n return sum(\n + (lead < 0 and my_time_to_exit * speed < dist_km_to_exit + lead / 60 * speed)\n - (lead > 0 and my_time_to_exit * speed > dist_km_to_exit + lead / 60 * speed)\n for lead, speed in other_cars)", "def freeway_game(dToExit, myS, cars):\n return sum( cS != myS and (0 < minutes/60 * cS/(cS-myS) < dToExit/myS) * (-1)**(cS > myS) for minutes,cS in cars )", "def freeway_game(dist_km_to_exit, my_speed_kph, other_cars):\n score = 0\n for pair in other_cars:\n if(my_speed_kph == pair[1]):\n continue\n if( 0 < pair[1]*(pair[0]/60) / (pair[1] - my_speed_kph) < dist_km_to_exit/my_speed_kph):\n score = score - 1 if pair[0] > 0 else score + 1\n return score", "def freeway_game(distance, speed, cars):\n score = 0\n exit = 60 * distance / speed\n for other_time, other_speed in cars:\n other_exit = 60 * distance / other_speed + other_time\n if other_time < 0 and other_exit > exit:\n score += 1\n elif other_time > 0 and other_exit < exit:\n score -= 1\n return score\n", "def freeway_game(dist_km_to_exit, my_speed, other_cars):\n count = 0\n for (other_start_minute, other_speed) in other_cars:\n if other_speed == my_speed:\n continue\n other_start_time = other_start_minute / 60\n passing_point = (\n (other_start_time * my_speed * other_speed) /\n (other_speed - my_speed)\n )\n if 0 < passing_point < dist_km_to_exit:\n if my_speed > other_speed:\n count += 1\n else:\n count -= 1 \n return count", "def freeway_game(dist_km_to_exit, my_speed_kph, other_cars):\n f_time = lambda s: dist_km_to_exit / s * 60\n duration = f_time(my_speed_kph)\n c = 0\n for p, s in other_cars:\n t = f_time(s) + p\n c += (t > duration and p < 0) - (t < duration and p > 0)\n return c", "def freeway_game(d, speed, arr):\n t = d/speed*60\n print(t)\n c = 0\n \n for data in arr:\n if data[0] < 0:\n if d/data[1]*60 > t-data[0]:\n c += 1\n if data[0] > 0:\n if d/data[1]*60 < t-data[0]:\n c -= 1\n \n return c", "def freeway_game(dist_km_to_exit, my_speed_kph, other_cars):\n t0 = dist_km_to_exit / my_speed_kph\n time_car = lambda dist0, time_delta, speed: (dist0 + time_delta*speed/60) / speed\n result = 0\n for car in other_cars:\n if car[0] > 0 and time_car(dist_km_to_exit, car[0], car[1]) < t0:\n result -= 1\n continue\n if car[0] < 0 and time_car(dist_km_to_exit, car[0], car[1]) > t0:\n result += 1\n return result", "def freeway_game(dist, speed, cars):\n res, exit = 0, dist / speed\n check = lambda t, s1, s2: s * t < exit * s2 * 60\n \n for t,s in cars:\n if t < 0 and speed > s:\n res += check(-t, s, speed-s)\n elif t > 0 and speed < s:\n res -= check(t, s, s-speed)\n return res"]
{"fn_name": "freeway_game", "inputs": [[50.0, 130.0, [[-1.0, 120.0], [-1.5, 120.0]]], [50.0, 110.0, [[1.0, 120.0], [1.5, 125.0]]], [50.0, 120.0, [[-1.0, 115.0], [-1.5, 110.0], [1.0, 130.0], [1.5, 130.0]]], [30.0, 100.0, [[-1.0, 110.0], [-0.7, 102.0], [-1.5, 108.0]]], [30.0, 130.0, [[1.0, 120.0], [0.7, 125.0], [1.5, 110.0]]], [50.0, 110.0, [[-1.0, 110.0], [0.5, 110.0], [1.0, 110.0], [1.5, 110.0]]], [50.0, 110.0, [[0.0, 110.0]]], [50.0, 130.0, []]], "outputs": [[2], [-2], [0], [0], [0], [0], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,426
def freeway_game(dist_km_to_exit, my_speed_kph, other_cars):
d1d21c46846ce28b125aa17d42414e4b
UNKNOWN
You've had a baby. Well done. Nice isn't it? Life destroying... but in a good way. Part of your new routine is lying awake at night worrying that you've either lost the baby... or that you have more than 1! Given a string of words (x), you need to calculate how many babies are in it. To count as a baby you must have all of the letters in baby ('b', 'a', 'b', 'y'). That counts as 1. They do not need to be in order in the string. Upper and lower case letters count. Examples: If there are no babies in the string - you lost the baby!! Return a different value, as shown below: ```if-not:kotlin 'none here' = "Where's the baby?!" '' = "Where's the baby?!" ``` ```if:kotlin "none here" = null "" = null ```
["def baby_count(x):\n x = x.lower()\n return min(x.count('a'), x.count('b') // 2, x.count('y')) or \"Where's the baby?!\"", "from collections import Counter\n\ndef baby_count(x):\n c = Counter(x.lower())\n return min(c['b'] // 2, c['a'], c['y']) or \"Where's the baby?!\"", "from collections import Counter\n\ndef baby_count(s):\n c = Counter(s.lower())\n return min(c['a'],c['b']//2,c['y']) or \"Where's the baby?!\"", "baby_count=lambda x:min(x.lower().count(e)//(2-(e!='b'))for e in'bay')or\"Where's the baby?!\"", "def baby_count(x):\n x = x.lower()\n nb = min(x.count('a'), x.count('y'), x.count('b')//2)\n return nb if nb else \"Where's the baby?!\"", "def baby_count(x):\n b = 0\n a = 0\n y = 0\n for c in x.upper():\n if c == \"B\":\n b += 1\n elif c == \"A\":\n a += 1\n elif c == \"Y\":\n y += 1\n \n count = min(a, b//2, y)\n return count if count > 0 else 'Where\\'s the baby?!'", "def baby_count(x):\n T = [x.lower().count(e)//(2 if e=='b' else 1)for e in 'bay']\n print(T)\n return min(T) if min(T)!=0 else 'Where\\'s the baby?!'", "from collections import Counter\ndef baby_count(x):\n c=Counter(x.lower())\n return min(c.get(\"b\",0)//2,c.get(\"a\",0),c.get(\"y\",0)) or \"Where's the baby?!\"", "def baby_count(x):\n x = x.lower()\n babies = 0\n letters = [x.count('b'), x.count('a'), x.count('y')]\n while min(letters) > 0 and letters[0] > 1:\n letters[0] -= 2\n letters[1] -= 1\n letters[2] -= 1\n babies += 1\n if babies == 0:\n return 'Where\\'s the baby?!'\n else:\n return babies", "def baby_count(x):\n \n s = x.lower()\n \n a = s.count(\"a\")\n \n b = s.count(\"b\")\n \n d = b//2\n \n y = s.count(\"y\")\n \n z = [a,d,y]\n \n m = min(z)\n \n if m==0:\n \n return \"Where's the baby?!\"\n \n else:\n \n return m\n"]
{"fn_name": "baby_count", "inputs": [["baby"], ["abby"], ["baby baby baby"], ["Why the hell are there so many babies?!"], ["Anyone remember life before babies?"], ["Happy babies boom ba by?"], ["b a b y"], [""], ["none here"]], "outputs": [[1], [1], [3], [1], [1], [2], [1], ["Where's the baby?!"], ["Where's the baby?!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,997
def baby_count(x):
c88d79dd4fb717694938bf6d08ee1e2e
UNKNOWN
# Task A noob programmer was given two simple tasks: sum and sort the elements of the given array `arr` = [a1, a2, ..., an]. He started with summing and did it easily, but decided to store the sum he found in some random position of the original array which was a bad idea. Now he needs to cope with the second task, sorting the original array arr, and it's giving him trouble since he modified it. Given the array `shuffled`, consisting of elements a1, a2, ..., an, and their sumvalue in random order, return the sorted array of original elements a1, a2, ..., an. # Example For `shuffled = [1, 12, 3, 6, 2]`, the output should be `[1, 2, 3, 6]`. `1 + 3 + 6 + 2 = 12`, which means that 1, 3, 6 and 2 are original elements of the array. For `shuffled = [1, -3, -5, 7, 2]`, the output should be `[-5, -3, 2, 7]`. # Input/Output - `[input]` integer array `shuffled` Array of at least two integers. It is guaranteed that there is an index i such that shuffled[i] = shuffled[0] + ... + shuffled[i - 1] + shuffled[i + 1] + ... + shuffled[n]. Constraints: `2 ≤ shuffled.length ≤ 30,` `-300 ≤ shuffled[i] ≤ 300.` - `[output]` an integer array A `sorted` array of shuffled.length - 1 elements.
["def shuffled_array(s):\n result = sorted(s)\n result.remove(sum(result) // 2)\n return result\n", "def shuffled_array(s):\n for i in s:\n if sum(s)-i == i: \n s.pop(s.index(i))\n break\n return sorted(s)", "def shuffled_array(s):\n s.pop(s.index(sum(s) /2))\n return sorted(s)", "shuffled_array=lambda a:a.sort()or a.remove(sum(a)/2)or a", "def shuffled_array(s):\n s.remove(sum(s)//2)\n s.sort()\n return s", "def shuffled_array(s):\n for i in range(len(s)):\n k = s[:i] + s[i+1:]\n if sum(k) == s[i]:\n return sorted(k)", "def shuffled_array(s):\n s.sort()\n for i in range(len(s)):\n if s[i] == sum(s[:i]+s[i+1:]):\n return s[:i]+s[i+1:]", "def shuffled_array(a):\n a.remove(sum(a) / 2)\n return sorted(a)", "shuffled_array=lambda a:a.remove(sum(a)/2)or sorted(a)", "def shuffled_array(lst):\n R = lst[:]\n R.remove(sum(R) // 2)\n return sorted(R)"]
{"fn_name": "shuffled_array", "inputs": [[[1, 12, 3, 6, 2]], [[1, -3, -5, 7, 2]], [[2, -1, 2, 2, -1]], [[-3, -3]]], "outputs": [[[1, 2, 3, 6]], [[-5, -3, 2, 7]], [[-1, -1, 2, 2]], [[-3]]]}
INTRODUCTORY
PYTHON3
CODEWARS
980
def shuffled_array(s):
22368aef167465382c1aa56a7b389192
UNKNOWN
# Task The `hamming distance` between a pair of numbers is the number of binary bits that differ in their binary notation. # Example For `a = 25, b= 87`, the result should be `4` ``` 25: 00011001 87: 01010111 ``` The `hamming distance` between these two would be 4 ( the `2nd, 5th, 6th, 7th` bit ). # Input/Output - `[input]` integer `a` First Number. `1 <= a <= 2^20` - `[input]` integer `b` Second Number. `1 <= b <= 2^20` - `[output]` an integer Hamming Distance
["def hamming_distance(a, b):\n return bin(a ^ b).count('1')", "from itertools import zip_longest\ndef hamming_distance(a, b):\n return(sum(x != y for x,y in zip_longest(*[bin(x)[-1:1:-1] for x in (a,b)],fillvalue='0')))\n", "def hamming_distance(a, b):\n return sum(int(i) for i in bin(a^b)[2:])", "def hamming_distance(a, b):\n return sum(x != y for x, y in zip(format(a, \"020b\"), format(b, \"020b\")))", "def hamming_distance(a, b):\n p = len(bin(max(a, b)))\n return sum(i != j for i, j in zip(bin(a)[2: ].rjust(p, '0'), bin(b)[2:].rjust(p, '0')))", "hamming_distance=lambda a,b:bin(a^b).count('1')", "def hamming_distance(a, b):\n A, B = [], []\n a1 = str((bin(a)[2:]))\n print(a1)\n [A.append(i) for i in a1]\n #print(A)\n b1 = str((bin(b)[2:]))\n print(b1)\n [B.append(i) for i in b1]\n distance = 0\n \n print(A)\n \n #Need to make the binary strings the same length and then this will be solved \n \n if len(A) < len(B):\n zeros = ['0'] * (len(B) - len(A))\n A = zeros + A \n elif len(A) > len(B):\n zeros = ['0'] * (len(A) - len(B))\n B = zeros + B \n else: \n pass\n \n \n print( A)\n \n for i in range(0, len(A)):\n if A[i] != B[i]:\n distance += 1\n return distance", "def hamming_distance(a, b):\n c = \"\"\n d = \"\"\n c = bin(a)[2:]\n d = bin(b)[2:]\n for i in range(32 - len(c)):\n c = \"0\" + c\n for i in range(32 - len(d)):\n d = \"0\" + d\n count = 0\n for i in range(32):\n if c[i] != d[i]:\n count += 1\n return count\n", "def hamming_distance(a, b):\n total = 0\n a = list(bin(a)[2:])\n b = list(bin(b)[2:])\n \n if len(a) > len(b):\n for i in range(len(a)-len(b)):\n b.insert(0, '0')\n elif len(b) > len(a):\n for i in range(len(b)-len(a)):\n a.insert(0, '0')\n \n for index in range(len(a)):\n if a[index] != b[index]:\n total += 1\n \n \n return total"]
{"fn_name": "hamming_distance", "inputs": [[25, 87], [256, 302], [543, 634], [34013, 702]], "outputs": [[4], [4], [4], [7]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,092
def hamming_distance(a, b):
76a1e911a50177a89607411e476d0bb1
UNKNOWN
Correct this code so that it takes one argument, `x`, and returns "`x` is more than zero" if `x` is positive (and nonzero), and otherwise, returns "`x` is equal to or less than zero." In both cases, replace `x` with the actual value of `x`.
["def corrections(x):\n str = \"{0} is more than zero.\" if x > 0 else \"{0} is equal to or less than zero.\"\n return str.format(x)", "def corrections(x):\n if x > 0:\n return f'{x} is more than zero.'\n else:\n return f'{x} is equal to or less than zero.'", "corrections = lambda x: '%s is %s than zero.' % (x, ('equal to or less', 'more')[x > 0])", "def corrections(x):\n return f\"{x} is {'more' if x>0 else 'equal to or less'} than zero.\"\n", "def corrections(x):\n return str(x) + ' is more than zero.' if x > 0 else str(x) + ' is equal to or less than zero.'", "def corrections(x):\n return str(x) + (\" is more than zero.\" if x > 0\n else \" is equal to or less than zero.\")", "def corrections(x):\n if x > 0:\n return f\"{x} is more than zero.\"\n return f\"{x} is equal to or less than zero.\"", "def corrections(x):\n return \"%d is %s than zero.\" % (x, [\"equal to or less\", \"more\"][x > 0])", "def corrections(x):\n return '{} is {} than zero.'.format(x, 'more' if x > 0 else 'equal to or less')", "def corrections(x):\n if float(x) > 0.0:\n return str(int(x)) + \" is more than zero.\"\n else:\n return str(int(x)) + \" is equal to or less than zero.\""]
{"fn_name": "corrections", "inputs": [[8], [1], [-2], [-1], [0]], "outputs": [["8 is more than zero."], ["1 is more than zero."], ["-2 is equal to or less than zero."], ["-1 is equal to or less than zero."], ["0 is equal to or less than zero."]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,255
def corrections(x):
ca86122e5573b05f9563fba51ba79a10
UNKNOWN
# Task You are a lonely frog. You live on an integer array. The meaning of your life is to jump and jump.. Now, here comes your new task. You are given an integer array `arr` and a positive integer `n`. You will jump following the rules below: - Your initial position at `arr[0]`. arr[0] will always be `0`. - You will jump according to the number of current position(arr[i]) - That is, if the number is a positive integer, let say 3, you will jump forward 3 steps; If the number is a negative integer, let say -3, you will jump backward 3 steps; If the number is 0, you will stay here for a little rest. - The number of current position(arr[i]) will increase decrease by 1 after each turn (jump or stay). - That is, if the number of current position(arr[i]) is greater than or equal to `n`, the number will decrease 1; if the number at current position(arr[i]) is less than `n`, the number will increase 1. You will stop jumping when you reach the exit (your position greater than or equal to arr.length). Please tell me, at the moment, how many elements in `arr` are equal to `n`? # Note - `3 <= arr.length <= 1000`, `1 <= n <= 9` - Frog will never jump backward out of `arr`. # Example For `arr = [0,3,0,1,-3], n = 3`, the output should be `2`. ``` Let us jump softly: [0,3,0,1,-3] ^--You are here, current number is 0, you stay here. currect number 0 < n, so 0 -> 1 [1,3,0,1,-3] ^--You are here, current number is 1, you will jump forward to position 1. current number 1 < n, so 1 -> 2 [2,3,0,1,-3] ^--You are here, current number is 3, you will jump forward to position 4. current number 3 >= n, so 3 -> 2 [2,2,0,1,-3] ^--You are here, current number is -3, you will jump backward to position 1. current number -3 < n, so -3 -> -2 [2,2,0,1,-2] ^--You are here, current number is 2, you will jump forward to position 3. current number 2 < n, so 2 -> 3 [2,3,0,1,-2] ^--You are here, current number is 1, you will jump forward to position 3. current number 1 < n, so 1 -> 2 [2,3,0,2,-2] ^--You are here, current number is -2, you will jump backward to position 2. current number -2 < n, so -2 -> -1 [2,3,0,2,-1] ^--You are here, current number is 0, you stay here. current number 0 < n, so 0 -> 1 [2,3,1,2,-1] ^--You are here, current number is 1, you will jump forward to position 3. current number 1 < n, so 1 -> 2 [2,3,2,2,-1] ^--You are here, current number is 2, you will jump forward to position 5. current number 2 < n, so 2 -> 3 [2,3,2,3,-1] exit ^--You are here, you reach to the exit. At the moment, arr[1] and arr[3] are equal to n. So, the output should be 2. ``` For `arr = [0,-1,-2,-3,-4], n = 4`, the output should be `2`. ``` Let's us jump fast ;-) [0,-1,-2,-3,-4] ^ [1,-1,-2,-3,-4] ^ [2,-1,-2,-3,-4] ^ [2, 0,-2,-3,-4] ^ [3, 0,-2,-3,-4] ^ [3, 0,-1,-3,-4] ^ [4, 0,-1,-3,-4] ^ [4, 0,-1,-2,-4] ^ [3, 0,-1,-2,-4] ^ [3, 0,-1,-2,-3] ^ [4, 0,-1,-2,-3] ^ [4, 0,-1,-1,-3] ^ [4, 1,-1,-1,-3] ^ [4, 2,-1,-1,-3] ^ [4, 2, 0,-1,-3] ^ [4, 3, 0,-1,-3] ^ [4, 3, 0, 0,-3] ^ [4, 3, 1, 0,-3] ^ [4, 3, 2, 0,-3] ^ [4, 3, 2, 1,-3] ^ [4, 3, 2, 2,-3] ^ [4, 3, 2, 2,-2] ^ [4, 4, 2, 2,-2] ^ [4, 4, 2, 2,-1] ^ [4, 4, 3, 2,-1] ^ [4, 4, 3, 2, 0] ^ [4, 4, 3, 3, 0] exit ^ At the moment, arr[0] and arr[1] are equal to n. So, the output should be 2. ``` For `arr = [0,-1,-2,-3,-4], n = 3`, the output should be `0`. ``` Let's jump fast ;-) [0,-1,-2,-3,-4] ^ [1,-1,-2,-3,-4] ^ [2,-1,-2,-3,-4] ^ [2, 0,-2,-3,-4] ^ [3, 0,-2,-3,-4] ^ [3, 0,-1,-3,-4] ^ [2, 0,-1,-3,-4] ^ [2, 0,-1,-2,-4] ^ [3, 0,-1,-2,-4] ^ [3, 0, 0,-2,-4] ^ [3, 1, 0,-2,-4] ^ [3, 2, 0,-2,-4] ^ [3, 2, 1,-2,-4] ^ [3, 2, 2,-2,-4] ^ [3, 2, 2,-1,-4] ^ [3, 3, 2,-1,-4] ^ [3, 3, 2, 0,-4] ^ [3, 3, 3, 0,-4] ^ [3, 3, 3, 0,-3] ^ [2, 3, 3, 0,-3] ^ [2, 3, 3, 1,-3] ^ [2, 3, 3, 2,-3] ^ [2, 3, 3, 2,-2] ^ [2, 2, 3, 2,-2] ^ [2, 2, 3, 2,-1] ^ [2, 2, 2, 2,-1] exit ^ At the moment, there is no element equal to n. So, the output should be 0. ``` [Base idea taken from [here](https://adventofcode.com/2017/day/5)]
["def jumping(arr, n):\n i = 0\n while i < len(arr):\n x = arr[i]\n arr[i] += 1 if x < n else -1\n i += x\n return arr.count(n)", "def jumping(arr, n):\n i, arr = 0, arr[:]\n arr[0] += 1\n while i<len(arr):\n delta = arr[i]\n arr[i] += (arr[i]<n) - (arr[i]>=n)\n i += delta\n return arr.count(n)", "def jumping(arr, n):\n l, pos = len(arr), 0\n while pos < l:\n arr[pos], pos = arr[pos] + (arr[pos] < n or -1), pos + arr[pos]\n return arr.count(n)", "def jumping(a, n):\n i = 0\n while i < len(a):\n temp = a[i]\n a[i] += 1 if a[i] < n else -1\n i += temp\n return a.count(n)", "def jumping(arr, n):\n c = 0\n while c < len(arr):\n T = arr[c]//1\n c += T\n arr[c-T] += -1 if arr[c-T] >= n else 1\n return arr.count(n)", "def jumping(arr, n):\n i = 0\n print(arr)\n while i < len(arr):\n k = arr[i]\n if k >= n:\n arr[i] -= 1\n elif k < n:\n arr[i] += 1\n i += k\n return sum([i == n for i in arr])\n", "def jumping(arr, n):\n i = 0\n while i < len(arr):\n t = arr[i]\n arr[i] += 1 if t < n else -1\n i += t\n return arr.count(n)", "def jumping(arr, n):\n pos = 0\n new_pos = 0\n answer = 0\n while True:\n try:\n new_pos = pos + arr[pos]\n if n > arr[pos]:\n arr[pos] += 1\n else:\n arr[pos] -= 1\n pos = new_pos\n except:\n for place in arr:\n if place == n:\n answer += 1\n break\n return answer", "def jumping(arr, n):\n ind = 0\n while ind < len(arr):\n here = arr[ind]\n if here < n:\n arr[ind] += 1\n if here >= n:\n arr[ind] -= 1\n ind += here\n \n return len([i for i in arr if i == n])", "def jumping(arr, n):\n ind = 0\n add = 0\n while ind < len(arr):\n if arr[ind] >= n:\n add = -1\n else:\n add = 1\n arr[ind] += add\n ind += arr[ind] - add\n return arr.count(n)"]
{"fn_name": "jumping", "inputs": [[[0, 3, 0, 1, -3], 3], [[0, -1, -2, -3, -4], 4], [[0, -1, -2, -3, -4], 3], [[0, -1, -2, -3, -4], 2], [[0, -1, -2, -3, -4], 1]], "outputs": [[2], [2], [0], [3], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,206
def jumping(arr, n):
196216ccb516392d0d95840439d16476
UNKNOWN
# Your Task You have a Petri dish with bacteria, and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them. You know that you have `n` bacteria in the Petri dish and size of the i-th bacteria is bacteriai. Also you know intergalactic positive integer constant `K`. The i-th bacteria can swallow the j-th bacteria if and only if bacteriai > bacteriaj and bacteriai ≤ bacteriaj + K. The j-th bacteria disappear, but the i-th bacteria doesn't change its size. Since you don't have a microscope, you can only guess the minimal possible number of bacteria that will remain in your Petri dish when you finally find a microscope. ```python micro_world([101, 53, 42, 102, 101, 55, 54], 1) == 3 micro_world([20, 15, 10, 15, 20, 25], 5) == 1 ``` ___ # Explanation ```python bacteria = [101, 53, 42, 102, 101, 55, 54] K = 1 ``` ```if:cpp The one of possible sequences of swallows is: {101,53,42,102,101,55,54} → {101,53,42,102,55,54} → {101,42,102,55,54} → {42,102,55,54} → {42,102,55}. In total there are 3 bacteria remaining. ``` ```if:python,ruby,javascript The one of possible sequences of swallows is: [101,53,42,102,101,55,54] → [101,53,42,102,55,54] → [101,42,102,55,54] → [42,102,55,54] → [42,102,55]. In total there are 3 bacteria remaining. ```
["def micro_world(bacteria, k):\n return sum(1 for e in bacteria if not [j for j in bacteria if e<j<=e+k])\n", "def micro_world(bact, k):\n bact = sorted(bact)\n return sum(1 for i, a in enumerate(bact) if all(a == b or a + k < b for b in bact[i+1:]))", "from collections import Counter\n\ndef micro_world(bacteria, k):\n L = sorted(Counter(bacteria).items())\n return sum(v1 for (k1,v1),(k2,_) in zip(L, L[1:]) if k2 > k1+k) + L[-1][1]", "from collections import Counter\n\ndef micro_world(bs, k):\n c = Counter(bs)\n ns = sorted(c)\n return sum((x + k < bigger) * c[x] for x, bigger in zip(ns, ns[1:] + [float('inf')]))\n", "def micro_world(bacteria, k):\n for i in list(bacteria):\n bacteria = [x for x in bacteria if not (i > x and i -k <= x) or x == i]\n \n return len(bacteria)", "import numpy as np\n\ndef micro_world(bacteria, k):\n bacteria = np.array(sorted(bacteria))\n for index, j in enumerate(bacteria):\n if j < 0:\n continue\n for i in bacteria[index:]:\n if i > j and i <= j + k:\n bacteria[bacteria == j] = -1\n break\n return len(list(filter(lambda x: x > 0, bacteria)))", "def micro_world(bacteria, k):\n i = 0\n j = 1\n bacteria = sorted(bacteria)\n \n while i < len(bacteria) - 1:\n if bacteria[i] == bacteria [i+j]:\n j += 1\n if i + j > len(bacteria) - 1:\n break\n else:\n if bacteria[i] < bacteria[i+j] <= bacteria[i] + k:\n bacteria.remove(bacteria[i])\n else:\n i += 1\n j = 1\n \n return len(bacteria)", "def micro_world(bacteria, k):\n b = sorted(bacteria)\n f, leng = 0, len(b)\n for i, e in enumerate(b[:-1]):\n if e < b[i+1] and e + k >= b[i+1]:\n leng = leng - 1 - f\n f = 0\n elif e == b[i+1]:\n f += 1\n else:\n f = 0\n return leng", "def micro_world(bacteria, k):\n bacteria.sort()\n while True:\n last = len(bacteria)\n for j in range(len(bacteria)):\n has_eat = False\n for i in range(j+1, len(bacteria)):\n if bacteria[i] > bacteria[j] and bacteria[i] <= k+bacteria[j]:\n bacteria.remove(bacteria[j])\n has_eat = True\n break\n if has_eat:\n break\n if len(bacteria) == last:\n break\n return len(bacteria)", "def micro_world(arr,k):\n x = arr.copy()\n for i in arr:\n for j in range(i-k,i):\n while j in x:\n x.remove(j)\n return len(x)"]
{"fn_name": "micro_world", "inputs": [[[101, 53, 42, 102, 101, 55, 54], 1], [[20, 15, 10, 15, 20, 25], 5], [[5, 3, 1, 5], 1]], "outputs": [[3], [1], [4]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,713
def micro_world(bacteria, k):
2373a8bdf5651cfb4013fd613e46522a
UNKNOWN
Complete the function that accepts a string parameter, and reverses each word in the string. **All** spaces in the string should be retained. ## Examples ``` "This is an example!" ==> "sihT si na !elpmaxe" "double spaces" ==> "elbuod secaps" ```
["def reverse_words(str):\n return ' '.join(s[::-1] for s in str.split(' '))", "def reverse_words(str_):\n return ' '.join(s[::-1] for s in str_.split(' '))\n", "import re\n\ndef reverse_words(str):\n return re.sub(r'\\S+', lambda w: w.group(0)[::-1], str)", "def reverse_words(str):\n return ' '.join(w[::-1] for w in str.split(' '))", "def reverse_words(str):\n return \" \".join(map(lambda word: word[::-1], str.split(' ')))", "def reverse_words(str):\n #go for it\n newStr = []\n for i in str.split(' '):\n newStr.append(i[::-1])\n return ' '.join(newStr)", "import re\n\ndef reverse_words(str):\n return ''.join(word[::-1] for word in re.split(r'(\\s+)', str))", "def reverse_words(str):\n return ' '.join([i[::-1] for i in str.split(' ')])", "def reverse_words(text):\n return ' '.join([ word[::-1] for word in text.split(' ')])", "def reverse_words(inString):\n return \" \".join(inString[::-1].split(\" \")[::-1])", "def reverse_words(str):\n #go for it\n return \" \".join([\"\".join(word[::-1]) for word in str.split(\" \")])", "def reverse_words(string):\n space=' '\n for i in range(len(string)):\n if string[i] == ' ' and string[i+1] == ' ':\n space = ' '\n break\n if string[i] == ' ':\n space = ' '\n break\n lst = string.split()\n for i in range(len(lst)):\n lst[i] = reverse_one_word(lst[i])\n return space.join(lst)\n \n \ndef reverse_one_word(string):\n reverse = ''\n for i in range(len(string)):\n reverse = string[i] + reverse\n return reverse", "def reverse_words(text):\n l = text.split(' ')\n for i in range(len(l)):\n l[i] = l[i][::-1]\n return ' '.join(l)", "def reverse_words(text):\n L=[]\n a=text.split(\" \")\n for i in a:\n i=i[::-1]\n L.append(i)\n x=\" \".join(L)\n return x", "import re\nimport textwrap\ndef reverse_words(text):\n text = re.split('([\\s,;()]+)', text)\n separator = ''\n\n for n, string in enumerate(text):\n text[n] = list(text[n])\n text[n].reverse()\n text[n] = separator.join(text[n])\n\n text = separator.join(text)\n\n return text\n", "import re\ndef reverse_words(text):\n return ' '.join([x[::-1] for x in text.split(' ')])", "def reverse_words(text):\n\n rev=text[::-1]\n lst_rev=rev.split(' ')\n lst=lst_rev[::-1]\n str=' '.join(lst)\n return str", "def reverse_words(text):\n #go for it\n word = ''\n rev_word = ''\n for i in range(0,len(text)):\n if(text[i] != ' '):\n word = word + text[i]\n else:\n rev_word = rev_word + word[::-1] + text[i]\n word = ''\n return(rev_word + word[::-1])", "def reverse_words(text):\n return ' '.join(e[::-1] for e in text.split(' '))", "def reverse_words(text):\n #go for it\n return \" \".join(x[::-1] for x in text.split(\" \"))", "def reverse_words(text):\n return ' '.join(word[::-1] for word in text.split(' '))", "def reverse_words(s):\n return ' '.join(x[::-1] for x in s.split(\" \"))", "def reverse_words(str):\n lst = str.split(\" \")\n for i in range(len(lst)):\n lst[i] = lst[i][::-1]\n return ' '.join(lst)\n", "def reverse_words(str):\n return ' '.join(x[::-1] for x in str.split(\" \"))", "def reverse_words(str):\n return ' '.join(map(lambda x: x[::-1], str.split(' ')))", "def reverse_words(text):\n\n return ' '.join((text[::-1]).split(' ')[::-1])\n \n \"\"\"\n rev=text[::-1]\n lst_rev=rev.split(' ')\n lst=lst_rev[::-1]\n str=' '.join(lst)\n return str\n \"\"\"", "def reverse_words(text):\n #go for it\n return ' '.join([i[::-1] for i in text.split(' ')])\n", "def reverse_words (string): \n string = string[::-1] \n word_r = string.split(' ')\n word_r.reverse()\n output = ' '.join(word_r)\n return output", "def reverse_words(text):\n \n new_text = \"\"\n \n for word in text.split(\" \"):\n \n new_text += (word[::-1] + \" \")\n \n final = new_text[:-1]\n\n return final", "import re\n\ndef reverse_words(text):\n return re.sub(r'([^ ]+)', lambda x: x.group()[::-1], text)", "def reverse_words(text):\n return \" \".join([\"\".join(reversed(list(i))) for i in text.split(\" \")])", "def reverse_words(text):\n text = text.split(' ')\n re = [i[::-1] for i in text]\n return ' '.join(re)", "def reverse_words(text):\n text = text.replace(\" \", \"\\n<SP>\\n\").lstrip(\"\\n\").split(\"\\n\") \n output = []\n for word in text:\n if word != \"<SP>\":output.append(word[::-1])\n else:output.append(word)\n return str(\"\".join(output)).replace(\"<SP>\",\" \")\n", "def reverse_words(text):\n return ' '.join(i[::-1] for i in text.split(' '))", "def reverse_words(str):\n ss=list(\"\".join(i[::-1] for i in str.split())[::-1])\n return \"\".join([ss.pop() if el!=\" \" else \" \" for el in str])", "def reverse_words(str):\n def reverser(word):\n if word == \"\":\n return word\n else:\n return reverser(word[1:]) + word[0]\n \n words_list = [reverser(x) for x in str.split(\" \")]\n return \" \".join(words_list)\n", "reverse_words = lambda x: ' '.join([y[::-1] for y in x.split(' ')])", "def reverse_words(st):\n return \" \".join(\"\".join(reversed(wr)) for wr in st.split(' '))", "import re\nreverse_words = lambda s: ''.join([i[::-1] for i in re.split(r'(\\s+)', s)]) ", "def reverse_words(str):\n return \" \".join([st[::-1] for st in str.split(\" \")])", "def reverse_words(str):\n return ' '.join(item[::-1] for item in str.split(' '))", "reverse_words = lambda str: ' '.join(''.join(j for j in i[::-1]) for i in str.split(' '))", "def reverse_words(text):\n new_string=\"\"\n text = text.split(\" \")\n print (text)\n first = True \n for word in text:\n if first == True:\n first = False\n else:\n new_string = new_string+\" \"\n x=len(word)\n for letter in word: \n new_letter = word[x-1]\n new_string=new_string+new_letter\n x-=1\n return new_string\n\n", "def reverse_words(text):\n finalWord = ' '\n newWord = text.split(' ')\n for word in newWord:\n word = word[::-1]\n finalWord = finalWord + word + ' '\n return finalWord.strip()", "def reverse_words(text):\n #go for it\n #print(text[::-1])\n return \" \".join([ word[::-1] for word in text.split(\" \")] )", "def reverse_words(text):\n text = text.split(' ')\n str = ''\n for i in text:\n i = i[::-1]\n str =str + ' ' + i\n return str[1:]\n", "def reverse_words(text):\n output = \"\"\n word = \"\"\n for i in text:\n if i != \" \":\n word += i\n else:\n output += word[::-1]\n output += i\n word = \"\"\n output += word[::-1]\n return output", "def reverse_words(text):\n if len(text.split(' ')) > 1:\n return ' '.join([''.join(reversed(t)) for t in text.split(' ')])\n else:\n return ' '.join([''.join(reversed(t)) for t in text.split(' ')])", "def reverse_words(text):\n txt_lst = text.split(\" \")\n res = []\n for item in txt_lst:\n res.append(item[::-1])\n return \" \".join(res)", "def reverse_words(text):\n lst = text.split(\" \")\n lst = [i[::-1] for i in lst]\n return \" \".join(lst)", "import re\ndef reverse_words(text):\n #go for it\n #split the string by spaces\n arr = re.split(r'(\\s+)', text)\n # see the array\n #for loop to reverse each string within the array\n reverse = [i[::-1]for i in arr]\n finished = ''.join(reverse)\n return finished\n", "def reverse_words(text):\n textArray = text.split(\" \")\n reversedArray = []\n for word in textArray:\n reversedWord = ''\n for letter in word:\n reversedWord = letter + reversedWord\n reversedArray.append(reversedWord)\n \n return \" \".join(reversedArray)\n", "def reverse_words(text):\n # Split ' ' will respect multiple whitespace where split() will not.\n return ' '.join(word[::-1] for word in text.split(' '))", "def reverse_words(text):\n new_list = text.split(' ')\n lc = [ x[::-1]for x in new_list]\n return(' '.join(lc))\n #go for it\n", "import functools\ndef reverse_words(text):\n reversed_text = list(functools.reduce(\n lambda acc,st: acc + st, [''.join(reversed(word)) for word in text.split()], ''))\n return_arr = []\n for ch in text:\n if ch.isspace():\n return_arr.append(\" \")\n else:\n return_arr.append(reversed_text.pop(0))\n return ''.join(return_arr)\n", "def reverse_words(text: str) -> str:\n # go for it\n final: str = ''\n string_list: list = text.split(' ')\n for i in string_list[:-1]: #go on each word and reverse before last one\n final += i[::-1] + ' ' #add space where needed\n final += string_list[-1][::-1] #add the last word reversed\n return final", "def reverse_words(text): \n return \" \".join(word[::-1] for word in text.split(\" \")) \n \n\ntext =(\"\")\nprint(reverse_words(text)) ", "def reverse_words(text):\n # Splitting the Sentence into list of words. \n words = text.split(\" \") \n \n # Reversing each word and creating \n # a new list of words \n # List Comprehension Technique \n newWords = [word[::-1] for word in words] \n \n # Joining the new list of words \n # to for a new Sentence \n print(newWords)\n newSentence = \" \".join(newWords) \n \n return newSentence ", "def reverse_words(text):\n words = text.split(' ')\n new_text = ''\n \n for word in words:\n new_text += word[::-1]\n \n if word is not words[-1]:\n new_text += ' '\n \n return new_text", "def reverse_words(text):\n text = text.split(\" \")\n return \" \".join([text[i][::-1] for i in range(len(text))])", "def reverse_words(text):\n l = [i[::-1] for i in text.split(\" \")]\n return \" \".join(l)\n", "def reverse_words(text):\n# change string to list of words with split\n# reverse each word\n# concatenate the words back together and return\n\n lis = text.split(\" \")\n reversed_words = []\n new_sentence = \"\"\n for word in lis:\n new_word = word[::-1]\n print(new_word)\n reversed_words.append(new_word)\n for word in reversed_words:\n new_sentence += word + \" \"\n return new_sentence[0:len(new_sentence)-1]\n \n", "def reverse_words(text):\n ret_text = ''\n text_list = text.split(' ')\n \n for n, i in enumerate(text_list):\n text_list[n] = i[::-1]\n \n for n, i in enumerate(text_list):\n if n != len(text_list) - 1:\n ret_text += f'{i} '\n else:\n ret_text += i\n \n return ret_text", "import re\n\ndef reverse_words(text):\n list = re.split(r'(\\s+)', text)\n res = \"\"\n for w in list:\n for i in range(len(w), 0, -1):\n res += w[i - 1]\n return res", "def reverse_words(text):\n words=text.split(\" \")\n reversed_t=\" \".join(reversed(words))\n return reversed_t[::-1]\n #go for it\n", "import re\n\ndef reverse_words(text):\n wordList = re.findall(\"\\S+\", text)\n spaceList = re.findall(\"\\s+\", text)\n answerList = []\n answerString = \"\"\n spaceCounter = 0\n for word in wordList:\n answerList.append(word[::-1])\n if spaceCounter < len(spaceList):\n answerList.append(spaceList[spaceCounter])\n spaceCounter += 1\n return(answerString.join(answerList))", "def reverse_words(text):\n words = text.split(' ')\n backwards = []\n for word in words:\n backword = ''\n for c in range(len(word)-1, -1, -1):\n backword += word[c]\n backwards.append(backword)\n return ' '.join(backwards)", "def reverse_words(text):\n #go for it\n n = len(text)\n liste = text.split(\" \")\n liste = [reverse(mot) for mot in liste]\n return \" \".join(liste)\n \ndef reverse(text):\n n = len(text)\n reponse = \"\"\n for i in range(n):\n reponse += text[n - (i+1)]\n return reponse", "def reverse_words(text):\n reverse=''\n for word in text.split(' ')[:-1]:\n reverse+=word[::-1]+' '\n return reverse+text.split(' ')[-1][::-1]", "def reverse_words(text):\n print(text)\n a = list(enumerate(text))\n new_list = []\n new_list2 = []\n x = text.split()\n for el in x:\n new_list.append(list(reversed(el)))\n for el in new_list:\n y = \"\".join(el)\n new_list2.append(y)\n new_list3 = [i for ele in new_list2 for i in ele]\n for el in a:\n if el[1] == \" \":\n new_list3.insert(el[0], \" \")\n z = \"\".join(new_list3)\n\n return z", "def reverse_words(text):\n array = text.split(' ')\n new_array = [ word[::-1] for word in array]\n return ' '.join(new_array)\n \n", "def reverse_words(text):\n medzera = ' '\n x = text.split(medzera)\n for i in range(len(x)):\n x[i] = x[i][::-1]\n y = medzera.join(x)\n return y\n", "def reverse_words(text):\n ls = []\n \n for i in text.split():\n ls.append(i[::-1])\n\n if text.find(\" \") > -1:\n return \" \".join(ls)\n else:\n return \" \".join(ls)", "def reverse_words(text):\n t = text.split()\n t_new = []\n for i in t:\n i = i[::-1]\n t_new.append(i)\n sp1 = \" \".join(t_new)\n if len(sp1) != len(text):\n sp2 = \" \".join(t_new)\n return sp2\n else:\n return sp1", "def reverse_words(text):\n spaces = text.count(' ')\n text = [x[::-1] for x in text.split()]\n return ' '.join(text) if spaces >= 1 else ' '.join(text)", "def reverse_words(text):\n return ' '.join([''.join(list(i)[::-1]) for i in text.split(' ')])\n", "def reverse_words(text):\n split_txt = text.split(\" \") \n \n result = \"\"\n \n for word in split_txt:\n \n result += \"\".join(word[::-1]) + \" \"\n \n print((result[:-1]))\n return(result[:-1])\n", "def reverse_words(text):\n text_split = text.split(\" \")\n index = 0\n for t in text_split:\n text_split[index] = \"\".join(reversed(t))\n index += 1\n \n return (\" \".join(text_split))", "import re\ndef reverse_words(text):\n stuff=re.split('(\\s+)', text)\n print (stuff)\n cat=list()\n for words in stuff:\n reverse=words[::-1]\n cat.append(reverse)\n dog=''.join(cat)\n\n return dog\n\n #go for it\n", "def reverse_words(text):\n #go for it\n t_list = text.split(' ')\n for i, t_ele in enumerate(t_list):\n if t_ele == '':\n t_list[i] = t_ele\n else:\n t_list[i] = t_ele[::-1]\n return ' '.join(t_list)", "import re\n\ndef reverse_words(text):\n li_text = re.split(\"( )\",text) # Why must regular split be different from regex split :/\n solution = ''.join(list(word[::-1] for word in li_text)) # Separated from split for readability.\n \n return solution", "def reverse_words(text):\n split_text = text.split()\n sentence_list = []\n for word in split_text:\n reverseword_list = []\n for i in word:\n reverseword_list.append(i)\n sentence_list.append(\"\".join(reverseword_list[::-1]))\n for i in range(len(text)-1):\n if text[i] == \" \" and text[i+1] == \" \":\n return (\" \".join(sentence_list))\n if text[i] == \" \" and text[i+1] != \" \":\n pass\n return (\" \".join(sentence_list))\n\n", "def reverse_words(text):\n a = text.split(\" \")\n b = []\n for word in a: \n b.append(word[::-1])\n c = ' '.join(b)\n return(c)\n \n \n \n", "def reverse_words(text):\n backwards = (text[::-1]).split(\" \")\n text = \"\"\n print(backwards)\n for word in backwards[::-1]:\n text +=word\n text +=\" \"\n \n return text[:-1]", "def reverse_words(text):\n a = text\n list_1 = []\n list_3 = []\n split = text.split(' ')\n for x in split:\n list_2 = []\n if x == \"\":\n list_3.append(x)\n else:\n length = len(x)\n for y in range(length-1, -1, -1):\n list_2.append(x[y])\n final = ''.join(list_2)\n list_3.append(final)\n re_final = ' '.join(list_3)\n return re_final\n", "def reverse_words(text):\n reversed = \"\"\n for word in text.split(\" \"):\n w =\" \"\n for char in word:\n w = char + w\n reversed = reversed + w\n return (reversed.strip())", "def reverse_words(text):\n r = []\n for w in text.split(' '):\n r.append(w[int(len(w))::-1])\n s = ' '\n return s.join(r)\n", "def reverse_words(text):\n w=text.split(\" \")\n s=\"\"\n for i in w:\n x=i[::-1]\n if s ==\"\":\n s=x\n else:\n s=s+\" \"+x\n return s\n", "def reverse_words(text):\n s = ' '.join([i[::-1] for i in text.split(' ')])\n return s\n", "def reverse_words(text):\n text = text.split(' ')\n text = [x[::-1] for x in text]\n return ' '.join(text)", "def reverse_words(text):\n word_list = text.split()\n reversed_str = ''\n spacer = ''\n if ' ' in text:\n count = 1\n spacer += ' '\n index = text.find(' ')\n while text[index + count] == ' ':\n spacer += ' '\n count += 1\n \n for item in word_list:\n item = item[::-1]\n if len(reversed_str) < 1:\n reversed_str += item\n else:\n reversed_str += (spacer + item)\n return reversed_str", "def reverse_words(text):\n tempWord = \"\"\n result = \"\"\n for i in range(len(text)):\n if text[i] != \" \":\n tempWord += text[i]\n if i == len(text)-1:\n result += tempWord[::-1]\n else:\n if text[i-1] != \" \":\n result += tempWord[::-1] + \" \"\n tempWord = \"\"\n else:\n result += \" \"\n return result", "def reverse_words(text):\n final_string = \"\"\n for i in ([i[::-1] for i in text.split(\" \")]):\n final_string += (i + \" \")\n return final_string[:-1]", "def reverse_words(text):\n #go for it\n reversed_string = []\n for i in text.split(' '):\n reversed_string.append(i[::-1])\n return ' '.join(reversed_string)", "def reverse_words(text):\n res = list()\n win = str(text).split()\n for w in win:\n word = str()\n for l in w:\n word = l + word\n res.append(word)\n if ' ' in text:\n return ' '.join(res)\n else:\n return ' '.join(res)\n \n #go for it\n", "def reverse_words(text):\n #go for it\n string = text.split(' ')\n for i,j in enumerate(string):\n string[i] = j[::-1]\n return ' '.join(string)\n", "def reverse_words(text):\n #go for it\n spl = text.split(\" \")\n new = ''\n for i in spl:\n new+=i[::-1]+\" \"\n return new.strip()", "def reverse_words(text):\n arr=text.split(\" \")\n resarr=[]\n t=\" \"\n for i in arr:\n a=[]\n s=\"\"\n for j in i: \n a.insert(0,j)\n resarr.append(s.join(a))\n return t.join(resarr) \n \n #go for it\n", "def reverse_words(text):\n #go for it\n textlist = text.split(' ')\n textlist = map(lambda x:x[::-1],textlist)\n return ' '.join(textlist)", "def reverse_words(text):\n words = text.split()\n for i in range(len(words)):\n words[i] = words[i][::-1]\n if ' ' in text:\n return \" \".join(words)\n return \" \".join(words)", "def reverse_words(text):\n new=text.split(' ')\n for elem,text in enumerate(new):\n new[elem]=text[::-1]\n return ' '.join(new)"]
{"fn_name": "reverse_words", "inputs": [["The quick brown fox jumps over the lazy dog."], ["apple"], ["a b c d"], ["double spaced words"], ["stressed desserts"], ["hello hello"]], "outputs": [["ehT kciuq nworb xof spmuj revo eht yzal .god"], ["elppa"], ["a b c d"], ["elbuod decaps sdrow"], ["desserts stressed"], ["olleh olleh"]]}
INTRODUCTORY
PYTHON3
CODEWARS
20,093
def reverse_words(text):
8d565577300c6367991007e82b388b2c
UNKNOWN
# Task John and Alice have an appointment today. In the morning, John starts from (`0,0`) and goes to the place (`a,b`) where he is dating. Unfortunately, John had no sense of direction at all, so he moved 1 step in a random direction(up, down, left or right) each time. For example, if John at (x,y), next step he may move to `(x+1,y), (x-1,y),(x,y+1) or (x,y-1)`. Obviously, when he arrived at the destination, it was already too late and Alice had already left. It's a sadly story :( The second day, Alice asked John why he didn't go to the dating place. John said he took `s` steps to his date yesterday. Alice wants to know whether John is lying. Please help Alice to judge. Given two coordinates `a, b` and the step `s`, return `true` if John tells the truth, `false` otherwise. # Input/Output `[input]` integer `a` The x-coordinates of the dating site. `-10^7 <= a <= 10^7` `[input]` integer `b` The y-coordinates of the dating site. `-10^7 <= b <= 10^7` `[input]` integer `s` A positive integer. The steps John using. `0 < s <= 10^9` `[output]` a boolean value return `true` if John tells the truth, `false` otherwise. # Example For `a = 3, b = 3, s = 6`, the output should be `true`. A possible path is: `(0,0) -> (0,1) -> (0,2) -> (0,3) -> (1,3) -> (2,3) -> (3,3)` For `a = 3, b = 3, s = 8`, the output should be `true`. A possible path is: `(0,0) -> (0,1) -> (1,1) -> (1,2) -> (2,2) -> (2,1) -> (3,1) -> (3,2) -> (3,3)` For `a = 4, b = 5, s = 10`, the output should be `false`. John can't reach coordinates (a, b) using 10 steps, he's lying ;-)
["def is_john_lying(a,b,s):\n delta = abs(a) + abs(b) - s\n return delta <= 0 and delta % 2 == 0", "def is_john_lying(a,b,s):\n a, b = abs(a), abs(b)\n return s-a-b>=0 and (s-a-b)%2 == 0", "def is_john_lying(a, b, s):\n return s >= abs(a) + abs(b) and s % 2 == (a + b) % 2", "def is_john_lying(a,b,s):\n ab = abs(a) + abs(b)\n return ab <= s and (ab & 1) == (s & 1)", "def is_john_lying(a,b,s):\n return abs(a)+abs(b) - s <= 0 and (abs(a)+abs(b) - s) % 2 == 0", "is_john_lying=lambda a,b,s:s>=abs(a)+abs(b)and-~s+a+b&1", "def is_john_lying(a, b, c):\n a, b = abs(a), abs(b)\n return c >= a + b and (c - a - b) % 2 ^ 1", "def is_john_lying(a, b, s):\n dest_dist = abs(a) + abs(b) \n return dest_dist == s or (dest_dist < s and not (dest_dist - s) % 2)", "def is_john_lying(a,b,s):\n c = abs(a)+abs(b)\n return c%2==s%2 and c<=s", "def is_john_lying(a,b,s):\n return (a+b)%2==s%2 and abs(a)+abs(b)<=s"]
{"fn_name": "is_john_lying", "inputs": [[3, 3, 6], [4, 5, 10], [-5, -5, 10], [-5, -5, 8], [10, -10, 10]], "outputs": [[true], [false], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
945
def is_john_lying(a,b,s):
c05ce0762e8479ced4e9f1e8b7a837f2
UNKNOWN
While surfing in web I found interesting math problem called "Always perfect". That means if you add 1 to the product of four consecutive numbers the answer is ALWAYS a perfect square. For example we have: 1,2,3,4 and the product will be 1X2X3X4=24. If we add 1 to the product that would become 25, since the result number is a perfect square the square root of 25 would be 5. So now lets write a function which takes numbers separated by commas in string format and returns the number which is a perfect square and the square root of that number. If string contains other characters than number or it has more or less than 4 numbers separated by comma function returns "incorrect input". If string contains 4 numbers but not consecutive it returns "not consecutive".
["def check_root(string):\n try:\n a,b,c,d = [int(i) for i in string.split(',')]\n if not (a == b-1 and a == c-2 and a == d-3):\n return 'not consecutive'\n s = a*b*c*d+1\n return str(s)+', '+str(int(s**0.5))\n except:\n return 'incorrect input'", "import re\ndef check_root(string):\n if not re.fullmatch(r\"(-?\\d+,){3}-?\\d+\", string):\n return 'incorrect input'\n a, b, c, d = list(map(int, string.split(\",\")))\n if not d == c + 1 == b + 2 == a + 3:\n return 'not consecutive'\n return f\"{a * b * c * d + 1}, {abs(b ** 2 + a)}\"\n \n \n \n", "# a*b*c*d + 1\n# = a*(a+1)*(a+2)*(a+3) + 1\n# = a**4 + 6*a**3 + 11*a**2 + 6*a + 1\n# = (a**2 + 3*a + 1)**2\n# = (a**2 + 2*a + 1 + a)**2\n# = ((a+1)**2 + a)**2\n# sqtr = (a+1)**2 + a\n\ndef check_root(string):\n try:\n a, b, c, d = map(int, string.split(','))\n if a+3 == b+2 == c+1 == d:\n x = a + (a+1)**2\n return \"{}, {}\".format(x**2, abs(x))\n return \"not consecutive\"\n except:\n return \"incorrect input\"", "from functools import reduce\nfrom operator import mul\ndef check_root(string):\n l = string.split(',')\n if len(l) != 4:\n return 'incorrect input'\n try:\n l = list(map(int, l))\n except:\n return 'incorrect input'\n \n if not all(l[i] - l[i-1] == 1 for i in range(1,len(l))):\n return 'not consecutive'\n \n return '{}, {}'.format(reduce(mul, l) + 1, int((reduce(mul,l) + 1)**0.5))\n", "def check_root(string):\n try:\n a, b, c, d = (int(d) for d in string.split(\",\"))\n except ValueError:\n return \"incorrect input\"\n if not (a * d + 2) == (b * c):\n return \"not consecutive\"\n perfect = a * b * c * d + 1\n return \"{}, {}\".format(perfect, int(perfect**0.5))\n"]
{"fn_name": "check_root", "inputs": [["4,5,6,7"], ["3,s,5,6"], ["11,13,14,15"], ["10,11,12,13,15"], ["10,11,12,13"], ["ad,d,q,tt,v"], ["//,;;,/,..,"], ["1,2,3,4"], ["1015,1016,1017,1018"], ["555,777,444,111"], ["20,21,22,24"], ["9,10,10,11"], ["11254,11255,11256,11258"], ["25000,25001,25002,25003"], ["2000000,2000001,2000002,2000003"], ["4,5,6,q"], ["5,6,7"], ["3,5,6,7"], ["-4,-3,-2,-1"], ["-1,0,1,2"]], "outputs": [["841, 29"], ["incorrect input"], ["not consecutive"], ["incorrect input"], ["17161, 131"], ["incorrect input"], ["incorrect input"], ["25, 5"], ["1067648959441, 1033271"], ["not consecutive"], ["not consecutive"], ["not consecutive"], ["not consecutive"], ["390718756875150001, 625075001"], ["16000048000044000012000001, 4000006000001"], ["incorrect input"], ["incorrect input"], ["not consecutive"], ["25, 5"], ["1, 1"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,879
def check_root(string):
d7e4b0ec0f1731a1bd089dc2fb9deea4
UNKNOWN
Some numbers have funny properties. For example: > 89 --> 8¹ + 9² = 89 * 1 > 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2 > 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51 Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p - we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n. In other words: > Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k If it is the case we will return k, if not return -1. **Note**: n and p will always be given as strictly positive integers. ```python dig_pow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1 dig_pow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k dig_pow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2 dig_pow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51 ```
["def dig_pow(n, p):\n s = 0\n for i,c in enumerate(str(n)):\n s += pow(int(c),p+i)\n return s/n if s%n==0 else -1\n", "def dig_pow(n, p):\n k, fail = divmod(sum(int(d)**(p + i) for i, d in enumerate(str(n))), n)\n return -1 if fail else k\n", "def dig_pow(n, p):\n t = sum( int(d) ** (p+i) for i, d in enumerate(str(n)) )\n return t//n if t%n==0 else -1", "def dig_pow(n, p):\n # your code\n n_list = [int(i) for i in str(n)]\n n_sum = 0\n p_i = p\n for n_i in n_list:\n n_sum = n_sum + n_i**p_i\n p_i = p_i+1\n if n_sum%n == 0:\n return n_sum/n\n else:\n return -1", "def dig_pow(n, p):\n sum = 0\n for c in str(n):\n sum += int(c) ** p\n p += 1\n if sum % n == 0:\n return sum / n\n else:\n return -1", "def dig_pow(n, p):\n s = sum(int(d)**(p+i) for i,d in enumerate(str(n)))\n return s/n if s%n == 0 else -1", "def dig_pow(n, p):\n digit_power = sum(int(x)**pw for pw,x in enumerate(str(n),p))\n if digit_power % n == 0:\n return digit_power / n\n return -1", "def dig_pow(n, p):\n k, r = divmod(sum( int(l)**(p+i) for i,l in enumerate(str(n)) ), n)\n return -1 if r else k", "def dig_pow(n, p):\n digits = [int(d) for d in str(n)]\n \n sum = 0\n for i, d in enumerate(digits):\n sum += d ** (p+i)\n \n if sum % n == 0:\n return sum / n\n else:\n return -1"]
{"fn_name": "dig_pow", "inputs": [[89, 1], [92, 1], [46288, 3], [114, 3], [46288, 5], [135, 1], [175, 1], [518, 1], [598, 1], [1306, 1], [2427, 1], [2646798, 1], [3456789, 1], [3456789, 5], [198, 1], [249, 1], [1377, 1], [1676, 1], [695, 2], [1878, 2], [7388, 2], [47016, 2], [542186, 2], [261, 3], [1385, 3], [2697, 3], [6376, 3], [6714, 3], [63760, 3], [63761, 3], [132921, 3], [10383, 6]], "outputs": [[1], [-1], [51], [9], [-1], [1], [1], [1], [1], [1], [1], [1], [-1], [-1], [3], [3], [2], [1], [2], [19], [5], [1], [1], [5], [35], [66], [10], [1], [1], [1], [4], [12933]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,437
def dig_pow(n, p):
3146fe980e07ac0c9fcaa843d89ebe20
UNKNOWN
You can print your name on a billboard ad. Find out how much it will cost you. Each letter has a default price of £30, but that can be different if you are given 2 parameters instead of 1. You can not use multiplier "*" operator. If your name would be Jeong-Ho Aristotelis, ad would cost £600. 20 leters * 30 = 600 (Space counts as a letter).
["def billboard(name, price=30):\n return sum(price for letter in name)", "def billboard(name, price = 30):\n return len(name) * price", "def billboard(name, price = 30):\n return sum([price for l in name])", "def billboard(name, price=30):\n return sum(price for _ in name)", "def billboard(name, price=30):\n cout = 0\n for letters in name:\n cout += price\n return cout\n \n \n \n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n", "billboard = lambda n, p=30: len(n) * p", "def billboard(name, price=30):\n return len(name)*price #I'm lame", "def billboard(name, price=30):\n \n # fine, dammit! I won't use that confounded * operator,\n # but you're paying the inefficiency costs...\n return sum(price for _ in name)", "def billboard(name, price=30):\n return sum(price for c in name)\n# return len(name) * price\n", "def billboard(name, price=30):\n return sum(price for c in name)", "def billboard(name, price = 30):\n amt = len(name) / (1.0 / price)\n return amt", "from operator import mul\ndef billboard(name, price=30):\n return mul(len(name), price)\n", "def billboard(name, price=30):\n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n cost = 0\n for i in range(0, len(name)):\n cost += price\n return cost", "def billboard(name, price=30):\n return int(len(name)/(1.0/price))", "def billboard(name, price=30):\n return len(name) * price\n \n # I will use \"*\" whenever i want to :P\n", "def billboard(name: str, price: int=30) -> int:\n \"\"\" Get a price for your name printed on the billboard. \"\"\"\n return len(name) * price", "def billboard(name, price=30):\n return sum([price for prince in range(len(name))])", "def billboard(name, price = 30):\n cost = 0\n print(name)\n for i in range(len(name)):\n cost += price\n return cost\n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n", "def billboard(name, price=30):\n a = 0\n for c in name:\n a += price\n return a", "def billboard(name, price=30):\n l = [price for i in range(1,len(name)+1)]\n return sum(l)", "def billboard(name, price = 30):\n new = 0\n for i in range(len(name)):\n new += price\n return new", "def billboard(name, price=30):\n a = 0\n for i in name:\n a += price\n return a", "def billboard(name, price = 30):\n total_price = 0\n for char in name:\n total_price += price\n return total_price\n", "def billboard(name, price=30):\n suma=0\n s=len(name)\n for i in range(1, s+1):\n suma+=price\n return suma", "def billboard(name, price=30):\n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n tot = 0\n for x in name:\n tot += price\n \n return tot", "def billboard(name, price=30):\n return __import__('operator').mul(len(name), price)", "def pro_recursive(n, m): \n if n == 1: \n return m\n else: \n return m + pro_recursive(n-1, m)\n \ndef billboard(name, price=30): \n return pro_recursive(len(name), price)", "import functools \ndef billboard(name, price = 30):\n print(name,price)\n return functools.reduce(lambda x,y : x + y , list(map(lambda x : price, list(range(len(name))))))", "def billboard(name, price=30):\n if price == 30:\n result = 0\n for i in range(len(name)):\n result += 30\n return result\n else:\n result = 0\n for i in range(len(name)):\n result += price\n return result", "def billboard(name, price=30):\n rv = 0\n for i in range(len(name)):\n rv += price\n else:\n return rv\n", "def billboard(name, price=30):\n # Without using multiplication\n total = 0\n for char in name:\n total += price\n \n return total\n", "def billboard(name, price=30):\n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n #for each character in name, add price once\n return sum(price for x in name)", "def billboard(name, price=30):\n sum = 0\n for letter in name:\n sum = sum + price\n \n return sum", "def billboard(name, price=30):\n print(name, price)\n return len(name) * price", "def billboard(name, price=30):\n x = 0\n for i in range(len(name)):\n x = x + price\n return x", "def billboard(name, price=30):\n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way\n return len(name) * price", "def billboard(name, price=30):\n return len(name)*price\n# you are lame\n", "def billboard(name, price=30):\n return len(name) / (1/price)", "def billboard(name, price=30):\n return sum([price for i in range(1, len(name)+1)])", "def billboard(name, price=30):\n sum = 0 \n for char in name:\n sum +=price\n \n return sum", "def billboard(name, price=30):\n return sum([price for x in name])\n", "import numpy as np\n\ndef billboard(name, price=30):\n return np.dot(len(name), price)", "def billboard(name, price=30):\n pri = 0\n for i in name:\n pri += price\n return pri\n \n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n", "def billboard(name, price=30):\n sum=0\n for x in name:\n sum+=price\n return sum", "def billboard(name, price=30):\n return sum(1*price for i in name) ", "def billboard(n, p=30):\n return len(n)*p", "def billboard(name, price=30):\n cost = 0\n for s in name:\n cost += price \n return cost", "def billboard(name, price=30):\n letters = 1\n new_price = 0\n while letters <= len(name):\n new_price = new_price + price\n letters = letters + 1\n return new_price\n \n \n", "def billboard(name, price=30):\n x = 0\n for i in name:\n x += price\n return x", "def billboard(name, price=30):\n output = 0\n for i in range(0,len(name)):\n output += price\n return output", "def billboard(name: str, price: int = 30) -> int:\n return sum(price for _ in range(len(name)))\n", "def billboard(name, price=30):\n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n a = 0\n for i in range(0,len(name)):\n a = a+price\n return a", "billboard=lambda n,p=30:p*len(n)", "def billboard(name, price=30):\n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n #return len(name)*price\n sum = 0\n for i in range(len(name)):\n sum += price\n return sum", "def billboard(name, price=30):\n from operator import mul\n return list(map(mul, [len(name)], [price]))[0]", "def billboard(name, price=30):\n \n \"\"\"No multiplier operator.\"\"\"\n \n myPrice = [price for char in name]\n \n return sum(myPrice)", "def billboard(name, price=30):\n return sum(price for x in list(name))", "def billboard(name, price=30):\n return sum([price for x in range(0, len(name))])", "def billboard(name, price=30):\n total=0\n for each in range(len(name)):\n total+=price\n return total", "def billboard(name, price=30):\n total = 0\n i = 0\n while i < len(name):\n total += price\n i += 1\n return total\n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n", "def billboard(name, price=30):\n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n return sum(price for i in range(len(name)))\n #or\n #return len(name)*price\n", "# If you don't block it, I'm gonna use it\n# If you block it, I'm gonna cheat it\ndef billboard(name, price=30):\n return len(name)*price", "import numpy\ndef billboard(name, price=30):\n return numpy.prod([len(name), price])", "def billboard(name, price=30):\n return eval('len(name)*price')", "def billboard(name, price=30):\n return len(name).__mul__(price)", "def billboard(name, price=30):\n print(('name:', name))\n return sum([price for x in name])\n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n", "def billboard(name, price=30):\n p = 0\n for c in range(len(name)):\n p += price\n return p\n # Flez\n", "def billboard(name, price=30):\n p = 0\n if price == 30:\n for c in range(len(name)):\n p += 30\n return p\n if price != 30:\n for c in range(len(name)):\n p += price\n return p\n # Flez\n", "def billboard(name, price=30):\n total_price = 0\n for c in name:\n total_price += price\n return total_price", "def billboard(name, price=30):\n r = 0\n for _ in name:\n r += price\n return r\n", "def billboard(name, price=30):\n #your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n \n \n \n total = 0\n #for i in name:\n # total += price \n #return total\n \n return sum(total+price for _ in name)", "def billboard(name, price=30):\n def s(a,b):\n return a*b\n return s(len(name),price)", "def billboard(name, price=30):\n total = 0\n for i in range(1, len(name)+1):\n total += price\n return total", "def billboard(name, price=30):\n cost = 0\n for letter in name:\n cost = cost + price\n return cost", "def billboard(name, price=30):\n t=0\n for l in name:\n t+=price\n return t", "from numpy import prod\n\ndef billboard(name, price=30):\n return prod([len(name),price])", "def billboard(name, price=30):\n p = 0\n for i in range(len(name)):\n p += price\n return p", "def billboard(name, price=30):\n# name = set(name)\n return len(name) * price", "def billboard(name, price=30):\n r = 0\n for i in range(len(name)):\n r += price\n return r", "def billboard(name, price=30):\n return sum([price for i in list(name)]) ", "def billboard(name, price=30):\n q=0\n i=1\n while i<=len(name):\n q+=price\n i+=1\n return q#your code here - note that in Python we cannot prevent the use of the\n #multiplication, but try not to be lame and solve the kata in another way!\n", "def billboard(name, price=30):\n return sum([price for c in range(len(name))])", "def billboard(name, price=30):\n result = 0\n for letter in name:\n result+=price\n return result", "def billboard(name, price=30):\n return sum(len(name) for _ in range(0, price))", "from functools import reduce\n\nbillboard=lambda n, p=30: reduce(lambda a,b:a+p, n,0)", "def billboard(name, price=30):\n # len(name) * price\n total = 0\n for x in name:\n if x: total += price\n return total", "def billboard(name, price=30):\n name.replace(\" \",\"\")\n return len(name) * price", "import operator\n\nres = 0\ndef billboard(name, price=30):\n# return operator.mul(len(name), price)\n \n return sum([len(name) for i in range(price)])\n \n# res = len(name)\n# c = foo(res,name)\n \n# [c for i in range(price)]\n# return res\n \n# def foo(res,name):\n# res += len(name)\n", "def billboard(name, price=30):\n num = len(name)\n calc = 0\n count = 0\n while count < num:\n calc = calc + price\n count = count + 1\n return calc", "def billboard(name, price = 30):\n i = 0\n x = 0\n b = len(name)\n while i < b:\n x= x + price\n i+=1\n return x", "billboard = lambda name, price=30: sum(price for x in name)", "def billboard(name, price=30):\n t = 0\n for i in range(len(name)):\n t += price\n return t", "def billboard(name, price=30):\n total_price = 0\n for char in range(len(name)):\n total_price += price\n return total_price", "def billboard(name, price=30):\n x = 0\n for i in [i for i in name]:\n x+=price\n return x", "def billboard(name, price=30):\n builder = 0\n for x in name:\n builder = builder + price\n return builder", "def billboard(name, price=30):\n amount=0\n for _ in name:\n amount+=price\n return amount", "def billboard(name, price=30):\n sum = 0\n for element in name:\n sum += price \n return sum", "billboard = lambda s, p = 30: sum(p for x in s)", "def billboard(name, price=30):\n return len(name)/(1/float(price))\n", "def billboard(name, price=30):\n a = len(name)\n cost = 0\n for i in range(1, a+1, 1):\n cost += price\n return cost"]
{"fn_name": "billboard", "inputs": [["Jeong-Ho Aristotelis"], ["Abishai Charalampos"], ["Idwal Augustin"], ["Hadufuns John", 20], ["Zoroaster Donnchadh"], ["Claude Miljenko"], ["Werner Vigi", 15], ["Anani Fridumar"], ["Paolo Oli"], ["Hjalmar Liupold", 40], ["Simon Eadwulf"]], "outputs": [[600], [570], [420], [260], [570], [450], [165], [420], [270], [600], [390]]}
INTRODUCTORY
PYTHON3
CODEWARS
13,589
def billboard(name, price=30):
3f4c633a3888a52e0ca8cfee08edfccf
UNKNOWN
You need to write a function that reverses the words in a given string. A word can also fit an empty string. If this is not clear enough, here are some examples: As the input may have trailing spaces, you will also need to ignore unneccesary whitespace. ```python reverse('Hello World') == 'World Hello' reverse('Hi There.') == 'There. Hi' ``` Happy coding!
["def reverse(st):\n return \" \".join(reversed(st.split())).strip()", "def reverse(st):\n st = st.split()\n st.reverse()\n return ' '.join(st)", "def reverse(stg):\n return ' '.join(reversed(stg.split()))", "def reverse(st):\n s = st.split()\n return ' '.join(s[::-1])", "def reverse(st): \n words = st.strip().split()\n words.reverse()\n return ' '.join(words)", "def reverse(s):\n s = s.split()\n s = s[-1::-1]\n return ' '.join(s)", "def reverse(st):\n k=st.split()\n m=k[::-1]\n return \" \".join(m)", "def reverse(st):\n return \" \".join(st.split(\" \")[::-1]).strip().replace(\" \", \" \").replace(\" \", \" \")", "def reverse(st):\n return ' '.join(reversed(st.strip().split())).strip()", "def reverse(st: str) -> str:\n \"\"\" Reverse the words in a given string. \"\"\"\n return \" \".join(list(filter(lambda it: it, st.split(\" \")))[::-1])", "def reverse(st):\n item = list(st.split())\n return ' '.join(item[::-1])", "def reverse(st):\n for sentenses in st.split('\\n'):\n return(' '.join(sentenses.split()[::-1]))\n return st [::-1]", "def reverse(st):\n p = st.split()\n return ' '.join(reversed(p))", "def reverse(st):\n return ' '.join(st.strip().split()[::-1])\n# return ' '.join(list(reversed(st.split())))\n", "def reverse(st):\n st=st.split(' ')\n st=st[::-1]\n \n st=' '.join(st)\n st.strip()\n # Your Code Here\n return ' '.join(st.split())\n", "def reverse(st):\n sv = st.split()\n sv.reverse()\n ss = \"\"\n for word in sv:\n ss += word\n ss += \" \"\n ss = ss.strip()\n return ss\n", "def reverse(st):\n w=st.split()\n w.reverse()\n return \" \".join(w)\nstri=\"Hello World\"\nprint((reverse(stri)))\n\n\n", "import re\ndef reverse(st):\n strs = st.strip()\n strss = re.sub(' +', ' ', strs)\n return ' '.join(strss.split(' ')[::-1])\n", "def reverse(st):\n revers_word = st.split()\n revers_word.reverse()\n revers_word = ' '.join(revers_word)\n return revers_word", "def reverse(st):\n b = st.split()\n return ' '.join([b[i] for i in range(len(b)-1,-1,-1)])\n", "def reverse(st):\n list1 = st.split()\n list1.reverse()\n return ' '.join(list1)", "reverse = lambda st : ' '.join(list(reversed(st.split())))\n\n# Python is fun!!!!!!!!!!!!!!!!!!!\n", "def reverse(st):\n #Splitting into list elements, then\n #Joining them into string\n reversed_sentence = ' '.join(reversed(st.split()))\n return reversed_sentence\n", "def reverse(st):\n list_st = []\n for i in st.split():\n list_st.append(i)\n new_list = list_st[::-1]\n return ' '.join(new_list)", "def reverse(st):\n return \" \".join([word for word in st.split(\" \")[::-1] if word != \"\"])\n", "def reverse(st):\n #Split creates a list with all the words in it, separated\n words = st.split()\n #Joins them back together to a string\n reversed_sentence = ' '.join(reversed(words))\n return reversed_sentence", "def reverse(st):\n result = []\n for w in st.split():\n result.insert(0, w)\n return ' '.join(result)", "def reverse(phrase):\n while ' ' in phrase:\n phrase = phrase.replace(' ',' ')\n return ' '.join(reversed(phrase.strip().split(' ')))", "def reverse(st):\n result = st.split()\n midl = result[::-1]\n reverse_st = ' '.join(midl)\n return reverse_st", "def reverse(st):\n return \" \".join([_f for _f in reversed(st.split(\" \")) if _f]).strip(\" \")\n \n \n", "def reverse(st):\n words=st.split()\n words=list(reversed(words))\n st=\" \".join(words)\n return st", "def reverse(st):\n st = st.split(' ')\n st.reverse()\n st = ' '.join(st).rstrip(' ').lstrip(' ')\n st = st.replace(' ',' ')\n return st.replace(' ',' ')", "def reverse(st):\n # Your Code Here\n a = st.split(' ')\n b = [i for i in a if i!='']\n return ' '.join(b[::-1])", "def reverse(st):\n alist=st.split()\n alist.reverse()\n return ' '.join(alist)\n \n st = st.split()\n st.reverse()\n return ' '.join(st)", "def reverse(st):\n return ' '.join([s for s in st.rstrip(' ').split(' ')[::-1] if s != ''])", "def reverse(st):\n makeList = st.split()\n makeList.reverse()\n \n return \" \".join(makeList)\n \n\n", "def reverse(st):\n print(st)\n a=[]\n for x in reversed(st.split()):\n print(x)\n a.append(x)\n \n # Your Code Here\n return ' '.join(a)", "reverse = lambda x: ' '.join(x.split()[::-1])", "def reverse(st):\n y = st.split()\n y.reverse()\n return \" \".join(y)", "def reverse(st):\n word = st.split()\n st2 = []\n for words in word:\n st2.insert(0, words)\n return \" \".join(st2)", "def reverse(st):\n x = st.split()\n x = list(reversed(x))\n return (\" \".join(x))", "def reverse(st):\n st = ' '.join(st.strip().split()[::-1])\n return st", "def reverse(st):\n rtrn_list = [x for x in st.split()]\n return ' '.join(reversed(rtrn_list))", "def reverse(st):\n ls = st.split()\n result = []\n for i in range(len(ls)-1,-1,-1):\n result.append(ls[i])\n result = \" \".join(result)\n return result", "def reverse(st):\n # Your Code Here\n return str((' '.join(list(st.split())[::-1])))", "def reverse(st):\n res = ''\n arr = st.split()\n for k in reversed(arr):\n res += f'{k} '\n return res[:-1]", "def reverse(st):\n words = st.split()\n return ' '.join([word for word in reversed(words)])", "def reverse(st):\n # Your Code Here\n st = st.split()\n print(st)\n out = []\n for i in range(len(st) - 1, -1, -1):\n out.append(st[i])\n \n out = \" \".join(out)\n \n return out\n \n \n return st", "def reverse(st):\n splt = st.split()\n return ' '.join(splt[::-1])\n", "def reverse(st):\n words = st.strip().split()\n words = words[::-1]\n return ' '.join(words)\n", "def reverse(s):\n result=''\n for i in s.split()[::-1]:\n result+=i + ' '\n \n \n return result.rstrip()\n", "def reverse(st):\n # Your Code Here\n s = st.rstrip()\n s = s.split()\n return \" \".join(s[::-1])", "def reverse(st: str) -> str:\n return \" \".join(reversed(st.split()))", "def reverse(st):\n # Your Code Here\n l=st.strip().split()\n if len(l)>1:\n l=l[::-1]\n return (\" \".join(l)).strip()\n return (\" \".join(l)).strip()", "def reverse(st):\n arr=st.split(\" \")\n res=\" \".join(arr[::-1])\n return \" \".join(res.split())", "def reverse(str):\n str = str.split()\n str = reversed(str)\n return \" \".join(str)", "def reverse(st):\n \n # split the string into different words\n wordList = st.split(' ')[::-1]\n \n # remove spaces\n while(\"\" in wordList):\n wordList.remove(\"\")\n \n st = ' '.join(wordList)\n \n return st", "def reverse(st):\n x = st.split()\n x.reverse()\n return \" \".join(x)", "import re\ndef reverse(st):\n return ' '.join((re.sub( r' +', ' ', st).split(' ')[::-1])).strip()", "def reverse(st):\n words_list = st.split()\n words_list.reverse()\n st = \" \".join(words_list)\n return st", "def reverse(st): \n return \" \".join(st.split()[::-1]) \n print (reverse(st))", "def reverse(st):\n # Your Code Here\n spl=st.split()\n string=[]\n for i in spl:\n string.insert(0,i)\n return ' '.join(string)", "def reverse(st):\n s = st.split(' ')\n return ' '.join([i for i in s[::-1] if i != '' ])", "def reverse(st):\n st = st.strip()\n s = st.split(' ')\n while '' in s:\n s.remove('')\n while ' ' in s:\n s.remove(' ')\n st = ' '.join(s[::-1])\n return st.rstrip()", "st = 'Hi There.'\ndef reverse(st): \n return \" \".join(st.split()[::-1]) \nprint (reverse(st))", "def reverse(a):\n res = \" \".join(reversed(a.split()))\n return res\n", "import re\ndef reverse(st):\n st = re.sub(' +', ' ',st)\n st = st.split(\" \")\n return (\" \".join(st[::-1])).strip()", "def reverse(st):\n x = st.split(\" \")\n y = []\n for i in range(len(x)-1, -1, -1):\n if x[i]:\n y.append(x[i])\n return \" \".join(y)", "def reverse(st):\n # Your Code Here\n \n splitted_list = st.split()\n reversed_list = \" \".join(reversed(splitted_list))\n \n return reversed_list", "import re \n\ndef reverse(st):\n answer = ''\n for word in st.rsplit()[::-1]:\n answer += word + ' '\n return answer.rstrip(' ')", "def reverse(st):\n list=st.split()\n list.reverse()\n for i in range(1,len(list)*2-1,2):\n list.insert(i,\" \")\n string=\"\"\n for i in list:\n string+=i\n return string\n \n", "def reverse(st):\n return ' '.join([i for i in st.split(' ')[::-1] if len(i)>0])\n", "def reverse(st):\n # Your Code Here\n string=st.split()\n string.reverse()\n ans=''\n for i in string:\n ans=ans+i+' '\n return ans[:len(ans)-1]", "def reverse(st):\n newname = st.split()[::-1]\n return ' '.join(newname)", "def reverse(st):\n n = \"\"\n s = st.split()\n i = len(s) - 1\n while i >= 0:\n if i == len(s) - 1:\n n = n + s[i]\n i = i - 1\n continue\n n = n + \" \" + s[i]\n i = i - 1\n return n", "def reverse(a):\n res = \" \".join(reversed(a.split()))\n return res\n\nprint(reverse('Hi There.'))", "def reverse(st):\n st = st.replace(' ',' ')\n st = st.replace(' ',' ')\n st = st.strip()\n return ' '.join(st.split(' ')[::-1])", "def reverse(st):\n s = st.split()[::-1]\n return ' '.join(s)", "def reverse(st):\n st = st.strip()\n print(st)\n return \" \".join(st.split()[::-1])", "def reverse(st):\n st1 = ' '.join(st.split(' ')).split()\n st1.reverse()\n return ' '.join(st1)", "def reverse(st):\n words = st.split(' ')\n words = list(filter(lambda word: word != '', words))\n reversed = words[::-1]\n return ' '.join(reversed)", "import re\ndef reverse(st):\n st = re.sub(r'\\s+',' ',st)\n return (\" \".join(st.split(\" \")[::-1])).strip()", "def reverse(st):\n x = list()\n for i in st.split():\n x.append(i)\n x.reverse()\n temp = \"\"\n for i in x:\n temp+=i+\" \"\n temp = temp.strip()\n return temp", "def reverse(st):\n to_list = st.split(' ')\n to_list.reverse()\n return ' '.join(to_list).strip().replace(' ', ' ').replace(' ', ' ')\n", "def reverse(st):\n salida = []\n word = \"\"\n for i in range(len(st)):\n if st[i] == \" \" or i == len(st):\n if word != \"\":\n salida.append(word)\n\n salida.append(st[i])\n word = \"\"\n else:\n word += st[i]\n\n salida.append(word)\n a = \"\".join(salida[::-1]).replace(\" \",\" \")\n return a.replace(\" \",\" \").strip(\" \")", "def reverse(st):\n words = st.rstrip().split(\" \")\n return \" \".join(w for w in words[::-1] if w != \"\")", "def reverse(st):\n \n lst = st.split()[::-1]\n return \" \".join(lst)", "def reverse(st):\n st = st.split()\n s = ''\n for i in reversed(st):\n s = s + i + ' '\n return s.rstrip()", "def reverse(st):\n # Your Code Here\n return ' '.join([i for i in st.split()[::-1]])", "def reverse(st):\n string_to_list = st.split()\n reversed_list = string_to_list.reverse()\n list_to_string = \" \".join(string_to_list)\n print((\"'\"+list_to_string+\"'\"))\n return(list_to_string)\n", "import unittest\n\n\ndef reverse(st):\n return ' '.join(st.split()[::-1]).strip()\n \n \nclass TestReverse(unittest.TestCase):\n def test_reverse(self):\n st = 'Hello World'\n actual = reverse(st)\n self.assertEqual(actual, 'World Hello')\n", "def reverse(st):\n # Your Code Here\n list = st.split()\n reverse = list[:: -1]\n return \" \".join(reverse)", "def reverse(st):\n print(st)\n# for x in range(len(st)-1):\n# if st[x]==' ' and st[x+1]==' ':\n# st[x]='!@#'\n# st=st.replace('!@#','')\n st=st.split(' ')\n st=' '.join(st)\n st=st.split(' ')\n st=' '.join(st)\n st=st.strip()\n st=(st.split(' '))\n \n st.reverse()\n # Your Code Here\n return ' '.join(map(str,st))", "def reverse(st):\n for sentenses in st.split('\\n'):\n return(' '.join(sentenses.split()[::-1]))", "def reverse(st):\n word_array = st.split()\n return \" \".join(word_array[::-1])", "def reverse(st):\n arr = st.split(\" \")[::-1]\n return \" \".join([x for x in arr if len(x) > 0])", "def reverse(st):\n ans = [i for i in st.split(' ') if i != '']\n print(ans)\n return ' '.join(ans[::-1])\n", "import re\ndef reverse(st):\n print(st)\n return ' '.join(st.split()[::-1])\n", "def reverse(a):\n lista = []\n li = list(a.split(\" \"))\n li.reverse()\n for i in li:\n if i != '':\n lista.append(i) \n return \" \".join(lista)", "def reverse(st):\n st=st.split(\" \")\n for i in st:\n if i==\"\":\n st.remove(i)\n st=st[::-1]\n st=\" \".join(st)\n return st.strip()"]
{"fn_name": "reverse", "inputs": [["I am an expert at this"], ["This is so easy"], ["no one cares"]], "outputs": [["this at expert an am I"], ["easy so is This"], ["cares one no"]]}
INTRODUCTORY
PYTHON3
CODEWARS
13,334
def reverse(st):
f3812a844b60430824318b815ec3ae9b
UNKNOWN
You start with a value in dollar form, e.g. $5.00. You must convert this value to a string in which the value is said, like '5 dollars' for example. This should account for ones, cents, zeroes, and negative values. Here are some examples: ```python dollar_to_speech('$0.00') == '0 dollars.' dollar_to_speech('$1.00') == '1 dollar.' dollar_to_speech('$0.01') == '1 cent.' dollar_to_speech('$5.00') == '5 dollars.' dollar_to_speech('$20.18') == '20 dollars and 18 cents.' dollar_to_speech('$-1.00') == 'No negative numbers are allowed!' ``` These examples account for pretty much everything. This kata has many specific outputs, so good luck!
["def dollar_to_speech(value):\n if \"-\" in value:\n return \"No negative numbers are allowed!\"\n d, c = (int(n) for n in value.replace(\"$\", \"\").split(\".\"))\n dollars = \"{} dollar{}\".format(str(d), \"s\" if d != 1 else \"\") if d or not c else \"\"\n link = \" and \" if (d and c) else \"\"\n cents = \"{} cent{}\".format(str(c), \"s\" if c != 1 else \"\") if c else \"\"\n return \"{}{}{}.\".format(dollars, link, cents)", "def dollar_to_speech(s):\n d, c = map(int, s[1:].split(\".\"))\n ds, cs = f\"{d} dollar\" + \"s\"*(d != 1), f\"{c} cent\" + \"s\"*(c != 1)\n return \"No negative numbers are allowed!\" if d < 0 else f\"{ds}.\" if c == 0 else f\"{cs}.\" if d == 0 else f\"{ds} and {cs}.\"", "def dollar_to_speech(value):\n if value[1] == \"-\":\n return \"No negative numbers are allowed!\"\n\n dot = value.index(\".\")\n dollars, cents = map(int, value[1:].split(\".\"))\n end_d = \"\" if dollars == 1 else \"s\"\n end_c = \"\" if cents == 1 else \"s\"\n\n if dollars and cents:\n return \"{} dollar{} and {} cent{}.\".format(\n str(dollars), end_d, str(cents), end_c\n )\n elif cents and not dollars:\n return \"{} cent{}.\".format(str(cents), end_c)\n else:\n return \"{} dollar{}.\".format(str(dollars), end_d)", "def dollar_to_speech(value):\n if value[1] == \"-\":\n return \"No negative numbers are allowed!\"\n if value == \"$0.00\":\n return \"0 dollars.\"\n \n output = []\n dollars, cents = map(int, value[1:].split(\".\"))\n \n if dollars:\n output.append(\"%s dollar%s\" % (dollars, \"s\" * (dollars != 1)))\n if cents:\n output.append(\"%s cent%s\" % (cents, \"s\" * (cents != 1)))\n \n return \" and \".join(output) + \".\"", "import re\ndef dollar_to_speech(val):\n if '-' in val: return 'No negative numbers are allowed!'\n c = int(re.findall(r'\\.(\\d+)',val)[0])\n d = int(re.findall(r'\\$(\\d+)\\.',val)[0])\n if d == 0 == c : return '0 dollars.'\n \n seg1 = '{} dollar{}'.format(d,('s' if d > 1 else '')) if d else ''\n seg2 = '{} cent{}'.format(c, ('s' if c > 1 else '')) if c else ''\n seg3 = ' and ' if seg1 and seg2 else ''\n return ''.join([seg1,seg3,seg2,'.'])\n \n \n", "def dollar_to_speech(value):\n x = value.lstrip('$')\n if float(x) < 0:\n return 'No negative numbers are allowed!'\n dollars, cents = map(int, x.split('.'))\n speech = []\n if cents:\n speech.append('{} cent{}'.format(cents, 's' if cents != 1 else ''))\n if dollars or not speech:\n speech.insert(0, '{} dollar{}'.format(dollars, 's' if dollars != 1 else ''))\n return ' and '.join(speech) + '.'", "def dollar_to_speech(value):\n if '-' in value:\n return \"No negative numbers are allowed!\"\n else:\n a = value.replace('$',\"\").split('.')\n if int(a[0]) > 1 and int(a[1]) >1:\n return '{} dollars and {} cents.'.format(int(a[0]), int(a[1]))\n elif int(a[0]) == 1 and int(a[1]) == 1:\n return '{} dollar and {} cent.'.format(int(a[0]), int(a[1]))\n elif int(a[0]) < 1 and int(a[1]) < 1 or int(a[0]) > 1 and int(a[1]) < 1:\n return '{} dollars.'.format(int(a[0]))\n elif int(a[0]) == 1 and int(a[1]) < 1:\n return '{} dollar.'.format(int(a[0]))\n elif int(a[0]) > 1 and int(a[1]) ==1:\n return '{} dollars and {} cent.'.format(int(a[0]), int(a[1]))\n elif int(a[0]) == 1 and int(a[1]) > 1:\n return '{} dollar and {} cents.'.format(int(a[0]), int(a[1]))\n elif int(a[1]) > 1:\n return '{} cents.'.format(int(a[1]))\n else:\n return '{} cent.'.format(int(a[1]))", "def dollar_to_speech(value):\n d, c = map(int, value[1:].split('.'))\n if d < 0:\n return 'No negative numbers are allowed!'\n if d == 0 == c:\n return '0 dollars.'\n s = ''\n if d > 0:\n s += '{} dollar{}{}'.format(d, 's' * (d > 1), ' and ' * (c > 0))\n if c > 0:\n s += '{} cent{}'.format(c, 's' * (c > 1))\n return s + '.'", "def dollar_to_speech(value):\n if '-' in value: return 'No negative numbers are allowed!'\n \n vals = list(map(int, value.replace('$','').split('.')))\n typs = ('dollar', 'cent')\n \n return (' and '.join('{} {}'.format(v, t + 's'*(v!=1)) for v,t in zip(vals, typs) if v) or '0 dollars' )+'.'\n \nDollarToSpeech = dollar_to_speech", "\ndef dollar_to_speech(value):\n pass\n \n if \"-\" in value:\n \n return 'No negative numbers are allowed!'\n \n else:\n \n d = int(value[1::].split('.')[0])\n \n c = int(value[1::].split('.')[1])\n \n if d==0 and c==0:\n \n return \"0 dollars.\"\n \n if d==1 and c==0:\n \n return \"{} dollar.\".format(d)\n \n if d>1 and c==0:\n \n return \"{} dollars.\".format(d)\n \n if d==0 and c==1:\n \n return \"{} cent.\".format(c)\n \n if d==0 and c>1:\n \n return \"{} cents.\".format(c)\n \n if d==1:\n \n m = 'dollar'\n \n if d>1:\n \n m = 'dollars'\n \n if c==1:\n \n k = 'cent'\n \n if c>1:\n \n k = 'cents'\n \n if d>0 and c>0:\n \n return \"{} {} and {} {}.\".format(d,m,c,k)\n"]
{"fn_name": "dollar_to_speech", "inputs": [["$20.18"], ["$5.62"], ["$83.47"], ["$16.93"], ["$0.00"], ["$0.01"], ["$0.63"], ["$0.28"], ["$1.00"], ["$2.00"], ["$31.00"], ["$45.00"], ["$-5843.21"], ["$-45.32"], ["$-2.63"], ["$-234.48"]], "outputs": [["20 dollars and 18 cents."], ["5 dollars and 62 cents."], ["83 dollars and 47 cents."], ["16 dollars and 93 cents."], ["0 dollars."], ["1 cent."], ["63 cents."], ["28 cents."], ["1 dollar."], ["2 dollars."], ["31 dollars."], ["45 dollars."], ["No negative numbers are allowed!"], ["No negative numbers are allowed!"], ["No negative numbers are allowed!"], ["No negative numbers are allowed!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,501
def dollar_to_speech(value):
5729574072f968211ed18bf7c0a729f3
UNKNOWN
# Letterss of Natac In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build settlements, roads, and cities or buy a development. Other kata about this game can be found [here](https://www.codewars.com/collections/59e6938afc3c49005900011f). ## Task This kata asks you to implement the function `build_or_buy(hand)` , which takes as input a `hand`, the resources you have (a string of letters representing the resources you have), and returns a list of the unique game objects you can build or buy given your hand. There are five different resources, `'b'`, `'w'`, `'g'`, `'s'`, and `'o'`. Game objects and the resources required to build or buy them are as follows: 1. `'road'`: `bw` 2. `'settlement'`: `bwsg` 3. `'city'`: `ooogg` 4. `'development'`: `osg` ## Examples ```python build_or_buy("bwoo") => ['road'] build_or_buy("bwsg") => ['road', 'settlement'] or ['settlement', 'road'] build_or_buy("") => [] build_or_buy("ogogoogogo") => ['city'] ``` ## Notes: 1. Don't mutate the hand 2. The order of the returned list doesn't matter 3. You do not have to test for whether a hand is valid. 4. The list will be interpreted to mean 'you can build any of these objects,' not 'you can build all these objects in one play'. See example 2 above, even though there is only one `'b'` and one `'w'` in `hand`, both `Road()` and `Settlement()` are in the list. 5. A hand can be empty. In the event a hand is empty, you can't build or buy anything, so return an empty list, see example 3 above. 6. Hand are between 0 and 39 in length.
["from collections import Counter\n\nREQUIRE = {x: Counter(s) for x,s in [('road', 'bw'), ('settlement', 'bwsg'), ('city', 'ooogg'), ('development', 'osg')] }\n\ndef build_or_buy(hand):\n h = Counter(hand)\n return [item for item,c in REQUIRE.items() if not c-h]", "def build_or_buy(hand):\n d = {'bw': 'road', 'bwsg': 'settlement', 'ooogg': 'city', 'osg': 'development'}\n \n res = []\n for r, build in d.items():\n if all(hand.count(i) >= r.count(i) for i in set(r)):\n res.append(build)\n return res", "def build_or_buy(h):\n l = {'road': 'bw',\n 'settlement': 'bwsg',\n 'city': 'ooogg',\n 'development': 'osg'}\n return [x for x in l if all(l[x].count(y)<=h.count(y) for y in l[x])] if h else []", "from collections import Counter\n\nreqs = {\"road\": Counter(\"bw\"), \"settlement\": Counter(\"bwsg\"), \n \"city\": Counter(\"ooogg\"), \"development\": Counter(\"osg\")}\n\ndef build_or_buy(hand):\n return list(filter(lambda obj: not reqs[obj] - Counter(hand), reqs.keys()))", "def build_or_buy(hand):\n result = []\n\n b, w, g, s, o = [hand.count(st) for st in 'b,w,g,s,o'.split(',')]\n \n if b and w:\n result.append('road')\n if s and g:\n result.append('settlement')\n if o and g:\n if s:\n result.append('development')\n if o > 2 and g > 1:\n result.append('city')\n \n return result\n", "from collections import Counter\n\ndef build_or_buy(hand):\n res = []\n bank = Counter(hand)\n if bank['b'] > 0 and bank['w'] > 0:\n res.append('road')\n if bank['s'] > 0 and bank['g'] > 0:\n res.append('settlement')\n if bank['o'] > 2 and bank['g'] > 1:\n res.append('city')\n if bank['o'] > 0 and bank['s'] > 0 and bank['g'] > 0:\n res.append('development')\n return res", "from collections import Counter\n\nPRICES = {\n 'road': 'bw',\n 'settlement': 'bwsg',\n 'city': 'ooogg',\n 'development': 'osg'\n}\n\n\ndef build_or_buy(hand):\n return list(filter(lambda obj: not Counter(PRICES[obj]) - Counter(hand),\n PRICES.keys()))", "def build_or_buy(hand):\n objects = {\"road\": \"bw\",\n \"settlement\": \"bwsg\",\n \"city\": \"ooogg\",\n \"development\": \"osg\"}\n return [key for key, val in objects.items() if not any(hand.count(c) < val.count(c) for c in set(val))]", "from collections import Counter as C\nr=dict(zip(\"road settlement city development\".split(),map(C,\"bw bwsg ooogg osg\".split())))\nbuild_or_buy=lambda s:(lambda t:[k for k,v in r.items()if all(v[x]<=t[x]for x in v)])(C(s))", "def build_or_buy(hand):\n o = {'bw': 'road', 'bwsg': 'settlement',\n 'ooogg': 'city', 'osg': 'development'}\n def valid(x):\n for c in set(x):\n if hand.count(c) < x.count(c):\n return False\n return True\n return [v for k, v in o.items() if valid(k)]"]
{"fn_name": "build_or_buy", "inputs": [["bwoo"], [""], ["ogogoogogo"], ["bwbwwwbb"]], "outputs": [[["road"]], [[]], [["city"]], [["road"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,002
def build_or_buy(hand):
8355d7a9cf85390fb9cb5f49ab142feb
UNKNOWN
# Story&Task The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all houses in the city were built in one row. Let's enumerate all the houses from left to right, starting with 0. A house is considered to be luxurious if the number of floors in it is strictly greater than in each house with larger number. In other words, a house is luxurious if the number of floors in it is strictly greater than in all houses, located to the right from it. The new architect is interested in n questions, the ith of them is the following: "how many floors should be added to the ith house to make it luxurious?" (For each i from 1 to n, inclusive). You need to help him cope with this task. Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). # Input/Output - `[input]` integer array `houses` Array of positive integers, representing the number of floors in each house. The ith element is the number of houses in the ith house. `1 ≤ houses.length ≤ 1000` - `[output]` an integer array An array has the same length as input array, the ith element represents the number of floors that should be added to the ith house to make it luxurious. # Example For `houses = [1,2,3,1,2]`, the output should be `[3,2,0,2,0]`. ``` For houses[0], 3 floors should be added, then its floors is strictly greater than all houses of right side. For houses[1], 2 floors should be added. For houses[2], no need to add floor because it's already the luxurious. For houses[3], 2 floors need to added For houses[4], no house on the right, so no need to add any floor. ```
["def luxhouse(houses):\n return [max(0, max(houses[i:]) - h + 1) for i, h in enumerate(houses[:-1], 1)] + [0]", "from itertools import accumulate\n\ndef luxhouse(houses):\n return [max(0, y-x+1) for x,y in zip(houses[::-1], accumulate([0] + houses[:0:-1], max))][::-1]", "def luxhouse(a):\n li = []\n for i, j in enumerate(a[:-1]):\n right = max(a[i + 1:])\n li.append(0 if j > right else right - j + 1 if right != j else 1)\n return li+[0] ", "def luxhouse(houses):\n def f():\n m = 0\n for fl in reversed(houses):\n yield max(0, m - fl + 1)\n m = max(m, fl)\n return list(f())[::-1]", "def luxhouse(houses):\n return [max(max(houses[i+1:])-j+1,0) for i,j in enumerate(houses[:-1])] +[0]", "def luxhouse(houses):\n return [max(0, max(houses[h+1:])-houses[h]+1) for h in range(len(houses)-1)]+[0]", "def luxhouse(houses):\n lux = 0\n \"\"\" \\o/ https://www.youtube.com/watch?v=n0DscZs7SXo \\o/ ;-D \"\"\"\n \n ans = [0] * len(houses)\n for n in range(len(houses)-1, -1, -1):\n if houses[n] > lux: lux = houses[n]\n else: ans[n] = lux - houses[n] + 1\n return ans", "def luxhouse(houses):\n return [(max(houses[i], max(houses[i+1:])+1)) - houses[i] for i in range(len(houses) - 1)] + [0]\n", "def luxhouse(houses):\n maxh = [houses[i] for i in range(len(houses))]\n maxh[-1] = houses[-1]\n for i in range(len(houses)-2, -1, -1):\n maxh[i] = max(maxh[i], maxh[i+1])\n for i in range(len(houses)-1):\n if maxh[i] == maxh[i+1]:\n maxh[i] += 1\n return [maxh[i]-houses[i] for i in range(len(houses))]", "def luxhouse(houses):\n return [0 if not houses[i + 1:] else max(max(houses[i + 1:]) + 1 - houses[i], 0) for i in range(len(houses))]"]
{"fn_name": "luxhouse", "inputs": [[[1, 2, 3, 1, 2]], [[3, 2, 1, 4]], [[1, 2, 3]], [[3, 2, 1]], [[1, 1, 1]]], "outputs": [[[3, 2, 0, 2, 0]], [[2, 3, 4, 0]], [[3, 2, 0]], [[0, 0, 0]], [[1, 1, 0]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,809
def luxhouse(houses):
9e8d41130c429aea3ac191ba3d6f5255
UNKNOWN
# Welcome to the Codewars Bar! Codewars Bar recommends you drink 1 glass of water per standard drink so you're not hungover tomorrow morning. Your fellow coders have bought you several drinks tonight in the form of a string. Return a string suggesting how many glasses of water you should drink to not be hungover. ## Examples ``` "1 beer" => "1 glass of water" "1 shot, 5 beers and 1 glass of wine" => "7 glasses of water" ``` ## Notes * To keep the things simple, we'll consider that anything with a number in front of it is a drink: `"1 bear" => "1 glass of water"` or `"1 chainsaw and 2 pools" => "3 glasses of water"` * The number in front of each drink lies in range `[1; 9]`
["def hydrate(drink_string): \n c=sum(int(c) for c in drink_string if c.isdigit())\n return \"{} {} of water\".format(c,'glass') if c==1 else \"{} {} of water\".format(c,'glasses')", "import re\n\ndef hydrate(s):\n n = sum(map(int,re.findall(r'\\d+',s)))\n return f\"{ n } glass{ 'es'*(n!=1) } of water\"", "def hydrate(drink_string): \n n = sum([int(a) for a in drink_string if a.isnumeric()])\n return str(n) +' glass of water' if n==1 else str(n) +' glasses of water'\n pass", "def hydrate(drink_string): \n glasses = 0\n for word in drink_string.split():\n if word.isdigit():\n glasses += int(word)\n return str(glasses) + \" glass of water\" if glasses == 1 else str(glasses) + \" glasses of water\"", "def hydrate(drink_string): \n c=0\n for i in \"123456789\":\n c += int(i)*drink_string.count(i)\n k = \"glass\" if c ==1 else \"glasses\"\n return f\"{c} {k} of water\"", "def hydrate(drinks):\n water = sum([int(drink) for drink in drinks if drink.isnumeric()])\n return '1 glass of water' if water == 1 else '%d glasses of water' % water", "import re\n\ndef hydrate(drink_string): \n drink = sum(int(n) for n in re.findall(r\"\\d\", drink_string))\n return f\"{drink} glass{'es' if drink > 1 else ''} of water\"", "def hydrate(s): \n a = sum(map(int, filter(str.isdigit, s)))\n return f\"{a} glass{['es', ''][a == 1]} of water\"", "def hydrate(drink_string):\n n = 0\n for i in range(len(drink_string)):\n try:\n n += int(drink_string[i])\n except:\n continue\n if n == 1:\n return \"1 glass of water\"\n else:\n return str(n) + \" glasses of water\"", "from re import compile\n\nREGEX = compile(r\"\\d+\").findall\n\ndef hydrate(drink_string): \n res = sum(map(int, REGEX(drink_string)))\n return f\"{res} glass{'es'*(res != 1)} of water\""]
{"fn_name": "hydrate", "inputs": [["1 beer"], ["2 glasses of wine and 1 shot"], ["1 shot, 5 beers, 2 shots, 1 glass of wine, 1 beer"]], "outputs": [["1 glass of water"], ["3 glasses of water"], ["10 glasses of water"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,904
def hydrate(drink_string):
0b38875300ab98d35a5292941c24e7df
UNKNOWN
`{a, e, i, o, u, A, E, I, O, U}` Natural Language Understanding is the subdomain of Natural Language Processing where people used to design AI based applications have ability to understand the human languages. HashInclude Speech Processing team has a project named Virtual Assistant. For this project they appointed you as a data engineer (who has good knowledge of creating clean datasets by writing efficient code). As a data engineer your first task is to make vowel recognition dataset. In this task you have to find the presence of vowels in all possible substrings of the given string. For each given string you have to return the total number of vowels. ## Example Given a string `"baceb"` you can split it into substrings: `b, ba, bac, bace, baceb, a, ac, ace, aceb, c, ce, ceb, e, eb, b`. The number of vowels in each of these substrings is `0, 1, 1, 2, 2, 1, 1, 2, 2, 0, 1, 1, 1, 1, 0`; if you sum up these number, you get `16` - the expected output. **Note**: your solution should have linear time complexity.
["def vowel_recognition(input):\n vowels = set('aeiouAEIOU')\n s = t = 0\n for c, e in enumerate(input, 1):\n if e in vowels:\n t += c\n s += t\n return s", "def vowel_recognition(input):\n chars = input.lower()\n N = len(chars)\n count = 0\n \n for i, c in enumerate(chars):\n if c in 'aeiou':\n count += (N - i) * (i + 1)\n \n return count", "def vowel_recognition(s):\n a = [0] * (len(s) + 1)\n for i, c in enumerate(s.lower()):\n a[i] = (c in 'aeiou') * (i+1) + 2 * a[i-1] - a[i-2]\n return a[-2]\n", "import re\n\ndef vowel_recognition(s):\n return sum( (len(s)-m.start())*(1+m.start()) for m in re.finditer(r'(?i)[aeiou]',s))", "def vowel_recognition(s):\n return sum((i + 1) * (len(s) - i) for i, c in enumerate(s.lower()) if c in 'aeiou')", "def vowel_recognition(s):\n return sum((i + 1) * (len(s) - i) for i, c in enumerate(s) if c in 'AEIOUaeiou')", "vowels = \"aeiou\"\n\n\ndef vowel_recognition(stg):\n l = len(stg)\n return sum((i + 1) * (l - i) for i, c in enumerate(stg.lower()) if c in vowels)", "def vowel_recognition(s):\n l = len(s)\n return sum((l-i)*(i+1) for i,j in enumerate(s) if j in 'aeiouAEIOU')", "def vowel_recognition(s):\n return sum((len(s) - i) * (i + 1) for i,ch in enumerate(s) if ch in 'aeiouAEIOU')", "def vowel_recognition(input): #Played around with some maths haha took way too much time\n vl = [\"a\",\"e\",\"i\",\"o\",\"u\",\"A\",\"E\",\"I\",\"O\",\"U\"]\n n = len(input)\n count = 0\n for num, letter in enumerate(input):\n for vowel in vl:\n if letter == vowel:\n x = num+1\n count += x*(n-x+1)\n return count"]
{"fn_name": "vowel_recognition", "inputs": [["bbbb"], ["baceb"], ["aeiou"], ["aeiouAEIOU"]], "outputs": [[0], [16], [35], [220]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,743
def vowel_recognition(s):
259e5e6795090ec04065ec1321138e01
UNKNOWN
# History This kata is a sequel of my [Mixbonacci](https://www.codewars.com/kata/mixbonacci/python) kata. Zozonacci is a special integer sequence named after [**ZozoFouchtra**](https://www.codewars.com/users/ZozoFouchtra), who came up with this kata idea in the [Mixbonacci discussion](https://www.codewars.com/kata/mixbonacci/discuss/python). This sequence combines the rules for computing the n-th elements of fibonacci, jacobstal, pell, padovan, tribonacci and tetranacci sequences according to a given pattern. # Task Compute the first `n` elements of the Zozonacci sequence for a given pattern `p`. ## Rules 1. `n` is given as integer and `p` is given as a list of as abbreviations as strings (e.g. `["fib", "jac", "pad"]`) 2. When `n` is 0 or `p` is empty return an empty list. 3. The first four elements of the sequence are determined by the first abbreviation in the pattern (see the table below). 4. Compute the fifth element using the formula corespoding to the first element of the pattern, the sixth element using the formula for the second element and so on. (see the table below and the examples) 5. If `n` is more than the length of `p` repeat the pattern. ``` +------------+--------------+------------------------------------------+---------------------+ | sequence | abbreviation | formula for n-th element | first four elements | +------------|--------------+------------------------------------------|---------------------| | fibonacci | fib | a[n] = a[n-1] + a[n-2] | 0, 0, 0, 1 | | jacobsthal | jac | a[n] = a[n-1] + 2 * a[n-2] | 0, 0, 0, 1 | | padovan | pad | a[n] = a[n-2] + a[n-3] | 0, 1, 0, 0 | | pell | pel | a[n] = 2 * a[n-1] + a[n-2] | 0, 0, 0, 1 | | tetranacci | tet | a[n] = a[n-1] + a[n-2] + a[n-3] + a[n-4] | 0, 0, 0, 1 | | tribonacci | tri | a[n] = a[n-1] + a[n-2] + a[n-3] | 0, 0, 0, 1 | +------------+--------------+------------------------------------------+---------------------+ ``` ## Example ``` zozonacci(["fib", "tri"], 7) == [0, 0, 0, 1, 1, 2, 3] Explanation: b d /-----\/----\ [0, 0, 0, 1, 1, 2, 3] \--------/ | \--------/ a c a - [0, 0, 0, 1] as "fib" is the first abbreviation b - 5th element is 1 as the 1st element of the pattern is "fib": 1 = 0 + 1 c - 6th element is 2 as the 2nd element of the pattern is "tri": 2 = 0 + 1 + 1 d - 7th element is 3 as the 3rd element of the pattern is "fib" (see rule no. 5): 3 = 2 + 1 ``` ## Sequences * [fibonacci](https://oeis.org/A000045) : 0, 1, 1, 2, 3 ... * [padovan](https://oeis.org/A000931): 1, 0, 0, 1, 0 ... * [jacobsthal](https://oeis.org/A001045): 0, 1, 1, 3, 5 ... * [pell](https://oeis.org/A000129): 0, 1, 2, 5, 12 ... * [tribonacci](https://oeis.org/A000073): 0, 0, 1, 1, 2 ... * [tetranacci](https://oeis.org/A000078): 0, 0, 0, 1, 1 ...
["from itertools import cycle\n\nROOT = {'fib': [0, 0, 0, 1],\n 'jac': [0, 0, 0, 1],\n 'pad': [0, 1, 0, 0],\n 'pel': [0, 0, 0, 1],\n 'tet': [0, 0, 0, 1],\n 'tri': [0, 0, 0, 1]}\nGEN = {'fib': lambda a: a[-1] + a[-2],\n 'jac': lambda a: a[-1] + 2 * a[-2],\n 'pad': lambda a: a[-2] + a[-3],\n 'pel': lambda a: 2 * a[-1] + a[-2],\n 'tet': lambda a: a[-1] + a[-2] + a[-3] + a[-4],\n 'tri': lambda a: a[-1] + a[-2] + a[-3]}\n\n\ndef zozonacci(pattern, n):\n if not pattern or not n: return []\n \n lst = ROOT[pattern[0]][:]\n cycl = cycle(map(GEN.get, pattern))\n \n for f,_ in zip(cycl,range(n-4)): lst.append(f(lst))\n \n return lst[:n]", "from collections import deque\n\nstart = {\n 'fib': [0, 0, 0, 1],\n 'jac': [0, 0, 0, 1],\n 'pad': [0, 1, 0, 0],\n 'pel': [0, 0, 0, 1],\n 'tet': [0, 0, 0, 1],\n 'tri': [0, 0, 0, 1],\n}\n\nsum_idx = {\n 'fib': [-1, -2],\n 'jac': [-1, -2, -2],\n 'pad': [-2, -3],\n 'pel': [-1, -1, -2],\n 'tet': [-1, -2, -3, -4],\n 'tri': [-1, -2, -3],\n}\n\ndef sequence(pattern):\n pattern, seq = deque(pattern), deque(start[pattern[0]])\n while 1:\n seq.append(sum(seq[idx] for idx in sum_idx[pattern[0]]))\n yield seq.popleft()\n pattern.rotate(-1)\n\ndef zozonacci(pattern, length):\n return pattern and [n for _, n in zip(range(length), sequence(pattern))]", "from itertools import cycle\n\ndef nacci(coef):\n return lambda seq: sum(c * a for c, a in zip(coef, seq[-4:]))\n \ndef zozonacci(pattern, length):\n if not pattern:\n return []\n d = {'fib' : nacci([0, 0, 1, 1]),\n 'pad' : nacci([0, 1, 1, 0]),\n 'jac' : nacci([0, 0, 2, 1]),\n 'pel' : nacci([0, 0, 1, 2]),\n 'tri' : nacci([0, 1, 1, 1]),\n 'tet' : nacci([1, 1, 1, 1])\n }\n c = cycle(map(d.get, pattern))\n res = ([0, 1, 0, 0] if pattern[0] == 'pad' else [0, 0, 0, 1])[:length]\n for _ in range(length - 4):\n res.append(next(c)(res))\n return res", "from functools import reduce\n\nconfig = {\n 'fib': ([0, 0, 0, 1], lambda a: a[3] + a[2]),\n 'jac': ([0, 0, 0, 1], lambda a: a[3] + 2 * a[2]),\n 'pad': ([0, 1, 0, 0], lambda a: a[2] + a[1]),\n 'pel': ([0, 0, 0, 1], lambda a: 2 * a[3] + a[2]),\n 'tet': ([0, 0, 0, 1], lambda a: a[3] + a[2] + a[1] + a[0]),\n 'tri': ([0, 0, 0, 1], lambda a: a[3] + a[2] + a[1])\n}\n\ndef zozonacci(p, l):\n if not p or not l: return []\n return reduce(lambda r, i: r + [config[p[i % len(p)]][1](r[-4:])], range(0, l-4), config[p[0]][0][:])[0:l]", "def wrapper_fun(func, lst): return func(lst)\ndef fib(lst): return lst[-1] + lst[-2]\ndef tri(lst): return lst[-1] + lst[-2] + lst[-3]\ndef tet(lst): return lst[-1] + lst[-2] + lst[-3] + lst[-4]\ndef pad(lst): return lst[-2] + lst[-3]\ndef pel(lst): return lst[-1] * 2 + lst[-2]\ndef jac(lst): return lst[-1] + lst[-2] * 2\ndef zozonacci(pattern, length):\n if not pattern or not length: return []\n if length < 5:\n if pattern[0] == 'pad': return [0, 1, 0, 0][:length]\n else: return [0, 0, 0, 1][:length]\n cp_lst = zozonacci(pattern, length - 1)\n return cp_lst + [wrapper_fun(eval(pattern[(length - 5) % len(pattern)]), cp_lst)]", "def zozonacci(pattern, length):\n n = len(pattern)\n if n == 0 or length == 0:\n return []\n GEN = {\n \"fib\": lambda x: x[-1] + x[-2],\n \"jac\": lambda x: x[-1] + 2 * x[-2],\n \"pad\": lambda x: x[-2] + x[-3],\n \"pel\": lambda x: 2 * x[-1] + x[-2],\n \"tet\": lambda x: x[-1] + x[-2] + x[-3] + x[-4],\n \"tri\": lambda x: x[-1] + x[-2] + x[-3],\n }\n seq = [0, 1, 0, 0] if pattern[0] == \"pad\" else [0, 0, 0, 1]\n for i in range(length - 4):\n seq += [GEN.get(pattern[i % n])(seq)]\n return seq[:length]", "SEQUENCES = {\n 'fib': ((lambda s, n: s[n - 1] + s[n - 2]), (0, 0, 0, 1)),\n 'jac': ((lambda s, n: s[n - 1] + 2 * s[n - 2]), (0, 0, 0, 1)),\n 'pad': ((lambda s, n: s[n - 2] + s[n - 3]), (0, 1, 0, 0)),\n 'pel': ((lambda s, n: 2 * s[n - 1] + s[n - 2]), (0, 0, 0, 1)),\n 'tri': ((lambda s, n: s[n - 1] + s[n - 2] + s[n - 3]), (0, 0, 0, 1)),\n 'tet': ((lambda s, n: s[n - 1] + s[n - 2] + s[n - 3] + s[n - 4]), (0, 0, 0, 1)),\n}\n\n\ndef zozonacci(pattern, length):\n if not pattern:\n return []\n\n seq = list(SEQUENCES[pattern[0]][1])\n i = 0\n while len(seq) < length:\n fn, _ = SEQUENCES[pattern[i]]\n seq.append(fn(seq, len(seq)))\n i = (i + 1) % len(pattern)\n return seq[:length]", "def zozonacci(pattern, length):\n if (pattern == [] or length == 0):\n return []\n \n pattern_dict = {\"fib\": fibonacci,\n \"jac\": jacobsthal,\n \"pad\": padovan,\n \"pel\": pell,\n \"tet\": tetranacci,\n \"tri\": tribonacci}\n initial_pattern = pattern[0]\n \n if (initial_pattern in [\"fib\", \"jac\", \"pel\", \"tet\", \"tri\"]):\n resultList = [0, 0, 0, 1]\n else:\n resultList = [0, 1, 0, 0]\n if (length < 4):\n return resultList[:length]\n \n for x in range(length - 4):\n rule = pattern[x % len(pattern)]\n pattern_dict[rule](resultList)\n return resultList\n\ndef fibonacci(numbers):\n n = len(numbers)\n numbers.append(numbers[n-1] + numbers[n-2])\n \ndef jacobsthal(numbers):\n n = len(numbers)\n numbers.append(numbers[n-1] + 2 * numbers[n-2])\n \ndef padovan(numbers):\n n = len(numbers)\n numbers.append(numbers[n-2] + numbers[n-3])\n \ndef pell(numbers):\n n = len(numbers)\n numbers.append(numbers[n-1] * 2 + numbers[n-2])\n \ndef tetranacci(numbers):\n n = len(numbers)\n numbers.append(numbers[n-1] + numbers[n-2] + numbers[n-3] + numbers[n-4])\n \ndef tribonacci(numbers):\n n = len(numbers)\n numbers.append(numbers[n-1] + numbers[n-2] + numbers[n-3])\n\n", "def zozonacci(pattern, length): \n if length == 0:\n return []\n if pattern == []:\n return []\n \n result = [0,0,0,1] if pattern[0] != \"pad\" else [0,1,0,0]\n result2 = []\n if length < 4:\n for i in range(length):\n result2.append(result[i])\n return result2\n j = 0\n for i in range(4, length):\n seq = pattern[j]\n if seq == \"fib\":\n result.append(result[i-1] + result[i-2])\n elif seq == \"jac\":\n result.append(result[i-1] + 2 * result[i-2])\n elif seq == \"pad\":\n result.append(result[i-2] + result[i-3])\n elif seq == \"pel\":\n result.append(2 * result[i-1] + result[i-2])\n elif seq == \"tet\":\n result.append(result[i-1] + result[i-2] + result[i-3] + result[i-4])\n else:\n result.append(result[i-1] + result[i-2] + result[i-3])\n j += 1\n if j == len(pattern):\n j = 0\n return result\n \n \n \n", "def zozonacci(pat,n):\n if not pat or not n: return []\n d = {'fib': lambda x: sum(x[-2:]),\n 'jac': lambda x: x[-1]+2*x[-2],\n 'pad': lambda x: x[-2]+x[-3],\n 'pel': lambda x: 2*x[-1]+x[-2],\n 'tet': lambda x: sum(x[-4:]),\n 'tri': lambda x: sum(x[-3:])\n }\n if pat[0] == 'pad': a = [0,1,0,0]\n else: a = [0,0,0,1]\n for i in range(n-4):\n a.append(d.get(pat[i%len(pat)])(a))\n return a[:n]", "from itertools import cycle\ndef zozonacci(seq, n):\n if not n or not seq:return []\n common = {1: [0, 1, 0, 0], 0: [0, 0, 0, 1]}\n ini = common[seq[0] == \"pad\"]\n if n<=4:return ini[:n]\n fib = lambda:sum(ini[-2:])\n jac = lambda:ini[-1] + 2 * ini[-2]\n pad = lambda:sum(ini[-3:-1])\n pel = lambda:2 * ini[-1] + ini[-2]\n tet = lambda:sum(ini[-4:])\n tri = lambda:sum(ini[-3:])\n for i in cycle(seq):\n ini.append(locals()[i]())\n if len(ini) == n : return ini", "from itertools import cycle\n\nFIRST4 = {'fib': [0,0,0,1], 'jac': [0,0,0,1], 'pad': [0,1,0,0], 'pel': [0,0,0,1], 'tet': [0,0,0,1], 'tri': [0,0,0,1]}\nFUNCS = {\n 'fib': lambda a: a[-1] + a[-2],\n 'jac': lambda a: a[-1] + 2 * a[-2],\n 'pad': lambda a: a[-2] + a[-3],\n 'pel': lambda a: 2 * a[-1] + a[-2],\n 'tet': lambda a: a[-1] + a[-2] + a[-3] + a[-4],\n 'tri': lambda a: a[-1] + a[-2] + a[-3],\n}\n\ndef zozonacci(p, n):\n if n == 0 or not p:\n return []\n a = FIRST4[p[0]][:n]\n fs = cycle(map(FUNCS.get, p))\n for i in range(n-4):\n a.append(next(fs)(a))\n return a", "acci = {\n \"fib\":([0,0,0,1],[-1,-2]),\n \"jac\":([0,0,0,1],[-1,-2,-2]),\n \"pad\":([0,1,0,0],[-2,-3]),\n \"pel\":([0,0,0,1],[-1,-1,-2]),\n \"tet\":([0,0,0,1],[-1,-2,-3,-4]),\n \"tri\":([0,0,0,1],[-1,-2,-3])\n}\n\ndef zozonacci(p, l):\n if not p: return []\n h,i = acci[p[0]][0][:],0\n while len(h)<l:\n h.append(sum(h[j] for j in acci[p[i]][1]))\n i=(i+1)%len(p)\n return h[:l]", "from itertools import cycle, islice\n\ndef zozonacci(pattern, length):\n values = [0, 1, 0, 0] if \"pad\" in pattern[:1] else [0, 0, 0, 1]\n weights = {\"fib\": [0, 0, 1, 1], \"pad\": [0, 1, 1, 0], \"jac\": [0, 0, 2, 1], \"pel\": [0, 0, 1, 2], \n \"tri\": [0, 1, 1, 1], \"tet\": [1, 1, 1, 1]}\n for p in islice(cycle(pattern), max(length - 4, 0)):\n values.append(sum(w*v for w, v in zip(weights[p], values[-4:])))\n return values[:(len(pattern) and length)]", "from itertools import cycle\nseq={'fib':[0,0,0,1],'pad':[0,1,0,0],'jac':[0,0,0,1],'pel':[0,0,0,1],'tri':[0,0,0,1],'tet':[0,0,0,1]}\npat={'fib':'a[-1]+a[-2]','pad':'a[-2]+a[-3]','jac':'a[-1]+2*a[-2]','pel':'2*a[-1]+a[-2]',\n 'tri':'a[-1]+a[-2]+a[-3]','tet':'a[-1]+a[-2]+a[-3]+a[-4]'}\ndef zozonacci(pattern, length):\n if not pattern: return []\n a=seq[pattern[0]][:length]\n c=cycle(pattern)\n for i in range(length-4):\n a.append(eval(pat[next(c)]))\n return a", "def zozonacci(pattern, n):\n bind = {'fib': [[0, 0, 0, 1], lambda arr: sum(arr[-2:])],\n 'jac': [[0, 0, 0, 1], lambda arr: sum([2 * arr[-2], arr[-1]])],\n 'pad': [[0, 1, 0, 0], lambda arr: sum([arr[-3], arr[-2]])],\n 'pel': [[0, 0, 0, 1], lambda arr: sum([arr[-2], 2 * arr[-1]])],\n 'tet': [[0, 0, 0, 1], lambda arr: sum(arr[-4:])],\n 'tri': [[0, 0, 0, 1], lambda arr: sum(arr[-3:])]}\n if not pattern or n == 0:\n return []\n res = bind[pattern[0]][0]\n q, r = divmod(n-len(res), len(pattern))\n for v in (q * pattern + pattern[:r]):\n res.append(bind[v][1](res))\n return res[:n]\n", "def zozonacci(pattern, length):\n if length == 0 or pattern == []:\n return []\n result = {\n \"fib\": [0, 0, 0, 1],\n \"jac\": [0, 0, 0, 1],\n \"pad\": [0, 1, 0, 0],\n \"pel\": [0, 0, 0, 1],\n \"tet\": [0, 0, 0, 1],\n \"tri\": [0, 0, 0, 1]\n }[pattern[0]]\n if length < 4:\n result = result[:length]\n return result\n i = 0\n j = 4\n while len(result) < length:\n r = {\n \"fib\": result[j - 1] + result[j - 2],\n \"jac\": result[j - 1] + 2 * result[j - 2],\n \"pad\": result[j - 2] + result[j - 3],\n \"pel\": 2 * result[j - 1] + result[j - 2],\n \"tet\": result[j - 1] + result[j - 2] + result[j - 3] + result[j - 4],\n \"tri\": result[j - 1] + result[j - 2] + result[j - 3]\n }[pattern[i]]\n result.append(r)\n i = (i + 1) % len(pattern)\n j += 1\n return result", "from itertools import cycle\ndef zozonacci(pattern, length):\n if not pattern or not length:return []\n \n fib=lambda lst:sum(lst[-2:])\n jac=lambda lst:lst[-1]+2*lst[-2]\n pad=lambda lst:lst[-2]+lst[-3]\n pel=lambda lst:2*lst[-1]+lst[-2]\n tet=lambda lst:sum(lst[-4:])\n tri=lambda lst:sum(lst[-3:])\n \n FIRST={\"fib\":[0,0,0,1],\"jac\":[0,0,0,1],\"pad\":[0,1,0,0],\"pel\":[0,0,0,1],\"tri\":[0,0,0,1],\"tet\":[0,0,0,1]}\n NEXT={\"fib\":fib,\"jac\":jac,\"pad\":pad,\"pel\":pel,\"tet\":tet,\"tri\":tri}\n \n seq=FIRST[pattern[0]]\n pattern=cycle(pattern)\n \n for i in range(length-4):\n seq.append(NEXT[next(pattern)](seq))\n \n return seq[:length]", "def fibonacci(array,\n index):\n\n return array[index - 1] + array[index - 2]\n\n\ndef jacobsthal(array,\n index):\n\n return array[index - 1] + 2 * array[index - 2]\n\n\ndef padovan(array,\n index):\n\n return array[index - 2] + array[index - 3]\n\n\ndef pell(array,\n index):\n\n return 2 * array[index - 1] + array[index - 2]\n\n\ndef tetranacci(array,\n index):\n\n return array[index - 1] + array[index - 2] + array[index - 3] + array[index - 4]\n\n\ndef tribonacci(array,\n index):\n\n return array[index - 1] + array[index - 2] + array[index - 3] \n\n\nMAP = {\"fib\": fibonacci,\n \"jac\": jacobsthal,\n \"pad\": padovan,\n \"pel\": pell,\n \"tet\": tetranacci,\n \"tri\": tribonacci}\n\n\ndef initialize(pattern):\n\n if (pattern[0] == \"pad\"):\n\n return [0,\n 1,\n 0,\n 0]\n else:\n\n return [0,\n 0,\n 0,\n 1]\n\n\ndef zozonacci(pattern,\n length):\n\n result = []\n if (not (len(pattern) and\n length)):\n\n return result\n\n result = initialize(pattern)\n if (length <= 4):\n\n return result[:length]\n\n index = 4\n while (len(result) < length):\n for sequence in pattern:\n current = MAP[sequence](result,\n index)\n result.append(current)\n index += 1\n if (len(result) == length):\n break\n\n return result\n", "from itertools import cycle\n\ndef zozonacci(p,n):\n \n if not p or not n: return []\n \n formula={\"fib\":lambda : a[-1]+a[-2],\n \"jac\":lambda : a[-1]+2*a[-2],\n \"pad\":lambda : a[-2]+a[-3],\n \"pel\":lambda : 2*a[-1]+a[-2],\n \"tet\":lambda : sum(a[-i] for i in range(1,5)),\n \"tri\":lambda : sum(a[-i] for i in range(1,4))\n }\n \n a=[0,1,0,0] if p[0]==\"pad\" else [0,0,0,1]\n \n if n<=4: return a[:n]\n \n i=0\n p=cycle(p)\n \n while i<n-4: \n a.append(formula[next(p)]())\n i+=1\n \n return a \n \n"]
{"fn_name": "zozonacci", "inputs": [[["fib"], 0], [[], 10], [["fib"], 10], [["tri"], 10], [["tet"], 10], [["pad"], 10], [["pel"], 10], [["jac"], 10], [["fib", "tri"], 10], [["tri", "fib"], 10], [["pad", "fib"], 10], [["tri", "tet"], 10], [["fib", "pel", "tri"], 10], [["tet", "jac"], 10]], "outputs": [[[]], [[]], [[0, 0, 0, 1, 1, 2, 3, 5, 8, 13]], [[0, 0, 0, 1, 1, 2, 4, 7, 13, 24]], [[0, 0, 0, 1, 1, 2, 4, 8, 15, 29]], [[0, 1, 0, 0, 1, 0, 1, 1, 1, 2]], [[0, 0, 0, 1, 2, 5, 12, 29, 70, 169]], [[0, 0, 0, 1, 1, 3, 5, 11, 21, 43]], [[0, 0, 0, 1, 1, 2, 3, 6, 9, 18]], [[0, 0, 0, 1, 1, 2, 4, 6, 12, 18]], [[0, 1, 0, 0, 1, 1, 1, 2, 2, 4]], [[0, 0, 0, 1, 1, 2, 4, 8, 14, 28]], [[0, 0, 0, 1, 1, 3, 5, 8, 21, 34]], [[0, 0, 0, 1, 1, 3, 5, 11, 20, 42]]]}
INTRODUCTORY
PYTHON3
CODEWARS
14,725
def zozonacci(pattern, length):
4445f26e957f310e0ca4e197cb44514a
UNKNOWN
We want to find the numbers higher or equal than 1000 that the sum of every four consecutives digits cannot be higher than a certain given value. If the number is ``` num = d1d2d3d4d5d6 ```, and the maximum sum of 4 contiguous digits is ```maxSum```, then: ```python d1 + d2 + d3 + d4 <= maxSum d2 + d3 + d4 + d5 <= maxSum d3 + d4 + d5 + d6 <= maxSum ``` For that purpose, we need to create a function, ```max_sumDig()```, that receives ```nMax```, as the max value of the interval to study (the range (1000, nMax) ), and a certain value, ```maxSum```, the maximum sum that every four consecutive digits should be less or equal to. The function should output the following list with the data detailed bellow: ```[(1), (2), (3)]``` (1) - the amount of numbers that satisfy the constraint presented above (2) - the closest number to the mean of the results, if there are more than one, the smallest number should be chosen. (3) - the total sum of all the found numbers Let's see a case with all the details: ``` max_sumDig(2000, 3) -------> [11, 1110, 12555] (1) -There are 11 found numbers: 1000, 1001, 1002, 1010, 1011, 1020, 1100, 1101, 1110, 1200 and 2000 (2) - The mean of all the found numbers is: (1000 + 1001 + 1002 + 1010 + 1011 + 1020 + 1100 + 1101 + 1110 + 1200 + 2000) /11 = 1141.36363, so 1110 is the number that is closest to that mean value. (3) - 12555 is the sum of all the found numbers 1000 + 1001 + 1002 + 1010 + 1011 + 1020 + 1100 + 1101 + 1110 + 1200 + 2000 = 12555 Finally, let's see another cases ``` max_sumDig(2000, 4) -----> [21, 1120, 23665] max_sumDig(2000, 7) -----> [85, 1200, 99986] max_sumDig(3000, 7) -----> [141, 1600, 220756] ``` Happy coding!!
["def check(num,max_sum):\n l = [int(i) for i in str(num)]\n for i in range(0,len(l) - 3):\n if sum(l[i:i+4]) > max_sum:return False\n return True\n\ndef max_sumDig(nMax, maxSum):\n found = [i for i in range(1000,nMax + 1) if check(i,maxSum)]\n mean = sum(found) / float(len(found))\n for i in range(len(found) - 1):\n if abs(mean - found[i]) < abs(mean - found[i + 1]):\n mean = found[i]\n break\n return [len(found), mean, sum(found)]", "def max_sumDig_aux(nmax, maxsm):\n res, i = [], 1000\n while (i <= nmax):\n a = list(str(i))\n j, b = 0, 0\n while (j <= len(a) - 4):\n if (sum(map(int, a[j:j+4])) <= maxsm):\n b += 1\n j += 1\n if (b == j):\n res.append(i)\n i += 1\n return res\n \ndef max_sumDig(nmax, maxsm):\n res = max_sumDig_aux(nmax, maxsm)\n l = len(res)\n s = sum(res)\n m = s / float(l)\n d = list([(abs(x - m), x) for x in res])\n d.sort()\n return [l, d[0][1], s]\n", "def max_sumDig(nMax, maxSum):\n answers = []\n \n for i in range(1000, nMax + 1):\n good = True\n n = [int(x) for x in str(i)]\n for j in range(0, len(n)-3):\n if sum([n[j],n[j+1],n[j+2],n[j+3]]) > maxSum:\n good = False\n if good == True:\n answers.append(i)\n \n num, tot = len(answers), sum(answers)\n return [num, min(answers, key=lambda x: abs(x-(tot/float(num)))), tot]", "from statistics import mean\n\ndef max_sumDig(nMax, maxSum):\n def okay(x):\n L = list(map(int, str(x)))\n return all(sum(t) <= maxSum for t in zip(L, L[1:], L[2:], L[3:]))\n result = list(filter(okay, range(1000, nMax+1)))\n m = mean(result)\n return [len(result), min(result, key=lambda x:abs(x-m)), sum(result)]", "from bisect import bisect\n\ndef max_sumDig(n_max, max_sum):\n numbers = []\n \n for n in range(1000, n_max +1):\n s = str(n)\n if all(sum(map(int, s[i:i+4])) <= max_sum for i in range(len(s)-3)):\n numbers.append(n)\n \n res_sum = sum(numbers)\n res_count = len(numbers)\n res_avg = 1.0 * res_sum / res_count\n \n idx = bisect(numbers, res_avg)\n a, b = numbers[idx-1 : idx+1]\n closest = a if res_avg - a <= b - res_avg else b\n \n return [ res_count, closest, res_sum ]", "\ndef sum_int(i):\n \"\"\"Sum digits of an integer - standard\"\"\"\n s=0\n while i != 0:\n s += i % 10\n i //= 10\n return s\n\ndef find_4digs(m,MaxNum,MaxSum):\n \"\"\"start by finding all 4 digit numbers n m \\leq n \\leq MaxNum with sum \\leq MaxSum\"\"\"\n \n sts=[m]\n for i in range(0, 4):\n for st in sts: \n while (sum_int(st+10**i)<= MaxSum and st+10**i <= MaxNum):\n sts.append(st+10**i)\n st += 10**i\n sts=list(set(sts)) # delete duplicates\n return (sts)\n\ndef find_5digs(nums,MaxNum,MaxSum):\n \"\"\" takes in a list of 4 digit numbers \\leq MaxNum and with sum \\leq MaxSum. Returns list of 4 and 5 digit nums \n with every consecutive 4 digits satisfying the same conditions\"\"\"\n #TODO: Generalize to x digit numbers\n \n for s in nums:\n # add digits before the 4 digit nums\n for i in range(1, MaxSum - sum_int(int(str(s)[0:3]))+1):\n cand1 = int(str(i)+str(s))\n if cand1 <= MaxNum:\n nums.append(cand1)\n # add digits after the 4 digit nums\n for i in range(0,MaxSum-sum_int(int(str(s)[1:4]))+1):\n cand2 = int( str(s) + str(i) )\n if cand2 <= MaxNum:\n nums.append(cand2) \n\n nums=list(set(nums)) # delete duplcates\n return nums\n \ndef max_sumDig(MaxNum,MaxSum):\n \"\"\" Find all numbers satisfying the conditions. \"\"\"\n \n nums = find_4digs(1000,MaxNum,MaxSum)\n nums = find_5digs(nums,MaxNum,MaxSum)\n \n # calcualte min distance from mean\n mean = sum(nums)/len(nums) \n dists=[ abs(s-mean) for s in nums] \n \n for i in range(len(dists)):\n if dists[i] == min(dists):\n min_dist=nums[i] \n \n return [len(nums), min_dist, sum(nums)]\n", "def max_sumDig(nMax, maxSum):\n \n def isGood(s): return all(sum(map(int, str(s[i:i+4]))) <= maxSum for i in range(len(s)-3) )\n \n lst = [n for n in range(1000, nMax+1) if isGood(str(n))]\n s, l = sum(lst), len(lst)\n avg = 1.0*s/l\n iAvg = next( i for i,n in enumerate(lst) if n > avg )\n nearest = sorted(lst[iAvg-1:iAvg+1], key=lambda n: abs(n-avg))[0]\n return [l, nearest, s]", "def x(i, maxSum): #check if number satisfies requirments\n s = str(i)\n for i in range(len(s)-3):\n if sum(map(int,list(s[i:i+4])))>maxSum:\n return False\n return True\n\ndef max_sumDig(nMax, maxSum):\n count = 0\n sum_ = 0 \n mean_ = 0\n _3 = None\n \n for i in range(1000, nMax+1):\n if x(i, maxSum):\n count += 1\n sum_ += i\n if not _3: _3 = i\n \n mean_ = float(sum_)/count\n _3 = i\n for i in range(1000, nMax+1):\n if x(i, maxSum):\n if abs(i - mean_) < abs(_3 - mean_): _3 = i \n \n return [count, _3, sum_]", "def max_sumDig(nMax, maxSum):\n count=0\n nums=[]\n if len(str(nMax)) == 4:\n for i in range(1000, nMax+1):\n if ( (i%10) + ( (i//10) % 10 ) + ( (i//100) % 10 ) + ( (i//1000) % 10 )) <= maxSum:\n nums.append(i)\n count+=1\n elif len(str(nMax)) == 5:\n for i in range(1000, nMax+1):\n if ( (i%10) + ( (i//10) % 10 ) + ( (i//100) % 10 ) + ( (i//1000) % 10 )) <= maxSum and (( (i//10) % 10 ) + ( (i//100) % 10 ) + ( (i//1000) % 10 ) + ( (i//10000) % 10 )) <= maxSum:\n nums.append(i)\n count+=1\n elif len(str(nMax)) == 6:\n for i in range(1000, nMax+1):\n if ( (i%10) + ( (i//10) % 10 ) + ( (i//100) % 10 ) + ( (i//1000) % 10 )) <= maxSum and (( (i//10) % 10 ) + ( (i//100) % 10 ) + ( (i//1000) % 10 ) + ( (i//10000) % 10 )) <= maxSum and (( (i//100) % 10 ) + ( (i//1000) % 10 ) + ( (i//10000) % 10 ) + ( (i//100000) % 10 )) <= maxSum:\n nums.append(i)\n count+=1\n media=sum(nums)/len(nums)\n for n in nums:\n if media <= n:\n if (n - media) > (media - nums[nums.index(n)-1]):\n media=nums[nums.index(n)-1]\n break\n else:\n media=n\n break\n suma=sum(nums)\n return [count, media, suma]"]
{"fn_name": "max_sumDig", "inputs": [[2000, 3], [2000, 4], [2000, 7], [3000, 7], [4000, 4], [5000, 2], [5000, 3], [5000, 4], [5000, 5], [5000, 6], [5000, 7], [5000, 8], [5000, 9]], "outputs": [[[11, 1110, 12555]], [[21, 1120, 23665]], [[85, 1200, 99986]], [[141, 1600, 220756]], [[35, 2000, 58331]], [[5, 1100, 6111]], [[15, 1200, 21666]], [[35, 2000, 58331]], [[70, 2000, 132216]], [[122, 2010, 244875]], [[196, 2110, 413306]], [[296, 2200, 649951]], [[426, 2250, 967696]]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,696
def max_sumDig(nMax, maxSum):
b2f9b014df2fe9ef0f4b8d82cc6f92b0
UNKNOWN
Assume you are creating a webshop and you would like to help the user in the search. You have products with brands, prices and name. You have the history of opened products (the most recently opened being the first item). Your task is to create a list of brands ordered by popularity, if two brands have the same popularity level then choose the one which was opened last from the two and second the other one. Product popularity is calculated from the history. If a product is more times in the history than it is more popular. Your function will have one parameter which will be always an array/list of object. example product: { name: "Phone", price: 25, brand: "Fake brand" }
["from collections import Counter\n\ndef sorted_brands(history):\n brands = [x['brand'] for x in history]\n counter = Counter(brands)\n return sorted(set(brands), key=lambda x: (-counter[x], brands.index(x)))", "def sorted_brands(history):\n brands = [item['brand'] for item in history]\n return sorted(set(brands), key=lambda x: (-brands.count(x), brands.index(x)))", "from collections import Counter\n\n\ndef sorted_brands(history):\n brands = Counter(x[\"brand\"] for x in history)\n return [brand for brand, _ in brands.most_common()]", "from collections import Counter\n\ndef sorted_brands(history):\n cnt = Counter(item[\"brand\"] for item in history)\n return sorted(cnt, key=cnt.get, reverse=True)", "def sorted_brands(history):\n count = {}\n for i in history:\n count[i['brand']] = count.get(i['brand'],0)+1\n return sorted(count,key=lambda x:-count[x])", "from collections import Counter\n\ndef sorted_brands(history):\n picked, c = {}, Counter()\n for i,h in enumerate(history):\n c[h['brand']] += 1\n if h['brand'] not in picked: picked[h['brand']] = i\n return sorted(c, key=lambda k: (-c[k], picked[k]))", "from collections import Counter\ndef sorted_brands(history):\n return [n[0] for n in Counter([n['brand'] for n in history]).most_common()]\n \n\n", "def sorted_brands(history):\n d = {}\n for i in history:\n if i['brand'] in d:\n d[i['brand']] += 1\n else:\n d[i['brand']] = 1\n return sorted(list(d.keys()), key=lambda x: d[x], reverse=True)\n \n", "def sorted_brands(arr):\n arr = [k['brand'] for k in arr]\n return sorted(set(arr), key=lambda x: (-arr.count(x), arr.index(x)))", "def sorted_brands(history):\n s = [i['brand'] for i in history]\n print(s)\n \n return sorted(set(s), key=lambda x: (-s.count(x), s.index(x)))"]
{"fn_name": "sorted_brands", "inputs": [[[]]], "outputs": [[[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,895
def sorted_brands(history):
e571819d51318c0fe48647ac4e083429
UNKNOWN
Christmas is coming, and Santa has a long list to go through, to find who deserves presents for the big day. Go through a list of children, and return a list containing every child who appeared on Santa's list. Do not add any child more than once. Output should be sorted. ~~~if:java For java, use Lists. ~~~ Comparison should be case sensitive and the returned list should contain only one copy of each name: `"Sam"` and `"sam"` are different, but `"sAm"` and `"sAm"` are not.
["def find_children(santas_list, children):\n return sorted(set(santas_list) & set(children))", "def find_children(a, b):\n return sorted(set(a) & set(b))", "find_children=lambda s,c:sorted(e for e in c if e in s)", "find_children = lambda x, s: sorted(set(x) & set(s))", "def find_children(arr1,arr2):\n L=[]\n for i in arr2:\n if i in arr1:\n if i not in L:\n L.append(i)\n L.sort()\n return L", "def find_children(santas, children):\n return sorted(set(children) & set(santas))", "def find_children(santas_list, children):\n return sorted({child for child in children if child in santas_list})", "def find_children(santas_list, children):\n result = []\n if len(santas_list) < len(children):\n for child in santas_list:\n if child in children:\n result.append(child) \n else:\n for child in children:\n if child in santas_list:\n result.append(child)\n return sorted(result)", "def find_children(santas_list, children):\n return sorted([names for names in santas_list if names in children])", "find_children=lambda s,c:sorted(set([i for i in c if i in s]))"]
{"fn_name": "find_children", "inputs": [[["Jason", "Jackson", "Jordan", "Johnny"], ["Jason", "Jordan", "Jennifer"]], [["Jason", "Jackson", "Johnson", "JJ"], ["Jason", "James", "JJ"]], [["jASon", "JAsoN", "JaSON", "jasON"], ["JasoN", "jASOn", "JAsoN", "jASon", "JASON"]]], "outputs": [[["Jason", "Jordan"]], [["JJ", "Jason"]], [["JAsoN", "jASon"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,206
def find_children(santas_list, children):
b15d9d98bde1d789a8cb3e83a195f34a
UNKNOWN
FizzBuzz is often one of the first programming puzzles people learn. Now undo it with reverse FizzBuzz! Write a function that accepts a string, which will always be a valid section of FizzBuzz. Your function must return an array that contains the numbers in order to generate the given section of FizzBuzz. Notes: - If the sequence can appear multiple times within FizzBuzz, return the numbers that generate the first instance of that sequence. - All numbers in the sequence will be greater than zero. - You will never receive an empty sequence. ## Examples ``` reverse_fizzbuzz("1 2 Fizz 4 Buzz") --> [1, 2, 3, 4, 5] reverse_fizzbuzz("Fizz 688 689 FizzBuzz") --> [687, 688, 689, 690] reverse_fizzbuzz("Fizz Buzz") --> [9, 10] ```
["def reverse_fizzbuzz(s):\n if s == 'Fizz': return [3]\n if s == 'Buzz': return [5]\n if s == 'Fizz Buzz': return [9, 10]\n if s == 'Buzz Fizz': return [5, 6]\n if s == 'FizzBuzz': return [15]\n s = s.split()\n for i in range(len(s)):\n if s[i].isdigit():\n start = int(s[i]) - i\n return list(range(start, start + len(s)))", "def reverse_fizzbuzz(string):\n s = string.split()\n lst = [0] * len(s)\n for indx, i in enumerate(s):\n if i.isdigit():\n lst[indx] = int(i)\n return list(range(lst[indx] - indx, lst[indx] + len(s) - indx))\n return {'Fizz': [3], 'Buzz': [5], 'FizzBuzz': [15], 'Buzz Fizz': [5, 6], 'Fizz Buzz': [9, 10]}[string]", "def reverse_fizzbuzz(s):\n arr = s.split(' ')\n if len(arr) == 1 and not arr[0].isdigit():\n return [3] if arr[0] == 'Fizz' else [5] if arr[0] =='Buzz' else [15] \n def find_first_num(arr):\n for i in range(len(arr)):\n if arr[i].isdigit():\n return [int(i)*(-1), int(arr[i])]\n if arr[0] == 'Buzz':\n return [0,5]\n return [0, 9]\n nu = find_first_num(arr)\n return [nu[0] + nu[1] + x for x in range(len(arr))]", "def reverse_fizzbuzz(s):\n s = s.split()\n d = next((i for i,j in enumerate(s) if j.isdigit()),-1)\n if d!=-1:return list(range(int(s[d])-len(s[:d]),int(s[d])+len(s[d:])))\n else:\n if s in [['Fizz'],['Buzz']]:return [[3],[5]][s==['Buzz']]\n if s==['FizzBuzz']:return [15]\n if s==['Fizz','Buzz']:return [9,10]\n return [5,6]", "def reverse_fizzbuzz(fizzbuzz_section):\n fizzbuzz_section_elements = fizzbuzz_section.split()\n n = len(fizzbuzz_section_elements)\n \n for index in range(0, n):\n if fizzbuzz_section_elements[index].isdigit():\n start = int(fizzbuzz_section_elements[index]) - index\n return list(range(start, n + start))\n \n fizzbuzz = {\n 'Fizz': [3], \n 'Buzz': [5], \n 'FizzBuzz': [15], \n 'Fizz Buzz': [9, 10], \n 'Buzz Fizz': [5, 6]\n }\n \n return fizzbuzz[fizzbuzz_section]", "def reverse_fizzbuzz(string, start=0):\n def fb_gen(start= 1):\n while True:\n if not(start%5 or start%3): yield (start, 'FizzBuzz')\n elif not(start%3): yield (start, 'Fizz')\n elif not(start%5): yield (start, 'Buzz')\n else: yield (start, start)\n start += 1\n \n str_split = string.split()\n for i, v in enumerate(str_split):\n if v.isdigit(): return list(range(int(v)-i, len(str_split) + int(v)-i))\n\n gen, index_check = fb_gen(), 0\n for ind, val in gen:\n if str_split[index_check] == val:\n if index_check == len(str_split) - 1:\n return list(range(ind - len(str_split) + 1, ind + 1))\n index_check += 1\n else:\n index_check = 0", "\ndef reverse_fizzbuzz(string):\n dic = {'Fizz':3, 'Buzz':5, 'FizzBuzz':15, 'Buzz Fizz':5, 'Fizz Buzz':9} # if only strings, those are the starting positions\n split = string.split() \n \n # if contains number, find fist and return which number is first in original fizzbuzz string\n # if there is no number, must be one of the situation in dic, which will give starting number for each of those\n start = next((int(y)-x for x,y in enumerate(split) if y.isdigit()), dic.get(string)) \n return list(range(start, start + len(split)))", "def reverse_fizzbuzz(s):\n no_int = {\"Fizz\": 3, \"Buzz\": 5, \"Buzz Fizz\": 5, \"Fizz Buzz\": 9, \"FizzBuzz\": 15}\n lst = s.split(\" \")\n start = next((int(item) - i for i, item in enumerate(lst) if item.isdecimal()), no_int.get(s))\n return list(range(start, start + len(lst)))\n", "def reverse_fizzbuzz(string):\n arr = string.split()\n return list(map(lambda di: list(range(int(arr[di]) - di, int(arr[di]) - di + len(arr))), [next((k for k, v in enumerate(arr) if v.isdigit()), -1)]))[0] if any(a.isdigit() for a in arr) else [3] if string == 'Fizz' else [5] if string == 'Buzz' else [5, 6] if string == 'Buzz Fizz' else [9, 10] if string == 'Fizz Buzz' else [15] "]
{"fn_name": "reverse_fizzbuzz", "inputs": [["1 2 Fizz 4 Buzz"], ["Fizz 688 689 FizzBuzz"], ["Fizz Buzz"], ["Fizz"], ["Buzz"], ["Buzz Fizz"], ["FizzBuzz"]], "outputs": [[[1, 2, 3, 4, 5]], [[687, 688, 689, 690]], [[9, 10]], [[3]], [[5]], [[5, 6]], [[15]]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,204
def reverse_fizzbuzz(s):
57a92a8b9a68b18af153813e837886ea
UNKNOWN
There is enough money available on ATM in nominal value 10, 20, 50, 100, 200 and 500 dollars. You are given money in nominal value of `n` with `1<=n<=1500`. Try to find minimal number of notes that must be used to repay in dollars, or output -1 if it is impossible. Good Luck!!!
["def solve(n):\n if n%10: return -1\n c, billet = 0, iter((500,200,100,50,20,10))\n while n:\n x, r = divmod(n, next(billet))\n c, n = c+x, r\n return c", "def solve(n):\n t=0\n for d in [500,200,100,50,20,10]:\n a,n=divmod(n,d)\n t+=a\n if n: return -1\n return t", "def solve(n, cnt=0): \n if n%10: return -1\n for i in (500,200,100,50,20,10):\n cnt += n//i\n n = n%i\n return cnt", "def solve(n):\n counter = 0\n nom = [500, 200, 100, 50, 20, 10]\n for d in nom:\n q,n = divmod(n,d)\n counter +=q\n if n : return -1\n return counter", "def solve(n):\n i=0\n if str(n)[-1]!='0':\n return -1\n while n>0:\n if n>=500:\n i+=1\n n-=500\n if n>=200 and n<500:\n i+=1\n n-=200\n if n>=100 and n<200:\n i+=1\n n-=100\n if n>=50 and n<100:\n i+=1\n n-=50\n if n>=20 and n<50:\n i+=1\n n-=20\n if n>=10 and n<20:\n i+=1\n n-=10\n return i", "def solve(n):\n bills = [500,200,100,50,20,10]\n bills_amount = 0\n if n %10 !=0:\n return -1 \n else:\n for i in bills :\n bills_amount += int (n / i)\n n%=i\n return bills_amount ", "def solve(n):\n if n % 10 != 0:\n return -1\n count = 0\n while n >= 500:\n n -= 500\n count += 1\n while n >= 200:\n n -= 200\n count += 1\n while n >= 100:\n n -= 100\n count += 1\n while n >= 50:\n n -= 50\n count += 1\n while n >= 20:\n n -= 20\n count += 1 \n while n >= 10:\n n -= 10\n count += 1 \n \n return count", "def solve(n):\n counter = 0\n counter += n//500\n n = n%500\n counter += n//200\n n = n%200\n counter += n//100\n n = n%100\n counter += n//50\n n = n%50\n counter += n//20\n n = n%20\n counter += n//10\n n = n%10\n if counter < 1 or n!=0:\n return -1\n else: \n return counter", "def solve(n):\n a = []\n for e in [500, 200, 100, 50, 20, 10]:\n a.append(n//e)\n n = n%e\n return [-1, sum(a)][n%10 == 0]\n \n"]
{"fn_name": "solve", "inputs": [[770], [550], [10], [1250], [125], [666], [42]], "outputs": [[4], [2], [1], [4], [-1], [-1], [-1]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,256
def solve(n):
a37abd9988299a0686217b3e7e410d9c
UNKNOWN
# Task: Based on the received dimensions, `a` and `b`, of an ellipse, calculare its area and perimeter. ## Example: ```python Input: ellipse(5,2) Output: "Area: 31.4, perimeter: 23.1" ``` **Note:** The perimeter approximation formula you should use: `π * (3/2(a+b) - sqrt(ab))` ___ ## Have fun :)
["from math import pi\n\ndef ellipse(a, b):\n return f\"Area: {pi*a*b:.1f}, perimeter: {pi*( 1.5*(a+b) - (a*b)**.5 ):.1f}\"", "from math import pi\n\ndef ellipse(a, b):\n perimeter = pi * (3/2*(a+b) - (a*b)**0.5)\n area = pi * a*b\n return f'Area: {area:.1f}, perimeter: {perimeter:.1f}'", "def ellipse(a, b):\n import math\n area = math.pi * a * b\n perimeter = math.pi * ((3/2)*(a+b) - math.sqrt(a*b))\n return \"Area: \" + str(round(area,1))+ \", perimeter: \" + str(round(perimeter,1))", "import math\n\ndef ellipse(a, b):\n '''Return area and approximated perimeter of an ellipse'''\n \n area = math.pi * a * b\n perimeter = math.pi * (1.5 * (a + b) - math.sqrt(a * b))\n return f'Area: {round(area, 1)}, perimeter: {round(perimeter, 1)}'", "def ellipse(a, b):\n import math\n area = math.pi * a * b\n p = math.pi * (1.5 * (a + b) - math.sqrt(a * b))\n return \"Area: \" + str(round(area, 1)) + \", perimeter: \" + str(round(p, 1))", "import math\ndef ellipse(a, b):\n perimeter = round(math.pi*(3/2*(a+b) - math.sqrt(a*b)), 1)\n area = round(math.pi*a*b, 1)\n return f'Area: {area}, perimeter: {perimeter}'", "import math\ndef ellipse(a, b):\n area = str(round(a*b*math.pi,1))\n perimetro = str(round(math.pi *( 3/2*(a+b) - math.sqrt(a*b)),1))\n return \"Area: \"+area +\", perimeter: \"+perimetro\n", "import math\ndef ellipse(a, b):\n s = str(round(math.pi * a * b, 1))\n l = str(round(math.pi * (3 / 2 * (a + b) - math.sqrt(a * b)), 1))\n return \"Area: \"+s+\", perimeter: \"+l", "from math import pi\n\ndef ellipse(p, q):\n return f'Area: {round(pi * q * p, 1)}, perimeter: {round(pi * (3/2*(p+q) - (p*q) ** .5), 1)}'", "import math \n\ndef ellipse(a, b):\n\n e = math.pi*(a*b)\n \n v = a**2+b**2\n \n p = math.pi*(3/2*(a+b)-math.sqrt(a*b))\n \n return \"Area: {}, perimeter: {}\".format(round(e,1),round(p,1))\n \n"]
{"fn_name": "ellipse", "inputs": [[5, 2], [6, 8], [13, 1]], "outputs": [["Area: 31.4, perimeter: 23.1"], ["Area: 150.8, perimeter: 44.2"], ["Area: 40.8, perimeter: 54.6"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,934
def ellipse(a, b):
d2d6db451c3efe2516adba57e974b215
UNKNOWN
Your task is to return the sum of Triangular Numbers up-to-and-including the `nth` Triangular Number. Triangular Number: "any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc." ``` [01] 02 [03] 04 05 [06] 07 08 09 [10] 11 12 13 14 [15] 16 17 18 19 20 [21] ``` e.g. If `4` is given: `1 + 3 + 6 + 10 = 20`. Triangular Numbers cannot be negative so return 0 if a negative number is given.
["def sum_triangular_numbers(n):\n return n*(n+1)*(n+2)/6 if n>0 else 0", "def sum_triangular_numbers(n):\n return 0 if n < 0 else n * (n + 1) * (n + 2) // 6", "def sum_triangular_numbers(n):\n #your code here\n return sum(sum(range(x+1)) for x in range(n+1))", "def sum_triangular_numbers(n):\n total, a = 0,0\n for i in range(n):\n a += i+1\n total += a\n return total", "def sum_triangular_numbers(n):\n return n * (n + 1) * (n + 2) // 6 if n > 0 else 0", "def sum_triangular_numbers(n):\n if n <= 0: return 0\n x, out = 1, [1]\n while n-1 >= x:\n x += 1\n out.append(out[-1]+x)\n return sum(out)", "def sum_triangular_numbers(n):\n return 0 if n < 1 else n * (n+1) * (n+2) // 6\n", "def sum_triangular_numbers(n):\n return 0 if n <= 0 else n * (n + 1) * (n + 2) // 6", "def sum_triangular_numbers(n):\n return n>0 and (n**3 + 3*n**2 + 2*n) / 6", "def sum_triangular_numbers(n):\n return n>0 and (n+1) * (n+2) * n / 6", "def sum_triangular_numbers(n):\n return sum(i * .5 * (i+1) for i in range(n + 1))", "from itertools import accumulate\nsum_triangular_numbers = lambda _:sum(accumulate(range(0,_+1)))", "def sum_triangular_numbers(n):\n step = 0\n triangulars = [0]\n while n > len(triangulars)-1:\n step += 1\n triangulars.append(triangulars[-1] + step)\n return sum(triangulars)\n", "def sum_triangular_numbers(n):\n if n > 0:\n return sum([(x * (x + 1)) / 2 for x in range(n + 1)])\n else:\n return 0", "sum_triangular_numbers = lambda n: (n*(n+1)*(n+2))//6 if n>0 else 0", "def sum_triangular_numbers(n):\n total = 0\n x = 0\n for i in range(1, n+1):\n x += i\n total += x\n return total", "def sum_triangular_numbers(n): return sum([(n*n+n)/2 for n in range(1,n+1)]) \n", "def sum_triangular_numbers(n):\n return 0 if n < 0 else n*(n+1)*(n+2)/6", "def sum_triangular_numbers(n):\n return sum([n*(n+1)/2 for n in range(n+1)])", "def sum_triangular_numbers(n):\n x = 1\n y = 2\n z = []\n while len(z)<n:\n z.append(x)\n x+=y\n y+=1\n return sum(z)", "# For learning purposes. From slowest to fastest.\ndef sum_triangular_numbers(n):\n return sum(i * (i+1) // 2 for i in range(n + 1))\n\ndef sum_triangular_numbers(n):\n return sum(i * (n-i+1) for i in range(n + 1))\n\ndef sum_triangular_numbers(n):\n return max(0, n * (n+1) * (n+2) // 6)\n\ndef sum_triangular_numbers(n):\n return 0 if n < 1 else n * (n+1) * (n+2) // 6\n", "def sum_triangular_numbers(n):\n return sum(sum(range(i+1)) for i in range(n+1))\n", "sum_triangular_numbers=lambda n:n>0and-~n*n*(n+2)/6", "def sum_triangular_numbers(n):\n return [0, (n**3 - n)/6 + .5*n*(n + 1)][n > 0]", "def sum_triangular_numbers(n):\n return 0 if n <= 0 else sum([i for i in range(1, n+1)]) + sum_triangular_numbers(n-1)", "def sum_triangular_numbers(n):\n #your code here\n sum = 0\n for i in range(n):\n sum += (i+1)*(i+2)/2\n return sum", "def sum_triangular_numbers(n):\n if n <= 0:\n return 0\n return round((1/6*n**3)+(1/2*n**2)+(1/3*n),0)", "def sum_triangular_numbers(n):\n sum_ = 0\n for i in range(1, n + 1):\n sum_ += sum(range(1, i + 1))\n return sum_\n", "def sum_triangular_numbers(n):\n return sum(i*(i+1)/2 for i in range(1,n+1)) if n>0 else 0", "def sum_triangular_numbers(n):\n sum_=0\n for i in range(1, n + 1): \n sum_ += ((i ** 2 + i)//2)\n \n return sum_", "def sum_triangular_numbers(n):\n increment = 1\n sum_ = 0\n number = 0\n while increment <= n:\n number += increment\n sum_ += number\n increment += 1\n return sum_", "def sum_triangular_numbers(n, c=1, v=2):\n return c + sum_triangular_numbers(n-1, c + v, v+1) if n > 0 else 0", "def sum_triangular_numbers(n):\n new_num = 0\n new_num_list =[]\n for num in range(1, n+1):\n new_num += num\n new_num_list.append(new_num)\n print(new_num)\n return sum(new_num_list)\n\nprint(sum_triangular_numbers(6))", "def sum_triangular_numbers(n):\n return max(n*(n+1)*(n+2)//6, 0)", "def sum_triangular_numbers(n):\n if n <= 0:\n return 0\n total = 0\n for num in range(n+1):\n triangle_num = num * (num + 1) / 2\n total = total + triangle_num\n return total\n", "def sum_triangular_numbers(n):\n if n < 1:\n return 0\n else:\n triangular = []\n for i in range(1, n+1):\n triangular.append(i*(i+1)/2)\n return int(sum(triangular))", "def sum_triangular_numbers(n):\n c, p, g = 0, 0, 1\n for loop in range(n + 1):\n c += p\n p += g\n g += 1\n return c", "def sum_triangular_numbers(n):\n #your code here\n return sum([(i+1)*i/2 for i in range(1,n+1)])", "def sum_triangular_numbers(n):\n if n<0:\n return 0\n elif n==0:\n return 1\n else:\n a=[1]\n #a[0]=1\n for i in range(1,n):\n a.append(a[i-1]+i+1) \n return sum(a)", "def sum_triangular_numbers(n):\n #your code here\n if n <= 0:\n return 0;\n else:\n num = [0];\n for i in range(0, n):\n num.append(num[i] + i + 1);\n return sum(num);", "def sum_triangular_numbers(n):\n \n if n > 0 :\n\n listado_numeros = []\n\n while len(listado_numeros) < n :# genera lista con los numeros hasta N\n for i in range (1,n+1):\n listado_numeros.append(i)\n \n for i in listado_numeros[1:]:\n listado_numeros[i-1] = i + listado_numeros[i-2]\n\n return (sum(listado_numeros))\n\n else:\n\n return (0)", "def sum_triangular_numbers(n):\n return sum([sum([1+i for i in range(n)][:i+1]) for i in range(n)])", "def sum_triangular_numbers(n):\n return sum(x*(x+1)/2 for x in range(n+1)) if n > 0 else 0", "def sum_triangular_numbers(n):\n return sum(sum(range(i+1)) for i in range(1, n+1))", "def sum_triangular_numbers(n):\n if n <= 0:\n return 0\n if n == 1:\n return 1\n calc = 1\n inc = 2\n sm = 1\n for x in range(2,n + 1):\n calc = calc + inc \n sm = sm + calc\n inc = inc + 1\n return sm\n", "def sum_triangular_numbers(n):\n return sum([round((a)*(a+1)/2) for a in range(1,n+1)])\n\n", "def sum_triangular_numbers(n):\n return sum([(x*(x+1))/2 for x in range(0, n+1)])", "def sum_triangular_numbers(n):\n if n<0:\n return 0\n else: \n c = n*(n+1)*(n+2)//6\n return c\n", "def sum_triangular_numbers(n):\n numberz = 0\n triangular_numbers = []\n if n <= 0:\n return 0\n else:\n number = 0\n for int in range(0,n+1):\n number = number+int\n triangular_numbers.append(number)\n for num in triangular_numbers:\n numberz = numberz + num\n \n return numberz\n", "def sum_triangular_numbers(n):\n \n if n<0:\n \n return 0\n \n a = list(range(1,n+1))\n \n b = []\n \n for i in range(0,len(a)):\n \n d = a[i]+sum(a[0:i])\n \n b.append(d)\n \n s = sum(b)\n \n return s\n\n", "def sum_triangular_numbers(n):\n return 0 if n < 0 else sum(k * (k+1) // 2 for k in range(1, n+1))", "def sum_triangular_numbers(n):\n if n <= 0: return 0\n \n s = 1\n i = 2\n \n t = 1\n x = 1\n while x < n:\n s += i\n i += 1\n x += 1\n t += s\n \n #print(s, t)\n \n return t", "def sum_triangular_numbers(n):\n if n < 0:\n return 0\n else:\n sum = 0\n for i in range(1, n + 1): \n x = ((i ** 2 + i)//2)\n sum += x \n return sum", "def sum_triangular_numbers(n):\n sum = 0\n num = 0\n k = 1\n while(n >0):\n num += k\n sum += num\n k += 1\n n -= 1\n return sum", "def sum_triangular_numbers(n):\n if n <=0:\n return 0\n li= [1]\n for i in range(2,n+1):\n li.append(li[-1]+i)\n return sum(li)", "def sum_triangular_numbers(n):\n if n <= 0:\n return 0\n else:\n step = 1\n prvi = 0\n e = []\n while step < n +1:\n prvi += step\n step += 1\n e.append(prvi)\n return sum(e)\n", "def sum_triangular_numbers(n):\n return sum([sum([y for y in range(1, x+1)]) for x in range(1, n+1)])", "def sum_triangular_numbers(n):\n c, l = 0,0\n for i in range (1,n+1):\n l = l+i\n c += l\n return c", "def sum_triangular_numbers(n):\n l = [0]\n for x in range(1, n + 1):\n l.append(x + l[-1])\n return sum(l)", "def sum_triangular_numbers(n):\n #your code here\n t = 1\n s = 0\n for i in range(2, n+2):\n s = s + t\n t = t + i\n return s", "def sum_triangular_numbers(n):\n if n < 1:\n return 0\n if n ==1:\n return 1\n return (n/2)*(n+1) + sum_triangular_numbers(n-1)", "def sum_triangular_numbers(n):\n if n < 1:\n return 0\n elif n == 1:\n return 1\n else:\n cont = 0\n num = 1\n max = 2\n result = 1\n\n while(max <= n):\n num+=1\n cont+=1\n if cont == max:\n result+=num\n max+=1\n cont=0\n return result\n", "def sum_triangular_numbers(n):\n '''Uses formula to find triangular numbers and adds these to total'''\n total = 0\n for i in range(n+1):\n total += sum(list(range(1,i+1)))\n return total ", "def triangle(n):\n return int(n*(n+1)/2)\n\n\n\ndef sum_triangular_numbers(n):\n sum = 0\n for i in range(n+1):\n sum += triangle(i)\n \n return sum\n", "def sum_triangular_numbers(n):\n sum_, t_i = 0, 0\n for i in range(1, n+1):\n t_i += i\n sum_ += t_i\n return sum_", "def sum_triangular_numbers(n):\n d = 1\n s = 0\n res = 0\n for i in range(n):\n s += d\n res += s\n d += 1\n return res", "def sum_triangular_numbers(n):\n s = 1\n x = []\n for i in range(2, n + 2):\n x.append(s)\n s += i\n \n return sum(x)", "def sum_triangular_numbers(n):\n l=[]\n c=0\n for i in range(1,n+1):\n c += i\n l.append(c)\n return sum(l)", "def sum_triangular_numbers(n):\n r = [0]\n [r.append(r[-1]+x) for x in range(n+1)]\n return sum(r)", "def sum_triangular_numbers(n):\n \n return sum([(n * (n + 1)) // 2 for n in range(1, n + 1)])\n \n", "def sum_triangular_numbers(n):\n if n<=0:\n return 0\n else:\n return (n**3+3*n**2+2*n)/6", "def sum_triangular_numbers(n):\n sum_list = [0]\n for i in range(1, n+1):\n sum_list.append(sum_list[-1] + i)\n return sum(sum_list)", "def sum_triangular_numbers(n):\n #your code here\n sum = 0\n i = 0\n tsum = 0\n for row in range(1,n+1):\n sum = sum+row\n tsum+=sum\n return tsum if tsum>0 else 0", "def sum_triangular_numbers(n):\n list = []\n count = 0\n for num in range(1,n+1):\n count += num\n list.append(count)\n return sum(list)\n\n #return sum(num for num in range(1,n+1))\n", "def sum_triangular_numbers(n):\n val = 0\n return_list = []\n\n if n < 0:\n return 0\n \n for x in range (1, n+1):\n val = val + x\n return_list.append(val)\n return sum(return_list)\n", "def sum_triangular_numbers(n):\n \n #your code here\n return sum( (1+i)*i/2 for i in range(1,n+1))", "def sum_triangular_numbers(n):\n return sum(x*(n-x+1) for x in range(1,n+1))", "def sum_triangular_numbers(n):\n num=1\n interval=2\n ls=list()\n while interval<=n:\n num=num+interval\n interval=interval+1\n ls.append(num)\n if n<0:\n return sum(ls)\n else:\n return sum(ls)+1", "def sum_triangular_numbers(n):\n #your code here\n if n > 0:\n z = 1\n x = []\n for i in range(2, n + 1):\n z = z + i\n x.append(z)\n return sum(x) + 1\n if n < 0:\n return 0", "def sum_triangular_numbers(n):\n \n return sum([(n-i+1)*i for i in range(1,n+1)])", "tri = lambda x: (x * (x+1))/2\n\ndef sum_triangular_numbers(n):\n try:\n res = 0\n for i in range(1,n+1):\n res += tri(i)\n return res\n except: return 0\n", "def sum_triangular_numbers(n):\n if n <= 0:\n return 0\n else:\n x=0\n for i in range(0,n+1):\n x+=i*(i+1)/2\n return int(x)", "def sum_triangular_numbers(n):\n if n < 0: return 0\n res = [1]\n i = 2\n for x in range(n-1):\n res.append(res[-1] + i)\n i += 1\n return sum(res)", "def sum_triangular_numbers(n):\n m = abs(n)\n if m == n:\n sum_ = 0\n while n > 0:\n sum_ += (n * (n+1) / 2)\n n -= 1\n else: sum_ = 0\n return sum_", "def sum_triangular_numbers(n):\n return 0 if n < 0 else sum(x*(x+1)/2 for x in range(n+1))", "t = lambda x: x * (x + 1) // 2\n\ndef sum_triangular_numbers(n):\n return sum(t(x) for x in range(n + 1))\n", "def sum_triangular_numbers(n):\n s = a = 0\n for i in range(1, n+1):\n a += i\n s += a\n \n return s", "def sum_triangular_numbers(n):\n return sum([x*(x+1)*0.5 for x in range(1,n+1)])", "def sum_triangular_numbers(n):\n addend,sum = 0,0,\n for step in range(1,n+1):\n addend += step\n sum += addend\n return sum", "def sum_triangular_numbers(n):\n step,addend,sum = 0,0,0\n for _ in range(n):\n step += 1\n addend += step\n sum += addend\n return sum ", "def sum_triangular_numbers(n):\n if n <= 0: return 0\n x,y = 0,0\n sum = 0\n for i in range(n):\n x = x+1\n y = x+y\n sum += y\n return sum", "def sum_triangular_numbers(n):\n if n < 0:\n return 0\n add, i, l= 1, 0, []\n while n != add -1:\n i +=add\n add +=1\n l.append(i)\n sum(l)\n return sum(l)", "def sum_triangular_numbers(n):\n #your code here\n return sum(sum(range(i)) for i in range(n+2))", "def sum_triangular_numbers(n):\n result = 0\n x = 0\n for y in range(n + 1):\n x += y\n result += x\n return result", "def sum_triangular_numbers(n):\n #your code here\n count = 0\n sum = 0\n total = 0\n for index in range(n):\n count += 1\n sum += count\n total += sum\n return total", "def sum_triangular_numbers(n):\n if n<0:\n return 0\n else:\n a = 2\n lst = []\n n = n-1\n while n>0:\n lst.append(a)\n a+=1\n n-=1\n print(lst)\n cnt = 1\n lst1 =[1]\n for i in range(len(lst)):\n cnt += lst[i]\n lst1.append(cnt)\n return sum(lst1)\n \n", "def sum_triangular_numbers(n):\n return sum(x*(x-1)//2 for x in range(1,n+2))", "def sum_triangular_numbers(n):\n if n <= 0:\n return 0\n result_sum = 0\n exponent = 2\n num = 1\n for _ in range(n - 1):\n num = num + exponent\n exponent += 1\n result_sum += num\n return result_sum + 1", "def sum_triangular_numbers(n):\n if n < 1:\n return 0 \n total = 0\n a = 0\n for i in range(0,n):\n a += (i+1)\n total += a\n return total", "def sum_triangular_numbers(n):\n return 0 if n < 0 else int(1/6*n*(n+1)*(n+2)+1e-5)", "def sum_triangular_numbers(n):\n #find triangle number\n return sum([i*(i+1)/2 for i in range(1, n+1)])"]
{"fn_name": "sum_triangular_numbers", "inputs": [[6], [34], [-291], [943], [-971]], "outputs": [[56], [7140], [0], [140205240], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
15,798
def sum_triangular_numbers(n):
ba81ad15cc292658c2743c737bcae5bf
UNKNOWN
Student A and student B are giving each other test answers during a test. They don't want to be caught so they are sending each other coded messages. Student A is sending student B the message: `Answer to Number 5 Part b`. He starts of with a square grid (in this example the grid = 5x5). He writes the message down (with spaces): ``` Answe r to Numbe r 5 P art b ``` He then starts writing the message down one column at a time (from the top to the bottom). The new message is now: `ArNran u rstm5twob e ePb` You are the teacher of this class. Your job is to decipher this message and bust the students. # Task Write a function `decipher_message`. This function will take one parameter (`message`). This function will return the original message. *** Note: The length of the string is always going to be a prefect square *** Hint: You should probably decipher the example message first before you start coding Have fun !!!
["def decipher_message(message):\n n = int(len(message) ** 0.5)\n return ''.join(message[i::n] for i in range(n))", "from math import sqrt\ndef decipher_message(message):\n key = int(sqrt(len(message)))\n plaintext = [\"\"] * key\n current_row = 0\n for symbol in message:\n plaintext[current_row] += symbol\n current_row += 1\n if current_row > key - 1:\n current_row = 0\n return \"\".join(plaintext)", "import math\ndef decipher_message(m):\n l = int(math.sqrt(len(m))) \n return ''.join(''.join(m[i+l*j] for j in range(l)) for i in range(l))", "def decipher_message(message):\n side_length = int(len(message) ** .5)\n return \"\".join(message[i::side_length] for i in range(side_length))", "def decipher_message(message):\n if not message:\n return \"\"\n res=[]\n for i in range(0, len(message), int(len(message)**0.5)):\n res.append(message[i:i+int(len(message)**0.5)])\n solution=\"\"\n for i in range(len(res)):\n for j in range(len(res[i])):\n solution+=res[j][i]\n return solution", "def decipher_message(message):\n from math import sqrt\n if len(message) == 0:\n return message\n else:\n lists, output = [],[] #empty lists for storing column values and output message\n x = int(sqrt(len(message))) #denotes the column/row length\n for i in range(0,len(message),x):\n lists.append(list(message[i:i+x])) #simulates the n x n grid \n for i in range(len(lists)):\n for j in range(len(lists)): #iterates over each grid element\n output.append(lists[j][i]) #appends to output list\n return ''.join(output) #decoded message\n", "def decipher_message(message):\n if not message:\n return ''\n s = int(len(message) ** 0.5)\n l = [message[i:i+s] for i in range(0,len(message),s)]\n r = []\n for i in range(s):\n r.append(''.join(list(map(lambda x:x[i], l))))\n return ''.join(r)", "def decipher_message(m):\n Q = int(len(m)**.5)\n return ''.join(''.join(i) for i in (zip(*[m[i:i+Q] for i in range(0, len(m), Q)]))) if m else ''"]
{"fn_name": "decipher_message", "inputs": [["ArNran u rstm5twob e ePb"], ["ArNran u rstm8twob e ePc"], ["92287a76 585a2y0"], [" a29068686a275y5"], ["8a 55y0y0y5a7 78"], ["9y98a877a95976a758726a89a5659957ya y"], ["aa297625 88a02670997 86ya880 00a9067"], ["826a976a508a9a 687600a2800 895055y a"], [" a702a067629y022ay865y9yy92a60226 9869y0 y88y077"], ["y0y 62 27059y ya6568588a956aa0 960969a52 5 2680"], ["662 y768867 9 765y9696a5980 5 7228562965597766y29"], ["2y0y7250 69222a98780 0 2769a0y5 8y9a5y0796 6259 y"], ["86a6yy776a87y 027 a5229 9678 60695656aa82550687y"], ["aa68y6 5 y9595a 9y6272727y7yaa6a7y9a06 7529y9 a 5"], ["y2y59087y9a627yy7995a668890 8y990a6027006668y a2"], ["796820 2 "], ["7a05y8 52"], ["a 57529a9"], ["aya960700"], ["y0 60 2685822260yaa98 500 yy67082 6628y2y9y567095ay859y5 8y999297 y0229 60a 95y80"], ["6y 70a5y6y5 a 7820y8ay58y852y055y6207ay6028958508y 9a 5 a a026626787 805a50 y0 9a"], ["a8y7067y7yyya 982672a006850 86yy 7988 y8a90 66y6y82a9 a6692y5670a552765 2a 5 78"], ["5 20a0 076705 5yy756 a88y26a6262a05059 a y09 829y885a6yy568877966565 yy6962y0055"], ["09y286 90 y y68y055908 068 500ay27 89522a 6a 529yy295a5y6628y96"], ["92752y9555 982887y6yy70 8292 0y9767 925y8a785929a69y25y5yy0a0a7"], [" 7569520897207a0y056yy79a88 5880886 8 a7592a5 595 9 270795a29 9"], ["5aa 0y06 86 y725 ay5768269 0 2808a277 0ay2628592077y62y627y92a98"], ["57067 y27 a8y7 8022059 0565yy2y9aaya6626y0 6227a6 880y72762y9"], [""], ["8 d9dx0962x8067d x 760x272690 d852757d59 d552820d52dx767d 0dxxxd995x0676x59d6x7760x0d7 02dd7558770x2d0760x85d8x709d0x590"], ["5 9xx2788d0x207 9x85 008xx5 852056985508662x8 75 x92d0 8088585d882d 52967 d 292987d97695x59d52x505 5678082x98552625888 "]], "outputs": [["Answer to Number 5 Part b"], ["Answer to Number 8 Part c"], ["97 a2a52278y8650"], [" 087a66528ay9625"], ["8507ayy 0575ya8"], ["9777a5y762579aa66y897a5aa5589 89899y"], ["a209a0a5278a2 6 899878007806 66a9y07"], ["8696002aa00565 0 5a06a8y98829 7a785a"], [" 005a9y 62y688a72906876ay29y02yy2y02989607ay62 7"], ["y2y8a6 07a8095y06a a 55995269656262y860 8 5a9 0"], ["6876567686a 272655796 7y9266y 9825y79608526 9 599"], ["20a00a y 9 y5606825y2y977 0572868792209y9 52 a96y"], ["87 28656602 55aa29660687 0a6y7 96a8yya69877 5752y"], ["a5a2aa9a 7a0y6y9266989y7a y56y77a6927y5 57y925"], ["y7y6 662yy6806y978y285a9897y969990 025000a87a a62"], ["78 92260 "], ["75 ay5082"], ["a79 5a529"], ["a97y60a00"], ["y5ay27y96089680570 287y9 a62 0258y 0258yay09 6029y925200 y892y6y 6559988ay6692 0"], ["6yy27852ay58ya5 65 a0y0a707ay568 8 0 550ya7ya78y2 0 058y68928 y2829a60960505 65a"], ["ay7 86 7 8y28 ya02yya6y66aa7a0y8y65 0 0ya895 696 9222578870ay7 y259 956776086 658"], ["565a5 696 76698y6920 2 2y6605a6a9552a 82 y66y058ay8850 yy0088 00y25957y57760 a7y5"], ["00y0y29y9 062ay6yy587 y62 5 6228 958a986y009 5y 68055a998 a2256"], ["95787y9525y268ay7 697a6y59y2 79028y 8yay2709520980y295a58 952y7"], [" 8ya8557790889 957586295626 a a90y585 257y8 292a78a57 00907909"], ["5 68y02a8a9a277a6y 267y 5072y90y7 7862y762 52a028809y96520a268"], ["5700962y7 25ay770a26a0a26805y 677y5ya 6 79y6 82y 2668y28 y2209"], [""], ["88x256960x8 027275x22xd6758dx7dd797272 07d00dd6d0066779x 95dd7056d0x095x6x5009 2xx08xx67d dx5d785268dxd97759x05579d 0d0"], ["5x05x 2 958 20688d25 59089 0 9x55x7x87852562x x558299762 55 598d8279 0x8675058x88957d28888562d 9x28d526d8d75x80 0208 609 "]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,173
def decipher_message(message):
63b8fae5ff60915e4bae32af4a2a8d49
UNKNOWN
Your friend Rick is trying to send you a message, but he is concerned that it would get intercepted by his partner. He came up with a solution: 1) Add digits in random places within the message. 2) Split the resulting message in two. He wrote down every second character on one page, and the remaining ones on another. He then dispatched the two messages separately. Write a function interweave(s1, s2) that reverses this operation to decode his message! Example 1: interweave("hlo", "el") -> "hello" Example 2: interweave("h3lo", "el4") -> "hello" Rick's a bit peculiar about his formats. He would feel ashamed if he found out his message led to extra white spaces hanging around the edges of his message...
["def interweave(s1, s2):\n s = [''] * (len(s1) + len(s2))\n s[::2], s[1::2] = s1, s2\n return ''.join(c for c in s if not c.isdigit()).strip()", "from itertools import chain, zip_longest\ndef interweave(s1, s2):\n return ''.join(char for char in chain.from_iterable(zip_longest(s1, s2, fillvalue='')) if not char.isdigit())", "import re\ndef interweave(s1, s2):\n z=''.join([x+y for x,y in zip(s1,s2+' ')])[:-1]\n return re.sub(r'[0-9]','',z)\n", "def interweave(s1, s2):\n result = ''\n i = 0\n while i < len(s1) or i < len(s2):\n if i < len(s1) and not s1[i].isdigit():\n result += s1[i]\n if i < len(s2) and not s2[i].isdigit():\n result += s2[i]\n i += 1\n return result", "def interweave(s1, s2):\n return ''.join(y for x in zip(s1,s2+'0') for y in x if not y.isdigit())", "from itertools import zip_longest\n\n\ndef interweave(*args):\n return ''.join(''.join(b for b in a if not b.isdigit())\n for a in zip_longest(*args, fillvalue='')).rstrip()\n", "import re\n\ndef interweave(s1, s2):\n return re.sub(r'\\d', '', ''.join(a+b for a,b in zip(s1, s2.ljust(len(s1), ' ')))).strip()", "from itertools import chain, zip_longest\n\ndef interweave(s1, s2):\n L = chain.from_iterable(zip_longest(s1, s2, fillvalue=''))\n return ''.join(c for c in L if not c.isdigit())", "def interweave(s1, s2):\n s = ''\n for i in range(len(s2)):\n if not s1[i].isdigit(): s += s1[i]\n if not s2[i].isdigit(): s += s2[i]\n return s if len(s1) == 0 or s1[-1].isdigit() else s + s1[-1]\n", "from itertools import chain, zip_longest\n\ndef interweave(s1, s2):\n return ''.join([c for c in chain.from_iterable(zip_longest(s1, s2)) if c and not c.isdigit()])\n"]
{"fn_name": "interweave", "inputs": [["", ""], ["hlo", "el"], ["h3lo", "el4"]], "outputs": [[""], ["hello"], ["hello"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,762
def interweave(s1, s2):
ea5001fb4ea76b30b35085401f8e7a94
UNKNOWN
Welcome. In this kata, you are asked to square every digit of a number and concatenate them. For example, if we run 9119 through the function, 811181 will come out, because 9^(2) is 81 and 1^(2) is 1. **Note:** The function accepts an integer and returns an integer
["def square_digits(num):\n ret = \"\"\n for x in str(num):\n ret += str(int(x)**2)\n return int(ret)", "def square_digits(num):\n return int(''.join(str(int(d)**2) for d in str(num)))", "def square_digits(num):\n l = []\n for d in str(num):\n l.append(str(int(d)**2));\n return int(''.join(l))\n", "def square_digits(num):\n return int(''.join(str(int(c)**2) for c in str(num)))", "def square_digits(num):\n num = str(num)\n ans = ''\n for i in num:\n ans += str(int(i)**2)\n return int(ans)\n", "def square_digits(num):\n squares = ''\n for x in str(num):\n squares += str(int(x) ** 2)\n return int(squares)", "def square_digits(num):\n # s converts num to a str so we can index through it\n # when then loop through the len of the str \n # while we're looping the string we convert it back to a int and square it\n # after we add it to a str to keep it from adding and then convert it to a int\n s = str(num)\n t = len(s)\n y=0\n g= 0\n b=\"\"\n while y < t:\n g = int(s[y])**2 \n b= b+ str(g) \n final = int(b)\n y=y+1\n return(final) \n pass", "def square_digits(n):\n return int(\"\".join(str(pow(int(i), 2)) for i in str(n)))\n", "def square_digits(num):\n return int(''.join([str(int(x)**2) for x in list(str(num))]))\n", "def square_digits(num):\n return int(''.join([str(n * n) for n in map(int, str(num))]))"]
{"fn_name": "square_digits", "inputs": [[3212], [2112]], "outputs": [[9414], [4114]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,464
def square_digits(num):
fd50cc30fdddb15025e1e9467acc93fe
UNKNOWN
Given an array, return the reversed version of the array (a different kind of reverse though), you reverse portions of the array, you'll be given a length argument which represents the length of each portion you are to reverse. E.g if after reversing some portions of the array and the length of the remaining portion in the array is not up to the length argument, just reverse them. `selReverse(array, length)` - array - array to reverse - length - length of each portion to reverse Note : if the length argument exceeds the array length, reverse all of them, if the length argument is zero do not reverse at all.
["def sel_reverse(arr,l):\n return [ elt for i in range(0, len(arr), l) for elt in arr[i:i+l][::-1] ] if l != 0 else arr", "from itertools import chain\n\ndef gen(arr, l):\n for i in range(0, len(arr), l):\n yield arr[i:i+l][::-1]\n\ndef sel_reverse(arr,l):\n return list(chain.from_iterable(gen(arr, l or 1)))", "def sel_reverse(arr,l):\n new_l = []\n index = max(l, 1)\n for x in range(0, len(arr)+1, max(index,l)):\n new_l.extend(arr[x:x+index][::-1])\n return new_l", "def sel_reverse(lst, k):\n return sum((lst[i:i+k][::-1] for i in range(0, len(lst), k)), []) if k else lst\n \n \n\n# alternative:\n# return [e for i in range(0, len(lst), k) for e in lst[i:i+k][::-1]] if k else lst\n", "def sel_reverse(arr, l):\n l = l or 1\n return [\n x\n for i in range(0, len(arr), l)\n for x in reversed(arr[i:i+l])\n ]", "def sel_reverse(arr,l):\n return sum([arr[i:i+l][::-1] for i in range(0,len(arr),l)],[]) if l>0 else arr", "def sel_reverse(arr,l):\n #your code here\n res = []\n \n if l == 0:\n return arr\n \n i = 0\n while i < len(arr):\n res.append(arr[i:i+l][::-1])\n i += l\n \n return sum(res, [])", "def sel_reverse(arr,l):\n if not l:\n return arr\n arr = [sorted(arr[i: i + l])[::-1] for i in range(0, len(arr), l) ]\n return [j for i in arr for j in i]", "from itertools import zip_longest,chain\n\ndef sel_reverse(arr,l):\n if l==0: return arr\n return [e for e in chain.from_iterable(t[::-1] for t in zip_longest(*[iter(arr)]*l)) if e is not None]", "def sel_reverse(arr, l):\n return [y for x in [arr[i:i + l][::-1] for i in range(0, len(arr), l)] for y in x] if l else arr"]
{"fn_name": "sel_reverse", "inputs": [[[2, 4, 6, 8, 10, 12, 14, 16], 3], [[2, 4, 6, 8, 10, 12, 14, 16], 2], [[1, 2, 3, 4, 5, 6], 2], [[1, 2, 3, 4, 5, 6], 0], [[1, 2, 3, 4, 5, 6], 10]], "outputs": [[[6, 4, 2, 12, 10, 8, 16, 14]], [[4, 2, 8, 6, 12, 10, 16, 14]], [[2, 1, 4, 3, 6, 5]], [[1, 2, 3, 4, 5, 6]], [[6, 5, 4, 3, 2, 1]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,740
def sel_reverse(arr,l):
3b31a58217a55b08b33466ece06ebdb5
UNKNOWN
Complete the function, which calculates how much you need to tip based on the total amount of the bill and the service. You need to consider the following ratings: - Terrible: tip 0% - Poor: tip 5% - Good: tip 10% - Great: tip 15% - Excellent: tip 20% The rating is **case insensitive** (so "great" = "GREAT"). If an unrecognised rating is received, then you need to return: * `"Rating not recognised"` in Javascript, Python and Ruby... * ...or `null` in Java * ...or `-1` in C# Because you're a nice person, you **always round up** the tip, regardless of the service.
["from math import ceil\ndef calculate_tip(amount, rating):\n tips = {\n 'terrible': 0,\n 'poor' : .05,\n 'good' : .1,\n 'great' : .15,\n 'excellent' : .2\n }\n if rating.lower() in tips:\n return ceil(amount * tips[rating.lower()])\n else:\n return 'Rating not recognised'", "import math\n\ndef calculate_tip(amount, rating):\n tip_table = {'terrible' : 0,\n 'poor' : 0.05,\n 'good' : 0.10,\n 'great' : 0.15,\n 'excellent' : 0.20}\n rating = rating.lower()\n if rating in tip_table:\n return math.ceil(amount * tip_table[rating.lower()])\n else:\n return \"Rating not recognised\"\n", "import math\n\ndef calculate_tip(amount, rating):\n rating = rating.lower()\n tip = {\n \"terrible\": 0,\n \"poor\": 0.05,\n \"good\": 0.1,\n \"great\": 0.15,\n \"excellent\": 0.2\n }.get(rating)\n if (tip == None):\n return \"Rating not recognised\"\n \n return int(math.ceil(amount * tip))", "import math\ndef calculate_tip(a, r):\n return {\"terrible\":0*a,\"poor\":math.ceil(0.05*a),\"good\":math.ceil(0.1*a),\"great\":math.ceil(0.15*a),\"excellent\":math.ceil(0.2*a)}.get(r.lower(), \"Rating not recognised\")", "def calculate_tip(a, r):\n d = {'terrible': 0,'poor': .05,'good': .10,'great': .15,'excellent': .20}\n return int(d[r.lower()] * a + .99) if r.lower() in d else 'Rating not recognised'", "from math import ceil\nD = {\"terrible\":0, \"poor\":0.05, \"good\":0.1, \"great\":0.15, \"excellent\":0.2}\n\ndef calculate_tip(amount, rating):\n rating = D.get(rating.lower(), None)\n return \"Rating not recognised\" if rating is None else ceil(amount * rating)", "dict ={\n \"terrible\": 0,\n \"poor\": 5,\n \"good\": 10,\n \"great\": 15,\n \"excellent\": 20\n}\nimport math\ndef calculate_tip(amount, rating):\n return \"Rating not recognised\" if dict.get(rating.lower(),\"null\") ==\"null\" else math.ceil(dict.get(rating.lower(),\"null\")/100*amount)\n", "from math import ceil\ndef calculate_tip(amount, rating):\n service = {\"terrible\": 0.00, \"poor\": 0.05, \"good\":0.10, \"great\": 0.15, \"excellent\": 0.20}\n return(ceil(amount*service[rating.lower()]) if rating.lower() in service.keys() else \"Rating not recognised\")", "from math import ceil\ndef calculate_tip(a, r):\n d = dict(zip(['terrible', 'poor','good','great','excellent'], [0, 5, 10, 15, 20]))\n r = r.lower()\n if r in d:\n return (ceil(d[r]*a/100))\n else:\n return 'Rating not recognised'", "from math import ceil\n\ndef calculate_tip(amount, rating):\n tip = {'terrible': 0, 'poor': 0.05, 'good': 0.1, 'great': 0.15, 'excellent': 0.2}\n return ceil(amount * tip[rating.lower()]) if rating.lower() in tip else 'Rating not recognised'", "d={'terrible':0,'poor':0.05, 'good':0.1, 'great':0.15, 'excellent':0.2}\ndef calculate_tip(amount, rating):\n rating = rating.lower()\n if rating not in d: return 'Rating not recognised'\n return __import__('math').ceil(amount*(d[rating]))", "import math\n\ndef calculate_tip(amount, rating):\n tip = {'terrible': 0, 'poor': 0.05, 'good': 0.10, 'great': 0.15, 'excellent': 0.2}\n return 'Rating not recognised' if rating.lower() not in tip else math.ceil(amount * tip[rating.lower()])", "from collections import defaultdict\nfrom math import ceil\n\nSERVICE = defaultdict(lambda: -1,\n {'terrible' : 0.00,\n 'poor' : 0.05,\n 'good' : 0.10,\n 'great' : 0.15,\n 'excellent': 0.20 })\n\ndef calculate_tip(amount, rating):\n value = SERVICE[rating.lower()]\n return ceil(amount * value) if value >= 0 else 'Rating not recognised'", "def calculate_tip(amount, rating):\n dict = {\"terrible\": 0,\n \"poor\": 5,\n \"good\": 10,\n \"great\": 15,\n \"excellent\": 20}\n try:\n result = float(amount) / float(100) * dict[rating.lower()]\n if result != int(str(result).split(\".\")[0]):\n return int(str(result).split(\".\")[0]) + 1\n return int(result)\n except KeyError:\n return 'Rating not recognised'", "from math import ceil\n\nRATES = {\"terrible\": 0, \"poor\": 5, \"good\": 10, \"great\": 15, \"excellent\": 20}\n\ndef calculate_tip(amount, rating):\n r = rating.lower()\n return 'Rating not recognised'if r not in RATES else ceil(RATES[r]/100.0*amount)", "import math\ndef calculate_tip(amount, rating):\n rates = {'terrible': 0, 'poor': 0.05, 'good': 0.1, 'great': 0.15, 'excellent':0.2}\n if rating.lower() not in rates:\n return \"Rating not recognised\"\n else:\n return math.ceil(amount * rates[rating.lower()])", "def calculate_tip(amount, rating):\n import math\n r = {'terrible': 0, 'poor': 5, 'good': 10, 'great': 15, 'excellent': 20}\n if not rating or rating.lower() not in r:\n return 'Rating not recognised'\n else:\n return math.ceil(amount * r[rating.lower()] / 100.0)", "def calculate_tip(amount, rating):\n from math import ceil\n\n # Rating is case insensitive\n rating = rating.lower()\n\n ratingMap = {\n 'terrible' : 0.0,\n 'poor' : 0.05,\n 'good' : 0.10,\n 'great' : 0.15,\n 'excellent' : 0.20\n }\n\n return ceil(amount * ratingMap[rating]) if rating in ratingMap else 'Rating not recognised'", "import math\ndef calculate_tip(amount, rating):\n tipTypes = [\"terrible\",\"poor\",\"good\",\"great\",\"excellent\"]\n if rating.lower() in tipTypes:\n return math.ceil(amount * tipTypes.index(rating.lower())*0.05)\n else: return \"Rating not recognised\"", "from math import ceil\n\ndef calculate_tip(amount, rating):\n tips, rating = 'terrible poor good great excellent'.split(), rating.lower()\n return ceil(amount * tips.index(rating) * .05) if rating in tips else 'Rating not recognised'", "calculate_tip = lambda a,r, p=[\"terrible\",\"poor\",\"good\",\"great\",\"excellent\"]: int(a*p.index(r.lower())*0.05+0.99) if r.lower() in p else \"Rating not recognised\"", "import math\ndef calculate_tip(amount, rating):\n ratings = {\n \"Terrible\": 0,\n \"Poor\": .05,\n \"Good\": .10,\n \"Great\": .15,\n \"Excellent\":.20\n }\n \n try:\n return math.ceil(amount * ratings.get(rating.title()))\n except:\n return \"Rating not recognised\"", "import math\n\ndef calculate_tip(amount, rating):\n rating = rating.lower()\n if (rating == 'terrible'):\n terrible = int(amount)*0\n terrible = math.ceil(terrible)\n return (terrible)\n elif (rating =='poor'):\n poor = int(amount)*0.05\n poor = math.ceil(poor)\n return (poor)\n elif (rating =='good'):\n good = int(amount)*0.1\n good = math.ceil(good)\n return (good)\n elif (rating =='great'):\n great = int(amount)*0.15\n great = math.ceil(great)\n return (great)\n elif (rating =='excellent'):\n excellent = int(amount)*0.20\n excellent = math.ceil(excellent)\n return (excellent)\n else:\n return(\"Rating not recognised\")", "import math\n\ndef calculate_tip(amount, rating):\n rating = rating.lower()\n tip = {\n \"terrible\": 0,\n \"poor\": 0.05,\n \"good\": 0.10,\n \"great\":0.15,\n \"excellent\": 0.20\n }\n return math.ceil(amount * tip[rating]) if rating in tip else \"Rating not recognised\"\n \n", "import math\n\ndef calculate_tip(amount, rating):\n service_perc = {\n \"terrible\": 0,\n \"poor\": 0.05,\n \"good\": 0.1,\n \"great\": 0.15,\n \"excellent\": 0.2\n }\n try:\n return math.ceil(amount * service_perc[rating.lower()])\n except KeyError:\n return \"Rating not recognised\"", "import math \n\ndef calculate_tip(amount, rating):\n rating = rating.lower()\n \n if rating == \"terrible\":\n return 0\n if rating == \"poor\":\n return int(math.ceil(amount*.05))\n if rating == \"good\":\n return int(math.ceil(amount*.1))\n if rating == \"great\":\n return int(math.ceil(amount*.15))\n if rating == \"excellent\":\n return int(math.ceil(amount*.2))\n else:\n return \"Rating not recognised\"", "from math import ceil\nfrom typing import Union\n\ndef calculate_tip(amount: int, rating: str) -> Union[int, str]:\n \"\"\" Calculates how much you need to tip based on the total amount of the bill and the service. \"\"\"\n tips = {\n \"terrible\": 0,\n \"poor\": 5,\n \"good\": 10,\n \"great\": 15,\n \"excellent\": 20\n }\n tip = tips.get(rating.lower())\n if tip is None:\n return \"Rating not recognised\"\n return ceil(amount * (tip / 100))", "def calculate_tip(amount, rating):\n d = {'terrible':0,'poor':0.05,'good':0.1,'great':0.15,'excellent':0.2}\n try:\n return -(-amount * d[rating.lower()] // 1)\n except KeyError:\n return 'Rating not recognised'", "from math import ceil\ndef calculate_tip(amount, rating):\n return {\n 'terrible': 0,\n 'poor': ceil(amount * 0.05),\n 'good': ceil(amount * 0.1),\n 'great': ceil(amount * 0.15),\n 'excellent': ceil(amount * 0.2)}.get(rating.lower(), 'Rating not recognised')", "calculate_tip=lambda a,r,R=\"terrible poor good great excellent\".split():int(\nR.index(r.lower())*a*.05+1-1e-9)if r.lower()in R else\"Rating not recognised\"", "import math\n\ndef calculate_tip(amount, rating):\n try:\n return math.ceil([\"terrible\", \"poor\", \"good\", \"great\", \"excellent\"].index(rating.lower()) * 0.05 * amount)\n except:\n return \"Rating not recognised\"", "from math import ceil; calculate_tip = lambda amount, rating: ceil(amount*[\"terrible\", \"poor\", \"good\", \"great\", \"excellent\"].index(rating.lower())*0.05) if rating.lower() in [\"terrible\", \"poor\", \"good\", \"great\", \"excellent\"] else \"Rating not recognised\"", "import math\ndef calculate_tip(amount, rating):\n bruh = {\n 'terrible': 0,\n 'poor': math.ceil(amount*.05),\n 'good': math.ceil(amount*.1),\n 'great': math.ceil(amount*.15),\n 'excellent': math.ceil(amount*.2)\n }\n sobaka = rating.lower()\n return bruh.get(sobaka) if sobaka in bruh.keys() else 'Rating not recognised'", "import math\ndef calculate_tip(amount, rating):\n ratings = [\"terrible\", \"poor\", \"good\", \"great\", \"excellent\"]\n index = ratings.index(rating.lower()) if rating.lower() in ratings else -1\n return math.ceil(amount * index * 0.05) if index != -1 else \"Rating not recognised\"", "def calculate_tip(amount, rating):\n import math\n tips = {'terrible': 1.0, 'poor': 1.05, 'good': 1.10, 'great': 1.15, 'excellent': 1.20}\n if rating.lower() in tips:\n return math.ceil(tips[rating.lower()] * amount - amount)\n else:\n return 'Rating not recognised'\n", "import math\ndef calculate_tip(amount, rating):\n r = {'terrible':0, 'poor':0.05, 'good':0.1, 'great': 0.15, 'excellent':0.2}.get(rating.lower(), -1)\n return 'Rating not recognised' if r == -1 else math.ceil(amount*r) ", "from math import ceil\n\nRATES = ('terrible', 'poor', 'good', 'great', 'excellent')\n\ndef calculate_tip(amount, rating):\n return {name: ceil(rate * amount * .05) for rate, name in enumerate(RATES)}.get(rating.lower(), \"Rating not recognised\")\n", "from math import ceil\n\nRATES = (('terrible', 0), ('poor', .05), ('good', .1), ('great', .15), ('excellent', .2))\n\ndef calculate_tip(amount, rating):\n return {name: ceil(rate * amount) for name, rate in RATES}.get(rating.lower(), \"Rating not recognised\")", "from math import ceil\n\n\ndef calculate_tip(amount, rating):\n service = {'terrible': 0, 'poor': .05, 'good': .10, 'great': .15, 'excellent': .20}\n tip = service.get(rating.lower(), 'Rating not recognised')\n return tip if isinstance(tip, str) else ceil(tip*amount)", "calculate_tip = lambda a, r, t={'excellent': .20, 'great': .15, 'good': .10, 'poor': .05, 'terrible': 0}, m=__import__('math'): m.ceil(a * t[r.lower()]) if r.lower() in t.keys() else 'Rating not recognised'", "import math\n\ndef calculate_tip(amount, rating):\n ratings = {\"terrible\": 0, \"poor\": 0.05, \"good\": 0.1, \"great\": 0.15, \"excellent\": 0.2}\n return math.ceil(amount * ratings.get(rating.lower())) if rating.lower() in ratings else \"Rating not recognised\"", "from math import ceil\ndef calculate_tip(amount, rating):\n tips = {'terrible' : 0, 'poor' : 5, 'good' : 10, 'great' : 15, 'excellent' : 20}\n return ceil(amount*tips[rating.lower()]/100) if rating.lower() in tips else \"Rating not recognised\"", "import math\n\ndef calculate_tip(amount, rating):\n tips = {'terrible': 0, 'poor': 5, 'good': 10, 'great': 15, 'excellent': 20}\n return math.ceil(tips[rating.lower()] / 100.0 * amount) if rating.lower() in tips else 'Rating not recognised'", "import math\ndef calculate_tip(amount, rating):\n str_rating = rating.lower()\n \n \n dict = {\n 'terrible': 0,\n 'poor': 5,\n 'good': 10,\n 'great': 15,\n 'excellent': 20\n \n }\n if str_rating in dict: \n result = ((amount * dict[str_rating]) / 100)\n return math.ceil(result)\n else:\n return \"Rating not recognised\"", "import math\ndef calculate_tip(amount, rating):\n ratings_dict = {\"terrible\": 0, \"poor\": 0.05, \"good\": 0.10, \"great\":0.15, \"excellent\":0.20}\n if rating.lower() not in ratings_dict.keys():\n return \"Rating not recognised\"\n else:\n return math.ceil(ratings_dict.get(rating.lower())*amount)", "import math\nd = {\n \n 'terrible': 0,\n 'poor': 5,\n 'good': 10,\n 'great': 15,\n 'excellent': 20,\n 'bla': 'Rating not recognised'\n}\n\ndef calculate_tip(amount, rating):\n rating = rating.lower()\n if rating in d.keys():\n return math.ceil((amount * d.get(rating)) / 100)\n else:\n return 'Rating not recognised'", "def calculate_tip(amount, rating):\n ratings_dict = {\n 'terrible': 0,\n 'poor': 5,\n 'good': 10,\n 'great': 15,\n 'excellent': 20\n }\n return int((amount / 100) * ratings_dict[rating.lower()] + 0.99) if rating.lower() in ratings_dict.keys() else 'Rating not recognised'", "def calculate_tip(amount, rating):\n from math import ceil\n if rating.lower() == \"terrible\":\n return 0\n if rating.lower() == \"poor\":\n return ceil(int(amount)/100*5)\n if rating.lower() == \"good\":\n return ceil(int(amount)/100*10)\n if rating.lower() == \"great\":\n return ceil(int(amount)/100*15)\n if rating.lower() == \"excellent\":\n return ceil(int(amount)/100*20)\n else:\n return \"Rating not recognised\"", "import math\n\ndef calculate_tip(amount, rating):\n case = {\n 'terrible' : 0,\n 'poor' : .05,\n 'good' : .1,\n 'great' : .15,\n 'excellent' : .2,\n } \n return 'Rating not recognised' if rating.lower() not in case else math.ceil(amount * case.get(rating.lower()))", "import math\n\ndef calculate_tip(amount, rating):\n d = {\n 'terrible' : 0.0,\n 'poor' : 0.05,\n 'good' : 0.10,\n 'great' : 0.15,\n 'excellent' : 0.20\n }\n return 'Rating not recognised' if rating.lower() not in d.keys() else math.ceil(amount * d.get(rating.lower()))", "import math\n\ndef calculate_tip(amount, rating):\n factor = 0\n rating = rating.lower()\n if (rating == \"terrible\"):\n pass\n elif (rating == \"poor\"):\n factor = 0.05\n elif (rating == \"good\"):\n factor = 0.1\n elif (rating == \"great\"):\n factor = 0.15\n elif (rating == \"excellent\"):\n factor = 0.2\n else:\n return 'Rating not recognised'\n return math.ceil(amount * factor)", "import math\ndef calculate_tip(amount, rating):\n #your code here\n c=rating.capitalize()\n if(c==\"Poor\" or \"Terrible\" or \"Good\" or \"Great\" or \"Excellent\" ):\n if(c==\"Poor\"):\n return math.ceil(amount*(5/100))\n elif(c==\"Excellent\"):\n return math.ceil(amount*(20/100))\n elif(c==\"Great\"):\n return math.ceil(amount*(15/100))\n elif(c==\"Good\"):\n return math.ceil(amount*(10/100))\n elif(c==\"Terrible\"):\n return 0\n return 'Rating not recognised'", "dict = {\n\"terrible\": 0.0,\n\"poor\": 0.05,\n\"good\": 0.1,\n\"great\": 0.15,\n\"excellent\": 0.2\n}\n \nimport math\n\n \ndef calculate_tip(amount, rating):\n try:\n return math.ceil(float(amount) * dict[rating.lower()])\n except:\n return 'Rating not recognised'", "from math import ceil\n\ndef calculate_tip(amount, rating):\n per = {\n \"terrible\": 0,\n \"poor\": 0.05,\n \"good\": 0.1,\n \"great\": 0.15,\n \"excellent\": 0.2\n }.get(rating.lower(), None)\n \n return ceil(amount * per) if per != None else 'Rating not recognised'\n", "import math\n\ndef calculate_tip(amount, rating):\n \n rating=rating.lower()\n \n result_2=\"Rating not recognised\"\n result=-1\n \n if rating==\"poor\":\n result=amount*0.05\n elif rating== \"good\":\n result=amount*0.1\n elif rating== \"great\": \n result=amount*0.15\n elif rating== \"excellent\": \n result=amount*0.2\n elif rating==\"terrible\":\n result=0\n \n \n \n \n if result==-1:\n result=result_2\n \n if rating not in (\"poor\",\"excellent\",\"great\",\"good\",\"terrible\") :\n return 'Rating not recognised'\n else:\n return math.ceil(result)", "import math\ndef calculate_tip(amount, rating):\n if rating.lower()==\"poor\":\n return math.ceil(0.05*amount)\n if rating.lower()==\"good\":\n return math.ceil(0.1*amount)\n if rating.lower()==\"great\":\n return math.ceil(0.15*amount)\n if rating.lower()==\"excellent\":\n return math.ceil(0.2*amount)\n if rating.lower()==\"terrible\":\n return 0\n return 'Rating not recognised'", "def calculate_tip(amount, rating):\n import math\n table = {\n \"terrible\": 0,\n \"poor\": 0.05,\n \"good\": .1,\n \"great\": 0.15,\n \"excellent\": .2\n }\n rating = rating.lower()\n if rating in table:\n return(math.ceil(amount * table[rating]))\n else:\n return(\"Rating not recognised\")", "def calculate_tip(amount, rating):\n \n error = 'Rating not recognised'\n ratings = {\n 'terrible' : 0,\n 'poor' : 0.05,\n 'good' : 0.1,\n 'great' : 0.15,\n 'excellent': 0.2, \n }\n\n try:\n if isinstance(amount, str):\n return error\n\n v = ratings[rating.lower()]*amount\n\n if not v % 2 == 0: \n return int(v+(1-(v%1)))\n else:\n return int(v)\n \n except KeyError:\n return error", "from math import ceil\n\nd = {\n \"terrible\":0, \"poor\":5, \"good\":10, \"great\":15, \"excellent\":20 \n}\n\ndef calculate_tip(amount, rating):\n #your code here\n rating = rating.lower()\n if rating not in d.keys():\n return 'Rating not recognised'\n else:\n return ceil(amount*d[rating]/100)", "from math import ceil\n\ndef calculate_tip(amount, rating):\n if rating.lower() == \"excellent\":\n return ceil(amount * 0.2)\n elif rating.lower() == \"great\":\n return ceil(amount * 0.15)\n elif rating.lower() == \"good\":\n return ceil(amount * 0.1)\n elif rating.lower() == \"poor\":\n return ceil(amount * 0.05)\n elif rating.lower() == \"terrible\":\n return 0\n return \"Rating not recognised\"", "import math\ndef calculate_tip(amount, rating):\n ratings = {'terrible': 0, 'poor': 0.05, 'good': 0.1, 'great': 0.15, 'excellent': 0.2}\n return math.ceil(amount * ratings.get(rating.lower(), 0)) if rating.lower() in ratings else 'Rating not recognised'", "from math import ceil\ndef calculate_tip(amount, rating):\n try:\n tip = {'terrible': 0, 'poor': 0.05, 'good': 0.1, 'great': 0.15, 'excellent': 0.2}.get(rating.lower())\n return ceil(amount * tip)\n except:\n return 'Rating not recognised'", "from math import ceil\n\n\ndef calculate_tip(amount, rating):\n TIP = {'terrible': 0, 'poor': 5, 'good': 10, 'great': 15, 'excellent': 20}.get(rating.lower(), None)\n if TIP == None:\n return 'Rating not recognised'\n return ceil((amount * TIP) / 100)", "import math\n\nrates = {\n 'terrible': 0,\n 'poor': 0.05,\n 'good': 0.1,\n 'great': 0.15,\n 'excellent': 0.2\n}\n\ndef calculate_tip(amount, rating):\n rating = rating.lower()\n \n return math.ceil(amount * rates[rating]) if rating in rates else 'Rating not recognised'\n", "import math \ndef calculate_tip(amount, rating):\n return math.ceil((amount*5)/100) if rating.lower() == \"poor\" else 0 if rating.lower() == \"terrible\" else math.ceil((amount*10)/100) if rating.lower() == \"good\" else math.ceil((amount*15)/100) if rating.lower() == \"great\" else math.ceil((amount*20)/100) if rating.lower() == \"excellent\" else \"Rating not recognised\"", "import numpy as np\n\nd = {\n 'Terrible':0,\n 'Poor':0.05,\n 'Good':0.1,\n 'Great':0.15,\n 'Excellent':0.2\n}\n\ndef calculate_tip(amount, rating):\n try:\n return np.ceil(amount * d[rating.title()])\n except:\n return \"Rating not recognised\"", "import math\ndef calculate_tip(amount, rating):\n rating=rating.lower() \n service={'terrible':0, 'poor':0.05, 'good':0.10, 'great':0.15, 'excellent':0.20}\n \n if rating in service:\n return(math.ceil(amount*service[rating]))\n else:\n return('Rating not recognised')\n \n", "tip = {\n 'terrible': 0,\n 'poor': 0.05,\n 'good': 0.1,\n 'great': 0.15,\n 'excellent': 0.2\n}\nimport math\ndef calculate_tip(amount, rating):\n rating = rating.lower()\n if rating not in tip:\n return \"Rating not recognised\"\n return math.ceil(amount * tip[rating])", "import math\n\ndef calculate_tip(amount, rating):\n r = {\n 'terrible': 0,\n 'poor': 5,\n 'good': 10,\n 'great': 15,\n 'excellent': 20, \n }\n \n p = r.get(rating.lower(), 'Rating not recognised')\n \n try:\n return math.ceil(amount * p / 100)\n except:\n return p", "import math\n \ndef calculate_tip(amount, rating):\n dict={\"terrible\":0,\"poor\":0.05,\"good\":0.10,\"great\":0.15,\"excellent\":0.20}\n return math.ceil(amount*dict[rating.lower()]) if rating.lower() in dict else \"Rating not recognised\"", "import math\ndef calculate_tip(amount, rating):\n if(rating.lower()==\"poor\".lower()):\n a=amount*(5/100)\n return math.ceil(a)\n elif(rating.lower()==\"Excellent\".lower()):\n a=amount*(20/100)\n return math.ceil(a)\n elif(rating.lower()==\"Great\".lower()):\n a=amount*(15/100)\n return math.ceil(a)\n elif(rating.lower()==\"Good\".lower()):\n a=amount*(10/100)\n return math.ceil(a)\n elif(rating.lower()==\"terrible\".lower()):\n return 0\n else:\n return \"Rating not recognised\"", "import math\ndef calculate_tip(amount, rating):\n \"\"\"(^-__-^)\"\"\"\n dic = {\"terrible\": 0, \"poor\": 5, \"good\": 10, \"great\": 15, \"excellent\": 20}\n return math.ceil((amount / 100) * dic.get(rating.lower())) if rating.lower() in dic else 'Rating not recognised'\n", "import math\ndef calculate_tip(amount, rating):\n try:\n k = {'terrible': 0, 'poor': 0.05, 'good': 0.1, 'great': 0.15, 'excellent': 0.20}[rating.lower()]*amount\n except:\n return 'Rating not recognised'\n return math.ceil(k)", "from math import ceil\n\ndef calculate_tip(amount, rating):\n percent = {\"terrible\": 0, \"poor\": 5, \"good\": 10, \"great\": 15, \"excellent\": 20}\n tip = percent.get(rating.lower())\n try:\n return ceil(amount*tip/100)\n except:\n return \"Rating not recognised\"", "def calculate_tip(a, r):\n tp = {\"terrible\": 0, \"poor\": 5, \"good\": 10, \"great\": 15, \"excellent\": 20}\n if tp.get(r.lower(), None) != None: return int(a*tp[r.lower()]/100 + .99)\n return 'Rating not recognised' ", "import math\ndef calculate_tip(amount, rating):\n if rating.lower() == 'poor':\n return math.ceil((amount / 100) * 5)\n elif rating.lower() == 'good':\n return math.ceil((amount / 100) * 10)\n elif rating.lower() == 'great':\n return math.ceil((amount / 100) * 15)\n elif rating.lower() == 'excellent':\n return math.ceil((amount / 100) * 20)\n elif rating.lower() not in ['poor', 'good', 'great', 'excellent', 'terrible']:\n return 'Rating not recognised'\n else:\n return 0", "import math\ndef calculate_tip(amount, rating):\n tip={\"Terrible\":0,\n \"Poor\":5/100,\n \"Good\":10/100,\n \"Great\":15/100,\n \"Excellent\":20/100}\n\n try:\n return math.ceil(int(amount) * (tip[rating.title()]))\n except:\n return \"Rating not recognised\"", "import math\n\ndef calculate_tip(amount, rating):\n tips = {\"terrible\" : 0,\n \"poor\" : 0.05,\n \"good\" : 0.1,\n \"great\" : 0.15,\n \"excellent\": 0.2}.get(rating.lower(), None)\n return math.ceil(amount * tips) if tips is not None else 'Rating not recognised'\n", "from math import ceil\n\ndef calculate_tip(amount, rating):\n tip = ceil(amount * {\"terrible\": 0, \"poor\": 0.05, \"good\": 0.1, \"great\": 0.15, \"excellent\": 0.20}.get(rating.lower(), -1))\n return tip if tip >= 0 else \"Rating not recognised\"", "import math\ndef calculate_tip(amount, rating):\n \n tips = {'Terrible': 0,\n 'Poor': 0.05,\n 'Good': 0.1,\n 'Great': 0.15,\n 'Excellent': 0.2\n }\n return math.ceil(amount*tips[rating.capitalize()]) if rating.capitalize() in tips else 'Rating not recognised'\n", "import math\n\ndef calculate_tip(amount, rating):\n rating = rating.lower()\n if rating == \"terrible\":\n return math.ceil(amount*0)\n if rating == \"poor\":\n return math.ceil(amount*0.06)\n if rating == \"good\":\n return math.ceil(amount*0.1)\n if rating == \"great\":\n return math.ceil(amount*0.15)\n if rating == \"excellent\":\n return math.ceil(amount*0.2)\n else:\n return 'Rating not recognised'\n \n", "from math import ceil\n\ndef calculate_tip(amount, rating):\n ratings = {\n \"terrible\": 0,\n \"poor\": 5,\n \"good\": 10,\n \"great\": 15,\n \"excellent\": 20,\n }\n if rating.lower() not in ratings.keys(): return \"Rating not recognised\"\n return ceil(ratings.get(rating.lower()) * amount / 100)", "from math import ceil\ndef calculate_tip(amount, rating):\n return {'terrible':0,'poor':ceil(amount*(0.05)),'good':ceil(amount*(1/10)),'great':ceil(amount*(15/100)),'excellent':ceil(amount*(1/5))}.get(rating.lower(),'Rating not recognised')\n\n \n", "from math import ceil\ndef calculate_tip(amount, rating):\n dict={\n'Terrible': 0,\n'Poor': 0.05,\n'Good': 0.1,\n'Great': 0.15,\n'Excellent': 0.2\n }\n return ceil(amount * dict.get(rating.capitalize())) if dict.get(rating.capitalize(),'nothing')!='nothing' else 'Rating not recognised'", "import math\ndef calculate_tip(amount, rating):\n rating = rating.lower()\n if rating == \"poor\":\n return math.ceil(amount*0.05)\n elif rating == \"terrible\":\n return 0\n elif rating == \"good\":\n return math.ceil(amount*0.1)\n elif rating == \"great\":\n return math.ceil(amount*0.15)\n elif rating == \"excellent\":\n return math.ceil(amount*0.2)\n else:\n return \"Rating not recognised\"", "import math\ndef calculate_tip(amount, rating):\n calc_tip = {\"terrible\":0, \"poor\":0.05, \"good\":0.10, \"great\":0.15, \"excellent\":0.20}\n if rating.lower() in calc_tip:\n res = amount* calc_tip[rating.lower()]\n if type(res) == float: res = math.ceil(res) \n return res\n else: return \"Rating not recognised\"", "from math import ceil\ndef calculate_tip(amount, rating):\n if rating.lower() == 'terrible':\n return ceil(amount * 0)\n elif rating.lower() == 'poor':\n return ceil(amount * 0.05)\n elif rating.lower() == 'good':\n return ceil(amount * 0.1)\n elif rating.lower() == 'great':\n return ceil(amount * 0.15)\n elif rating.lower() == 'excellent':\n return ceil(amount * 0.2)\n else:\n return \"Rating not recognised\"\n", "import math\n\ndef calculate_tip(amount, rating):\n x = {\n 'terrible': 0,\n 'poor': 5,\n 'good': 10,\n 'great': 15,\n 'excellent': 20\n }.get(rating.lower())\n return math.ceil(x * amount/100) if x != None else 'Rating not recognised'", "from math import ceil\ndef calculate_tip(amount, rating):\n dict_ = {'excellent': .2, 'great': .15, 'good': .1, 'poor': .05, 'terrible': 0}\n if rating.lower() in dict_:\n return ceil(amount * dict_[rating.lower()])\n else:\n return 'Rating not recognised'", "import math\n\ndef calculate_tip(amount, rating):\n d = {'terrible': 0,\n 'poor': 0.05,\n 'good': 0.10,\n 'great': 0.15,\n 'excellent': 0.20}\n\n for key, val in d.items():\n if key == rating.lower():\n return math.ceil(amount * val)\n return 'Rating not recognised'", "import math\ndef calculate_tip(amount, rating):\n rating = rating.lower()\n if rating == \"poor\":\n return math.ceil(amount*0.05)\n elif rating == \"good\":\n return math.ceil(amount * 0.1)\n elif rating == \"great\":\n return math.ceil(amount * 0.15)\n elif rating == \"excellent\":\n return math.ceil(amount * 0.2)\n elif rating == \"terrible\":\n return math.ceil(amount * 0)\n else:\n return \"Rating not recognised\"", "import math\ndef calculate_tip(amount, rating):\n amount = math.ceil(amount)\n if rating.title() == 'Terrible':\n return amount * 0\n elif rating.title() == 'Poor':\n return math.ceil(amount * 0.05)\n elif rating.title() == 'Good':\n return math.ceil(amount * 0.10)\n elif rating.title() == 'Great':\n return math.ceil(amount * 0.15)\n elif rating.title() == 'Excellent':\n return math.ceil(amount * 0.2)\n else:\n return 'Rating not recognised'", "import numpy as np\ndef calculate_tip(amount, rating):\n tips={'terrible': 0, 'poor':0.05, 'good': 0.1, 'great': 0.15, 'excellent':0.2}\n try:\n return np.ceil(tips[rating.lower()]*amount)\n except:\n return 'Rating not recognised'", "import math\n\ndef calculate_tip(amount, rating):\n rate = rating.lower()\n \n discount = 0\n discountTwo = amount * .05\n discountThree = amount * .10\n discountFour = amount * .15\n discountFive = amount * .20\n \n if rate == \"terrible\":\n return math.ceil(discount)\n elif rate == \"poor\":\n return math.ceil(discountTwo)\n elif rate == \"good\":\n return math.ceil(discountThree)\n elif rate == \"great\":\n return math.ceil(discountFour)\n elif rate == \"excellent\":\n return math.ceil(discountFive)\n return \"Rating not recognised\"", "from math import ceil\ndef calculate_tip(amount, rating):\n tab = {'terrible': 0, 'poor': 0.05, 'good': 0.1, 'great': 0.15, 'excellent': 0.2}\n mpl = tab.get(rating.lower(), -1)\n return ceil(amount * mpl) if mpl >= 0 else \"Rating not recognised\"", "from math import ceil\n\ndef calculate_tip(amount, rating):\n ratings = [\"terrible\",\"poor\",'good','great','excellent']\n if rating.lower() in ratings:\n tip = 5 * ratings.index(rating.lower())\n return ceil((tip/100) * amount)\n else:\n return \"Rating not recognised\"", "from math import ceil\n\ndef calculate_tip(amount, rating):\n rating_table = {\n 'Terrible': 0, 'Poor': 0.05, 'Good': 0.1, 'Great': 0.15, 'Excellent': 0.2\n }\n rating = rating.title()\n if rating in rating_table:\n return ceil(amount * rating_table.get(rating))\n else:\n return 'Rating not recognised'", "import math\ndef calculate_tip(amount, rating):\n rates = {\"terrible\":0, \"poor\":0.05, \"good\":0.1, \"great\":0.15,\"excellent\":0.2}\n \n return math.ceil(amount * rates[rating.lower()]) if rating.lower() in rates.keys() else \"Rating not recognised\"", "import math\ndef calculate_tip(amount, rating):\n legend=[(\"terrible\",0),(\"poor\",5),(\"good\",10),(\"great\",15),(\"excellent\",20)]\n for i in range (len(legend)):\n if rating.lower()==legend[i][0]:\n return math.ceil(amount*legend[i][1]/100)\n else:\n pass\n return \"Rating not recognised\"\n", "def calculate_tip(amount: int, rating: str) -> int:\n return {\n \"Terrible\": round((lambda x: x * 0.00)(amount) + 0.5),\n \"Poor\": round((lambda x: x * 0.05)(amount) + 0.5),\n \"Good\": round((lambda x: x * 0.10)(amount) + 0.5),\n \"Great\": round((lambda x: x * 0.15)(amount) + 0.5),\n \"Excellent\": round((lambda x: x * 0.20)(amount) + 0.5),\n }.get(rating.title(), \"Rating not recognised\")"]
{"fn_name": "calculate_tip", "inputs": [[30, "poor"], [20, "Excellent"], [20, "hi"], [107.65, "GReat"], [20, "great!"]], "outputs": [[2], [4], ["Rating not recognised"], [17], ["Rating not recognised"]]}
INTRODUCTORY
PYTHON3
CODEWARS
33,944
def calculate_tip(amount, rating):
7a57c2974eeb2b5b4b7ad27bf8e4aa64
UNKNOWN
We are interested in obtaining two scores from a given integer: **First score**: The sum of all the integers obtained from the power set of the digits of the given integer that have the same order E.g: ``` integer = 1234 ---> (1 + 2 + 3 + 4) + (12 + 13 + 14 + 23 + 24 + 34) + (123 + 124 + 134 + 234) + 1234 = 10 + 120 + 615 + 1234 = 1979 ``` **Second score**: The sum of all the integers obtained from the all the contiguous substrings of the given integer as a string. E.g. ``` integer = 1234 ---> (1 + 2 + 3 + 4) + (12 + 23 + 34) + (123 + 234) + 1234 = 10 + 69 + 357 + 1234 = 1670 ``` The first integer, higher than ```100```, that has both scores with ```3``` common divisors is ```204```. Its first score is ```258``` and the second one ```234```. The common divisors for both scores are ```2, 3, 6```. In fact the integers ```294``` and ```468``` are the ones in the range ```[100, 500]```, that have both scores with ```7``` common divisors, the maximum amount of common factors in that range. Your task in this kata is to create a function that may find the integer or integers that have the maximum amount of common divisors for the scores described above. The example given above will be: ```python find_int_inrange(100, 500) == [7, 294, 468] ``` As you can see, the function should receive the limits of a range [a, b], and outputs an array with the maximum amount of factors, ```max_am_div``` and the found numbers sorted ``` find_int_inrange(a, b) ----> [max_am_div, k1, k2, ...., kn] # k1 < k2 < ...< kn ``` The function may output only one number. ```python find_int_inrange(100, 300) == [7, 294] ``` Enjoy it! Features of the random tests: ``` 100 < a < b < 55000 ```
["score = lambda sub_gen: lambda n: sum(int(''.join(sub)) for length in range(1, len(str(n)) + 1) for sub in sub_gen(str(n), length))\nscore1 = score(__import__('itertools').combinations)\nscore2 = score(lambda s, r: (s[i: i+r] for i in range(len(s) - r + 1)))\n\ndivs = lambda n: set.union(*({d, n // d} for d in range(1, int(n ** .5) + 1) if not n % d)) - {1, n}\n\ndef find_int_inrange(a, b):\n div_range = [0]\n for n in range(a, b + 1):\n common_divisors = divs(score1(n)) & divs(score2(n))\n if len(common_divisors) > div_range[0]: div_range = [len(common_divisors)]\n if len(common_divisors) == div_range[0]: div_range.append(n)\n return div_range", "from itertools import combinations as C\nfrom functools import lru_cache as LC\nget_score1=LC(None)(lambda n:sum([sum([int(''.join(k)) for k in C(n, i)]) for i in range(1, len(n) + 1)]))\nget_score2=LC(None)(lambda n:sum(int(n[j:j + i]) for i in range(1, len(n) + 1) for j in range(len(n) - i + 1)))\nget_div=LC(None)(lambda n:set(sum([[i, n // i] for i in range(2, int(n ** .5) + 1) if not n % i], [])))\n@LC(None)\ndef find_int_inrange(a, b):\n d = {i:len(get_div(get_score1(str(i))) & get_div( get_score2(str(i)))) for i in range(a, b)}\n m = max(d.values())\n return [m]+sorted([i for i,j in d.items() if j==m]) #sorted for py 3.4", "from math import gcd\n\nbase1 = {3: (121, 22, 4),\n 4: (1331, 242, 44, 8),\n 5: (14641, 2662, 484, 88, 16)}\nbase2 = {3: (111, 22, 3),\n 4: (1111, 222, 33, 4),\n 5: (11111, 2222, 333, 44, 5)}\n\nmemo = {100: 0}\n\ndef find_int_inrange(a, b):\n for n in range(max(memo) + 1, b + 1):\n base = 3 if n < 1000 else 4 if n < 10000 else 5\n digits = [int(d) for d in str(n)]\n score1 = sum(b * d for b, d in zip(base1[base], digits))\n score2 = sum(b * d for b, d in zip(base2[base], digits))\n hcf = gcd(score1, score2)\n common = 0\n for factor in range(2, hcf + 1):\n if score1 % factor == score2 % factor == 0:\n common += 1\n memo[n] = common\n maxCommon, numbers = 0, []\n for n in range(a, b + 1):\n m = memo[n]\n if maxCommon < m:\n maxCommon, numbers = m, [n]\n elif maxCommon == m:\n numbers.append(n)\n return [maxCommon] + numbers", "from itertools import combinations\n\npwrdivs = lambda s: divisors(sum(sum(int(''.join(c)) for c in combinations(s, k)) for k in range(1, len(s)+1)))\nstrdivs = lambda s: divisors(sum(sum(int(s[i:i+k]) for i in range(len(s)-k+1)) for k in range(1, len(s)+1))) \n\ndef find_int_inrange(a, b):\n d = {k:len(pwrdivs(str(k)) & strdivs(str(k))) for k in range(a, b+1)}\n mx = max(d.values())\n return [mx] + [k for k in d if d[k] == mx]\n \ndef divisors(n):\n f, d = [], 2\n while d*d <= n:\n while n % d == 0:\n f, n = f +[d], n//d\n d += 1\n if n > 1: f.append(n)\n s, f = set(), sorted(f)\n [[s.add(c) for c in combinations(f, k)] for k in range(1, len(f))] \n return s", "from itertools import combinations\nfrom math import gcd\ndef first(n):\n s=str(n)\n r=0\n for i in range(1,len(s)+1):\n for t in combinations(s,i):\n r+=int(''.join(t))\n return r\n\ndef second(n):\n s=str(n)\n r=0\n for i in range(1,len(s)+1):\n for j in range(len(s)-i+1):\n r+=int(s[j:j+i])\n return r\n\ndef common_divisors(n):\n f=first(n)\n s=second(n)\n g=gcd(f,s)\n r=1\n for x in range(2,int(g**0.5)+1):\n if g%x==0:\n if x*x==g:\n r+=1\n else:\n r+=2\n return r\n \nc=[common_divisors(x) for x in range(0,55000)]\n\ndef find_int_inrange(a, b):\n m=max(c[a:b+1])\n r=[m]\n for x in range(a,b+1):\n if c[x]==m:\n r.append(x)\n return r", "from itertools import combinations as C\nfrom functools import lru_cache as LC\nget_score1=LC(None)(lambda n:sum([sum([int(''.join(k)) for k in C(n, i)]) for i in range(1, len(n) + 1)]))\nget_score2=LC(None)(lambda n:sum(int(n[j:j + i]) for i in range(1, len(n) + 1) for j in range(len(n) - i + 1)))\nget_div=LC(None)(lambda n:set(sum([[i, n // i] for i in range(2, int(n ** .5) + 1) if not n % i], [])))\n@LC(None)\ndef find_int_inrange(a, b):\n d = {i:len(get_div(get_score1(str(i))) & get_div( get_score2(str(i)))) for i in range(a, b)}\n m = max(d.values())\n return [m]+[i for i,j in d.items() if j==m]", "from itertools import combinations\nfrom functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef factors(x):\n return {v for i in range(2, int(x**0.5)+1) if not x%i for v in (i, x//i)}\n\n@lru_cache(maxsize=None)\ndef nb_common_div(s):\n l = len(s)\n s1 = sum(int(''.join(v)) for i in range(l) for v in combinations(s, i+1))\n s2 = sum(int(''.join(s[i:j+1])) for i in range(l) for j in range(i, l))\n f1, f2 = factors(s1), factors(s2)\n return len(f1 & f2)\n\ndef find_int_inrange(a, b):\n best, res = -1, []\n for x in range(a, b+1):\n nb = nb_common_div(str(x))\n if nb > best: best, res = nb, [nb, x]\n elif nb == best: res.append(x)\n return res", "class Eq:\n def __eq__(self, _):\n return True\n\ndef find_int_inrange(*args, **kwargs):\n return Eq()", "import itertools\nimport numpy as np\n\ndef sum_1(n):\n ketas = list(map(int, str(n)))\n pattern = [itertools.combinations(ketas, i+1) for i in range(len(ketas))]\n pattern = list(itertools.chain.from_iterable(pattern))\n pattern = [''.join(map(str,i)) for i in pattern]\n sum = np.sum([int(i) for i in pattern])\n return sum\n\ndef sum_2(n):\n ketas = list(map(int, str(n)))\n i_s = itertools.combinations(list(range(len(ketas) + 1)), 2)\n pattern_i = [ketas[i:j] for i, j in i_s]\n sum = np.sum([int(''.join(map(str,i))) for i in pattern_i])\n return sum\n\ndef common_divisors(a, b):\n while b:\n a, b = b, a % b\n d = 1\n while a % 2 == 0:\n d += 1\n a /= 2\n e = 3\n while a > 1:\n c = 1\n while a % e == 0:\n c += 1\n a /= e\n d *= c\n e += 2\n return d - 1\n\ndef find_int_inrange(a, b):\n # your code here\n maxlen = 0\n result = []\n for i in range(a,b):\n divisors = common_divisors(sum_1(i), sum_2(i))\n if divisors > maxlen:\n maxlen = divisors\n result = [maxlen, i]\n elif divisors == maxlen:\n result.append(i)\n return result\n"]
{"fn_name": "find_int_inrange", "inputs": [[100, 300], [100, 500], [300, 900]], "outputs": [[[7, 294]], [[7, 294, 468]], [[7, 468, 834]]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,585
def find_int_inrange(a, b):
e4d77e80b9c1336a3147354b36093d91
UNKNOWN
### Count the number of Duplicates Write a function that will return the count of **distinct case-insensitive** alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits. ### Example "abcde" -> 0 `# no characters repeats more than once` "aabbcde" -> 2 `# 'a' and 'b'` "aabBcde" -> 2 ``# 'a' occurs twice and 'b' twice (`b` and `B`)`` "indivisibility" -> 1 `# 'i' occurs six times` "Indivisibilities" -> 2 `# 'i' occurs seven times and 's' occurs twice` "aA11" -> 2 `# 'a' and '1'` "ABBA" -> 2 `# 'A' and 'B' each occur twice`
["def duplicate_count(s):\n return len([c for c in set(s.lower()) if s.lower().count(c)>1])\n", "# My 1st Solution \n\ndef duplicate_count(text): \n count = 0 \n counted = [] \n test = list(text.lower()) \n for i, c in enumerate(test): \n if test.count(test[i]) >= 2 and counted.count(test[i]) == 0: \n count += 1 \n counted.append(test[i]) \n test.remove(test[i]) \n return count \n", "def duplicate_count(text):\n seen = set()\n dupes = set()\n for char in text:\n char = char.lower()\n if char in seen:\n dupes.add(char)\n seen.add(char)\n return len(dupes)", "from collections import Counter\n\ndef duplicate_count(text):\n return sum(1 for c, n in Counter(text.lower()).items() if n > 1)\n", "def duplicate_count(text):\n count = 0\n for c in set(text.lower()):\n if text.lower().count(c) > 1:\n count += 1\n return count\n", "from collections import Counter\n\ndef duplicate_count(text):\n counter = Counter(text.lower())\n return len([list(counter.keys()) for i in list(counter.values()) if i>1])\n", "def duplicate_count(text):\n text = text.lower()\n duplicates = []\n for i in text:\n if text.count(i) > 1 and i not in duplicates:\n duplicates.append(i) \n return len(duplicates)", "def duplicate_count(text):\n text = text.lower()\n return(sum([text.count(c) > 1 for c in set(text)]))\n", "from collections import Counter\n\ndef duplicate_count(text):\n return sum(v > 1 for v in Counter(text.lower()).values())\n", "def duplicate_count(text):\n n=0\n text=text.lower()\n for i in set(text):\n if text.count(i) >1:\n n+=1\n return n", "from re import findall\n\ndef duplicate_count(text):\n return (len(findall(\"(\\w)\\\\1+\", \"\".join(sorted(text.upper())))))\n"]
{"fn_name": "duplicate_count", "inputs": [[""], ["abcde"], ["abcdeaa"], ["abcdeaB"], ["Indivisibilities"]], "outputs": [[0], [0], [1], [2], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,899
def duplicate_count(text):
b5abac06f070b28d5056d437ee91b515
UNKNOWN
The [half-life](https://en.wikipedia.org/wiki/Half-life) of a radioactive substance is the time it takes (on average) for one-half of its atoms to undergo radioactive decay. # Task Overview Given the initial quantity of a radioactive substance, the quantity remaining after a given period of time, and the period of time, return the half life of that substance. # Usage Examples ```if:csharp Documentation: Kata.HalfLife Method (Double, Double, Int32) Returns the half-life for a substance given the initial quantity, the remaining quantity, and the elasped time. Syntax public static double HalfLife( double quantityInitial,   double quantityRemaining, int time   ) Parameters quantityInitial Type: System.Double The initial amount of the substance. quantityRemaining Type: System.Double The current amount of the substance. time Type: System.Int32 The amount of time elapsed. Return Value Type: System.Double A floating-point number representing the half-life of the substance. ```
["from math import log\n\ndef half_life(N0, N, t):\n return t / log(N0/N, 2)", "from math import log2\n\ndef half_life(ini, rem, t):\n return t / log2(ini / rem)", "from math import log\n\n\ndef half_life(initial, remaining, time):\n return time*log(2.0)/log(initial/remaining)", "from math import log2\n\ndef half_life(initial, remaining, time):\n return time / log2(initial / remaining)", "from math import log2\n\ndef half_life(initial, remaining, time):\n return -time/log2(remaining/initial)", "import math\ndef half_life(q0, q1, t):\n return 1/(math.log(q0/q1)/(t*math.log(2)))", "from math import log; half_life=lambda i,r,t: t/log(i/r,2)", "import math\ndef half_life(initial, remaining, time):\n return time / math.log2( initial / remaining )", "from math import *\n\ndef half_life(initial, remaining, time):\n return time*log(.5) / log(remaining/initial)", "from math import log2 as lg\n\ndef half_life(initial, remaining, time):\n return time / lg(initial / remaining)"]
{"fn_name": "half_life", "inputs": [[10, 5, 1], [8, 4, 2], [12, 3, 2]], "outputs": [[1], [2], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,007
def half_life(initial, remaining, time):
c837317b40320464c40e05bbf74e7e6d
UNKNOWN
#Detail [Countdown](https://en.wikipedia.org/wiki/Countdown_(game_show) is a British game show with number and word puzzles. The letters round consists of the contestant picking 9 shuffled letters - either picking from the vowel pile or the consonant pile. The contestants are given 30 seconds to try to come up with the longest English word they can think of with the available letters - letters can not be used more than once unless there is another of the same character. #Task Given an uppercase 9 letter string, ```letters```, find the longest word that can be made with some or all of the letters. The preloaded array ```words``` (or ```$words``` in Ruby) contains a bunch of uppercase words that you will have to loop through. Only return the longest word; if there is more than one, return the words of the same lengths in alphabetical order. If there are no words that can be made from the letters given, return ```None/nil/null```. ##Examples ``` letters = "ZZZZZZZZZ" longest word = None letters = "POVMERKIA", longest word = ["VAMPIRE"] letters = "DVAVPALEM" longest word = ["VAMPED", "VALVED", "PALMED"] ```
["def longest_word(letters):\n try:\n word_list = [w for w in words if all(w.count(c) <= letters.count(c) for c in w)]\n largest = sorted([w for w in word_list if len(w) == len(max(word_list, key=len))])\n return largest if largest else None\n except:\n return None"]
{"fn_name": "longest_word", "inputs": [[""], ["MKMKMKMKM"], ["IIIWUGEZI"]], "outputs": [[null], [null], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
301
def longest_word(letters):
9cbc83f365669da33e39ecbf0b96c53d
UNKNOWN
# Task A lock has `n` buttons in it, numbered from `1 to n`. To open the lock, you have to press all buttons in some order, i.e. a key to the lock is a permutation of the first `n` integers. If you push the right button in the right order, it will be pressed into the lock. Otherwise all pressed buttons will pop out. When all buttons are pressed into the lock, it opens. Your task is to calculate the number of times you've got to push buttons in order to open the lock in the `worst-case scenario`. # Example For `n = 3`, the result should be `7`. ``` Let's assume the right order is 3-2-1. In the worst-case scenario, we press the buttons: Press 1, wrong, button 1 pop out Press 2, wrong, button 2 pop out Press 3, right, button 3 pressed in Press 1, wrong, button 1,3 pop out Press 3, right, button 3 pressed in Press 2, right, button 2 pressed in Press 1, right, button 1 pressed in We pressed button total 7 times.``` For `n = 4`, the result should be `14`. ``` Let's assume the right order is 4-3-2-1. In the worst-case scenario, we press the buttons: Press 1, wrong, button 1 pop out Press 2, wrong, button 2 pop out Press 3, wrong, button 3 pop out Press 4, right, button 4 pressed in Press 1, wrong, button 1,4 pop out Press 4, right, button 4 pressed in Press 2, wrong, button 2,4 pop out Press 4, right, button 4 pressed in Press 3, right, button 3 pressed in Press 1, wrong, button 1,3,4 pop out Press 4, right, button 4 pressed in Press 3, right, button 3 pressed in Press 2, right, button 2 pressed in Press 1, right, button 1 pressed in We pressed button total 14 times.``` # Input/Output - `[input]` integer `n` The number of buttons in the lock. `0 < n ≤ 2000` - `[output]` an integer The number of times you've got to push buttons in the `worst-case scenario`.
["def press_button(n):\n return (n*n+5)*n/6", "def press_button(n):\n return sum((n-i)*(i+1)-i for i in range(n))", "press_button=lambda n:sum(i*(n-i) for i in range(1,n))+n", "def press_button(n):\n return n + sum(i * (n-i) for i in range(1, n))", "def press_button(n):\n return n*(n**2 + 5)/6", "def press_button(n):\n return sum(i * (n - i) + 1 for i in range(1, n + 1))\n", "def press_button(n):\n return n*(n*n+5)/6", "press_button=lambda n:n*(n*n+5)/6", "def press_button(n):\n return n+sum([i*(n-i) for i in range(1,n+1)])"]
{"fn_name": "press_button", "inputs": [[1], [3], [4], [10], [2000]], "outputs": [[1], [7], [14], [175], [1333335000]]}
INTRODUCTORY
PYTHON3
CODEWARS
546
def press_button(n):
e06ff31299b233f06fc1093b921aac9f
UNKNOWN
Write a function which outputs the positions of matching bracket pairs. The output should be a dictionary with keys the positions of the open brackets '(' and values the corresponding positions of the closing brackets ')'. For example: input = "(first)and(second)" should return {0:6, 10:17} If brackets cannot be paired or if the order is invalid (e.g. ')(') return False. In this kata we care only about the positions of round brackets '()', other types of brackets should be ignored.
["def bracket_pairs(string):\n brackets = {}\n open_brackets = []\n\n for i, c in enumerate(string):\n if c == '(':\n open_brackets.append(i)\n elif c == ')':\n if not open_brackets:\n return False\n brackets[open_brackets.pop()] = i\n\n return False if open_brackets else brackets\n", "def bracket_pairs(string):\n res, open = {}, []\n for i,c in enumerate(string):\n if c == '(':\n open.append(i)\n if c == ')':\n try:\n res[open.pop()] = i\n except IndexError:\n return False\n return not open and res", "def bracket_pairs(stg):\n open, dic = [], {}\n for i, e in enumerate(stg):\n if e =='(':\n open.append(i)\n if e == ')':\n if not open:\n return False\n dic[open.pop(-1)] = i\n return False if open else dic\n\n", "def bracket_pairs(s):\n a, d = [], {}\n for i, x in enumerate(s):\n if x == \"(\":\n a.append(i)\n if x == \")\":\n if not a: return 0\n d[a.pop()] = i\n return not a and d", "def bracket_pairs(string):\n result = {}\n stack = []\n for i, c in enumerate(string):\n if c == ')':\n if not stack:\n return False\n result[stack.pop()] = i\n elif c == '(':\n stack.append(i)\n if stack:\n return False\n return result", "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[len(self.items)-1]\n\n def size(self):\n return len(self.items)\n\ndef bracket_pairs(s):\n l = len(s);\n stack = Stack(); i = 0; res = {}; flag = True\n while i < l and flag:\n if s[i] == \"(\": stack.push(i)\n elif s[i] == \")\":\n if stack.is_empty(): flag = False\n else: \n a = stack.pop()\n res[a] = i\n i += 1\n if flag and stack.is_empty(): return res\n return False", "def bracket_pairs(strng):\n matching_indexes = {}\n open_indexes = []\n for i, a in enumerate(strng):\n if a == '(':\n open_indexes.append(i)\n elif a == ')':\n try:\n matching_indexes[open_indexes.pop()] = i\n except IndexError:\n return False\n return matching_indexes if not open_indexes else False\n", "def bracket_pairs(string):\n opened = []\n result = {}\n for i, ch in enumerate(string):\n if ch == \"(\": \n opened.append((ch, i))\n elif ch == \")\":\n if not opened: return False\n result[opened[-1][1]] = i\n opened = opened[:-1]\n \n return False if opened else result\n", "def bracket_pairs(string):\n ob, res = [], {}\n \n for n,e in enumerate(string):\n if e == '(':\n ob.append(n)\n elif e == ')':\n if not ob:\n return False\n res[ob.pop()] = n\n return False if ob else res"]
{"fn_name": "bracket_pairs", "inputs": [["len(list)"], ["string"], [""], ["def f(x"], [")("], ["(a(b)c()d)"], ["f(x[0])"]], "outputs": [[{"3": 8}], [{}], [{}], [false], [false], [{"0": 9, "2": 4, "6": 7}], [{"1": 6}]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,304
def bracket_pairs(string):
9fbeee2b75d2d43813e4dde528e568d6
UNKNOWN
# Task Your task is to sort the characters in a string according to the following rules: ``` - Rule1: English alphabets are arranged from A to Z, case insensitive. ie. "Type" --> "epTy" - Rule2: If the uppercase and lowercase of an English alphabet exist at the same time, they are arranged in the order of oringal input. ie. "BabA" --> "aABb" - Rule3: non English alphabet remain in their original position. ie. "By?e" --> "Be?y" ``` # Input/Output `[input]` string `s` A non empty string contains any characters(English alphabets or non English alphabets). `[output]` a string A sorted string according to the rules above. # Example For `s = "cba"`, the output should be `"abc"`. For `s = "Cba"`, the output should be `"abC"`. For `s = "cCBbAa"`, the output should be `"AaBbcC"`. For `s = "c b a"`, the output should be `"a b c"`. For `s = "-c--b--a-"`, the output should be `"-a--b--c-"`. For `s = "Codewars"`, the output should be `"aCdeorsw"`.
["def sort_string(s):\n a = iter(sorted((c for c in s if c.isalpha()), key=str.lower))\n return ''.join(next(a) if c.isalpha() else c for c in s)", "import re\n\ndef sort_string(s):\n sortedChr = iter(sorted(re.sub(r'[^a-zA-Z]', '', s), key=str.lower))\n return re.sub(r'[a-zA-Z]', lambda m: next(sortedChr), s)", "def sort_string(s):\n alphas = [x for x in s if x.isalpha()]\n res = iter(sorted(alphas, key=lambda x: x.lower()))\n return ''.join(next(res) if x.isalpha() else x for x in s)", "def sort_string(stg):\n stg_ascii = (char for char in stg if char.isalpha())\n sorted_ascii = iter(sorted(stg_ascii, key=str.lower))\n return \"\".join(next(sorted_ascii) if char.isalpha() else char for char in stg)", "def sort_string(s):\n it = iter(sorted(filter(str.isalpha, s), key=str.lower))\n return ''.join(next(it) if c.isalpha() else c for c in s)", "from string import ascii_letters\n\nsortable = frozenset(ascii_letters)\n\ndef sort_string(s):\n sorted_chars = iter(sorted((c for c in s if c in sortable), key=str.lower))\n return ''.join(next(sorted_chars) if c in sortable else c for c in s)", "sort_string=lambda s: (lambda r: \"\".join(r.pop(0) if e.isalpha() else e for e in s))([e[0] for e in sorted(sorted([[k,i] for i,k in enumerate(s) if k.isalpha()],key=lambda a: a[1]),key=lambda a: a[0].lower())])", "def sort_string(s):\n it = iter(sorted([(i, x) for i, x in enumerate(s) if x.isalpha()], key=lambda p: (p[1].lower(), p[0])))\n return ''.join(next(it)[1] if x.isalpha() else x for x in s)", "def sort_string(s):\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n rule12 = list(sorted([x for x in s if x.lower() in alphabet], key=lambda i: alphabet.find(i.lower())))\n for i, sym in enumerate(s):\n if sym.lower() not in alphabet:\n rule12.insert(i, sym)\n return \"\".join(rule12)\n", "def sort_string(s):\n a = iter(sorted(filter(str.isalpha, s), key=str.lower))\n return \"\".join(next(a) if x.isalpha() else x for x in s)"]
{"fn_name": "sort_string", "inputs": [["a"], ["cba"], ["Cba"], ["cCBbAa"], ["!"], ["c b a"], ["-c--b--a-"], ["cbaCcC"], ["Codewars"], [" MkWD{RB=//k-^ J@,xH Vfi uAz+$ kV _[ }a!}%pSBwn !kKB (b q PQF +}wS .kfU r wFNEs#NsR UVMdG"]], "outputs": [["a"], ["abc"], ["abC"], ["AaBbcC"], ["!"], ["a b c"], ["-a--b--c-"], ["abcCcC"], ["aCdeorsw"], [" AaBB{Bb=//D-^ d@,Ef FfF GHi+$ Jk _[ }k!}%kkKkM !MnN (N p PqQ +}Rr .RSS s suUUV#VVW wwwxz"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,024
def sort_string(s):
68db11af8be74c469b5439767831db26
UNKNOWN
Implement a function which behaves like the 'uniq -c' command in UNIX. It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance together with the number of times a duplicate elements occurred in the original array. Example: ```python ['a','a','b','b','c','a','b','c'] --> [('a',2),('b',2),('c',1),('a',1),('b',1),('c',1)] ```
["from itertools import groupby\n\ndef uniq_c(seq): \n return [ (k,sum(1 for _ in g)) for k,g in groupby(seq)]", "\n\ndef uniq_c(s):\n lst = []\n c = 1\n for i in range(len(s)-1):\n if s[i] != s[i+1]:\n lst.append((s[i],c))\n c = 1\n else:\n c += 1\n if s:\n lst.append((s[-1],c))\n return lst", "from itertools import groupby\n\n\ndef uniq_c(seq):\n return [(chr, len(list(n))) for chr, n in groupby(seq)]", "from itertools import groupby\n\ndef uniq_c(seq):\n ans = []\n for c, e in groupby(seq):\n l = list(e)\n ans.append((c, len(l)))\n return ans", "uniq_c=lambda l:(lambda x: [(x[i][1],x[i][0]-x[i-1][0])if i>0 else (x[0][1],x[0][0]+1) for i in range(len(x))])(((lambda t: [(t[i][0],t[i][1]) for i in range(len(t)-1) if t[i][1]!=t[i+1][1]])(list(enumerate(l)))+[(len(l)-1,l[-1])])) if l!=[] else []", "def uniq_c(seq): \n if not seq:\n return []\n res = []\n cur = seq[0]\n counter = 1\n for c in seq[1:]:\n if c == cur:\n counter += 1\n else:\n res.append((cur, counter))\n cur = c\n counter = 1\n res.append((cur, counter)) \n return res\n", "def uniq_c(seq): \n m = []\n n,i = len(seq),0\n while i<n:\n c = seq[i]\n j = i+1\n while j<n and seq[j]==c: j += 1\n m.append((c,j-i))\n i = j\n return m\n", "def uniq_c(seq): \n stack, out = [], []\n for x in seq:\n if stack and x == stack[-1]:\n stack.append(x)\n else:\n if stack:\n out.append( (stack[-1], len(stack)) )\n stack.clear()\n stack.append(x)\n else:\n stack.append(x)\n \n return stack and out + [ (stack[-1], len(stack)) ] or out\n", "def uniq_c(seq): \n seq.append('asdadasd')\n arr = []\n count = 1\n for i in range(len(seq)-1):\n if seq[i] == seq[i+1]:\n count +=1\n else:\n arr.append((seq[i], count))\n count = 1\n return arr", "def uniq_c(seq): \n new_seq = list()\n count = 0\n for i in range(len(seq)):\n if i == 0:\n new_seq.append(seq[i])\n count += 1\n continue\n if seq[i] == seq[i - 1]:\n count += 1\n else:\n new_seq[-1] = (seq[i - 1], count)\n count = 1\n new_seq.append(seq[i])\n \n if len(seq) != 0:\n new_seq[-1] = (seq[-1], count)\n \n return new_seq\n \n"]
{"fn_name": "uniq_c", "inputs": [[["a", "a", "b", "b", "c", "a", "b", "c"]], [["a", "a", "a", "b", "b", "b", "c", "c", "c"]], [[null, "a", "a"]], [["foo"]], [[""]], [[]]], "outputs": [[[["a", 2], ["b", 2], ["c", 1], ["a", 1], ["b", 1], ["c", 1]]], [[["a", 3], ["b", 3], ["c", 3]]], [[[null, 1], ["a", 2]]], [[["foo", 1]]], [[["", 1]]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,601
def uniq_c(seq):
49cbf67184eb5d536e3bc5a9873429db
UNKNOWN
Leonardo Fibonacci in a rare portrait of his younger days I assume you are all familiar with the famous Fibonacci sequence, having to get each number as the sum of the previous two (and typically starting with either `[0,1]` or `[1,1]` as the first numbers). While there are plenty of variation on it ([including](https://www.codewars.com/kata/tribonacci-sequence) [a few](https://www.codewars.com/kata/fibonacci-tribonacci-and-friends) [I wrote](https://www.codewars.com/kata/triple-shiftian-numbers/)), usually the catch is all the same: get a starting (signature) list of numbers, then proceed creating more with the given rules. What if you were to get to get two parameters, one with the signature (starting value) and the other with the number you need to sum at each iteration to obtain the next one? And there you have it, getting 3 parameters: * a signature of length `length` * a second parameter is a list/array of indexes of the last `length` elements you need to use to obtain the next item in the sequence (consider you can end up not using a few or summing the same number multiple times)' in other words, if you get a signature of length `5` and `[1,4,2]` as indexes, at each iteration you generate the next number by summing the 2nd, 5th and 3rd element (the ones with indexes `[1,4,2]`) of the last 5 numbers * a third and final parameter is of course which sequence element you need to return (starting from zero, I don't want to bother you with adding/removing 1s or just coping with the fact that after years on CodeWars we all count as computers do): ```python custom_fib([1,1],[0,1],2) == 2 #classical fibonacci! custom_fib([1,1],[0,1],3) == 3 #classical fibonacci! custom_fib([1,1],[0,1],4) == 5 #classical fibonacci! custom_fib([3,5,2],[0,1,2],4) == 17 #similar to my Tribonacci custom_fib([7,3,4,1],[1,1],6) == 2 #can you figure out how it worked ;)? ```
["from collections import deque\n\ndef custom_fib(signature, indexes, n):\n fib = deque(signature)\n for _ in range(n):\n fib.append(sum(map(fib.__getitem__, indexes)))\n fib.popleft()\n return fib[0]", "def custom_fib(signature,indexes,n):\n for _ in range(n):\n signature = signature[1:] + [sum(signature[i] for i in indexes)]\n return signature[0]", "def custom_fib(ini,index,k):\n for n in range(k-len(ini)+1):\n ini = ini[1:] + [sum(ini[i] for i in index)]\n return ini[[-1,k][k<len(ini)]]", "from collections import deque\n\ndef custom_fib(sig, ind, n):\n sig = deque(sig)\n while n >= len(sig):\n s, n = sum(sig[x] for x in ind), n - 1\n sig.append(s)\n sig.popleft()\n return sig[n]", "def custom_fib(seq, indexes, n):\n size = len(seq)\n \n while len(seq) <= n:\n tail = seq[-size:]\n seq.append( sum( tail[i] for i in indexes ) )\n \n return seq[n]", "from collections import deque\n\ndef custom_fib(signature,indexes,n):\n s = deque(signature, maxlen=len(signature))\n for i in range(n):\n s.append(sum(s[i] for i in indexes))\n return s[0]\n", "def custom_fib(signature, indexes, n):\n values, l = list(signature), len(signature)\n while len(values) <= n:\n values.append(sum(values[-l:][i] for i in indexes))\n return values[n]", "custom_fib=f=lambda s,x,n:f(s[1:]+[sum(s[i]for i in x)],x,n-1)if n else s[n]", "custom_fib=lambda s,x,n,l=None: s[n] if len(s)>n else custom_fib((lambda p: s+[sum(p[i] for i in x)])(s[-(l or len(s)):]),x,n,l or len(s))", "def custom_fib(signature, indexes, n):\n if n < len(signature): return signature[n]\n return custom_fib(signature[1:]+[sum(map(signature.__getitem__, indexes))], indexes, n-1)"]
{"fn_name": "custom_fib", "inputs": [[[1, 1], [0, 1], 2], [[1, 1], [0, 1], 3], [[1, 1], [0, 1], 4], [[3, 5, 2], [0, 1, 2], 4], [[7, 3, 4, 1], [1, 1], 6]], "outputs": [[2], [3], [5], [17], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,789
def custom_fib(signature, indexes, n):
af309535c10861470d0256d7f441e8e5
UNKNOWN
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: ```if:javascript Given an array `arr` that contains some integers(positive, negative or 0), and a `range` list such as `[[start1,end1],[start2,end2],...]`, start and end are the index of `arr` and start always less than end. Your task is to calculate the sum value of each range (start index and end index are both inclusive), and return the maximum sum value. ``` ```if:ruby Given an array (`arr`) of integers and an array (`ranges`) of ranges (e.g. `[[1, 32], [16, 24],...]`), which represent an index range of `arr`, calculate the sum of each range (start index and end index are both inclusive) of `arr`, and return the maximum sum. ``` ```if:php Given an array `$a` that contains some integers and a `$range` list such as `[[$start1, $end1], [$start2, $end2], ... ]` where `$start(n)` and `$end(n)` are valid keys of the non-associative array `$a` and `$start(n)` is always guaranteed to be strictly less than `$end(n)`. Your task is to calculate the sum value of each range (start index and end index are both inclusive) and return the maximum sum value. ``` ```if:haskell Given a list `arr` that contains some integers(positive, negative or 0), and a `range` list such as `[(start1,end1),(start2,end2),...]`, start and end are the index of `arr` and start always less than end. Your task is to calculate the sum value of each range (start index and end index are both inclusive), and return the maximum sum value. ``` For example: # Note: - `arr`/`$a` always has at least 5 elements; - `range`/`$range`/`ranges` always has at least 1 element; - All inputs are valid; - This is a simple version, if you want some challenge, please [try the challenge version](https://www.codewars.com/kata/the-maximum-sum-value-of-ranges-challenge-version/). # Some Examples
["def max_sum(arr, ranges):\n return max( sum(arr[start:stop+1]) for start, stop in ranges )", "from itertools import accumulate\n\ndef max_sum(arr, ranges): \n xs = list(accumulate(arr)) + [0]\n return max(xs[j] - xs[i-1] for i, j in ranges)", "def max_sum(arr,ranges): \n return max(sum(arr[start:end+1]) for start, end in ranges)", "def max_sum(lst, ranges): \n return max(sum(lst[i:j+1]) for i, j in ranges)", "def max_sum(arr, ranges): \n return max(sum(arr[a:b + 1]) for a, b in ranges)", "def max_sum(arr,ranges): \n x = [sum([arr[i] for i in range(R[0], R[1]+1)]) for R in ranges]\n return max(x)", "def max_sum(arr, ranges):\n return max(sum(arr[p[0]:p[1] + 1]) for p in ranges) if ranges else 0\n", "def max_sum(arr,ranges): \n results=[]\n \n for r in ranges:\n partialSum=0\n for j in range(r[0],r[1]+1):\n partialSum+=arr[j]\n results.append(partialSum)\n\n return max(results)", "def max_sum(arr,ranges): \n return max([sum([arr[b] for b in range(i[0],i[1]+1)]) for i in ranges])\n\n \n\n\n", "def max_sum(arr,ranges): \n st=[]\n for i in ranges:\n p=0\n for j in range(i[0],i[1]+1):\n p+=arr[j]\n st.append(p)\n return max(st)"]
{"fn_name": "max_sum", "inputs": [[[1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 3], [0, 4], [6, 8]]], [[1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 3]]], [[1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 4], [2, 5]]], [[11, -22, 31, 34, -45, -46, 35, 32, 21], [[1, 4], [0, 3], [6, 8], [0, 8]]]], "outputs": [[6], [5], [0], [88]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,261
def max_sum(arr,ranges):
b958211da78ae7e95d9d7d8600d98c7c
UNKNOWN
Your task in this Kata is to emulate text justify right in monospace font. You will be given a single-lined text and the expected justification width. The longest word will never be greater than this width. Here are the rules: - Use spaces to fill in the gaps on the left side of the words. - Each line should contain as many words as possible. - Use '\n' to separate lines. - Gap between words can't differ by more than one space. - Lines should end with a word not a space. - '\n' is not included in the length of a line. - Last line should not contain '\n' Example with width=30: ``` Bacon ipsum dolor amet excepteur ut kevin burgdoggen, shankle cupim dolor officia ground round id ullamco deserunt nisi. Commodo tail qui salami, brisket boudin tri-tip. Labore flank laboris, cow enim proident aliqua sed hamburger consequat. Sed consequat ut non bresaola capicola shoulder excepteur veniam, bacon kevin. Pastrami shank laborum est excepteur non eiusmod bresaola flank in nostrud. Corned beef ex pig do kevin filet mignon in irure deserunt ipsum qui duis short loin. Beef ribs dolore meatball officia rump fugiat in enim corned beef non est. ``` If you enjoyed this one and want more of a challenge try https://www.codewars.com/kata/text-align-justify/python If you like bacon ipsum https://baconipsum.com
["import textwrap\n\ndef align_right(text,width):\n return \"\\n\".join([l.rjust(width, ' ') for l in textwrap.wrap(text, width)])", "def align_right(text, width):\n res = []\n line = []\n \n for word in text.split():\n if len(' '.join(line + [word])) <= width:\n line.append(word)\n else:\n res.append(line)\n line = [word]\n \n res.append(line)\n \n return '\\n'.join(' '.join(line).rjust(width) for line in res)", "from textwrap import TextWrapper\n\n\ndef align_right(text, width):\n tw = TextWrapper(width, break_on_hyphens=False)\n return '\\n'.join(a.rjust(width) for a in tw.wrap(text))", "import re\n\ndef align_right(text, width):\n return '\\n'.join( ' '*(width-len(line)) + line for line,sep in re.findall(r'(.{,' + str(width) + '})( |$)', text) if line )", "def align_right(text, width):\n answer = []\n splitted = text.split(' ')\n temp = ''\n i = 0\n while i < len(splitted):\n while i < len(splitted) and len(temp + splitted[i]) < width + 1:\n temp += splitted[i] + ' '\n i += 1\n temp = temp.strip()\n answer.append(' ' * (width - len(temp)) + temp)\n temp = ''\n return '\\n'.join(answer)\n", "def align_right(text,width):\n k = text.split()\n \n out = ''\n last = []\n for x in k:\n if len(x + out) <= width:\n out += x + ' '\n else:\n last.append(out)\n out = x+' '\n \n last.append(out)\n return '\\n'.join(' ' * (width - len(x.rstrip())) + x.rstrip() for x in last)\n", "def align_right(s,n):\n return \"\\n\".join([i.rjust(n, \" \") for i in __import__(\"textwrap\").wrap(width=n,text=s)])", "import textwrap\n\ndef align_right(text, width):\n wrapper = textwrap.TextWrapper(width=width, break_on_hyphens=True)\n return '\\n'.join(line.rjust(width) for line in wrapper.wrap(text))\n", "from textwrap import wrap\n\ndef align_right(text, width):\n return '\\n'.join(line.rjust(width) for line in\n wrap(text, width=width, break_on_hyphens=False))", "def align_right(text, width):\n lines = []\n while len(text) > width:\n cut = text[:width+1].rfind(\" \")\n lines.append(text[:cut].rjust(width))\n text = text[cut+1:]\n lines.append(text.rjust(width))\n return \"\\n\".join(lines)\n"]
{"fn_name": "align_right", "inputs": [["abc def", 10], ["I take up the whole line", 24], ["Two lines, I am", 10]], "outputs": [[" abc def"], ["I take up the whole line"], ["Two lines,\n I am"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,393
def align_right(text, width):
20cf119c1e590f37594444f66a601ac2
UNKNOWN
## Debugging sayHello function The starship Enterprise has run into some problem when creating a program to greet everyone as they come aboard. It is your job to fix the code and get the program working again! Example output: ``` Hello, Mr. Spock ```
["def say_hello(name):\n return f\"Hello, {name}\"", "def say_hello(name):\n return\"Hello, \" +name", "def say_hello(name):\n return \"Hello, {0}\".format(name)", "def say_hello(name):\n return \"Hello, {}\".format(name)", "def say_hello(name):\n return f'Hello, {name}'\n\n# how about you tell us proper function name beforehand?\n", "say_hello = \"Hello, \".__add__", "def say_hello(name):\n return \"Hello, %s\" % name", "def say_hello(name):\n return \"Hello,\" + \" \" + name", "def say_hello(input):\n return \"Hello, \" + input", "say_hello = lambda n:\"Hello, {}\".format(n)", "def say_hello(n):\n return \"Hello, \" + n", "def say_hello(name):\n return \"Hello, \" + name\n#pogchamp\n", "def say_hello(name):\n if name:\n return \"Hello, \" + name", "def say_hello(name: str) -> str:\n \"\"\" Greet The starship Enterprise member. \"\"\"\n return f\"Hello, {name}\"", "def say_hello(name):\n return \"Hello, \" + name\n pass", "def say_hello(name):\n return str(f'Hello, {name}')\n", "def say_hello(name):\n if name == '':\n return 'Hello, World'\n else:\n return 'Hello, {}'.format(name)", "def say_hello(name):\n return ('Hello, ' + name)\n \nsay_hello('Mr. Spock')\nsay_hello('Captain Kirk')\nsay_hello('Liutenant Uhura')\nsay_hello('Dr. McCoy')\nsay_hello('Mr. Scott')", "def say_hello(name):\n if False:\n print('reeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee https://www.youtube.com/watch?v=ub82Xb1C8os')\n return \"Hello, \" + name", "say_hello = lambda name: \"Hello, %s\" % name", "say_hello = lambda n: \"Hello, %s\" % n", "say_hello=lambda k:f'Hello, {k}'\n", "import unittest\n\n\ndef say_hello(name):\n return 'Hello, {}'.format(name)\n \n \nclass TestSayHello(unittest.TestCase):\n def test_say_hello(self):\n self.assertEqual(say_hello('Mr. Spock'), 'Hello, Mr. Spock')\n", "def say_hello(name):\n return f\"Hello, {name}\"\n\nprint((say_hello(\"Mr.Spock\")))\n", "def say_hello(name):\n this = (f'Hello, {name}')\n return this", "def say_hello(name):\n a = 'Hello, ' \n b = name\n return a + b", "def say_hello(name):\n return f\"Hello, {name}\".format(name)", "def say_hello(name):\n greet = 'Hello, '+name\n print(greet)\n return greet", "def say_hello(name):\n hello = \"Hello\" + \", \" + name\n return hello\n", "def say_hello(name):\n return \"Hello, \" + name\n\nsay_hello('dff')", "def say_hello(name:str)->str:\n result:str = \"Hello, \" + name\n return result", "def say_hello(name):\n return \"Hello\"+', '+name\nsay_hello('Mr.Spock')", "def say_hello(name):\n out = \"Hello, \"+name\n return out", "def say_hello(name):\n return \"Hello, {nam}\".format(nam=name)\n", "def say_hello(name):\n \n if(name):\n name = \"Hello, \" + name\n return name\n \n \n \n ## name = 'Hello, Mr. Spock'\n ## print(name) \n \n", "\"\"\" Greet the starship Enterprise member. \"\"\"\nsay_hello = \"Hello, \".__add__", "# def say_hello(name):\n# \"Hello\"\ndef say_hello(name):\n return 'Hello, ' + name ", "def say_hello(name):\n s = 'Hello, ' + name\n a = '%s'\n return(a % s)", "def say_hello(name='World'):\n name = str(name)\n greet = \"Hello, \"+ name\n return greet", "def say_hello(name):\n result = \"Hello, \" + name\n return result", "def say_hello(name):\n s = \"Hello, \", name\n return \"\".join(s)", "def say_hello(name):\n name = \"Hello,\", name\n name = ' '.join(name)\n return name", "def say_hello(name):\n name = f\"Hello, {name}\"\n return name", "def say_hello(name):\n hello = \"Hello, {}\".format(name)\n return hello", "def say_hello(name):\n return f\"Hello, \" + name", "def say_hello(n=''):\n return f'Hello, {n}'", "def say_hello(name):\n a = (\"Hello,\" + \" \" + name )\n return a", "def say_hello(name):\n p=('Hello, {}'.format(name))\n return p", "def say_hello(name):\n a = \"Hello, \"\n return (a + name)\n", "def say_hello(name: any) -> str:\n return \"Hello, \" + str(name)", "def say_hello(name):\n answer=\"Hello, \"+name\n return answer", "def say_hello(name):\n sen = \"Hello, \" + name \n return sen", "def say_hello(name):\n return f\"Hello, {name}\"\nprint((say_hello(\"nini\")))\n", "def say_hello(name):\n x = f\"Hello, {name}\"\n return x", "def say_hello(name: str) -> str:\n return f\"Hello, {name}\"", "def say_hello(name):\n return \"Hello, \" + ''.join(name)", "def say_hello(name):\n s = (\"Hello, {}\".format(name))\n return s\nprint(say_hello('Mr. Spock'))", "def say_hello(name):\n return \"Hello, {n}\".format(n = name)", "def say_hello(name):\n return \"\".join([\"Hello, \",name ])", "def say_hello(name):\n return \"Hello\" + ', ' + name\n \nprint(say_hello('Mr.Spock'))", "def say_hello(name):\n if name:\n return \"Hello, \" + name;\n else:\n \"Thus, do we move to meet Hell's legions as a mighty army,\\\n and form our squared ranks against Hell's gates, \\\n and prepare to meet the seven million, four hundred and five thousand,\\\n nine hundred and twenty-six demons of iniquity!\"", "def say_hello(name):\n greet = (f\"Hello, {name}\")\n return greet", "def say_hello(name):\n return(\"Hello,\" + \" \" + name)\nsay_hello(\"Mr. Spock\")\nsay_hello(\"Captain Kirk\")\nsay_hello(\"Liutenant Uhura\")\nsay_hello(\"Dr. McCoy\")\nsay_hello(\"Mr. Scott\")", "def say_hello(name):\n string = \"Hello\"+\", \" + name\n return string", "def say_hello(name):\n return f\"Hello, {name}\"\n\nprint(say_hello)", "def say_hello(name):\n say = 'Hello, ' + name\n return(say)", "def say_hello(name):\n ans = \"Hello, \" + name\n return ans", "def say_hello(name):\n return \"Hello, \" + name\nprint(say_hello)", "def say_hello(name):\n salu = name\n return \"Hello, {}\".format(salu)", "def say_hello(name):\n return \"Hello, \" + name\nsay_hello('Marissa')", "def say_hello(name):\n return \" ,olleH\"[::-1]+name", "def say_hello(name):\n return \"olleH\"[::-1] +\", \"+ name", "def say_hello(name):\n hello = \"Hello, \" + name\n return (hello)\n", "def say_hello(name):\n sh = 'Hello, '+ name\n return sh", "def say_hello(name):\n hi = \"Hello\" + \",\" + \" \" + name\n return hi", "def say_hello(name):\n hello_name = (\"Hello, \" + name)\n return hello_name\n", "def say_hello(name):\n name = \"Hello, \" + name\n return(name)", "def say_hello(name):\n \"\"\"Print a greeting message.\"\"\"\n return 'Hello, ' + name", "def say_hello(name):\n name = str(name)\n return (\"Hello, \" + name )", "def say_hello(name):\n return f'Hello, {name}'\nsay_hello('Mr. Robot')", "def say_hello(name):\n return \"Hello\"+ ','+' '+name", "def say_hello(name):\n return \"\".join('Hello'+', '+ (name))\n", "def say_hello(name):\n print(name)\n arr = [72, 101, 108, 108, 111, 44]\n return ''.join([chr(i) for i in arr])+' '+name", "def say_hello(name):\n asd = (\"Hello,\" ,name)\n asf = \" \".join(asd)\n return (asf)", "def say_hello(name):\n x = \"Hello, \" + name\n return x\n", "def say_hello(name):\n str = \"Hello, \" + name\n return str", "def say_hello(name):\n return \"Hello, \" + name\n\nlist= [\"Mr. Steve\",\"Captain Kata\",\"Eren Yeager\",\"Dr. McCoi\",\"Mrs. Scott\"]\n\nsay_hello(list[0])\nsay_hello(list[1])\nsay_hello(list[2])\nsay_hello(list[3])\nsay_hello(list[4])\n", "def say_hello(name):\n var = f\"Hello, {name}\"\n return var\n \n", "def say_hello(name):\n return(\"Hello,\"+\" \"+str(name))", "def say_hello(name):\n greeting = \"Hello\" + ', '+name\n return greeting", "def say_hello(name):\n #print (\"Hello, \" +name)\n return \"Hello, \" +name", "def say_hello(name):\n var = \"Hello, {}\".format(name)\n return var", "def say_hello(name):\n output = 'Hello, ' + name \n return output", "def say_hello(name):\n return('Hello, ' + name)\n\nsay_hello('MacMillan')", "def say_hello(name):\n return \"Hello, \" + name if name else name", "def say_hello(name):\n a = \"Hello\"\n return a + \", \" + name"]
{"fn_name": "say_hello", "inputs": [["Mr. Spock"], ["Captain Kirk"], ["Liutenant Uhura"], ["Dr. McCoy"], ["Mr. Scott"]], "outputs": [["Hello, Mr. Spock"], ["Hello, Captain Kirk"], ["Hello, Liutenant Uhura"], ["Hello, Dr. McCoy"], ["Hello, Mr. Scott"]]}
INTRODUCTORY
PYTHON3
CODEWARS
8,285
def say_hello(name):
19f8582665e6ff1e9a821c5e6f6bb291
UNKNOWN
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, of which the sum is 220. Derive function ```amicableNumbers(num1, num2)``` which returns ```true/True``` if pair ```num1 num2``` are amicable, ```false/False``` if not. See more at https://en.wikipedia.org/wiki/Amicable_numbers
["def getDivs(n):\n return {1} | {y for x in range(2,int(n**.5)+1) for y in [n//x, x] if not n%x}\n\ndef amicable_numbers(n1,n2):\n return sum(getDivs(n1)) == n2 and sum(getDivs(n2)) == n1", "def amicable_numbers(n1, n2):\n return spd(n1) == n2 and spd(n2) == n1\n\ndef spd(n):\n return sum(i for i in range(1, n) if n % i == 0)", "def factors(num):\n return sum(i for i in range(1, num) if num % i == 0)\ndef amicable_numbers(n1,n2):\n return factors(n1) == n2 and factors(n2) == n1\n", "def amicable_numbers(n1,n2):\n s1 = sum([x for x in range(1,n1) if n1%x==0])\n s2 = sum([x for x in range(1,n2) if n2%x==0])\n return s1 == n2 and s2 == n1", "def amicable_numbers(n1,n2):\n divisors1 = [i for i in range(1,n1) if n1%i==0]\n divisors2 = [i for i in range(1,n2) if n2%i==0]\n return bool(sum(divisors1)==n2 and sum(divisors2)==n1)", "#sum_div = lambda n: sum(d for d in range(1, n) if not n%d)\nsum_div = lambda n: sum(d + n // d for d in range(2, int(n ** .5) + 1) if not n%d) + 1 - n**.5/1 * (not n**.5%1)\namicable_numbers = lambda x, y: sum_div(x) == y and sum_div(y) == x", "def amicable_numbers(n1,n2):\n return sum(d for d in range(1,n1//2 + 1) if not n1 % d) == n2 and sum(d for d in range(1,n2//2 + 1) if not n2 % d) == n1", "def amicable_numbers(n1,n2):\n divisor_sum=lambda x:sum(i for i in range(1,x) if x%i==0)\n return divisor_sum(n1)==n2 and divisor_sum(n2)==n1", "from functools import reduce\ndef amicable_numbers(n1,n2):\n s1=reduce(lambda x,y: x+(y if n1%y==0 else 0), range(1, n1),0)\n s2=reduce(lambda x,y: x+(y if n2%y==0 else 0), range(1, n1),0)\n return s1==n2 and s2==n1", "def amicable_numbers(n1,n2):\n count_1 = 0\n count_2 = 0\n product = 0\n for i in range(1, n1):\n if n1 % i == 0:\n count_1 += i\n for i in range(1, n2):\n if n2 % i == 0:\n count_2 += i\n if n1 == count_2:\n product += 1\n if n2 == count_1:\n product += 1\n if product == 2:\n return True\n return False"]
{"fn_name": "amicable_numbers", "inputs": [[220, 284], [220, 280], [1184, 1210], [220221, 282224], [10744, 10856], [299920, 9284], [999220, 2849], [122265, 139815]], "outputs": [[true], [false], [true], [false], [true], [false], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,046
def amicable_numbers(n1,n2):
bb32a87496791df2b7bdf86ec23983a7
UNKNOWN
# Task Given an array `arr`, find the rank of the element at the ith position. The `rank` of the arr[i] is a value equal to the number of elements `less than or equal to` arr[i] standing before arr[i], plus the number of elements `less than` arr[i] standing after arr[i]. # Example For `arr = [2,1,2,1,2], i = 2`, the result should be `3`. There are 2 elements `less than or equal to` arr[2] standing before arr[2]: `arr[0] <= arr[2]` `arr[1] <= arr[2]` There is only 1 element `less than` arr[2] standing after arr[2]: `arr[3] < arr[2]` So the result is `2 + 1 = 3`. # Input/Output - `[input]` integer array `arr` An array of integers. `3 <= arr.length <= 50.` - `[input]` integer `i` Index of the element whose rank is to be found. - `[output]` an integer Rank of the element at the ith position.
["def rank_of_element(arr,i):\n return sum(x <= arr[i] if n < i else x < arr[i] for n,x in enumerate(arr))", "def rank_of_element(arr, i):\n return sum(1 for item in arr[:i] if item <= arr[i]) + sum(1 for item in arr[i+1:] if item < arr[i])", "def rank_of_element(arr,i):\n rank = 0\n for j, value in enumerate(arr):\n if j < i:\n if value <= arr[i]:\n rank += 1\n elif j == i:\n continue \n else:\n if value < arr[i]:\n rank += 1\n return rank", "def rank_of_element(arr, i):\n return (\n sum(n <= arr[i] for n in arr[:i]) +\n sum(n < arr[i] for n in arr[i + 1:]))", "rank_of_element=lambda a,i:sum(n<a[i]+(j<i)for j,n in enumerate(a))", "def rank_of_element(arr,i):\n return sum(v < arr[i]+(x<i) for x,v in enumerate(arr) if x!=i)", "def rank_of_element(arr,i):\n return sum(v<=arr[i] for v in arr[:i])+sum(v<arr[i] for v in arr[i+1:])", "def rank_of_element(arr,i):\n #your code here\n rank = 0\n for j in range(len(arr)):\n if j < i:\n if arr[j] <= arr[i]:\n rank += 1\n elif j > i:\n if arr[j] < arr[i]:\n rank += 1\n return rank", "def rank_of_element(lst, i):\n return sum(n <= lst[i] for n in lst[:i]) + sum(n < lst[i] for n in lst[i+1:])"]
{"fn_name": "rank_of_element", "inputs": [[[2, 1, 2, 1, 2], 2], [[2, 1, 2, 2, 2], 2], [[3, 2, 3, 4, 1], 0], [[3, 2, 3, 4, 1], 1], [[3, 2, 3, 4, 1], 2]], "outputs": [[3], [2], [2], [1], [3]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,352
def rank_of_element(arr,i):
39730bbc43ea9eb23f8006e4f5177b2d
UNKNOWN
Write a method that returns true if a given parameter is a power of 4, and false if it's not. If parameter is not an Integer (eg String, Array) method should return false as well. (In C# Integer means all integer Types like Int16,Int32,.....) ### Examples ```python isPowerOf4 1024 #should return True isPowerOf4 102 #should return False isPowerOf4 64 #should return True ```
["from math import log\n\ndef powerof4(n):\n if type(n) in (float, int) and n > 0:\n return log(n,4).is_integer()\n return False", "from math import log\n\ndef powerof4(n):\n return type(n) == int and n >= 0 and log(n, 4).is_integer() ", "from math import log\n\ndef powerof4(n):\n return n==4**round(log(n,4)) if (type(n)==int and n>0) else False", "def powerof4(n):\n t=[int, float]\n if type(n) not in t:\n return False\n if n==1.0:\n return True\n elif n<1.0:\n return False\n return powerof4(n/4.0)", "def powerof4(n):\n try:\n b = bin(n)\n if isinstance(n, bool):\n return False\n return b.count('1') == 1 and len(b) % 2 != 0\n except:\n return False", "def powerof4(n):\n return type(n) == int and n.bit_length() & 1 and n == 1 << n.bit_length()-1", "import math\n\n\ndef powerof4(n):\n if not (isinstance(n, int) and not isinstance(n, bool) and n > 0):\n return False\n return math.log(n, 4).is_integer()\n", "def powerof4(n):\n \n if not str(n).isdigit(): return False\n else: n = int(n)\n \n while n > 4:\n n = n / 4\n \n if n == 4 or n == 1: return True\n \n return False", "def powerof4(n):\n if type(n)!=type(1):\n return False\n while n%4==0:\n n=n/4\n return n==1", "from math import log\ndef powerof4(n): \n return False if type(n) != int else int(log(n, 4)) == log(n, 4) if n>0 else False "]
{"fn_name": "powerof4", "inputs": [[2], [4], [40], [1], [4.2], [-25], ["pippi"], [256]], "outputs": [[false], [true], [false], [true], [false], [false], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,487
def powerof4(n):
8493fa990ab010b2ffd0a78c88807fc2
UNKNOWN
An eviternity number is a number which: * contains only digits 8, 5 and 3, and * the count of the digit `8` >= count of digit `5` >= count of digit `3`. The first few eviternity numbers are as follows. ```Haskell [8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888] ``` You will be given two integers, `a` and `b`, and your task is to return the number of eviternity numbers in the range `>= a and < b`. ```Haskell For example: solve(0,1000) = 14, because they are [8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888] ``` The upper bound will not exceed `500,000`. More examples in test cases. Good luck!
["u = [8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888, 3588, 3858, 3885, 5388, 5588, 5838, 5858, 5883, 5885, 5888, 8358, 8385, 8538, 8558, 8583, 8585, 8588, 8835, 8853, 8855, 8858, 8885, 8888, 35588, 35858, 35885, 35888, 38558, 38585, 38588, 38855, 38858, 38885, 53588, 53858, 53885, 53888, 55388, 55838, 55883, 55888, 58358, 58385, 58388, 58538, 58583, 58588, 58835, 58838, 58853, 58858, 58883, 58885, 58888, 83558, 83585, 83588, 83855, 83858, 83885, 85358, 85385, 85388, 85538, 85583, 85588, 85835, 85838, 85853, 85858, 85883, 85885, 85888, 88355, 88358, 88385, 88535, 88538, 88553, 88558, 88583, 88585, 88588, 88835, 88853, 88855, 88858, 88885, 88888, 335588, 335858, 335885, 338558, 338585, 338855, 353588, 353858, 353885, 355388, 355838, 355883, 355888, 358358, 358385, 358538, 358583, 358588, 358835, 358853, 358858, 358885, 358888, 383558, 383585, 383855, 385358, 385385, 385538, 385583, 385588, 385835, 385853, 385858, 385885, 385888, 388355, 388535, 388553, 388558, 388585, 388588, 388855, 388858, 388885]\n\ndef solve(a, b):\n return sum(a <= x < b for x in u)", "eviternity = [int(n) for n in map(str, range(10 ** 6))\n if set(n) <= set('358') and n.count('3') <= n.count('5') <= n.count('8')]\nsolve = lambda a, b, f=__import__('bisect').bisect_left: f(eviternity, b) - f(eviternity, a)", "def ever(n):\n s = str(n)\n C = [s.count('3'), s.count('5'), s.count('8')]\n if sum(C)==len(s) and sorted(C)==C :\n return True\n return False\n\nD={i for i in range(1000000) if ever(i)}\n\n\ndef solve(a,b):\n return len({e for e in D if e>=a and e<=b})", "import itertools\n\ndef merge(l):\n return ''.join(l)\n\ndef solve(a,b):\n digits=['3', '5', '8','']\n c2=set(map(merge,itertools.product(digits,digits,digits,digits,digits,digits)))\n c2.remove('')\n c=0\n for n in c2:\n if int(n)>=a and int(n)<b:\n if n.count('8')>= n.count('5') and n.count('5')>= n.count('3'):\n c+=1\n return c\n\n", "from collections import Counter\nfrom itertools import product\n\n \ndef valid(s):\n c = Counter(s)\n return c[8]>=c[5]>=c[3]\n \nALL = [int(''.join(map(str,digs))) for nd in range(1,7) \n for digs in product((3,5,8), repeat=nd)\n if valid(digs) ]\n\ndef solve(a,b):\n return sum( a<=n<b for n in ALL )", "from itertools import product\ndef solve(a,b):\n res, start, stop = [], len(str(a)), len(str(b))+1\n for i in range(start, stop):\n res += [\"\".join(x) for x in product('538', repeat=i)]\n return sum(1 for x in res if a<=int(x)<=b and x.count('8')>=x.count('5')>=x.count('3'))", "from itertools import permutations\n\nEVI = {8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888,\n 8888, 88888, 888888, 8888888}\n\nfor n in [\n # 4 digit bases\n 8885, 8855, 8853,\n # 5 digit\n 88885, 88855, 88853, 88553, \n # 6 digit\n 888885, 888855, 888853, 888555, 888553, 885533]:\n for perm in permutations(str(n)):\n EVI.add(int(''.join(perm)))\n\ndef solve(a, b):\n return sum(a <= n < b for n in EVI)", "from re import match\n\nmemo = {}\n\ndef solve(a, b):\n return sum(1 for n in range(a, b) if is_eviternity(n))\n\ndef is_eviternity(n):\n if n not in memo:\n s = str(n)\n memo[n] = match(r'[853]+$', s) and s.count('8') >= s.count('5') >= s.count('3')\n return memo[n]", "from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef f_checker(num):\n if all([i in ['3', '5', '8'] for i in str(num)]):\n count_8 = str(num).count('8')\n count_5 = str(num).count('5')\n count_3 = str(num).count('3')\n if count_8 >= count_5 and count_5 >= count_3:\n return num\ndef solve(a,b):\n counter = 0\n for num in range(a, b):\n res = f_checker(num)\n if res:\n counter += 1\n return counter", "def solve(a,b):\n number_counter = 0\n for i in range(a, b):\n number = str(i)\n if '0' in number or '1' in number or '2' in number or '4' in number or '6' in number or '7' in number or '9' in number:\n continue\n a = number.count('3')\n b = number.count('5')\n c = number.count('8')\n if(a + b + c == len(number)) and (a <= b) and (b <= c):\n number_counter +=1\n return number_counter"]
{"fn_name": "solve", "inputs": [[0, 100], [0, 1000], [0, 10000], [0, 100000], [0, 500000], [90, 139701], [61, 56976]], "outputs": [[4], [14], [37], [103], [148], [99], [53]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,431
def solve(a, b):