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
664afe69ee38f6e589de07cbc7fc72f3
UNKNOWN
=====Problem Statement===== The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where: The first line contains the sum of the two numbers. The second line contains the difference of the two numbers (first - second). The third line contains the product of the two numbers. =====Example===== a = 3 b = 5 Print the following: 8 -2 15 =====Input Format===== The first line contains the first integer, a. The second line contains the second integer, b. =====Constraints===== 1≤a≤10^10 1≤b≤10^10 =====Output Format===== Print the three lines as explained above.
["# Enter your code here. Read input from STDIN. Print output to STDOUT\na=int(input())\nb=int(input())\nprint((a+b))\nprint((a-b))\nprint((a*b))\n", "def __starting_point():\n a = int(input())\n b = int(input())\n \n print((a + b))\n print((a - b))\n print((a * b))\n\n__starting_point()"]
{"inputs": ["3\n2"], "outputs": ["5\n1\n6"]}
INTRODUCTORY
PYTHON3
HACKERRANK
308
if __name__ == '__main__': a = int(input()) b = int(input())
aefd8a835223c126ed36c8ceb989617d
UNKNOWN
=====Problem Statement===== Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications: Mat size must be NXM. (N is an odd natural number, M and is 3 times N.) The design should have 'WELCOME' written in the center. The design pattern should only use |, . and - characters. Sample Designs Size: 7 x 21 ---------.|.--------- ------.|..|..|.------ ---.|..|..|..|..|.--- -------WELCOME------- ---.|..|..|..|..|.--- ------.|..|..|.------ ---------.|.--------- Size: 11 x 33 ---------------.|.--------------- ------------.|..|..|.------------ ---------.|..|..|..|..|.--------- ------.|..|..|..|..|..|..|.------ ---.|..|..|..|..|..|..|..|..|.--- -------------WELCOME------------- ---.|..|..|..|..|..|..|..|..|.--- ------.|..|..|..|..|..|..|.------ ---------.|..|..|..|..|.--------- ------------.|..|..|.------------ ---------------.|.--------------- =====Input Format===== A single line containing the space separated values of N and M. =====Constraints===== 5 < N < 101 15 < M < 303 =====Output Format===== Output the design pattern.
["N, M = list(map(int,input().split())) # More than 6 lines of code will result in 0 score. Blank lines are not counted.\nfor i in range(1,N,2): \n print((int((M-3*i)/2)*'-'+(i*'.|.')+int((M-3*i)/2)*'-'))\nprint((int((M-7)/2)*'-'+'WELCOME'+int((M-7)/2)*'-'))\nfor i in range(N-2,-1,-2): \n print((int((M-3*i)/2)*'-'+(i*'.|.')+int((M-3*i)/2)*'-'))\n", "N, M = list(map(int,input().split())) # More than 6 lines of code will result in 0 score. Blank lines are not counted.\nfor i in range(1, N, 2): \n print(((i*\".|.\").center(3*N, \"-\")))\nprint((\"-WELCOME-\".center(3*N, \"-\")))\nfor i in range(N - 2, -1, -2): \n print(((i*\".|.\").center(3*N, \"-\")))\n"]
{"inputs": ["7 21"], "outputs": ["---------.|.---------\n------.|..|..|.------\n---.|..|..|..|..|.---\n-------WELCOME-------\n---.|..|..|..|..|.---\n------.|..|..|.------\n---------.|.---------"]}
INTRODUCTORY
PYTHON3
HACKERRANK
673
# Enter your code here. Read input from STDIN. Print output to STDOUT
2cb4b3feeafacbfe304889a8a3f552ed
UNKNOWN
=====Problem Statement===== A valid postal code P have to fullfil both below requirements: 1. P must be a number in the range from 100000 to 999999 inclusive. 2. P must not contain more than one alternating repetitive digit pair. Alternating repetitive digits are digits which repeat immediately after the next digit. In other words, an alternating repetitive digit pair is formed by two equal digits that have just a single digit between them. For example: 121426 # Here, 1 is an alternating repetitive digit. 523563 # Here, NO digit is an alternating repetitive digit. 552523 # Here, both 2 and 5 are alternating repetitive digits. Your task is to provide two regular expressions regex_integer_in_range and regex_alternating_repetitive_digit_pair. Where: regex_integer_in_range should match only integers range from 100000 to 999999 inclusive regex_alternating_repetitive_digit_pair should find alternating repetitive digits pairs in a given string. Both these regular expressions will be used by the provided code template to check if the input string P is a valid postal code using the following expression: (bool(re.match(regex_integer_in_range, P)) and len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2) =====Input Format===== Locked stub code in the editor reads a single string denoting P from stdin and uses provided expression and your regular expressions to validate if P is a valid postal code. =====Output Format===== You are not responsible for printing anything to stdout. Locked stub code in the editor does that.
["import re\np = input().strip()\nrange_check = bool(re.match(r'^[1-9][0-9]{5}$',p))\nrepeat_check = len(re.findall(r'(?=([0-9])[0-9]\\1)',p))\nprint((range_check == True and repeat_check<2))\n", "import re\n\nnum = input()\nprint(bool(re.match(r'^[1-9][\\d]{5}$', num) and len(re.findall(r'(\\d)(?=\\d\\1)', num))<2 ))"]
{"inputs": ["110000"], "outputs": ["False"]}
INTRODUCTORY
PYTHON3
HACKERRANK
321
regex_integer_in_range = r"_________" # Do not delete 'r'. regex_alternating_repetitive_digit_pair = r"_________" # Do not delete 'r'. import re P = input() print (bool(re.match(regex_integer_in_range, P)) and len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2)
c4f8f7c1adc6fea79bce750b939717e9
UNKNOWN
=====Function Descriptions===== We have seen the applications of union, intersection, difference and symmetric difference operations, but these operations do not make any changes or mutations to the set. We can use the following operations to create mutations to a set: .update() or |= Update the set by adding elements from an iterable/another set. >>> H = set("Hacker") >>> R = set("Rank") >>> H.update(R) >>> print H set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R']) .intersection_update() or &= Update the set by keeping only the elements found in it and an iterable/another set. >>> H = set("Hacker") >>> R = set("Rank") >>> H.intersection_update(R) >>> print H set(['a', 'k']) .difference_update() or -= Update the set by removing elements found in an iterable/another set. >>> H = set("Hacker") >>> R = set("Rank") >>> H.difference_update(R) >>> print H set(['c', 'e', 'H', 'r']) .symmetric_difference_update() or ^= Update the set by only keeping the elements found in either set, but not in both. >>> H = set("Hacker") >>> R = set("Rank") >>> H.symmetric_difference_update(R) >>> print H set(['c', 'e', 'H', 'n', 'r', 'R']) =====Problem Statement===== You are given a set A and N number of other sets. These N number of sets have to perform some specific mutation operations on set A. Your task is to execute those operations and print the sum of elements from set A. =====Input Format===== The first line contains the number of elements in set A. The second line contains the space separated list of elements in set A. The third line contains integer N, the number of other sets. The next 2 * N lines are divided into N parts containing two lines each. The first line of each part contains the space separated entries of the operation name and the length of the other set. The second line of each part contains space separated list of elements in the other set. =====Constraints===== 0<len(set(A))<1000 0<len(otherSets)<100 0<N<100 =====Output Format===== Output the sum of elements in set A.
["n = int(input())\na = set(map(int,input().split()))\nN = int(input())\nfor i in range(N):\n cmd = input().split()\n opt = cmd[0]\n s = set(map(int,input().split()))\n if (opt == 'update'):\n a |= s\n elif (opt == 'intersection_update'):\n a &= s\n elif (opt == 'difference_update'):\n a -= s\n elif (opt == 'symmetric_difference_update'):\n a ^= s\nprint((sum(a)))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n n = int(input())\n s = set(map(int, input().split())) \n num_cmds = int(input())\n \n for _i in range(num_cmds):\n cmd = list(input().strip().split(' '))\n if cmd[0] == 'intersection_update':\n get_set = set(map(int, input().split(' ')))\n s &= get_set\n elif cmd[0] == 'update':\n get_set = set(map(int, input().split(' ')))\n s |= get_set\n elif cmd[0] == 'difference_update':\n get_set = set(map(int, input().split(' ')))\n s -= get_set\n elif cmd[0] == 'symmetric_difference_update':\n get_set = set(map(int, input().split(' ')))\n s ^= get_set\n \n print((sum(s)))\n\n__starting_point()"]
{"inputs": ["16\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 24 52\n4\nintersection_update 10\n2 3 5 6 8 9 1 4 7 11\nupdate 2\n55 66\nsymmetric_difference_update 5\n22 7 35 62 58\ndifference_update 7\n11 22 35 55 58 62 66"], "outputs": ["38"]}
INTRODUCTORY
PYTHON3
HACKERRANK
1,210
# Enter your code here. Read input from STDIN. Print output to STDOUT
0a40438378715edc5e95976f2cfb38a0
UNKNOWN
=====Problem Statement===== The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python. You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing) with a uniform probability from the list. Find the probability that at least one of the K indices selected will contain the letter: ''. =====Input Format===== The input consists of three lines. The first line contains the integer N, denoting the length of the list. The next line consists of N space-separated lowercase English letters, denoting the elements of the list. The third and the last line of input contains the integer K, denoting the number of indices to be selected. =====Output Format===== Output a single line consisting of the probability that at least one of the K indices selected contains the letter: 'a'. Note: The answer must be correct up to 3 decimal places. =====Constraints===== 1≤N≤10 1≤K≤N
["from itertools import combinations\nn = int(input())\nar = input().split()\nk = int(input())\ncomb_list = list(combinations(ar,k))\na_list = [e for e in comb_list if 'a' in e]\nprint((len(a_list) / len(comb_list)))\n", "#!/usr/bin/env python3\n\nimport string\nsymbols = string.ascii_lowercase\n\nfrom itertools import combinations\n\ndef __starting_point():\n n = int(input().strip())\n arr = list(map(str, input().strip().split(' ')))\n times = int(input().strip())\n cmbts = list(combinations(sorted(arr), times))\n \n print((\"{:.4f}\".format(len(list([a for a in cmbts if a[0] == 'a']))/(len(cmbts)))))\n \n\n__starting_point()"]
{"inputs": ["4\na a c d\n2"], "outputs": ["0.833333333333"]}
INTRODUCTORY
PYTHON3
HACKERRANK
657
# Enter your code here. Read input from STDIN. Print output to STDOUT
f3b9269f18d17ee37bf1c133837f9e87
UNKNOWN
=====Problem Statement===== The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but the only difference is that a defaultdict will have a default value if that key has not been set yet. If you didn't use a defaultdict you'd have to check to see if that key exists, and if it doesn't, set it to what you want. For example: from collections import defaultdict d = defaultdict(list) d['python'].append("awesome") d['something-else'].append("not relevant") d['python'].append("language") for i in d.items(): print i This prints: ('python', ['awesome', 'language']) ('something-else', ['not relevant']) In this challenge, you will be given 2 integers, n and m. There are n words, which might repeat, in word group A. There are m words belonging to word group B. For each m words, check whether the word has appeared in group A or not. Print the indices of each occurrence of m in group A. If it does not appear, print -1. =====Constraints===== 1≤n≤10000 1≤m≤100 1≤length of each word in the input≤100 =====Input Format===== The first line contains integers, n and m separated by a space. The next n lines contains the words belonging to group A. The next m lines contains the words belonging to group B. =====Output Format===== Output m lines. The ith line should contain the 1-indexed positions of the occurrences of the ith word separated by spaces.
["from collections import defaultdict\nd = defaultdict(list)\nn,m=list(map(int,input().split()))\nfor i in range(n):\n w = input()\n d[w].append(str(i+1))\nfor j in range(m):\n w = input()\n print((' '.join(d[w]) or -1))\n", "#!/usr/bin/env python3\n\nfrom collections import defaultdict\n\ndef __starting_point():\n n, m = list(map(int, input().strip().split(' ')))\n library = defaultdict(list)\n \n for ind in range(1, n + 1):\n word = input().strip()\n library[word].append(ind)\n \n for ind in range(m):\n word = input().strip()\n if len(library[word]) > 0:\n print((\" \".join(map(str, library[word]))))\n else:\n print(\"-1\")\n\n__starting_point()"]
{"inputs": ["5 2\na\na\nb\na\nb\na\nb"], "outputs": ["1 2 4\n3 5"]}
INTRODUCTORY
PYTHON3
HACKERRANK
744
# Enter your code here. Read input from STDIN. Print output to STDOUT
2154af0a62325149fe836af21b748dce
UNKNOWN
=====Function Descriptions===== HTML Hypertext Markup Language is a standard markup language used for creating World Wide Web pages. Parsing Parsing is the process of syntactic analysis of a string of symbols. It involves resolving a string into its component parts and describing their syntactic roles. HTMLParser An HTMLParser instance is fed HTML data and calls handler methods when start tags, end tags, text, comments, and other markup elements are encountered. Example (based on the original Python documentation): Code from HTMLParser import HTMLParser # create a subclass and override the handler methods class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print "Found a start tag :", tag def handle_endtag(self, tag): print "Found an end tag :", tag def handle_startendtag(self, tag, attrs): print "Found an empty tag :", tag # instantiate the parser and fed it some HTML parser = MyHTMLParser() parser.feed("<html><head><title>HTML Parser - I</title></head>" +"<body><h1>HackerRank</h1><br /></body></html>") Output Found a start tag : html Found a start tag : head Found a start tag : title Found an end tag : title Found an end tag : head Found a start tag : body Found a start tag : h1 Found an end tag : h1 Found an empty tag : br Found an end tag : body Found an end tag : html .handle_starttag(tag, attrs) This method is called to handle the start tag of an element. (For example: <div class='marks'>) The tag argument is the name of the tag converted to lowercase. The attrs argument is a list of (name, value) pairs containing the attributes found inside the tag’s <> brackets. .handle_endtag(tag) This method is called to handle the end tag of an element. (For example: </div>) The tag argument is the name of the tag converted to lowercase. .handle_startendtag(tag,attrs) This method is called to handle the empty tag of an element. (For example: <br />) The tag argument is the name of the tag converted to lowercase. The attrs argument is a list of (name, value) pairs containing the attributes found inside the tag’s <> brackets. =====Problem Statement===== You are given an HTML code snippet of N lines. Your task is to print start tags, end tags and empty tags separately. Format your results in the following way: Start : Tag1 End : Tag1 Start : Tag2 -> Attribute2[0] > Attribute_value2[0] -> Attribute2[1] > Attribute_value2[1] -> Attribute2[2] > Attribute_value2[2] Start : Tag3 -> Attribute3[0] > None Empty : Tag4 -> Attribute4[0] > Attribute_value4[0] End : Tag3 End : Tag2 Here, the -> symbol indicates that the tag contains an attribute. It is immediately followed by the name of the attribute and the attribute value. The > symbol acts as a separator of the attribute and the attribute value. If an HTML tag has no attribute then simply print the name of the tag. If an attribute has no attribute value then simply print the name of the attribute value as None. Note: Do not detect any HTML tag, attribute or attribute value inside the HTML comment tags (<!-- Comments -->).Comments can be multiline as well. =====Input Format===== The first line contains integer N, the number of lines in a HTML code snippet. The next N lines contain HTML code. =====Constraints===== 0<N<100 =====Output Format===== Print the HTML tags, attributes and attribute values in order of their occurrence from top to bottom in the given snippet. Use proper formatting as explained in the problem statement.
["import re\nfrom html.parser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n print(\"Start\".ljust(6) + \":\", tag)\n for at in attrs:\n print(\"-> {} > {}\".format(at[0], at[1]))\n def handle_endtag(self, tag):\n print(\"End\".ljust(6) + \":\", tag)\n def handle_startendtag(self, tag, attrs):\n print(\"Empty\".ljust(6) + \":\", tag)\n for at in attrs:\n print(\"-> {} > {}\".format(at[0], at[1]))\n\ndef __starting_point():\n parser = MyHTMLParser()\n n = int(input().strip())\n for _ in range(n):\n line = input()\n parser.feed(line)\n__starting_point()"]
{"inputs": ["2\n<html><head><title>HTML Parser - I</title></head>\n<body data-modal-target class='1'><h1>HackerRank</h1><br /></body></html>"], "outputs": ["Start : html\nStart : head\nStart : title\nEnd : title\nEnd : head\nStart : body\n-> data-modal-target > None\n-> class > 1\nStart : h1\nEnd : h1\nEmpty : br\nEnd : body\nEnd : html"]}
INTRODUCTORY
PYTHON3
HACKERRANK
697
# Enter your code here. Read input from STDIN. Print output to STDOUT
1b57a4a6dc43c77808c8f0be83ce774b
UNKNOWN
=====Problem Statement===== You are given a positive integer N. Your task is to print a palindromic triangle of size N. For example, a palindromic triangle of size 5 is: 1 121 12321 1234321 123454321 You can't take more than two lines. The first line (a for-statement) is already written for you. You have to complete the code using exactly one print statement. Note: Using anything related to strings will give a score of 0. Using more than one for-statement will give a score of 0. =====Input Format===== A single line of input containing the integer N. =====Constraints===== 0<N<10 =====Output Format===== Print the palindromic triangle of size N as explained above.
["for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also\n print(((10**i//9)**2))\n"]
{"inputs": ["5"], "outputs": ["1\n121\n12321\n1234321\n123454321"]}
INTRODUCTORY
PYTHON3
HACKERRANK
141
for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also print
4639cc7693fb05098a3c1b4b1c6654fc
UNKNOWN
=====Problem Statement===== You are given a function f(X) = X^2. You are also given K lists. The ith list consists of N_i elements. You have to pick one element from each list so that the value from the equation below is maximized: S = (f(X_1) + f(X_2) + ... + f(X_k))%M X_i denotes the element picked from the ith list. Find the maximized value S_max obtained. % denotes the modulo operator. Note that you need to take exactly one element from each list, not necessarily the largest element. You add the squares of the chosen elements and perform the modulo operation. The maximum value that you can obtain, will be the answer to the problem. =====Input Format===== The first line contains 2 space separated integers K and M. The next K lines each contains an integer N_i, denoting the number of elements in the ith list, followed by space separated integers denoting the elements in the list. =====Constraints===== 1≤K≤7 1≤M≤1000 1≤N_i≤7 1≤Magnitude of elements in list≤10^9 =====Output Format===== Output a single integer denoting the value S_max.
["import itertools\n\nk, m = list(map(int,input().split()))\n\nmain_ar = []\nfor i in range(k):\n ar = list(map(int,input().split()))\n main_ar.append(ar[1:])\n\nall_combination = itertools.product(*main_ar)\nresult = 0\nfor single_combination in all_combination: \n result = max(sum([x*x for x in single_combination])%m,result)\nprint(result)\n", "#!/usr/bin/env python3\n\n\nfrom itertools import product\n\nK,M = list(map(int,input().split()))\nN = (list(map(int, input().split()))[1:] for _ in range(K))\nresults = [sum(i**2 for i in x)%M for x in product(*N)]\nprint((max(results)))\n\n\n\n\n"]
{"inputs": ["3 1000\n2 5 4\n3 7 8 9\n5 5 7 8 9 10"], "outputs": ["206"]}
INTRODUCTORY
PYTHON3
HACKERRANK
610
# Enter your code here. Read input from STDIN. Print output to STDOUT
064041b7797e456e67a5bdbee51a2b1d
UNKNOWN
=====Function Descriptions===== collections.OrderedDict An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Example Code >>> from collections import OrderedDict >>> >>> ordinary_dictionary = {} >>> ordinary_dictionary['a'] = 1 >>> ordinary_dictionary['b'] = 2 >>> ordinary_dictionary['c'] = 3 >>> ordinary_dictionary['d'] = 4 >>> ordinary_dictionary['e'] = 5 >>> >>> print ordinary_dictionary {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} >>> >>> ordered_dictionary = OrderedDict() >>> ordered_dictionary['a'] = 1 >>> ordered_dictionary['b'] = 2 >>> ordered_dictionary['c'] = 3 >>> ordered_dictionary['d'] = 4 >>> ordered_dictionary['e'] = 5 >>> >>> print ordered_dictionary OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) =====Problem Statement===== You are the manager of a supermarket. You have a list of N items together with their prices that consumers bought on a particular day. Your task is to print each item_name and net_price in order of its first occurrence. item_name = Name of the item. net_price = Quantity of the item sold multiplied by the price of each item. =====Input Format===== The first line contains the number of items, N. The next N lines contains the item's name and price, separated by a space. =====Constraints===== 0<N≤100 =====Output Format===== Print the item_name and net_price in order of its first occurrence.
["import collections, re\nn = int(input())\nitem_od = collections.OrderedDict()\nfor i in range(n):\n record_list = re.split(r'(\\d+)$',input().strip())\n item_name = record_list[0]\n item_price = int(record_list[1])\n if item_name not in item_od:\n item_od[item_name]=item_price\n else:\n item_od[item_name]=item_od[item_name]+item_price\n \nfor i in item_od:\n print((i+str(item_od[i])))\n", "from collections import OrderedDict\n\ndef __starting_point():\n num = int(input().strip())\n history = OrderedDict()\n \n for _ in range(num):\n get_log = input().strip().split()\n good = \" \".join(get_log[:-1])\n sold = int(get_log[-1])\n if good not in list(history.keys()):\n history[good] = sold\n else:\n history[good] += sold\n \n \n for key in list(history.keys()):\n print((\"{} {}\".format(key, history[key])))\n\n__starting_point()"]
{"inputs": ["9\nBANANA FRIES 12\nPOTATO CHIPS 30\nAPPLE JUICE 10\nCANDY 5\nAPPLE JUICE 10\nCANDY 5\nCANDY 5\nCANDY 5\nPOTATO CHIPS 30"], "outputs": ["BANANA FRIES 12\nPOTATO CHIPS 60\nAPPLE JUICE 20\nCANDY 20"]}
INTRODUCTORY
PYTHON3
HACKERRANK
980
# Enter your code here. Read input from STDIN. Print output to STDOUT
429cd569903e6ec3b99a25bdd4520608
UNKNOWN
=====Problem Statement===== You are given a spreadsheet that contains a list of N athletes and their details (such as age, height, weight and so on). You are required to sort the data based on the Kth attribute and print the final resulting table. Follow the example given below for better understanding. image Note that K is indexed from 0 to M-1, where M is the number of attributes. Note: If two attributes are the same for different rows, for example, if two atheletes are of the same age, print the row that appeared first in the input. =====Input Format===== The first line contains N and M separated by a space. The next N lines each contain M elements. The last line contains K. =====Constraints===== 1≤N,M≤1000 0≤K≤M Each element ≤ 1000 =====Output Format===== Print the N lines of the sorted table. Each line should contain the space separated elements. Check the sample below for clarity.
["n, m = map(int,input().split())\nar = []\nfor i in range(n):\n ar.append(list(map(int,input().split())))\nk = int(input())\nar = sorted(ar,key = lambda x:x[k])\nfor i in ar:\n [print(x,end=' ') for x in i]\n print('')\n", "#!/bin/python3\n\nimport sys\n\ndef __starting_point():\n n, m = input().strip().split(' ')\n n, m = [int(n), int(m)]\n arr = []\n for arr_i in range(n):\n arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]\n arr.append(arr_t)\n k = int(input().strip())\n \n for el in sorted(arr, key = lambda x: x[k]):\n print((\" \".join(map(str, el))))\n\n__starting_point()"]
{"inputs": ["5 3\n10 2 5\n7 1 0\n9 9 9\n1 23 12\n6 5 9\n1"], "outputs": ["7 1 0\n10 2 5\n6 5 9\n9 9 9\n1 23 12"]}
INTRODUCTORY
PYTHON3
HACKERRANK
655
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': nm = input().split() n = int(nm[0]) m = int(nm[1]) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) k = int(input())
2bf554d3e4c95e394d66e72a6442fd52
UNKNOWN
=====Function Descriptions===== The NumPy module also comes with a number of built-in routines for linear algebra calculations. These can be found in the sub-module linalg. linalg.det The linalg.det tool computes the determinant of an array. print numpy.linalg.det([[1 , 2], [2, 1]]) #Output : -3.0 linalg.eig The linalg.eig computes the eigenvalues and right eigenvectors of a square array. vals, vecs = numpy.linalg.eig([[1 , 2], [2, 1]]) print vals #Output : [ 3. -1.] print vecs #Output : [[ 0.70710678 -0.70710678] # [ 0.70710678 0.70710678]] linalg.inv The linalg.inv tool computes the (multiplicative) inverse of a matrix. print numpy.linalg.inv([[1 , 2], [2, 1]]) #Output : [[-0.33333333 0.66666667] # [ 0.66666667 -0.33333333]] =====Problem Statement===== You are given a square matrix A with dimensions NXN. Your task is to find the determinant. Note: Round the answer to 2 places after the decimal. =====Input Format===== The first line contains the integer N. The next N lines contains the space separated elements of array A. =====Output Format===== Print the determinant of A.
["import numpy\nn = int(input())\nar = []\nfor i in range(n):\n tmp = list(map(float,input().split()))\n ar.append(tmp)\nnp_ar = numpy.array(ar,float)\nprint((numpy.linalg.det(np_ar)))\n", "import numpy as np\n\nn = int(input().strip())\narray = np.array([[float(x) for x in input().strip().split()] for _ in range(n)], dtype = float)\n\nprint((np.linalg.det(array)))\n"]
{"inputs": ["2\n1.1 1.1\n1.1 1.1"], "outputs": ["0.0"]}
INTRODUCTORY
PYTHON3
HACKERRANK
377
import numpy
eb7abbebdf7240322859b3a254116687
UNKNOWN
=====Problem Statement===== In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left. NOTE: String letters are case-sensitive. =====Input Format===== The first line of input contains the original string. The next line contains the substring. =====Constraints===== 1 ≤ len(string) ≤ 200 Each character in the string is an ascii character. =====Output Format===== Output the integer number indicating the total number of occurrences of the substring in the original string.
["# Enter your code here. Read input from STDIN. Print output to STDOUT\ns=input()\nss=input()\ncnt=0\nlen_s=len(s)\nlen_ss=len(ss)\nfor i in range(0,len_s):\n tmp=s[i:i+len_ss]\n if(tmp==ss):\n cnt=cnt+1\nprint(cnt)\n", "def count_substring(string, sub_string):\n res = 0\n len_sub = len(sub_string)\n \n for i in range(len(string) - len_sub + 1):\n if string[i:i + len_sub] == sub_string:\n res += 1\n i += 1\n \n return res\n"]
{"inputs": ["ABCDCDC\nCDC"], "outputs": ["2"]}
INTRODUCTORY
PYTHON3
HACKERRANK
490
def count_substring(string, sub_string): return if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
a36299c0cc15a27a4e5901bb2cb14f80
UNKNOWN
=====Function Descriptions===== zip([iterable, ...]) This function returns a list of tuples. The ith tuple contains the ith element from each of the argument sequences or iterables. If the argument sequences are of unequal lengths, then the returned list is truncated to the length of the shortest argument sequence. Sample Code >>> print zip([1,2,3,4,5,6],'Hacker') [(1, 'H'), (2, 'a'), (3, 'c'), (4, 'k'), (5, 'e'), (6, 'r')] >>> >>> print zip([1,2,3,4,5,6],[0,9,8,7,6,5,4,3,2,1]) [(1, 0), (2, 9), (3, 8), (4, 7), (5, 6), (6, 5)] >>> >>> A = [1,2,3] >>> B = [6,5,4] >>> C = [7,8,9] >>> X = [A] + [B] + [C] >>> >>> print zip(*X) [(1, 6, 7), (2, 5, 8), (3, 4, 9)] =====Problem Statement===== The National University conducts an examination of N students in X subjects. Your task is to compute the average scores of each student. Average score = Sum of scores obtained in all subjects by a student / Total number of subjects The format for the general mark sheet is: Student ID -> ___1_____2_____3_____4_____5__ Subject 1 | 89 90 78 93 80 Subject 2 | 90 91 85 88 86 Subject 3 | 91 92 83 89 90.5 |______________________________ Average 90 91 82 90 85.5 =====Input Format===== The first line contains N and X separated by a space. The next X lines contains the space separated marks obtained by students in a particular subject. =====Constraints===== 0<N≤100 0<X≤100 =====Output Format===== Print the averages of all students on separate lines. The averages must be correct up to 1 decimal place.
["n, x = list(map(int,input().split()))\nar = [0 for i in range(n)]\nfor i in range(x):\n temp_ar=list(map(float,input().split()))\n for j in range(n):\n ar[j] += temp_ar[j]\nfor i in range(n):\n print((ar[i]/x))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n st_num, sb_num = list(map(int, input().strip().split()))\n scores = []\n \n for _ in range(sb_num):\n scores.append(list(map(float, input().strip().split())))\n \n for el in zip(*scores):\n print((sum(el)/sb_num))\n \n \n\n__starting_point()"]
{"inputs": ["5 3\n89 90 78 93 80\n90 91 85 88 86\n91 92 83 89 90.5"], "outputs": ["90.0 \n91.0 \n82.0 \n90.0 \n85.5"]}
INTRODUCTORY
PYTHON3
HACKERRANK
575
# Enter your code here. Read input from STDIN. Print output to STDOUT
67cebaf29ad3c17bab6c3b5bbf7d1ad3
UNKNOWN
=====Problem Statement===== ABC is a right triangle, 90°, at B. Therefore, ANGLE{ABC} = 90°. Point M is the midpoint of hypotenuse AC. You are given the lengths AB and BC. Your task is to find ANGLE{MBC} (angle θ°, as shown in the figure) in degrees. =====Input Format===== The first contains the length of side AB. The second line contains the length of side BC. =====Constraints===== 0<AB≤100 0<BC≤100 Lengths AB and BC are natural numbers. =====Output Format===== Output ANGLE{MBC} in degrees. Note: Round the angle to the nearest integer. Examples: If angle is 56.5000001°, then output 57°. If angle is 56.5000000°, then output 57°. If angle is 56.4999999°, then output 56°.
["import math\nab = float(input())\nbc = float(input())\nac = math.sqrt((ab*ab)+(bc*bc))\nbm = ac / 2.0\nmc = bm\n#let, \nb = mc\nc = bm\na = bc\n#where b=c\nangel_b_radian = math.acos(a / (2*b))\nangel_b_degree = int(round((180 * angel_b_radian) / math.pi))\noutput_str = str(angel_b_degree)+'\u00b0'\nprint(output_str)\n", "#!/usr/bin/env python3\n\nfrom math import atan\nfrom math import degrees\n\ndef __starting_point():\n ab = int(input().strip())\n bc = int(input().strip())\n \n print(\"{}\u00b0\".format(int(round(degrees(atan(ab/bc))))))\n__starting_point()"]
{"inputs": ["10\n10"], "outputs": ["45\u00b0"]}
INTRODUCTORY
PYTHON3
HACKERRANK
582
# Enter your code here. Read input from STDIN. Print output to STDOUT
6dfb7c008931e8d8b02189f93340e712
UNKNOWN
=====Problem Statement===== Neo has a complex matrix script. The matrix script is a NXM grid of strings. It consists of alphanumeric characters, spaces and symbols (!,@,#,$,%,&). To decode the script, Neo needs to read each column and select only the alphanumeric characters and connect them. Neo reads the column from top to bottom and starts reading from the leftmost column. If there are symbols or spaces between two alphanumeric characters of the decoded script, then Neo replaces them with a single space '' for better readability. Neo feels that there is no need to use 'if' conditions for decoding. Alphanumeric characters consist of: [A-Z, a-z, and 0-9]. =====Input Format===== The first line contains space-separated integers N (rows) and M (columns) respectively. The next N lines contain the row elements of the matrix script. =====Constraints===== 0<N,M<100 Note: A 0 score will be awarded for using 'if' conditions in your code. =====Output Format===== Print the decoded matrix script.
["import re\nn, m = list(map(int,input().split()))\ncharacter_ar = [''] * (n*m)\nfor i in range(n):\n line = input()\n for j in range(m):\n character_ar[i+(j*n)]=line[j]\ndecoded_str = ''.join(character_ar)\nfinal_decoded_str = re.sub(r'(?<=[A-Za-z0-9])([ !@#$%&]+)(?=[A-Za-z0-9])',' ',decoded_str)\nprint(final_decoded_str) \n", "import re\n\nn, m = input().strip().split(' ')\nn, m = [int(n), int(m)]\nmatrix = []\nfor _ in range(n):\n matrix_t = str(input())\n matrix.append(matrix_t)\n \ncomplete = \"\"\nfor el in zip(*matrix):\n complete += \"\".join(el)\nprint((re.sub(r'(?<=\\w)([^\\w]+)(?=\\w)', \" \", complete)))\n \n\n"]
{"inputs": ["7 3\nTsi\nh%x\ni #\nsM \n$a \n#t%\nir!"], "outputs": ["This is Matrix# %!"]}
INTRODUCTORY
PYTHON3
HACKERRANK
660
#!/bin/python3 import math import os import random import re import sys first_multiple_input = input().rstrip().split() n = int(first_multiple_input[0]) m = int(first_multiple_input[1]) matrix = [] for _ in range(n): matrix_item = input() matrix.append(matrix_item)
b9400e161dc992b8bc7cdd8c74449689
UNKNOWN
=====Function Descriptions===== The eval() expression is a very powerful built-in function of Python. It helps in evaluating an expression. The expression can be a Python statement, or a code object. For example: >>> eval("9 + 5") 14 >>> x = 2 >>> eval("x + 3") 5 Here, eval() can also be used to work with Python keywords or defined functions and variables. These would normally be stored as strings. For example: >>> type(eval("len")) <type 'builtin_function_or_method'> Without eval() >>> type("len") <type 'str'> =====Problem Statement===== You are given an expression in a line. Read that line as a string variable, such as var, and print the result using eval(var). NOTE: Python2 users, please import from __future__ import print_function. =====Constraints===== Input string is less than 100 characters.
["input()\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n input().strip()\n__starting_point()"]
{"inputs": ["print(2 + 3)"], "outputs": ["5"]}
INTRODUCTORY
PYTHON3
HACKERRANK
107
# Enter your code here. Read input from STDIN. Print output to STDOUT
6c125112fb67ec840da05e10cc890210
UNKNOWN
=====Problem Statement===== There is a horizontal row of n cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube_i is on top of cube_j then sideLength_j ≥ sideLength_i. When stacking the cubes, you can only pick up either the leftmost or the rightmost cube each time. Print "Yes" if it is possible to stack the cubes. Otherwise, print "No". Do not print the quotation marks. =====Input Format===== The first line contains a single integer T, the number of test cases. For each test case, there are 2 lines. The first line of each test case contains n, the number of cubes. The second line contains n space separated integers, denoting the sideLengths of each cube in that order. =====Constraints===== 1≤T≤5 1≤n≤10^5 1≤sideLength≤2^31 =====Output Format===== For each test case, output a single line containing either "Yes" or "No" without the quotes.
["from collections import deque\ncas = int(input())\nfor t in range(cas):\n n = int(input())\n dq = deque(list(map(int,input().split())))\n possible = True\n element = (2**31)+1\n while dq:\n left_element = dq[0]\n right_element = dq[-1]\n if left_element>=right_element and element>=left_element:\n element = dq.popleft()\n elif right_element>=left_element and element>=right_element:\n element = dq.pop()\n else:\n possible = False\n break\n if possible:\n print('Yes')\n else:\n print('No') \n", "#!/usr/bin/env python3\n\nfrom collections import deque\n\ndef __starting_point():\n t = int(input().strip())\n \n for _ in range(t):\n num_cnt = int(input().strip())\n deq = deque(list(map(int, input().strip().split(' '))))\n \n prev = max(deq[0], deq[-1])\n while deq:\n if prev >= deq[0] and prev >= deq[-1]:\n if deq[0] >= deq[-1]:\n prev = deq.popleft()\n else:\n prev = deq.pop()\n else:\n break\n \n if len(deq) == 0:\n print('Yes')\n else:\n print('No')\n \n\n__starting_point()"]
{"inputs": ["2\n6\n4 3 2 1 3 4\n3\n1 3 2\n"], "outputs": ["Yes\nNo\n"]}
INTRODUCTORY
PYTHON3
HACKERRANK
1,315
# Enter your code here. Read input from STDIN. Print output to STDOUT
f8f6700100689364c58949fe4d7d4873
UNKNOWN
=====Problem Statement===== When users post an update on social media,such as a URL, image, status update etc., other users in their network are able to view this new post on their news feed. Users can also see exactly when the post was published, i.e, how many hours, minutes or seconds ago. Since sometimes posts are published and viewed in different time zones, this can be confusing. You are given two timestamps of one such post that a user can see on his newsfeed in the following format: Day dd Mon yyyy hh:mm:ss +xxxx Here +xxxx represents the time zone. Your task is to print the absolute difference (in seconds) between them. =====Input Format===== The first line contains T, the number of tescases. Each testcase contains 2 lines, representing time t_1 and time t_2.
["import datetime\ncas = int(input())\nfor t in range(cas):\n timestamp1 = input().strip()\n timestamp2 = input().strip()\n time_format = \"%a %d %b %Y %H:%M:%S %z\"\n time_second1 = datetime.datetime.strptime(timestamp1,time_format)\n time_second2 = datetime.datetime.strptime(timestamp2,time_format)\n print((int(abs((time_second1-time_second2).total_seconds()))))\n", "import sys\nfrom datetime import datetime as dt\n\ndformat = \"%a %d %b %Y %H:%M:%S %z\"\ndef time_delta(t1, t2):\n first = dt.strptime(t1, dformat) \n second = dt.strptime(t2, dformat) \n \n return int(abs((first - second).total_seconds()))\n\ndef __starting_point():\n t = int(input().strip())\n for a0 in range(t):\n t1 = input().strip()\n t2 = input().strip()\n delta = time_delta(t1, t2)\n print(delta)\n\n__starting_point()"]
{"inputs": ["2\nSun 10 May 2015 13:54:36 -0700\nSun 10 May 2015 13:54:36 -0000\nSat 02 May 2015 19:54:36 +0530\nFri 01 May 2015 13:54:36 -0000"], "outputs": ["25200\n88200"]}
INTRODUCTORY
PYTHON3
HACKERRANK
867
#!/bin/python3 import math import os import random import re import sys # Complete the time_delta function below. def time_delta(t1, t2): if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): t1 = input() t2 = input() delta = time_delta(t1, t2) fptr.write(delta + '\n') fptr.close()
ccd08d4f8fd54f96c001609780d80071
UNKNOWN
=====Problem Statement===== You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. =====Example===== Www.HackerRank.com → wWW.hACKERrANK.COM Pythonist 2 → pYTHONIST 2 =====Input Format===== A single line containing a string S. =====Output Format===== Print the modified string S.
["def swap_case(s):\n newstring = \"\"\n \n for item in s:\n if item.isupper():\n newstring += item.lower()\n else:\n newstring += item.upper()\n \n return newstring\n", "def swap_case(s):\n out = ''\n for ind, let in enumerate(s):\n if let.isalpha():\n if let.islower():\n out += s[ind].capitalize()\n else:\n out += s[ind].lower()\n else:\n out += let\n return out"]
{"fn_name": "swap_case", "inputs": [["HackerRank.com presents \"Pythonist 2\"."]], "outputs": ["hACKERrANK.COM PRESENTS \"pYTHONIST 2\"."]}
INTRODUCTORY
PYTHON3
HACKERRANK
513
def swap_case(s): return if __name__ == '__main__': s = input() result = swap_case(s) print(result)
478467351e797ce778c2a7ae5eaab44f
UNKNOWN
=====Function Descriptions===== .symmetric_difference() The .symmetric_difference() operator returns a set with all the elements that are in the set and the iterable but not both. Sometimes, a ^ operator is used in place of the .symmetric_difference() tool, but it only operates on the set of elements in set. The set is immutable to the .symmetric_difference() operation (or ^ operation). >>> s = set("Hacker") >>> print s.symmetric_difference("Rank") set(['c', 'e', 'H', 'n', 'R', 'r']) >>> print s.symmetric_difference(set(['R', 'a', 'n', 'k'])) set(['c', 'e', 'H', 'n', 'R', 'r']) >>> print s.symmetric_difference(['R', 'a', 'n', 'k']) set(['c', 'e', 'H', 'n', 'R', 'r']) >>> print s.symmetric_difference(enumerate(['R', 'a', 'n', 'k'])) set(['a', 'c', 'e', 'H', (0, 'R'), 'r', (2, 'n'), 'k', (1, 'a'), (3, 'k')]) >>> print s.symmetric_difference({"Rank":1}) set(['a', 'c', 'e', 'H', 'k', 'Rank', 'r']) >>> s ^ set("Rank") set(['c', 'e', 'H', 'n', 'R', 'r']) =====Problem Statement===== Students of District College have subscriptions to English and French newspapers. Some students have subscribed to English only, some have subscribed to French only, and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to either the English or the French newspaper but not both. =====Input Format===== The first line contains the number of students who have subscribed to the English newspaper. The second line contains the space separated list of student roll numbers who have subscribed to the English newspaper. The third line contains the number of students who have subscribed to the French newspaper. The fourth line contains the space separated list of student roll numbers who have subscribed to the French newspaper. =====Constraints===== 0 < Total number of students in college < 1000 =====Output Format===== Output total number of students who have subscriptions to the English or the French newspaper but not both.
["e = int(input())\neng = set(map(int,input().split())) \nf = int(input())\nfre = set(map(int,input().split()))\nprint((len(eng ^ fre)))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n n = int(input().strip())\n english = set(map(int, input().strip().split(' ')))\n m = int(input().strip())\n french = set(map(int, input().strip().split(' ')))\n \n print(len(english.symmetric_difference(french)))\n__starting_point()"]
{"inputs": ["9\n1 2 3 4 5 6 7 8 9\n9\n10 1 2 3 11 21 55 6 8"], "outputs": ["8"]}
INTRODUCTORY
PYTHON3
HACKERRANK
446
# Enter your code here. Read input from STDIN. Print output to STDOUT
2ad6b4e666b3c39ac6faf6dfc62df2fe
UNKNOWN
=====Function Descriptions===== Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc. str.isalnum() This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9). >>> print 'ab123'.isalnum() True >>> print 'ab123#'.isalnum() False str.isalpha() This method checks if all the characters of a string are alphabetical (a-z and A-Z). >>> print 'abcD'.isalpha() True >>> print 'abcd1'.isalpha() False str.isdigit() This method checks if all the characters of a string are digits (0-9). >>> print '1234'.isdigit() True >>> print '123edsd'.isdigit() False str.islower() This method checks if all the characters of a string are lowercase characters (a-z). >>> print 'abcd123#'.islower() True >>> print 'Abcd123#'.islower() False str.isupper() This method checks if all the characters of a string are uppercase characters (A-Z). >>> print 'ABCD123#'.isupper() True >>> print 'Abcd123#'.isupper() False =====Problem Statement===== You are given a string S. Your task is to find out if the string S contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters. =====Input Format===== A single line containing a string S. =====Constraints===== 0 < len(S) < 1000 =====Output Format===== In the first line, print True if S has any alphanumeric characters. Otherwise, print False. In the second line, print True if S has any alphabetical characters. Otherwise, print False. In the third line, print True if S has any digits. Otherwise, print False. In the fourth line, print True if S has any lowercase characters. Otherwise, print False. In the fifth line, print True if S has any uppercase characters. Otherwise, print False.
["# Enter your code here. Read input from STDIN. Print output to STDOUT\ninputStr=input()\nresalnum = False\nresalpha = False\nresdigit = False\nreslower = False\nresupper = False\nfor i in inputStr:\n if(i.isalnum()):\n resalnum=True\n if(i.isalpha()):\n resalpha=True\n if(i.isdigit()):\n resdigit=True\n if(i.islower()):\n reslower=True\n if(i.isupper()):\n resupper=True\n \nprint(resalnum)\nprint(resalpha)\nprint(resdigit)\nprint(reslower)\nprint(resupper)\n", "def __starting_point():\n s = input()\n \n print((any(char.isalnum() for char in s)))\n print((any(char.isalpha() for char in s)))\n print((any(char.isdigit() for char in s)))\n print((any(char.islower() for char in s)))\n print((any(char.isupper() for char in s)))\n\n__starting_point()"]
{"inputs": ["qA2"], "outputs": ["True\nTrue\nTrue\nTrue\nTrue"]}
INTRODUCTORY
PYTHON3
HACKERRANK
831
if __name__ == '__main__': s = input()
24655525c67de984dbfeee4aa2f843c8
UNKNOWN
=====Function Descriptions===== itertools.combinations_with_replacement(iterable, r) This tool returns length subsequences of elements from the input iterable allowing individual elements to be repeated more than once. Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order. Sample Code >>> from itertools import combinations_with_replacement >>> >>> print list(combinations_with_replacement('12345',2)) [('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '2'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '3'), ('3', '4'), ('3', '5'), ('4', '4'), ('4', '5'), ('5', '5')] >>> >>> A = [1,1,3,3,3] >>> print list(combinations(A,2)) [(1, 1), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (3, 3), (3, 3), (3, 3)] =====Problem Statement===== You are given a string S. Your task is to print all possible size k replacement combinations of the string in lexicographic sorted order. =====Input Format===== A single line containing the string S and integer value k separated by a space. =====Constraints===== 0<k≤len(S) The string contains only UPPERCASE characters. =====Output Format===== Print the combinations with their replacements of string S on separate lines.
["from itertools import *\ns,n = input().split()\nn = int(n)\ns = sorted(s)\nfor j in combinations_with_replacement(s,n):\n print((''.join(j)))\n", "#!/usr/bin/env python3\n\nfrom itertools import combinations_with_replacement\n\ndef __starting_point():\n in_data = list(input().strip().split(' '))\n \n for el in combinations_with_replacement(sorted(in_data[0]), int(in_data[1])):\n print(\"\".join(el))\n__starting_point()"]
{"inputs": ["HACK 2"], "outputs": ["AA\nAC\nAH\nAK\nCC\nCH\nCK\nHH\nHK\nKK"]}
INTRODUCTORY
PYTHON3
HACKERRANK
445
# Enter your code here. Read input from STDIN. Print output to STDOUT
013822ed13ee23ada4a102ee2f9fc79b
UNKNOWN
=====Problem Statement===== CSS colors are defined using a hexadecimal (HEX) notation for the combination of Red, Green, and Blue color values (RGB). Specifications of HEX Color Code It must start with a '#' symbol. It can have 3 or 6 digits. Each digit is in the range of 0 to F. (1, 2, 3, 4, 5, 6, 7, 8, 9, 0, A, B, C, D, E and F). A – F letters can be lower case. (a, b, c, d, e and f are also valid digits). Examples Valid Hex Color Codes #FFF #025 #F0A1FB Invalid Hex Color Codes #fffabg #abcf #12365erff You are given N lines of CSS code. Your task is to print all valid Hex Color Codes, in order of their occurrence from top to bottom. CSS Code Pattern Selector { Property: Value; } =====Input Format===== The first line contains N, the number of code lines. The next N lines contains CSS Codes. =====Constraints===== 0<N<50 =====Output Format===== Output the color codes with '#' symbols on separate lines.
["import re\nn = int(input())\nfor t in range(n):\n s = input()\n match_result = re.findall(r'(#[0-9A-Fa-f]{3}|#[0-9A-Fa-f]{6})(?:[;,.)]{1})',s)\n for i in match_result:\n if i != '':\n print(i)\n", "import re\n\nn = int(input().strip())\ninside = False\nfor _ in range(n):\n line = input()\n \n for el in line.split(' '):\n if el == \"{\":\n inside = True\n continue\n elif el == \"}\":\n inside = False\n continue\n elif inside:\n found = re.search(r'\\#[0-9a-fA-F]{3,6}', el)\n if found:\n print(found.group(0))"]
{"inputs": ["11\n#BED\n{\n color: #FfFdF8; background-color:#aef;\n font-size: 123px;\n\n}\n#Cab\n{\n background-color: #ABC;\n border: 2px dashed #fff;\n}"], "outputs": ["#FfFdF8\n#aef\n#ABC\n#fff"]}
INTRODUCTORY
PYTHON3
HACKERRANK
654
# Enter your code here. Read input from STDIN. Print output to STDOUT
21b347154ac3a5078e76e07203106839
UNKNOWN
=====Problem Statement===== You are given a string S. Your task is to find out whether is a valid regex or not. =====Input Format===== The first line contains integer T, the number of test cases. The next T lines contains the string S. =====Constraints===== 0<T<100 =====Output Format===== Print "True" or "False" for each test case without quotes.
["import re\nn = int(input())\nfor i in range(n):\n s = input()\n try:\n re.compile(s)\n print(True)\n except Exception as e:\n print(False)\n", "#!/usr/bin/env python3\n\nimport re\n\ndef __starting_point():\n t = int(input().strip())\n \n for _ in range(t):\n try:\n re.compile(input().strip())\n res = True\n except BaseException:\n res = False\n print(res)\n__starting_point()"]
{"inputs": ["2\n.*\\+\n.*+"], "outputs": ["True\nFalse"]}
INTRODUCTORY
PYTHON3
HACKERRANK
475
# Enter your code here. Read input from STDIN. Print output to STDOUT
3cfd87a8f57b391e7b978cc1a873e5f9
UNKNOWN
=====Function Descriptions===== .difference() The tool .difference() returns a set with all the elements from the set that are not in an iterable. Sometimes the - operator is used in place of the .difference() tool, but it only operates on the set of elements in set. Set is immutable to the .difference() operation (or the - operation). >>> s = set("Hacker") >>> print s.difference("Rank") set(['c', 'r', 'e', 'H']) >>> print s.difference(set(['R', 'a', 'n', 'k'])) set(['c', 'r', 'e', 'H']) >>> print s.difference(['R', 'a', 'n', 'k']) set(['c', 'r', 'e', 'H']) >>> print s.difference(enumerate(['R', 'a', 'n', 'k'])) set(['a', 'c', 'r', 'e', 'H', 'k']) >>> print s.difference({"Rank":1}) set(['a', 'c', 'e', 'H', 'k', 'r']) >>> s - set("Rank") set(['H', 'c', 'r', 'e']) =====Problem Statement===== Students of District College have a subscription to English and French newspapers. Some students have subscribed to only the English newspaper, some have subscribed to only the French newspaper, and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to only English newspapers. =====Input Format===== The first line contains the number of students who have subscribed to the English newspaper. The second line contains the space separated list of student roll numbers who have subscribed to the English newspaper. The third line contains the number of students who have subscribed to the French newspaper. The fourth line contains the space separated list of student roll numbers who have subscribed to the French newspaper. =====Constraints===== 0<Total number of students in college<1000 =====Output Format===== Output the total number of students who are subscribed to the English newspaper only.
["e = int(input())\neng = set(map(int,input().split())) \nf = int(input())\nfre = set(map(int,input().split()))\nprint((len(eng - fre)))\n", "#!/usr/bin/env python3\n\ndef __starting_point():\n n = int(input().strip())\n english = set(map(int, input().strip().split(' ')))\n m = int(input().strip())\n french = set(map(int, input().strip().split(' ')))\n \n print(len(english.difference(french)))\n__starting_point()"]
{"inputs": ["9\n1 2 3 4 5 6 7 8 9\n9\n10 1 2 3 11 21 55 6 8"], "outputs": ["4"]}
INTRODUCTORY
PYTHON3
HACKERRANK
436
# Enter your code here. Read input from STDIN. Print output to STDOUT
0d1edf4399593305127db81f35680698
UNKNOWN
=====Problem Statement===== Here is a sample line of code that can be executed in Python: print("Hello, World!") You can just as easily store a string as a variable and then print it to stdout: my_string = "Hello, World!" print(my_string) The above code will print Hello, World! on your screen. Try it yourself in the editor below! =====Input Format===== You do not need to read any input in this challenge. =====Output Format===== Print Hello, World! to stdout.
["def __starting_point():\n print(\"Hello, World!\")\n\n__starting_point()"]
{"inputs": [""], "outputs": ["Hello, World!"]}
INTRODUCTORY
PYTHON3
HACKERRANK
79
print("")
60a3a0ca04dca00e2d30c266dac63687
UNKNOWN
Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L. She will concatenate all of the strings in some order, to produce a long string. Among all strings that she can produce in this way, find the lexicographically smallest one. Here, a string s=s_1s_2s_3...s_n is lexicographically smaller than another string t=t_1t_2t_3...t_m if and only if one of the following holds: - There exists an index i(1≦i≦min(n,m)), such that s_j = t_j for all indices j(1≦j<i), and s_i<t_i. - s_i = t_i for all integers i(1≦i≦min(n,m)), and n<m. -----Constraints----- - 1 ≦ N, L ≦ 100 - For each i, the length of S_i equals L. - For each i, S_i consists of lowercase letters. -----Input----- The input is given from Standard Input in the following format: N L S_1 S_2 : S_N -----Output----- Print the lexicographically smallest string that Iroha can produce. -----Sample Input----- 3 3 dxx axx cxx -----Sample Output----- axxcxxdxx The following order should be used: axx, cxx, dxx.
["n,l = map(int,input().split())\na = []\nfor i in range(n):\n a.append(input())\n \na.sort()\nprint(\"\".join(str(i) for i in a))", "n,l = [int(x) for x in input().split()]\ns = []\nfor i in range(n):\n s.append(input())\ns.sort()\n\nprint(\"\".join(s))", "n, l = map(int, input().split( ))\nt = list()\nfor i in range(n):\n s = input()\n t.append(s)\nt.sort()\nans = \"\"\nfor j in range(n):\n ans += t[j]\nprint(ans)", "n, l = list(map(int, input().split()))\ns = []\nfor i in range(n):\n s.append(input())\ns.sort()\nprint((''.join(s)))\n", "N,L=map(int,input().split())\nS=[]\nfor i in range(N):\n S.append(input())\nS.sort()\nprint(\"\".join(S))", "#-*-coding:utf-8-*-\nimport sys\ninput=sys.stdin.readline\n\ndef main():\n n,l = map(int,input().split())\n words=[]\n words=[input().rstrip() for _ in range(n)]\n s_words=sorted(words,key=lambda x:x[0:])\n ans=\"\"\n\n for s_word in s_words:\n ans+=s_word\n print(ans)\ndef __starting_point():\n main()\n__starting_point()", "def main():\n N, L = list(map(int, input().split()))\n Sn = [input() for i in range(N)]\n Sn2 = sorted(Sn)\n ans = \"\"\n for val in Sn2 :\n ans = ans + val\n print(ans)\n\ndef __starting_point():\n main()\n\n__starting_point()", "N, L = list(map(int, input().split()))\nS = []\nfor i in range(N):\n S.append(input())\n\nprint((''.join(sorted(S))))\n", "n,l = map(int,input().split())\ns = [input() for _ in range(n)]\ns.sort()\nprint(\"\".join(s))", "import sys\ndef readint():\n return int(sys.stdin.readline())\n\ndef readints():\n return tuple(map(int,sys.stdin.readline().split()))\n\ndef readintslist(n):\n return [tuple(map(int,sys.stdin.readline().split())) for _ in range(n)]\n\ndef main():\n n,l = readints()\n\n s = [input() for _ in range(n)]\n\n s = sorted(s)\n print(*s,sep='')\n\ndef __starting_point():\n main()\n__starting_point()", "_, _, *S = open(0).read().split()\nprint(\"\".join(sorted(S)))", "N, L = map(int,input().split())\nl = list()\nfor i in range(N):\n\tl.append(input())\nprint(*sorted(l),sep='')", "N, L = input().split()\nN, L = int(N), int(L)\nS = []\ncount = 0\n\nwhile count < N:\n\tstr = input()\n\tS.append(str)\n\tcount += 1\n\nS_ord = sorted(S)\nprint(''.join(S_ord))", "a,b=map(int,input().split())\ns=[]\nfor i in range(a):\n s.append(input())\ns.sort()\nfor i in range(a):\n print(s[i],end=\"\")", "n,l = map(int,input().split())\ns = sorted([input() for i in range(n)])\nprint(*s,sep=\"\")\n", "n, l = map(int, input().split())\ns = [input() for _ in range(n)]\ns = sorted(s)\n\nfor i in s:\n print(i,end = '')", "N, L = map(int, input().split())\nS = [input() for i in range(N)]\nsort = sorted(S)\n\nprint(''.join(sort))", "nl = list(map(int,input().split()))\nN = nl[0]\nL = nl[1]\nss = [input() for i in range(N)]\nss.sort()\nres = \"\"\nfor i in ss:\n res = res+i\nprint(res)", "N, L = map(int, input().split())\n\nS = sorted([input() for i in range(N)])\n\nprint(*S, sep=\"\")\n\n\n", "N,L=list(map(int,input().split()))\nS=[]\nfor i in range(N):\n S.append(input())\n\nprint((''.join(sorted(S))))\n", "nl = input().split()\n\nN = int(nl[0])\nL = int(nl[1])\n\nlst = []\n\nfor i in range(N):\n lst.append(input())\n\nlst.sort()\n\nans = ''\n\nfor s in lst:\n ans += s\n\nprint(ans)", "n,l=map(int,input().split())\ns=[]\nfor _ in range(n):\n s.append(input())\ns.sort()\nss=\"\".join(s)\nprint(ss)", "N,L = map(int, input().split())\nS = [input() for i in range(N)]\nS.sort()\nprint(\"\".join(S))", "main = list([int(x) for x in input().split()])\nn, l = main[0], main[1]\nfinal = []\nfor i in range(n):\n string = input()\n final.append(string)\n\nfinal.sort()\nprint((''.join(final)))\n", "n,l = map(int,input().split())\ns = [input() for _ in range(n)]\nan = ''\nfor _ in range(n):\n an += min(s)\n s.remove(min(s))\nprint(an)", "n,l = map(int, input().split())\nprint(\"\".join(sorted([input() for _ in range(n)])))", "#from statistics import median\n#import collections\n#aa = collections.Counter(a) # list to list || .most_common(2)\u3067\u6700\u5927\u306e2\u500b\u3068\u308a\u3060\u305b\u308b\u304a a[0][0]\nfrom math import gcd\nfrom itertools import combinations,permutations,accumulate, product # (string,3) 3\u56de\n#from collections import deque\nfrom collections import deque,defaultdict,Counter\nimport decimal\nimport re\nimport math\nimport bisect\nimport heapq\n#\n#\n#\n# python\u3067\u7121\u7406\u306a\u3068\u304d\u306f\u3001pypy\u3067\u3084\u308b\u3068\u6b63\u89e3\u3059\u308b\u304b\u3082\uff01\uff01\n#\n#\n# my_round_int = lambda x:np.round((x*2 + 1)//2)\n# \u56db\u6368\u4e94\u5165g\n#\n# \u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u7cfb\n# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);\n# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);\n#\n#\nimport sys\nsys.setrecursionlimit(10000000)\nmod = 10**9 + 7\n#mod = 9982443453\n#mod = 998244353\nINF = float('inf')\nfrom sys import stdin\nreadline = stdin.readline\ndef readInts():\n return list(map(int,readline().split()))\ndef readTuples():\n return tuple(map(int,readline().split()))\ndef I():\n return int(readline())\nn,l = readInts()\nS = sorted([input() for _ in range(n)])\nprint((''.join(S)))\n", "n, l = map(int,input().split())\na = []\nfor i in range(n):\n a.append(input())\n \na.sort()\nprint(''.join(a))", "N, L = map(int,input().split())\n\nword = []\ncount = 0\nwhile N > count:\n S = input()\n word.append(S)\n count += 1\n\nword = sorted(word)\nans = ''.join(word)\n\nprint(ans)", "n,l=map(int,input().split())\ns=list(input() for i in range(n))\ns.sort()\na=\"\"\nfor i in range(n):\n a=a+s[i]\nprint(a)", "n, l = list(map(int, input().split()))\n\nstrList = []\nfor _ in range(0, n):\n strList.append(input())\n\nstrList.sort()\n\nans = \"\"\nfor i in range(0, n):\n ans += strList[i]\n\nprint(ans)\n", "n, l = map(int, input().split())\nS = []\n\nfor i in range(n):\n s = input()\n S.append(s)\n \nS.sort()\n\nans = ''\nfor i in range(n):\n ans += S[i]\n \nprint(ans)", "N, L = map(int, input().split())\nS = []\nfor n in range(N):\n s = input()\n S.append(s)\nS.sort()\nprint(''.join(S))", "N, L = map(int, input().split())\nS = [\"\"] * N\nfor i in range(N):\n S[i] = input()\n\nS.sort()\nfor s in S:\n print(s, end = \"\")", "n,l = map(int,input().split())\nstrings = []\nfor _ in range(n):\n s = input()\n strings.append(s)\nstrings.sort()\nans = ''\nfor string in strings:\n ans += string\nprint(ans)", "N, L = map(int, input().split())\narray = [str(input()) for i in range(N)]\narray = sorted(array)\nans = ''\nfor j in array:\n ans = ans + j\nprint(ans)", "def main():\n N, L = list(map(int, input().split()))\n S = []\n for i in range(N):\n s = input()\n S.append(s)\n S.sort()\n ans = ''.join(S)\n print(ans)\n\ndef __starting_point():\n main()\n\n__starting_point()", "N, L = list(map(int, input().split()))\nS = [input() for _ in range(N)]\nS.sort()\nprint((\"\".join(S)))\n\n", "n, l = map(int, input().split())\ns = []\nfor i in range(n):\n s.append(input())\ns.sort()\nprint(''.join(s))", "N, L = map(int, input().split())\n\nstr_list = []\n\nfor w in range(N):\n str_list.append(input())\n\noutput = \"\".join(sorted(str_list))\nprint(output)", "#from statistics import median\n#import collections\n#aa = collections.Counter(a) # list to list || .most_common(2)\u3067\u6700\u5927\u306e2\u500b\u3068\u308a\u3060\u305b\u308b\u304a a[0][0]\nfrom math import gcd\nfrom itertools import combinations,permutations,accumulate, product # (string,3) 3\u56de\n#from collections import deque\nfrom collections import deque,defaultdict,Counter\nimport decimal\nimport re\nimport math\nimport bisect\nimport heapq\n#\n#\n#\n# python\u3067\u7121\u7406\u306a\u3068\u304d\u306f\u3001pypy\u3067\u3084\u308b\u3068\u6b63\u89e3\u3059\u308b\u304b\u3082\uff01\uff01\n#\n#\n# my_round_int = lambda x:np.round((x*2 + 1)//2)\n# \u56db\u6368\u4e94\u5165g\n#\n# \u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u7cfb\n# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);\n# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);\n#\n#\nimport sys\nsys.setrecursionlimit(10000000)\nmod = 10**9 + 7\n#mod = 9982443453\n#mod = 998244353\nINF = float('inf')\nfrom sys import stdin\nreadline = stdin.readline\ndef readInts():\n return list(map(int,readline().split()))\ndef readTuples():\n return tuple(map(int,readline().split()))\ndef I():\n return int(readline())\nn,l = readInts()\nlis = [input() for _ in range(n)]\nlis = sorted(lis)\nprint((''.join(lis)))\n", "N, L = map(int, input().split())\nS = [input() for _ in range(N)]\nS.sort()\nprint(''.join(S))", "n, l = map(int,input().split())\nwords = [input() for i in range(n)]\nwords = list(sorted(words))\ns = \"\"\nfor i in range(n):\n s += words[i]\nprint(s)", "N, L = map(int, input().split())\nS = [input() for i in range(N)]\n\nS_sorted = sorted(S)\nWord = ''.join(S_sorted)\n\nprint(Word)", "N,L,*Ss =open(0).read().split()\n\nans = \"\"\nfor s in sorted(Ss):\n ans+=s\nprint(ans)", "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\na = input().split()\nc = int(a[0])\nstrlist = []\nd = ''\nfor i in range(c):\n b = input().split()\n strlist.append(b[0])\n\nstrlist.sort()\nfor i in range(c):\n d += strlist[i] \nprint(d)", "n,l = map(int,input().split())\narr = []\nfor i in range(n):\n\tarr.append(input())\narr.sort()\nprint(''.join(arr))", "from sys import stdin, stdout\nfrom time import perf_counter\n\nimport sys\nsys.setrecursionlimit(10**9)\nmod = 10**9+7\n\n# import sys\n# sys.stdout = open(\"e:/cp/output.txt\",\"w\")\n# sys.stdin = open(\"e:/cp/input.txt\",\"r\")\n\nn,l = map(int,input().split())\na = [input() for item in range(n)]\nb = sorted(a)\nprint(''.join(b))", "n,l=map(int,input().split())\ns=sorted([input() for i in range(n)])\nans=\"\"\nfor i in range(n):\n ans+=s[i]\nprint(ans)", "n,l=map(int, input().split())\n\ns_list=[input() for i in range(n)]\n\ns_list.sort()\n\nprint(\"\".join(s_list))", "N,L = map(int,input().split())\nS = [input() for _ in range(N)]\n\nS.sort()\nprint(\"\".join(S))", "#N\u3068L\u3092\u5165\u529b\nN, L = map(int, input().split())\n\n\n# \u7a7a\u306e\u30ea\u30b9\u30c8\u3092\u751f\u6210\nS = []\n\n#\u5165\u529b\nfor i in range(N):\n array = input()\n S.append(array)\n\n#\u8f9e\u66f8\u9806\u306b\u4e26\u3079\u66ff\u3048\nS.sort()\n\n#python\u306e\u30ea\u30b9\u30c8\u306e\u51fa\u529b\u3067\u306f[\u3068,\u304c\u51fa\u529b\u3055\u308c\u308b\u306e\u3067\u53d6\u308b\nS=''.join(S)\n\n#\u51fa\u529b\nprint(S)", "N, L = map(int, input().split())\nS = sorted([input() for i in range(N)])\nprint(*S, sep=\"\")\n", "N, L = map(int, input().split())\ntext_list = [input() for _ in range(N)]\n\nsorted_list = sorted(text_list)\n\nprint(''.join(sorted_list))", "N, L = map(int, input().split())\nS = [input() for _ in range(N)]\nS.sort()\nfor s in S:\n print(s, end=\"\")", "N, L = map(int, input().split()) \nS = [input() for _ in range(N)] \nS.sort()\nprint(''.join(map(str, S)))", "N,L = map(int,input().split())\nS = []\nfor i in range(N):\n S.append(str(input()))\nS.sort()\nprint(''.join(S))", "n, l = list(map(int, input().split()))\ns = []\nfor i in range(n):\n s.append(input())\n\ns.sort()\nres = \"\"\nfor i in range(n):\n res += s[i]\nprint(res)\n", "N, L = map(int, input().split())\nprint(''.join(sorted([input() for _ in range(N)])))", "from collections import Counter\nimport math\nimport statistics\nimport itertools\na,b=list(map(int,input().split()))\n# b=input()\n# c=[]\n# for i in a:\n# c.append(int(i))\n# A,B,C= map(int,input().split())\n# f = list(map(int,input().split()))\n#g = [list(map(lambda x: '{}'.format(x), list(input()))) for _ in range(a)]\n# h = []\n# for i in range(a):\n# h.append(list(map(int,input().split())))\n# a = [[0] for _ in range(H)]#nizigen\nlis=[input() for i in range(a)]\nra=a-1\nfor i in range(ra):\n for k in range(ra-i):\n if lis[k]>lis[k+1]:\n a=lis[k]\n lis[k]=lis[k+1]\n lis[k+1]=a\nprint((\"\".join(lis)))\n\n", "n,l = map(int,input().split())\ns = [input() for _ in range(n)]\nans = sorted(s)\nprint(''.join(ans))", "import collections\nimport sys\n\nm = collections.defaultdict(int)\nline = input()\ntokens = line.split()\nn = int(tokens[0])\nstrings = []\nfor i in range(n):\n s = input()\n strings.append(s)\n\nprint(''.join(sorted(strings)))", "N, L = map(int,input().split())\nmat = []\nfor i in range(N):\n mat.append(input())\nwhile i <= N:\n FINISH = 0\n for i in range(N-1):\n if mat[i] > mat[i+1]:\n tmp = mat[i]\n mat[i] = mat[i+1]\n mat[i+1] = tmp\n FINISH += 1\n if FINISH == 0:\n break\nfor i in range(N):\n print(mat[i], end = \"\")", "n,l=map(int, input().split())\ns=[input() for i in range(n)]\nprint(\"\".join(sorted(s)))", "# N\u3001L\u306e\u5165\u529b\u53d7\u4ed8\nN, L = list(map(int, input().split()))\n# N\u56de\u9023\u7d9a\u3067\u5165\u529b\u6587\u5b57\u5217\u3092\u53d7\u4ed8\nS = []\nfor i in range(N):\n S.append(input())\n# S\u5185\u3092\u30bd\u30fc\u30c8\nS.sort()\n# S\u306e\u8981\u7d20\u3092\u7d50\u5408\nresult = \"\"\nfor i in range(N):\n result = result + S[i]\n# result\u3092\u51fa\u529b\nprint(result)\n", "n, l = map(int, input().split())\nstr = [input() for i in range(n)]\nstr.sort()\nfor i in str:\n print(i, end = '')", "# coding:UTF-8\nimport sys\n\n\ndef resultSur97(x):\n return x % (10 ** 9 + 7)\n\n\ndef __starting_point():\n # ------ \u5165\u529b ------#\n nl = list(map(int, input().split())) # \u30b9\u30da\u30fc\u30b9\u533a\u5207\u308a\u9023\u7d9a\u6570\u5b57\n\n x = nl[0]\n sList = [input() for _ in range(x)]\n\n # ------ \u51e6\u7406 ------#\n sListSorted = sorted(sList)\n out = \"\"\n for s in sListSorted:\n out += s\n\n # ------ \u51fa\u529b ------#\n print((\"{}\".format(out)))\n # if flg == 0:\n # print(\"YES\")\n # else:\n # print(\"NO\")\n\n__starting_point()", "n = list(map(int, input().split()))[0]\nss = list(sorted([input() for _ in range(n)]))\nprint((\"\".join(ss)))\n", "n, l = list(map(int, input().split()))\nA = [input() for _ in range(n)]\nA.sort()\nprint((\"\".join(A)))\n", "n, l = map(int,input().split())\nlw=[]\nfor i in range(n):\n lw.append(input())\nlw.sort()\nprint(\"\".join(lw))", "N, L = map(int, input().split())\nans = [input() for i in range(N)]\nans.sort()\nans = ''.join(ans)\nprint(ans)", "n,l = map(int, input().split())\nprint(\"\".join(sorted([input() for _ in range(n)])))", "#!/usr/bin/env python3\n\ndef main():\n n, l = list(map(int, input().split()))\n s = sorted([input() for i in range(n)])\n print((\"\".join(s)))\n\n\ndef __starting_point():\n main()\n\n__starting_point()", "N, L = map(int, input().split())\nans = [input() for i in range(N)]\nans.sort()\nans = ''.join(ans)\nprint(ans)", "n,l=map(int,input().split())\nli=[input() for i in range(n)]\n\nsortli=sorted(li)\nprint(''.join(sortli))", "n, l = map(int, input().split())\nsl = sorted(list(input() for _ in range(n)))\n\nprint(*sl, sep='')", "n, l = map(int, input().split())\nsl = list(input() for _ in range(n))\nsl_s = sorted(sl)\n\nprint(*sl_s, sep='')", "n,l = map(int, input().split())\nstring_list =[input() for i in range(n)]\nstring_list.sort()\nans = string_list[0]\nfor i in range(1,n):\n ans += string_list[i]\nprint(ans)", "n, l = map(int, input().split())\ns = [input() for _ in range(n)]\ns.sort()\nprint(\"\".join(s))", "# -*- coding: utf-8 -*-\n\nn,l = map(int,input().split())\ns = [input() for i in range(n)]\ns = sorted(s)\nprint(*s,sep=\"\")\n\n", "import itertools\nn,l = map(int,input().split())\nli = [list(input().split()) for i in range(n)]\n#print(li)\nli.sort()\n#print(li)\nlis = list(itertools.chain.from_iterable(li))\nprint(''.join(lis))", "n, l = map(int, input().split())\ns = [input() for _ in range(n)]\ns = sorted(s)\nprint(\"\".join(s))", "\nN,L = map(int,input().split())\n\nl = []\nfor _ in range(N):\n s = input()\n l.append(s)\n\nl.sort()\n\nfor i in l:\n print(i,end='')\n", "import math\nfrom datetime import date\n\ndef main():\n\t\t\n\tline = input().split()\n\tn = int(line[0])\n\tk = int(line[1])\n\n\n\ta = []\n\tfor i in range(n):\n\t\ts = input()\n\t\ta.append(s)\n\n\tans = \"\";\n\tfor x in sorted(a):\n\t\tans += x\n\n\tprint(ans)\n\t\nmain()\n", "n, l = map(int, input().split())\ns = [input() for _ in range(n)]\ns = sorted(s)\nprint(''.join(s))", "n,l=map(int,input().split())\na=[]\nfor i in range(n):\n s=input()\n a.append(s)\na.sort()\nprint(''.join(a))", "#!/usr/bin/env python3\n\nN, L = list(map(int ,input().split()))\nS = []\nfor i in range(N):\n S.append(input())\nS.sort()\nout = ''\nfor i in range(N):\n out = out + S[i]\n\nprint(out)\n", "n, l = map(int, input().split())\nlst = []\nfor i in range(n):\n s = input()\n lst.append(s)\nlst = sorted(lst)\nprint(''.join(lst))", "N, L = map(int, input().split())\na = []\n\nfor i in range(N):\n a.append(input())\n\na.sort()\n\nfor i in range(N):\n print(a[i],end=\"\")", "n,l = map(int,input().split())\nans = ''\nk = []\nfor i in range(n):\n s = input()\n k.append(s)\nk.sort()\nfor i in k:\n ans +=i\nprint(ans)", "N,L = map(int, input().split())\nword_list = [input() for i in range(N)]\n\nword_list.sort()\n\nfor i in word_list:\n print(i, end=\"\")\n\nprint()", "n, l = map(int, input().split())\ns_l = [ str(input()) for _ in range(n) ]\ns_l = sorted(s_l)\nprint(''.join(s_l))", "N, L = map(int, input().split())\nw = []\nfor _ in range(N):\n w.append(input())\n\nw.sort()\n\nprint(\"\".join(w))", "n,l = map(int,input().split())\ns = []\nfor i in range(n):\n s.append(input())\ns.sort()\nprint(\"\".join(s))", "N, L = map(int, input().split())\ns = []\nfor i in range(N):\n s.append(input())\nprint(''.join(sorted(s)))", "n,l= [int(x) for x in input().split()]\nla = []\nfor i in range(n):\n la.append(str(input()))\nla.sort()\nprint(\"\".join(str(x) for x in la))", "N,L=map(int, input().split())\nS=[]\n\nfor i in range(N):\n S.append(input())\nS.sort()\n\nfor i in range(N):\n print(S[i], end=\"\")", "n, l = list(map(int, input().split()))\n\ns = []\nfor i in range(n):\n s.append(input())\n\n\nprint((\"\".join(sorted(s))))\n", "from typing import List\n\n\ndef answer(n: int, l: int, s: List[str]) -> str:\n return ''.join(sorted(s))\n\n\ndef main():\n n, l = map(int, input().split())\n s = [input() for _ in range(n)]\n print(answer(n, l, s))\n\n\ndef __starting_point():\n main()\n__starting_point()", "# -*- coding: utf-8 -*-\n\ndef __starting_point():\n N, L = list(map(int, input().split()))\n si = []\n for i in range(N):\n si.append(str(input()))\n si.sort()\n print((''.join(si)))\n\n__starting_point()"]
{"inputs": ["3 3\ndxx\naxx\ncxx\n"], "outputs": ["axxcxxdxx\n"]}
INTRODUCTORY
PYTHON3
ATCODER.JP
18,815
30d073b697e7f43ee2842f1ec74fabf1
UNKNOWN
We are still with squared integers. Given 4 integers `a, b, c, d` we form the sum of the squares of `a` and `b` and then the sum of the squares of `c` and `d`. We multiply the two sums hence a number `n` and we try to decompose `n` in a sum of two squares `e` and `f` (e and f integers >= 0) so that `n = e² + f²`. More: `e` and `f` must result only from sums (or differences) of products between on the one hand `(a, b)` and on the other `(c, d)` each of `a, b, c, d` taken only once. For example, prod2sum(1, 2, 1, 3) should return [[1, 7], [5, 5]]) because ``` 1==1*3-1*2 7==2*3+1*1 5==1*2+1*3 ``` Suppose we have `a = 1, b = 2, c = 1, d = 3`. First we calculate the sums `1² + 2² = 5 and 1² + 3² = 10` hence `n = 50`. `50 = 1² + 7² or 50 = 7² + 1²` (we'll consider that these two solutions are the same) or `50 = 5² + 5²`. The return of our function will be an array of subarrays (in C an array of Pairs) sorted on the first elements of the subarrays. In each subarray the lower element should be the first. `prod2sum(1, 2, 1, 3) should return [[1, 7], [5, 5]]` `prod2sum(2, 3, 4, 5) should return [[2, 23], [7, 22]]` because `(2² + 3²) * (4² + 5²) = 533 = (7² + 22²) = (23² + 2²)` `prod2sum(1, 2, 2, 3) should return [[1, 8], [4, 7]]` `prod2sum(1, 1, 3, 5) should return [[2, 8]]` (there are not always 2 solutions). ##Hint Take a sheet of paper and with a bit of algebra try to write the product of squared numbers in another way.
["def prod2sum(a, b, c, d):\n e = sorted([abs(a*d-b*c), abs(a*c+b*d)])\n f = sorted([abs(a*c-b*d), abs(a*d+b*c)])\n if e == f:\n return [e]\n else:\n return sorted([e, f])\n\n", "def prod2sum(a, b, c, d):\n r1 = sorted([abs(a*c-b*d),abs(a*d+b*c)])\n r2 = sorted([abs(a*c+b*d),abs(a*d-b*c)])\n return sorted([r1,r2]) if r1!=r2 else [r1]", "prod2sum=lambda a,b,c,d:sorted([list(i) for i in {tuple(sorted(map(abs,[(a*d)+(b*c),(a*c)-(b*d)]))),tuple(sorted(map(abs,[(a*c)+(b*d),abs((a*d)-(b*c))])))}])", "def prod2sum(a, b, c, d):\n num = [a, b, c, d]\n if sorted([abs(num[0] * num[2] - num[1] * num[3]), abs(num[0] * num[3] + num[1] * num[2])]) == sorted([num[0] * num[3] - num[1] * num[2], num[0] * num[2] + num[1] * num[3]]):\n return [sorted([abs(num[0] * num[3] + num[1] * num[2]), abs(num[0] * num[2] - num[1] * num[3])])]\n else:\n if sorted([abs(num[0] * num[3] - num[1] * num[2]), abs(num[0] * num[2] + num[1] * num[3])])[0] < sorted([abs(num[0] * num[2] - num[1] * num[3]), abs(num[0] * num[3] + num[1] * num[2])])[0]:\n return [sorted([abs(num[0] * num[3] - num[1] * num[2]), abs(num[0] * num[2] + num[1] * num[3])]), sorted([abs(num[0] * num[2] - num[1] * num[3]), abs(num[0] * num[3] + num[1] * num[2])])]\n else:\n return [sorted([abs(num[0] * num[2] - num[1] * num[3]), abs(num[0] * num[3] + num[1] * num[2])]), sorted([abs(num[0] * num[3] - num[1] * num[2]), abs(num[0] * num[2] + num[1] * num[3])])]\n\n\n", "def chsgn(k):\n r = []\n for x in k:\n if (x < 0):\n r.append(-x)\n else:\n r.append(x)\n return r\n\ndef prod2sum(a, b, c, d):\n e1 = a * c + b * d\n f1 = a * d - b * c\n e2 = a * c - b * d\n f2 = a * d + b * c \n k = chsgn([e1, e2, f1, f2])\n e1 = k[0]; e2 = k[1]; f1 = k[2]; f2 = k[3]\n if ((e1 == f2) and (f1 == e2)) or ((e1 == e2) and (f1 == f2)): \n res = [[min(e1,f1), max(e1,f1)]]\n else:\n res = [[min(e1,f1), max(e1,f1)]]\n res.append([min(e2,f2), max(e2,f2)])\n res = sorted(res, key=lambda x: x[0])\n return res\n", "def prod2sum(a, b, c, d):\n result = map(sorted, [map(abs, [a * d - b * c, a * c + b * d]), map(abs, [b * d - a * c, b * c + a * d])])\n return sorted(result, key=lambda x: x[0])[:2 - (a == b or b == 0)]", "prod2sum = lambda a, b, c, d: sorted(map(list, {tuple(sorted(map(abs, s))) for s in ((a*c - b*d, a*d + b*c), (a*d - b*c, a*c + b*d))}))", "def prod2sum(a, b, c, d):\n l1 = sorted([abs(a*c+b*d),abs(a*d-b*c)])\n l2 = sorted([abs(a*c-b*d),abs(a*d+b*c)])\n if l1==l2:\n return [l1]\n else:\n return sorted([l1,l2])", "def prod2sum(a,b,c,d):\n hi = sorted([abs(a*c+b*d), abs(a*d-b*c)])\n hello = sorted([abs(a*c-b*d), abs(a*d+b*c)])\n if hi == hello:\n return [hi]\n else:\n return sorted([hi, hello])", "def as_pair(z):\n pos_int = lambda x: abs(int(x))\n return sorted( map(pos_int, [z.real, z.imag]) )\n\ndef prod2sum(a, b, c, d):\n z = complex(a,b)\n w = complex(c,d)\n results = list(map(as_pair, [z * w, z * w.conjugate()]))\n if results[1]==results[0]:\n results.pop()\n return sorted(results)\n"]
{"fn_name": "prod2sum", "inputs": [[1, 2, 1, 3], [2, 3, 4, 5], [1, 2, 2, 3], [1, 1, 3, 5], [10, 11, 12, 13], [1, 20, -4, -5], [100, 100, 100, 100], [0, 0, 0, 0], [-14, 12, -10, 8], [7, 96, -1, 81], [112, 0, 0, 1]], "outputs": [[[[1, 7], [5, 5]]], [[[2, 23], [7, 22]]], [[[1, 8], [4, 7]]], [[[2, 8]]], [[[2, 263], [23, 262]]], [[[75, 104], [85, 96]]], [[[0, 20000]]], [[[0, 0]]], [[[8, 236], [44, 232]]], [[[471, 7783], [663, 7769]]], [[[0, 112]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,227
def prod2sum(a, b, c, d):
b916178c8aa3f1ee1dee900e0c0ac636
UNKNOWN
Your task is to write a function which counts the number of squares contained in an ASCII art picture. The input pictures contain rectangles---some of them squares---drawn with the characters `-`, `|`, and `+`, where `-` and `|` are used to represent horizontal and vertical sides, and `+` is used to represent corners and intersections. Each picture may contain multiple, possibly overlapping, rectangles. A simple example input looks like this: +--+ +----+ | | | | +-+ | | +----+ | | +--+ +-+ There are two squares and one rectangle in this picture, so your function should return 2 for this input. The following picture does not contain any squares, so the answer for this one is 0: +------+ | | +------+ Here is another, more complex input: +---+ | | | +-+-+ | | | | +-+-+ | | | +---+ The answer for this one is 3: two big squares, and a smaller square formed by the intersection of the two bigger ones. Similarly, the answer for the following picture is 5: +-+-+ | | | +-+-+ | | | +-+-+ You are going to implement a function `count_squares()` which takes an ASCII art picture as input and returns the number of squares the picture shows. The input to that function is an array of strings, where each string corresponds to a line of the ASCII art picture. Each string is guaranteed to contain only the characters `-`, `|`, `+`, and `` `` (space). The smallest valid square has a side length of 2 and is represented by four `+` characters arranged in a square; a single `+` character is not considered a square. Have fun!
["def count_squares(lines):\n def s(i, j, z):\n try:\n return (\n '+' == lines[i+z][j] == lines[i][j+z] == lines[i+z][j+z]\n and all(lines[i][c] in '-+' for c in range(j+1, j+z))\n and all(lines[i+z][c] in '-+' for c in range(j+1, j+z))\n and all(lines[r][j] in '|+' for r in range(i+1, i+z))\n and all(lines[r][j+z] in '|+' for r in range(i+1, i+z))\n )\n except IndexError:\n return 0\n return sum(\n x == '+' and sum(s(i, j, z) for z in range(1, min(len(lines)-i, len(row)-j)))\n for i, row in enumerate(lines[:-1])\n for j, x in enumerate(row[:-1])\n )\n", "import re\ndef count_squares(lines):\n h, w = len(lines), max(map(len, lines))\n grid = \"\\t\".join(line.ljust(w) for line in lines)\n\n return sum(\n len(re.findall(r\"(?=\\+[-+]{%d}\\+.{%d}(?:[|+].{%d}[|+].{%d}){%d}\\+[-+]{%d}\\+)\"\n % (i, w+1-i-2, i, w+1-i-2, i, i), grid))\n for i in range(0, min(w,h)-1)\n )", "def count_squares(img):\n h,w,r=len(img),max([len(s) for s in img]),0\n img=[s+\" \"*(w-len(s)) for s in img]\n for i in range(h): \n for j in range(w):\n if img[i][j]==\"+\":\n for k in range(1,min(h-i,w-j)):\n if img[i+k][j+k]==\"+\" and img[i+k][j]==\"+\" and img[i][j+k]==\"+\":\n s1=img[i][j+1:j+k]+img[i+k][j+1:j+k]\n s2=\"\".join([x[j] for x in img])[i+1:i+k]+\"\".join([x[j+k] for x in img])[i+1:i+k]\n if not (\" \" in s1+s2 or \"|\" in s1 or \"-\" in s2): r+=1\n return r", "def count_squares(lines):\n print('\\n'.join(lines))\n tot=0\n for l in range(len(lines)):\n for i in range(len(lines[l])-1):\n if lines[l][i]!='+': continue\n for j in range(i+1,len(lines[l])):\n if lines[l][j]=='+':\n try:\n n=j-i\n if lines[l+n][i]=='+'==lines[l+n][j] \\\n and all(lines[m][i] not in ' -' for m in range(l+1,l+n)) \\\n and all(lines[m][j] not in' -' for m in range(l+1,l+n)) \\\n and all(lines[l][m] not in ' |' for m in range(i+1,j)) \\\n and all(lines[l+n][m] not in ' |' for m in range(i+1,j)):\n tot+=1\n except:\n pass\n return tot", "import re\ndef count_squares(shapes):\n squares = 0\n for i, j in enumerate(shapes):\n ind = [k for k, l in enumerate(j) if l == '+']\n for o in range(len(ind)):\n for p in range(o + 1, len(ind)):\n \n k, l = ind[o], ind[p]\n width = l - k\n if i + width >= len(shapes): continue\n \n upper_line = j[k:l + 1]\n left_line = ''.join([n[k] if k < len(n) else ' ' for n in shapes[i:i + width + 1]])\n right_line = ''.join([n[l] if l < len(n) else ' ' for n in shapes[i:i + width + 1]])\n bottom_line = shapes[i + width][k:l + 1]\n \n if all(re.fullmatch(r'\\+[{}]*\\+'.format(ch), seq) for seq, ch in \\\n zip([upper_line, left_line, right_line, bottom_line], '\\+\\- |\\+ |\\+ \\-\\+'.split())):\n squares += 1\n return squares", "from itertools import combinations\n\ndef count_squares(lines):\n def is_valid(x, y, size):\n if any([chars.get((nx, y), '@') not in '-+' or chars.get((nx, y+size), '@') not in '-+' for nx in range(x+1, x+size)]):\n return False\n if any([chars.get((x, ny), '@') not in '|+' or chars.get((x+size, ny), '@') not in '|+' for ny in range(y+1, y+size)]):\n return False\n return True\n\n chars, corners = dict(), [[] for _ in range(len(lines))]\n for y, line in enumerate(lines):\n for x, ch in enumerate(line):\n chars[(x, y)] = ch\n if ch == '+':\n corners[y].append(x)\n return sum(is_valid(tl, y, tr - tl) for y, co in enumerate(corners) for tl, tr in combinations(co, 2)\n if chars.get((tl, y + tr - tl)) == '+' and chars.get((tr, y + tr - tl)) == '+')", "from itertools import count\n\n# Optimization, what's that?\ndef count_squares(lines):\n def check(i, j, k):\n return (lines[i+k][j] == lines[i][j+k] == lines[i+k][j+k] == '+'\n and all(lines[x][j] in \"|+\" for x in range(i+1, i+k))\n and all(lines[i][x] in \"-+\" for x in range(j+1, j+k))\n and all(lines[x][j+k] in \"|+\" for x in range(i+1, i+k))\n and all(lines[i+k][x] in \"-+\" for x in range(j+1, j+k)))\n res = 0\n for i,row in enumerate(lines):\n for j,c in enumerate(row):\n if c == '+':\n for k in count(1):\n try: res += check(i, j, k)\n except: break\n return res", "def isInvalid(lines, y, x, chars):\n if y >= len(lines) or x >= len(lines[y]):\n return True\n return lines[y][x] not in chars\n\ndef isSquare(lines, x, y, size):\n if isInvalid(lines, y, x, '+') or \\\n isInvalid(lines, y+size, x, '+') or \\\n isInvalid(lines, y, x+size, '+') or \\\n isInvalid(lines, y+size, x+size, '+'):\n return False\n for s in range(size + 1):\n if isInvalid(lines, y, x+s, '+-') or \\\n isInvalid(lines, y+s, x, '+|') or \\\n isInvalid(lines, y+size, x+s, '+-') or \\\n isInvalid(lines, y+s, x+size, '+|'):\n return False\n return True\n\ndef count_squares(lines):\n count = 0\n for y in range(len(lines)):\n for x in range(len(lines[y])):\n for s in range(1, min(len(lines)-y, len(lines[y])-x)):\n if isSquare(lines, x, y, s):\n count += 1\n return count", "def count_squares(lines):\n \n sides = {(r, c):v for r, row in enumerate(lines) for c, v in enumerate(row) if v in '+-|'}\n nodes = sorted(k for k, v in sides.items() if v == '+')[::-1]\n\n sideh = lambda r, c, target: all(sides.get((r, c + cc), ' ') in '+-' for cc in range(target - c))\n sidev = lambda r, c, target: all(sides.get((r + rr, c), ' ') in '+|' for rr in range(target - r))\n\n t = 0\n while nodes:\n r, c = nodes.pop()\n for cc in [p[1] for p in nodes if r == p[0] and sideh(r, c, p[1])]:\n rr = r + cc - c\n if (rr, c) in nodes and (rr, cc) in nodes and sidev(r, c, rr) and sidev(r, cc, rr) and sideh(rr, c, cc):\n t += 1\n return t", "def count_squares(lines):\n def is_topleft(i, j):\n b = lines[i][j] == '+'\n b = b and i+1 < len(lines) and j < len(lines[i+1]) and lines[i+1][j] in '|+' \n b = b and j+1 < len(lines[i]) and lines[i][j+1] in '-+'\n return b\n def is_square(i, j, k):\n b = i + k < len(lines) and all(j + k < len(lines[r]) for r in range(i, i+k+1))\n b = b and lines[i][j] == lines[i][j+k] == lines[i+k][j] == lines[i+k][j+k] == '+'\n if k > 1:\n b = b and all(lines[r][j] in '+|' and lines[r][j+k] in '+|' for r in range(i, i+k+1))\n b = b and all(lines[i][c] in '+-' and lines[i+k][c] in '+-'for c in range(j, j+k+1))\n return b\n cnt = 0\n for i in range(len(lines)-1):\n for j in range(len(lines[i])-1):\n if is_topleft(i, j):\n for k in range(1, len(lines[i]) - j):\n if is_square(i, j, k):\n cnt += 1\n return cnt"]
{"fn_name": "count_squares", "inputs": [[["+--+ +----+", "| | | | +-+", "| | +----+ | |", "+--+ +-+"]], [["+-----+", "| |", "+-----+"]], [["+---+", "| |", "| +-+-+", "| | | |", "+-+-+ |", " | |", " +---+"]], [["+-+-+", "| | |", "+-+-+", "| | |", "+-+-+"]], [["+---+", "| |", "| |", "| |", "| |", "| |", "| |", "| |", "+---+"]], [["+---+", "| |", "| |", "| |", "+---+"]], [["+---+", "| |", "| ++--+", "| || |", "+--++ |", " | |", " +---+"]], [[" +---+", " | |", "+--++ |", "| || |", "| ++--+", "| |", "+---+"]], [["+---+", "| |", "| | +---+", "| | | |", "+---+ | |", " | |", " +---+"]], [["+---+---+", "| | |", "| | |", "| | |", "+---+---+", "| | |", "| | |", "| | |", "+---+---+"]], [["+----+--+", "| | |", "| | |", "| | |", "+----+--+", "| | |", "| | |", "| | |", "+----+--+"]], [["+---+---+", "| | |", "| | |", "| | |", "| | |", "+---+---+", "| | |", "| | |", "+---+---+"]], [["+---+---+", "| | |", "| +-+-+ |", "| | | | |", "+-+-+-+-+", "| | | | |", "| +-+-+ |", "| | |", "+---+---+"]], [[" +---+", " | |", " | | +--+", "+-+-+ | | |", "| +-+-+ | |", "+---+ +--+"]], [["+---+", "| |", "| |", "+--+|+--+", "+--++| |", "+--+-+--+", " | |", " | |", " +-+"]], [["+---------+--+", "| +---+ | |", "| | | | |", "| | | +--+", "| | | |", "| +---+ |", "| |", "| |", "| |", "| |", "| +---+---+", "| | | |", "| | | |", "+----+---+---+", " +---+"]], [["++", "++"]], [["+"]], [[" +--+", " | |", " | |", "+--+--+--+", "| | | |", "| | | |", "+--+--+--+", " | |", " | |", " +--+"]], [["+--+ +--+", "| | | |", "| | | |", "+--+--+--+", " | |", " | |", "+--+--+--+", "| | | |", "| | | |", "+--+ +--+"]], [[" +--+ +--+", " | | | |", " | | | |", "+--+--+--+--+", "| | | |", "| | | |", "+--+--+--+--+", " | | | |", " | | | |", "+--+--+--+--+", "| | | |", "| | | |", "+--+ +--+"]], [["+-+ +-+", "| | | |", "+-+ +-+", "+-+ +-+", "| | | |", "+-+ +-+"]], [["+-+---+", "| | |", "| | |", "+-+-+-+", "| | | |", "| | | |", "+-+ +-+"]], [["++++++++", "++++++++", "++++++++", "++++++++", "++++++++", "++++++++", "++++++++", "++++++++"]], [["", " +--+", " +--++ | +-+", " | || | | |", " | ++-+---+-+", " | | | |", " +---+-+ |", " | |", " +---+", "", "+---+", "| |", "| |", "| |", "+---+"]]], "outputs": [[2], [0], [3], [5], [0], [1], [2], [2], [2], [5], [1], [1], [10], [2], [1], [4], [1], [0], [5], [5], [11], [4], [0], [140], [6]]}
INTRODUCTORY
PYTHON3
CODEWARS
7,666
def count_squares(lines):
74e5178cab2d5f563590aca48825bb45
UNKNOWN
For this game of `BINGO`, you will receive a single array of 10 numbers from 1 to 26 as an input. Duplicate numbers within the array are possible. Each number corresponds to their alphabetical order letter (e.g. 1 = A. 2 = B, etc). Write a function where you will win the game if your numbers can spell `"BINGO"`. They do not need to be in the right order in the input array). Otherwise you will lose. Your outputs should be `"WIN"` or `"LOSE"` respectively.
["BINGO = {ord(c)-64 for c in \"BINGO\"}\n\ndef bingo(lst): \n return \"WIN\" if set(lst) >= BINGO else \"LOSE\"", "def bingo(array): \n return \"WIN\" if all(i in array for i in [2,9,14,7,15]) else \"LOSE\"", "def bingo(array):\n ctr = 0\n for i in [2, 9, 14, 7, 15]:\n if i in list(set(array)):\n ctr += 1\n if ctr == 5:\n return \"WIN\"\n else:\n return \"LOSE\"\n pass", "def bingo(array): \n return \"WIN\" if {2, 7, 9, 14, 15}.issubset(set(array)) else \"LOSE\"\n", "def bingo(array): \n return [\"LOSE\", \"WIN\"][{2, 7, 9, 14, 15} <= set(array)]", "def bingo(array): \n return ('LOSE', 'WIN')[{2, 7, 9, 14, 15} <= set(array)]", "def bingo(array): \n return 'LOSE' if set('bingo') - set(chr(i + 96) for i in array) else 'WIN'", "def bingo(a): \n return \"WIN\" if all([x in a for x in [2, 7, 9, 14, 15]]) else \"LOSE\"", "def bingo(array):\n a = set()\n for x in array:\n if x ==2 or x == 9 or x == 14 or x ==7 or x== 15:\n a.add(x)\n return (\"WIN\" if len(a) >= 5 else \"LOSE\")\n", "def bingo(a):\n return \"LWOISNE\"[{2, 7, 9, 14, 15} <= set(a)::2]"]
{"fn_name": "bingo", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [[20, 12, 23, 14, 6, 22, 12, 17, 2, 26]], [[1, 2, 3, 7, 5, 14, 7, 15, 9, 10]], [[5, 2, 13, 7, 5, 14, 17, 15, 9, 10]]], "outputs": [["LOSE"], ["LOSE"], ["WIN"], ["WIN"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,159
def bingo(array):
ee517dace9c54c0460411a114f220a42
UNKNOWN
Kate and Michael want to buy a pizza and share it. Depending on the price of the pizza, they are going to divide the costs: * If the pizza is less than €5,- Michael invites Kate, so Michael pays the full price. * Otherwise Kate will contribute 1/3 of the price, but no more than €10 (she's broke :-) and Michael pays the rest. How much is Michael going to pay? Calculate the amount with two decimals, if necessary.
["def michael_pays(cost):\n return round(cost if cost < 5 else max(cost*2/3, cost-10), 2)", "def michael_pays(c):\n return round(c if c < 5 else c * 2 / 3 if c <= 30 else c - 10, 2)", "def michael_pays(costs):\n if costs < 5:\n michael = costs\n else:\n kate = min(costs / 3, 10)\n michael = costs - kate\n return round(michael, 2)", "def michael_pays(c):\n return round(max(c if c < 5 else c * 2/3, c - 10), 2)", "def michael_pays(costs):\n return round(costs - (costs >= 5)*min(costs/3., 10), 2)", "def michael_pays(costs):\n if costs<5: return round(costs, 2)\n else: return round(max(costs-10, 2/3*costs), 2)", "def michael_pays(costs):\n return round(costs - min(0 if costs < 5 else 10, costs / 3), 2)", "def michael_pays(costs):\n return round(costs, 2) if costs < 5 else round(max(costs-10, costs/3*2), 2)", "def michael_pays(costs):\n kate = round((costs/3), 2)\n if costs < 5:\n return round(costs, 2)\n return round(costs - kate, 2) if kate <= 10 else round(costs - 10, 2)", "def michael_pays(costs):\n micheal=0\n if costs<5:\n micheal = costs\n else:\n if ((1/3)*costs)>10:\n micheal = costs-10\n else:\n micheal = costs-((1/3)*costs)\n \n try:\n if isinstance(micheal,float):\n micheal = float(\"{0:.2f}\".format(micheal))\n except:\n micheal = micheal\n \n return micheal"]
{"fn_name": "michael_pays", "inputs": [[15], [4], [4.99], [5], [30], [80], [22], [5.9181], [28.789], [4.325]], "outputs": [[10], [4], [4.99], [3.33], [20], [70], [14.67], [3.95], [19.19], [4.33]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,457
def michael_pays(costs):
4f5607e089e3f82abbd88c9091ef1b32
UNKNOWN
You've arrived at a carnival and head straight for the duck shooting tent. Why wouldn't you? You will be given a set amount of ammo, and an aim rating of between 1 and 0. No your aim is not always perfect - hey maybe someone fiddled with the sights on the gun... Anyway your task is to calculate how many successful shots you will be able to make given the available ammo and your aim score, then return a string representing the pool of ducks, with those ducks shot marked with 'X' and those that survived left unchanged. You will always shoot left to right. Example of start and end duck string with two successful shots: Start ---> |~~~~~22~2~~~~~| **Bang!! Bang!!** End ---> |~~~~~XX~2~~~~~| All inputs will be correct type and never empty.
["def duck_shoot(ammo, aim, ducks):\n return ducks.replace('2', 'X', int(ammo * aim))", "duck_shoot = lambda am, aim, d: d.replace('2','X', int(am*aim))", "def duck_shoot(ammo, aim, ducks):\n b = 0\n b += int(aim * ammo)\n return ducks.replace('2','X', b)\n", "duck_shoot=lambda a,b,c:c.replace('2','X',int(a*b))", "import math\n\ndef duck_shoot(ammo, aim, duck_pool):\n #your code here\n shots = math.floor(ammo*aim)\n return duck_pool.replace('2','X',shots)\n", "from math import floor\n\n\ndef duck_shoot(ammo, aim, ducks):\n kills = [i for i,c in enumerate(ducks) if c == '2'][:min(floor(aim*ammo),ducks.count('2'))]\n return ''.join(['X' if i in kills else c for i, c in enumerate(ducks)])\n \n \n", "def duck_shoot(ammo, aim, ducks):\n indices = [i for i, c in enumerate(ducks) if c == '2']\n hits = int(aim * ammo)\n result = list(ducks)\n for i in indices[:hits]:\n result[i] = 'X'\n return ''.join(result)", "def duck_shoot(ammo, aim, ducks):\n hit = min(int(ammo * aim), ducks.count('2'))\n return ducks.replace('2', 'X', hit)\n", "def duck_shoot(ammo, aim, ducks):\n output = ''\n kills = int(ammo*aim)\n for duck in ducks:\n if duck == '2':\n if kills > 0:\n output += 'X'\n kills -= 1\n else:\n output += duck\n else:\n output += duck\n return output", "def duck_shoot(ammo, aim, ducks):\n bangs = int(ammo * aim)\n if bangs == 0: return ducks\n res = list(ducks)\n shot = 0\n for i, c in enumerate(res):\n if c == \"2\":\n res[i] = \"X\"\n shot += 1\n if shot >= bangs:\n break\n return \"\".join(res)"]
{"fn_name": "duck_shoot", "inputs": [[4, 0.64, "|~~2~~~22~2~~22~2~~~~2~~~|"], [9, 0.22, "|~~~~~~~2~2~~~|"], [6, 0.41, "|~~~~~22~2~~~~~|"], [8, 0.05, "|2~~~~|"], [8, 0.92, "|~~~~2~2~~~~~22~~2~~~~2~~~2|"]], "outputs": [["|~~X~~~X2~2~~22~2~~~~2~~~|"], ["|~~~~~~~X~2~~~|"], ["|~~~~~XX~2~~~~~|"], ["|2~~~~|"], ["|~~~~X~X~~~~~XX~~X~~~~X~~~X|"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,755
def duck_shoot(ammo, aim, ducks):
f622647d715fe8c7542187db3d984b69
UNKNOWN
In the world of birding there are four-letter codes for the common names of birds. These codes are created by some simple rules: * If the bird's name has only one word, the code takes the first four letters of that word. * If the name is made up of two words, the code takes the first two letters of each word. * If the name is made up of three words, the code is created by taking the first letter from the first two words and the first two letters from the third word. * If the name is four words long, the code uses the first letter from all the words. *(There are other ways that codes are created, but this Kata will only use the four rules listed above)* Complete the function that takes an array of strings of common bird names from North America, and create the codes for those names based on the rules above. The function should return an array of the codes in the same order in which the input names were presented. Additional considertations: * The four-letter codes in the returned array should be in UPPER CASE. * If a common name has a hyphen/dash, it should be considered a space. ## Example If the input array is: `["Black-Capped Chickadee", "Common Tern"]` The return array would be: `["BCCH", "COTE"]`
["import re\n\nSPLITTER = re.compile(r\"[\\s-]\")\n\ndef birdify(lst):\n return ''.join(x[:4//len(lst)] for x in lst) + ('' if len(lst)!=3 else lst[-1][1])\n\ndef bird_code(arr):\n return [birdify(SPLITTER.split(name)).upper() for name in arr]", "def bird_code(arr):\n codes = []\n \n for name in arr:\n name = name.replace(\"-\", \" \").split()\n \n if len(name) == 1:\n code = name[0][:4]\n \n elif len(name) == 2:\n code = name[0][:2] + name[1][:2]\n \n elif len(name) == 3:\n code = name[0][0] + name[1][0] + name[2][:2]\n \n elif len(name) == 4:\n code = \"\".join(n[0] for n in name)\n \n else:\n return \"More than 4 words!\"\n \n codes.append(code.upper())\n \n return codes", "def encode(bird):\n words = bird.replace('-', ' ').split()\n patterns = {\n 1: (4, ),\n 2: (2, 2),\n 3: (1, 1, 2,),\n 4: (1, 1, 1, 1),\n }\n return \"\".join(map(lambda w, l: w[:l], words, patterns[len(words)])).upper()\n\n\ndef bird_code(birds):\n return list(map(encode, birds)) ", "RULES = {\n 1: lambda x: ''.join(x[0][:4]).upper(),\n 2: lambda x: ''.join(x[0][:2] + x[1][:2]).upper(),\n 3: lambda x: ''.join(\n x[0][:1] + x[1][:1] + x[2][:2]\n ).upper(),\n 4: lambda x: ''.join(\n x[0][:1] + x[1][:1] + x[2][:1] + x[3][:1]\n ).upper(),\n}\n\ndef bird_code(arr):\n arr = [bird.replace('-', ' ') for bird in arr]\n ret_arr = []\n \n for bird in arr:\n name_parts = bird.split()\n ret_arr.append(\n RULES[len(name_parts)](name_parts)\n )\n \n return ret_arr", "def bird_code(birds):\n codes = []\n for bird in birds:\n words = bird.upper().replace(\"-\", \" \").split()\n if len(words) == 1:\n codes.append(words[0][:4])\n elif len(words) == 2:\n codes.append(\"\".join(word[:2] for word in words))\n else:\n code = \"\".join(word[0] for word in words)\n codes.append(f\"{code}{words[2][1] if len(words) == 3 else ''}\")\n return codes\n", "REGEX = __import__(\"re\").compile(r\"[ -]\").split\nletters = ((4,), (2,2), (1,1,2), (1,1,1,1))\n\ndef code(L):\n return ''.join(L[i][:j] for i,j in enumerate(letters[len(L)-1])).upper()\n\ndef bird_code(arr):\n return [code(REGEX(name)) for name in arr]", "import re\ndef bird_code(s):\n li = []\n for i in s:\n i = re.sub(r\" *-\", \" \", i).upper().split()\n if len(i) == 1 : li.append(i[0][:4])\n if len(i) == 2 : li.append(i[0][:2] + i[1][:2])\n if len(i) == 3 : li.append(i[0][0] + i[1][0] + i[2][:2])\n if len(i) == 4 : li.append(\"\".join([k[0] for k in i]))\n return li", "def bird_code(a):\n return [bird(b.upper()) for b in a]\n \ndef bird(s):\n b = s.replace('-', ' ').split()\n if len(b) == 1: return s[:4]\n if len(b) == 2: return b[0][:2] + b[1][:2]\n if len(b) == 3: return b[0][0] + b[1][0] + b[2][:2]\n if len(b) == 4: return b[0][0] + b[1][0] + b[2][0] + b[3][0]", "import re\n\ndef f(name):\n words = re.findall(\"[\\w']+\", name)\n if len(words) == 1:\n return words[0][:4]\n elif len(words) == 2:\n return words[0][:2] + words[1][:2]\n elif len(words) == 3:\n return words[0][:1] + words[1][:1] + words[2][:2]\n return ''.join(word[0] for word in words)\n \ndef bird_code(arr):\n return [f(name).upper() for name in arr]", "def bird_code(arr):\n arr1=[s.replace('-',' ') for s in arr]\n res=[]\n for s in arr1:\n arr2=s.split(' ')\n if len(arr2)==1:\n res.append(arr2[0][:4].upper())\n elif len(arr2)==2:\n res.append(arr2[0][:2].upper()+arr2[1][:2].upper())\n elif len(arr2)==3:\n res.append(arr2[0][0].upper()+arr2[1][0].upper()+arr2[2][:2].upper())\n else:\n res.append(arr2[0][0].upper()+arr2[1][0].upper()+arr2[2][0].upper()+arr2[3][0].upper())\n return res"]
{"fn_name": "bird_code", "inputs": [[["American Redstart", "Northern Cardinal", "Pine Grosbeak", "Barred Owl", "Starling", "Cooper's Hawk", "Pigeon"]], [["Great Crested Flycatcher", "Bobolink", "American White Pelican", "Red-Tailed Hawk", "Eastern Screech Owl", "Blue Jay"]], [["Black-Crowned Night Heron", "Northern Mockingbird", "Eastern Meadowlark", "Dark-Eyed Junco", "Red-Bellied Woodpecker"]], [["Scarlet Tanager", "Great Blue Heron", "Eastern Phoebe", "American Black Duck", "Mallard", "Canvasback", "Merlin", "Ovenbird"]], [["Fox Sparrow", "White-Winged Crossbill", "Veery", "American Coot", "Sora", "Northern Rough-Winged Swallow", "Purple Martin"]]], "outputs": [[["AMRE", "NOCA", "PIGR", "BAOW", "STAR", "COHA", "PIGE"]], [["GCFL", "BOBO", "AWPE", "RTHA", "ESOW", "BLJA"]], [["BCNH", "NOMO", "EAME", "DEJU", "RBWO"]], [["SCTA", "GBHE", "EAPH", "ABDU", "MALL", "CANV", "MERL", "OVEN"]], [["FOSP", "WWCR", "VEER", "AMCO", "SORA", "NRWS", "PUMA"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,097
def bird_code(arr):
eedd552f1b78429402e7314a6b94647c
UNKNOWN
Complete the function to determine the number of bits required to convert integer `A` to integer `B` (where `A` and `B` >= 0) The upper limit for `A` and `B` is 2^(16), `int.MaxValue` or similar. For example, you can change 31 to 14 by flipping the 4th and 0th bit: ``` 31 0 0 0 1 1 1 1 1 14 0 0 0 0 1 1 1 0 --- --------------- bit 7 6 5 4 3 2 1 0 ``` Thus `31` and `14` should return `2`.
["def convert_bits(a,b):\n return bin(a^b).count(\"1\")", "def convert_bits(a, b):\n return f'{a^b:b}'.count('1')", "def convert_bits(a, b):\n return str(bin(a ^ b)).count('1')", "def convert_bits(a, b):\n return format(a ^ b, 'b').count('1')", "def convert_bits(a, b):\n difference=bin(a^b)[2:]\n return difference.count(\"1\")\n", "def convert_bits(a, b):\n return list(bin(a^b)).count('1')", "binary = lambda x : bin(x)[2:].zfill(32)\n\ndef convert_bits(a, b):\n a, b = binary(a), binary(b)\n return sum(a[i] != b[i] for i in range(32))", "def convert_bits(a, b):\n n = a ^ b\n c = 0\n while n:\n c += n & 1\n n >>= 1\n return c", "def convert_bits(a, b):\n A = f'{abs(a):040b}'\n B = f'{abs(b):040b}'\n diffs = 0\n for i, j in zip(A, B):\n if i != j:\n diffs+=1\n return diffs\n", "def countSetBits(n):\n count = 0\n while n:\n count += n & 1\n n >>= 1\n return count\n\n\ndef convert_bits(a, b):\n return countSetBits(a^b)\n"]
{"fn_name": "convert_bits", "inputs": [[31, 14], [7, 17], [31, 0], [0, 0], [127681, 127681], [312312312, 5645657], [43, 2009989843]], "outputs": [[2], [3], [5], [0], [0], [13], [17]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,011
def convert_bits(a, b):
4090bed183a91a9da476ef109944daca
UNKNOWN
There's a waiting room with N chairs set in single row. Chairs are consecutively numbered from 1 to N. First is closest to the entrance (which is exit as well). For some reason people choose a chair in the following way 1. Find a place as far from other people as possible 2. Find a place as close to exit as possible All chairs must be occupied before the first person will be served So it looks like this for 10 chairs and 10 patients Chairs 1 2 3 4 5 6 7 8 9 10 Patients 1 7 5 8 3 9 4 6 10 2 Your task is to find last patient's chair's number. Input - N - integer greater than 2 - number of chairs. Output should positive integer too - last patient's chair's number Have fun :)
["def last_chair(n):\n return n - 1", "def last_chair(n):\n # Propn:\n # Given there are n seats, n >= 2. The (n-1)th seat is always the\n # last to be taken (taken in iteration n).\n # Proof:\n # Suppose that, for some n >= 2, the (n-1)th seat is taken on\n # iteration i > 2. The nth seat is already taken, since the 2nd\n # iteration will always claim it. Therefore i must sit beside\n # at least one person (the occupant of seat n).\n # Additionally, the (n-2)th seat must also already be taken.\n # If it were not taken, (n-2) would have a free seat at (n-1)\n # and would be closer to the exit, and so would rank higher\n # than (n-1) in the choice algorithm.\n # Therefore (n-1) will only be chosen when (n-2) and (n) are\n # both taken.\n # Also, all other seats must also be taken, since\n # otherwise i would taken them, having at most as many people\n # around as seat (n-1) and being closer to the exit.\n # Therefore (n-1) is the last seat to be taken.\n return n - 1", "last_chair = lambda n: n - 1", "def last_chair(n):\n return n if n<3 else n-1", "def last_chair(n):\n if n < 3:\n return n\n return n - 1", "def last_chair(n):\n # Last chair will allways be the 2nd to the last chair\n return n - 1 ", "def last_chair(n):\n if n == 1 or n == 2:\n return n\n else:\n return n - 1", "def last_chair(n):\n # The secret is, that it's always the next to last seat!\n return n-1\n \n # Actual simulation for fun :)\n # dist to e, used, nearest l, nearest r, nearest, spaces\n spots = [[i, False, None, None, None, None] for i in range(n)]\n\n clean = lambda n, d=0: n if n is not None else d\n live = lambda s: not s[1]\n position = lambda s: s[0]\n near = lambda s: s[4]\n spaces = lambda s: s[5]\n\n while any(filter(live, spots)):\n nearest = None\n for i in range(n):\n if spots[i][1]:\n nearest = 0\n elif nearest is not None:\n nearest += 1\n spots[i][2] = nearest\n\n nearest = None\n for i in range(n-1, -1, -1):\n if spots[i][1]:\n nearest = 0\n elif nearest is not None:\n nearest += 1\n spots[i][3] = nearest\n\n for i in range(n):\n spots[i][4] = min(clean(spots[i][2], n), clean(spots[i][3], n))\n spots[i][5] = clean(spots[i][2]) + clean(spots[i][3])\n\n options = list(filter(live, spots))\n options.sort(key=near, reverse=True)\n best = near(options[0])\n options = [s for s in options if near(s) == best]\n #print \"Options\"\n #for s in options:\n # print s\n options.sort(key=spaces, reverse=True)\n best = spaces(options[0])\n options = [s for s in options if spaces(s) == best]\n options.sort(key=position)\n options[0][1] = True\n result = position(options[0])\n return result + 1\n", "last_chair = 1 .__rsub__"]
{"fn_name": "last_chair", "inputs": [[10]], "outputs": [[9]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,096
def last_chair(n):
412f7715a6f6402692df53dca8fa9bf8
UNKNOWN
Given an array of arguments, representing system call arguments keys and values, join it into a single, space-delimited string. You don't need to care about the application name -- your task is only about parameters. Each element of the given array can be: * a single string, * a single string array, * an array of two strings In the last case (array of two strings) the first string should have a `"--"` prefix if it is more than one character long; or a `"-"` prefix otherwise; e.g.: * `["foo", "bar"]` becomes `"--foo bar"` * `["f", "bar"]` becomes `"-f bar"` You may assume that all strings are non-empty and have no spaces. ## Examples ```python ["foo", "bar"] # "foo bar" [["foo", "bar"]] # "--foo bar" [["f", "bar"]] # "-f bar" [["foo", "bar"], "baz"] # "--foo bar baz" [["foo"], ["bar", "baz"], "qux"] # "foo --bar baz qux" ```
["def args_to_string(args):\n L = []\n for arg in args:\n if isinstance(arg, str):\n L.append(arg)\n elif len(arg) == 1:\n L.append(arg[0])\n elif len(arg[0]) == 1:\n L.append('-' + ' '.join(arg))\n else:\n L.append('--' + ' '.join(arg))\n return ' '.join(L)", "def args_to_string(A):\n return ' '.join(e if isinstance(e, str) else e[0] if len(e)==1 else '-'+(len(e[0])>1)*'-' +' '.join(e) for e in A)", "def args_to_string(args):\n return ' '.join(x if type(x) == str else ' '.join(('-' if len(v) == 1 else '--') + v if k == 0 and len(x) > 1 else v for k, v in enumerate(x)) for x in args)", "def args_to_string(args):\n return ' '.join('-'*(len(a)>1 and 1+(len(a[0])>1))+' '.join(a) if type(a)==list else a for a in args)", "def args_to_string(args):\n for i in args:\n if len(i) > 1 and type(i) != str:\n i[0] = f\"--{i[0]}\" if len(i[0]) > 1 else f\"-{i[0]}\"\n return \" \".join(i if type(i) != list else \" \".join(i) for i in args)", "def args_to_string(args):\n params = []\n for arg in args:\n if isinstance(arg, str):\n params.append(arg)\n else:\n if arg:\n first = arg.pop(0)\n if arg:\n if len(first) == 1:\n first = '-' + first\n else:\n first = '--' + first\n params.append(first)\n for a in arg:\n params.append(a)\n return ' '.join(params)", "def args_to_string(args):\n ls=[]\n for i in args:\n if type(i)==list and len(i)==2:\n if len(i[0])>1:\n i[0]='--'+i[0]\n ls.extend(i)\n else:\n i[0]='-'+i[0]\n ls.extend(i)\n else:\n ls.append(i) if type(i)!=list else ls.extend(i)\n return ' '.join(ls)\n", "def args_to_string(args):\n r=[]\n for a in args:\n if type(a)==list:\n if len(a)==1:\n r+=a[0],\n else:\n s='-'\n if len(a[0])>1:s+='-'\n r+=s+' '.join(a),\n else:r+=a,\n return' '.join(r)", "def args_to_string(args):\n res = []\n for chunk in args:\n if type(chunk) == str:\n res.append(chunk)\n elif len(chunk) == 1:\n res.append(chunk[0])\n else:\n res.append(f'{\"-\" * (1 + (len(chunk[0]) > 1))}{\" \".join(s for s in chunk)}')\n return ' '.join(res)\n", "def args_to_string(args):\n s = []\n for i in args:\n if type(i) == str: s.append(i)\n elif type(i) == list and len(i) == 2: s.append('-'*(1 if len(i[0]) == 1 else 2)+ ' '.join(i))\n else: s += i\n return ' '.join(s)"]
{"fn_name": "args_to_string", "inputs": [[["foo"]], [["f"]], [[["f"]]], [[["foo", "bar"]]], [[["f", "bar"]]], [[["foo", "bar"], ["baz", "qux"]]], [[["foo"], "bar", ["baz", "qux"], ["xyzzy", "a"], "a", ["a"], ["a", "plugh"]]], [[]], [[["---"], "---", ["---", "---"], ["-----", "-"], "-", ["-"], ["-", "-----"]]]], "outputs": [["foo"], ["f"], ["f"], ["--foo bar"], ["-f bar"], ["--foo bar --baz qux"], ["foo bar --baz qux --xyzzy a a a -a plugh"], [""], ["--- --- ----- --- ------- - - - -- -----"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,844
def args_to_string(args):
fd5b950d54d68ec7677b64a82616161e
UNKNOWN
Pete and his mate Phil are out in the countryside shooting clay pigeons with a shotgun - amazing fun. They decide to have a competition. 3 rounds, 2 shots each. Winner is the one with the most hits. Some of the clays have something attached to create lots of smoke when hit, guarenteed by the packaging to generate 'real excitement!' (genuinely this happened). None of the explosive things actually worked, but for this kata lets say they did. For each round you will receive the following format: [{P1:'XX', P2:'XO'}, true] That is an array containing an object and a boolean. Pl represents Pete, P2 represents Phil. X represents a hit and O represents a miss. If the boolean is true, any hit is worth 2. If it is false, any hit is worth 1. Find out who won. If it's Pete, return 'Pete Wins!'. If it is Phil, return 'Phil Wins!'. If the scores are equal, return 'Draw!'. Note that as there are three rounds, the actual input (x) will look something like this: [[{P1:'XX', P2:'XO'}, true], [{P1:'OX', P2:'OO'}, false], [{P1:'XX', P2:'OX'}, true]]
["def shoot(results):\n pete = phil = 0\n \n for shots, double in results:\n pete += shots[\"P1\"].count(\"X\") * (1 + double)\n phil += shots[\"P2\"].count(\"X\") * (1 + double)\n \n return \"Pete Wins!\" if pete > phil else \"Phil Wins!\" if phil > pete else \"Draw!\"", "def shoot(results):\n pt1, pt2 = 0, 0\n countPts = lambda elt,pt: (elt[1]+1)*elt[0][pt].count('X')\n for elt in results:\n pt1 += countPts(elt,'P1')\n pt2 += countPts(elt,'P2')\n if pt1>pt2 : return 'Pete Wins!'\n elif pt1==pt2 : return 'Draw!'\n else: return 'Phil Wins!'", "# Works for any number of rounds or shots\ndef shoot(results):\n P1 = P2 = 0\n for D, b in results:\n P1 += D[\"P1\"].count('X') * (b + 1)\n P2 += D[\"P2\"].count('X') * (b + 1)\n return (\"Draw!\", \"Pete Wins!\", \"Phil Wins!\")[(P1>P2) - (P1<P2)]", "def shoot(results):\n score = sum(rnd[f\"P{i+1}\"].count(\"X\") * (mul + 1) * (-1)**i for i in (0, 1) for rnd, mul in results)\n return \"Pete Wins!\" if score > 0 else \"Phil Wins!\" if score < 0 else \"Draw!\"\n", "def shoot(a):\n main = {}\n for i, j in a:\n hit = 2 if j else 1\n main[\"p1\"] = main.get(\"p1\", 0) + i['P1'].count(\"X\")*hit\n main[\"p2\"] = main.get(\"p2\", 0) + i['P2'].count(\"X\")*hit\n return [\"Draw!\", [\"Pete Wins!\", \"Phil Wins!\"][main[\"p1\"] < main[\"p2\"]]][main[\"p1\"] != main[\"p2\"]]", "def shoot(results):\n pete, phil = [sum(d[p].count('X') * (1+b) for d, b in results) for p in ['P1', 'P2']]\n return 'Pete Wins!' if pete > phil else 'Phil Wins!' if phil > pete else 'Draw!'", "def shoot(results):\n pete, phil = (sum(r[player].count('X') * (1+dbl) for r, dbl in results) for player in ['P1', 'P2'])\n return 'Pete Wins!' if pete > phil else 'Phil Wins!' if phil > pete else 'Draw!'", "def shoot(arr):\n pete, phil = 0, 0\n for i in arr:\n score = 2 if i[1] == True else 1\n pete += i[0]['P1'].count('X')*score\n phil += i[0]['P2'].count('X')*score\n return \"Pete Wins!\" if pete > phil else \"Phil Wins!\" if phil > pete else \"Draw!\"", "def shoot(results):\n p1_score = 0\n p2_score = 0\n \n for round in results:\n if round[1]:\n inc = 2\n else:\n inc = 1\n \n p1_shoots = round[0]['P1']\n p2_shoots = round[0]['P2']\n \n for shoot in p1_shoots:\n if shoot == 'X':\n p1_score += inc\n \n for shoot in p2_shoots:\n if shoot == 'X':\n p2_score += inc\n \n if p1_score > p2_score:\n return 'Pete Wins!'\n elif p1_score < p2_score:\n return 'Phil Wins!'\n else:\n return 'Draw!'"]
{"fn_name": "shoot", "inputs": [[[[{"P1": "XX", "P2": "XO"}, true], [{"P1": "OX", "P2": "OO"}, false], [{"P1": "XX", "P2": "OX"}, true]]], [[[{"P1": "XX", "P2": "XO"}, false], [{"P1": "OX", "P2": "XX"}, false], [{"P1": "OO", "P2": "XX"}, true]]], [[[{"P1": "OO", "P2": "XX"}, false], [{"P1": "OO", "P2": "XX"}, false], [{"P1": "XX", "P2": "OO"}, true]]], [[[{"P1": "XX", "P2": "XX"}, true], [{"P1": "XX", "P2": "OX"}, false], [{"P1": "OO", "P2": "OX"}, true]]], [[[{"P1": "XX", "P2": "XX"}, true], [{"P1": "OO", "P2": "OO"}, false], [{"P1": "XX", "P2": "XX"}, true]]]], "outputs": [["Pete Wins!"], ["Phil Wins!"], ["Draw!"], ["Phil Wins!"], ["Draw!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,791
def shoot(results):
07a099af80cfb2b0621f0194a1ba187f
UNKNOWN
What adds up =========== Given three arrays of integers your task is to create an algorithm that finds the numbers in the first two arrays whose sum is equal to any number in the third. The return value should be an array containing the values from the argument arrays that adds up. The sort order of the resulting array is not important. If no combination of numbers adds up return a empty array. ### Example A small example: Given the three input arrays `a1 = [1, 2]; a2 = [4,3]; a3 = [6,5,8]`, we need to find the number pairs from `a1` and `a2` that sum up to a number in `a3` and return those three numbers in an array. In this example, the result from the function would be `[[1, 4, 5] , [2, 4, 6], [2, 3, 5]]`. ``` Given three arrays a1 a2 a3 1 4 6 (a1 a2 a3) (a1 a2 a3) (a1 a2 a3) 2 3 5 => [[1, 4, 5] , [2, 4, 6], [2, 3, 5]] 8 each value in the result array contains one part from each of the arguments. ``` ### Testing A function `compare_array` is given. This function takes two arrays and compares them invariant of sort order. ```python test.expect(compare_arrays(addsup([1,2], [3,1], [5,4]), [[1,3,4], [2,3,5]])) ``` ### Greater goal For extra honor try and make it as effective as possible. Discuss whats the most effective way of doing this. The fastest way i can do this is in *O(n^2)*. Can you do it quicker?
["def addsup(a1, a2, a3):\n return [[x,y,x+y] for x in a1 for y in a2 if x+y in a3]", "from itertools import product\n\ndef addsup(a1, a2, a3):\n goal = set(a3).__contains__\n return [[x, y, x+y] for x,y in product(a1, a2) if goal(x+y)]", "def addsup(a, b, t):\n t = set(t)\n return [[m, n, m+n] for m in a for n in b if m + n in t]", "def addsup(a1, a2, a3):\n a3 = set(a3)\n return [[x1, x2, x1 + x2] for x1 in a1 for x2 in a2 if x1 + x2 in a3]", "def addsup(a1, a2, a3):\n r = {}\n for s in a3:\n for i in a1:\n r[s-i] = [i] + r.get(s-i, [])\n result = []\n for j in a2:\n if j in r:\n for i in r[j]:\n result.append([i, j, j+i])\n return result", "def addsup(a1, a2, a3):\n sums = []\n # test every possible combination of a1 and a2, if sum in a3, append to result list\n for i in a1:\n for j in a2:\n if (i+j) in a3:\n sums.append([i, j, i+j])\n return sums", "def addsup(a1, a2, a3):\n results = []\n for ele1 in a1:\n for ele2 in a2:\n if ele1+ele2 in a3:\n results.append([ele1, ele2, ele1+ele2])\n return results", "addsup = lambda a1, a2, a3: [[x, y, x + y] for x in a1 for y in a2 if x + y in a3]", "def addsup(a1, a2, a3):\n l = [[c-b,b,c] for b in a2 for c in a3]\n return list(filter((lambda e: e[0] in a1), l))", "def addsup(a1, a2, a3):\n a4 = []\n for n1 in a1:\n for n2 in a2:\n if n1 + n2 in a3:\n a4.append([n1, n2, n1 + n2])\n return a4"]
{"fn_name": "addsup", "inputs": [[[], [1, 2, 3], [5, 2, 3]], [[1, 3, 4], [], [4, 6, 5]], [[1, 2, 3], [4, 5, 6], []]], "outputs": [[[]], [[]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,571
def addsup(a1, a2, a3):
0693185e09aafe315fc3afecce6e0c0f
UNKNOWN
In this Kata, you will check if it is possible to convert a string to a palindrome by changing one character. For instance: ```Haskell solve ("abbx") = True, because we can convert 'x' to 'a' and get a palindrome. solve ("abba") = False, because we cannot get a palindrome by changing any character. solve ("abcba") = True. We can change the middle character. solve ("aa") = False solve ("ab") = True ``` Good luck! Please also try [Single Character Palindromes](https://www.codewars.com/kata/5a2c22271f7f709eaa0005d3)
["def solve(s):\n v = sum(s[i] != s[-1-i] for i in range((len(s))//2) )\n return v == 1 or not v and len(s)%2", "solve=lambda s:any(s[:y]+c+s[y+1:]==(s[:y]+c+s[y+1:])[::-1]!=s for y,x in enumerate(s)for c in set(s))", "def solve(s):\n d = sum(1 for i in range(len(s) // 2) if s[i] != s[-i-1])\n return d == 1 or d == 0 and len(s) % 2 == 1", "def solve(s):\n h = len(s) // 2\n diffs = sum(1 for a, b in zip(s[:h], s[-h:][::-1]) if a != b)\n return diffs == 1 or (diffs == 0 and len(s) % 2 == 1)", "def solve(s):\n r = sum(a != b for a, b in zip(s, s[::-1]))\n return r == 2 or r == 0 and len(s)%2", "def solve(s):\n r = sum([1 for i,x in enumerate(s[:len(s)//2]) if x!=s[-i-1]])\n return s==s[::-1] and len(s)%2 or r==1\n", "def solve(s):\n if s == s[::-1] and len(s) % 2 == 0: return False\n \n start = 0\n end = len(s)-1\n mid = end//2\n count = 0\n while start < mid:\n for i in range(mid):\n if s[start] != s[end]:\n count += 1\n start += 1\n end -= 1\n if count <= 1:\n return True\n return False\n", "def solve(s):\n if len(s) % 2 and s == s[::-1]:\n return True\n return len([c for i, c in enumerate(s[:len(s)//2]) if c != s[-(i+1)]]) == 1", "def solve(s):\n dif = sum(a != b for a, b in zip(s, s[::-1]))\n return dif == 2 or not dif and len(s) & 1", "def solve(s):\n return 1 == ((sum([op!=code for (op, code) in zip(s[0:len(s)//2:1], s[-1:len(s)//2-1:-1])]))|(len(s)%2))", "def solve(s):\n r = sum(s[i] != s[-1-i] for i in range(len(s)//2))\n return r == 1 or (r == 0 and len(s) % 2)", "def solve(s):\n n = sum(s[i] != s[-i - 1] for i in range(len(s) // 2))\n return True if n == 1 else n ==0 and len(s) % 2 != 0", "def solve(s): \n c=sum(s[i]!=s[-1-i] for i in range(len(s)//2))\n return c==1 or (c==0)*len(s)%2\n", "def solve(s):\n t=s[::-1]\n return sum(x!=y for x,y in zip(s,t))==2 or (s!=t and len(s)==2) or (len(t)%2==1 and t[:len(t)//2]==s[:len(t)//2])", "def solve(s):\n all = sum(1 for i in range(len(s) // 2) if s[i] != s[-i-1])\n return all == 1 or all == 0 and len(s)%2 == 1", "def solve(s):\n r = [s[i] != s[len(s)-1-i] for i in range(len(s)//2)]\n if len(s)%2: return True if sum(r)<2 else False\n else: return True if sum(r)==1 else False", "def solve(s):\n print(s)\n return True if len([x for y,x in enumerate(s) if s[y] != s[-(y+1)]]) == 2 else True if (len(s) % 2 and not [x for y,x in enumerate(s) if s[y] != s[-(y+1)]] ) else False", "def solve(s):\n reversed = s[::-1]\n middle = len(s)//2\n count = 0\n \n for i in range(middle):\n if s[i] != reversed[i]:\n count += 1\n \n if middle*2 == len(s):\n if count == 1:\n return True\n else:\n if count == 0 or count == 1:\n return True\n return False", "def solve(s):\n print(s)\n \n if s == s[::-1] and len(s) % 2 == 0: return False\n \n left, right = [], []\n l = list(s)\n counter = 0\n \n while l:\n e = l.pop(0)\n if l:\n e2 = l.pop()\n if e != e2 and counter == 0:\n e2 = e\n counter += 1\n right.insert(0, e2)\n else:\n e = left[-1]\n left.append(e)\n \n s = ''.join(left + right)\n \n return s == s[::-1]\n \n \n", "def solve(n):\n s = [0, 1][len(n)%2]\n lh = n[:len(n)//2]\n hh = n[len(n)//2+s:]\n if s and lh == hh[::-1]:\n return True\n diffs = 0\n for u, v in zip(lh, hh[::-1]):\n if u != v:\n diffs += 1\n if diffs > 1:\n return False\n return diffs == 1\n"]
{"fn_name": "solve", "inputs": [["abba"], ["abbaa"], ["abbx"], ["aa"], ["ab"], ["abcba"]], "outputs": [[false], [true], [true], [false], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,743
def solve(s):
e5604f72f0392d087dc5b56f66ed3dea
UNKNOWN
Your job at E-Corp is both boring and difficult. It isn't made any easier by the fact that everyone constantly wants to have a meeting with you, and that the meeting rooms are always taken! In this kata, you will be given an array. Each value represents a meeting room. Your job? Find the **first** empty one and return its index (N.B. There may be more than one empty room in some test cases). 'X' --> busy 'O' --> empty If all rooms are busy, return 'None available!'. More in this series: The Office I - Outed The Office II - Boredeom Score The Office III - Broken Photocopier The Office V - Find a Chair
["def meeting(rooms):\n try:\n return rooms.index('O')\n except ValueError:\n return 'None available!'\n", "def meeting(rooms):\n return rooms.index(\"O\") if \"O\" in rooms else \"None available!\"", "def meeting(rooms):\n return next((i for i, r in enumerate(rooms) if r == 'O'), 'None available!')", "def meeting(rooms):\n try:\n return rooms.index(\"O\")\n except:\n return \"None available!\"", "def meeting(rooms):\n if 'O' not in rooms: return 'None available!'\n return rooms.index('O')", "def meeting(rooms):\n for num, status in enumerate(rooms):\n if status == 'O':\n return num\n return 'None available!'", "def meeting(rooms):\n return [o for o,v in enumerate(rooms) if v=='O'][0] if 'O' in rooms else 'None available!'", "def meeting(rooms):\n tally = 0\n for i in rooms:\n if i == \"O\":\n return tally\n else:\n tally += 1\n return(\"None available!\")\n \n \n", "def meeting(rooms):\n for x in rooms:\n if (x is 'O'):\n return(rooms.index(x))\n return('None available!')\n", "def meeting(rooms):\n return next((i for i, x in enumerate(rooms) if x=='O'), 'None available!')"]
{"fn_name": "meeting", "inputs": [[["X", "O", "X"]], [["O", "X", "X", "X", "X"]], [["X", "X", "O", "X", "X"]], [["X"]]], "outputs": [[1], [0], [2], ["None available!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,268
def meeting(rooms):
ff8deea0a7799f3a44e00f38771a5cc0
UNKNOWN
Kevin is noticing his space run out! Write a function that removes the spaces from the values and returns an array showing the space decreasing. For example, running this function on the array ['i', 'have','no','space'] would produce ['i','ihave','ihaveno','ihavenospace'].
["from itertools import accumulate\n\ndef spacey(a):\n return list(accumulate(a))", "def spacey(array):\n return [''.join(array[:i+1]) for i in range(len(array))]", "def spacey(array):\n strr = ''\n out = []\n for el in array:\n strr += str(el)\n out.append(strr)\n return out", "def spacey(array):\n return [\"\".join(array[:i]) for i, _ in enumerate(array, 1)]", "from itertools import accumulate\ndef spacey(array):\n return list(accumulate(array))", "def spacey(array):\n new_s = []\n s = \"\"\n for i in array:\n s+=i\n new_s.append(s)\n return new_s", "from functools import reduce\n\ndef spacey(array):\n return reduce(lambda a, b: a + [a[-1] + b] if a else [b], array, [])", "def spacey(array):\n \n if len(array) != 0:\n string = [array[0]]\n for index in range(2,len(array)+1):\n for i in range(index-1,index):\n string = string + [string[i-1]+array[i]]\n return string\n else:\n return array", "spacey=lambda a:list(__import__('itertools').accumulate(a))", "from itertools import accumulate\n\n\ndef spacey(array):\n return list(map(\"\".join, accumulate(array)))"]
{"fn_name": "spacey", "inputs": [[["kevin", "has", "no", "space"]], [["this", "cheese", "has", "no", "holes"]]], "outputs": [[["kevin", "kevinhas", "kevinhasno", "kevinhasnospace"]], [["this", "thischeese", "thischeesehas", "thischeesehasno", "thischeesehasnoholes"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,209
def spacey(array):
cc372c2bcff4c6397071755da24436d1
UNKNOWN
Will you make it? You were camping with your friends far away from home, but when it's time to go back, you realize that your fuel is running out and the nearest pump is ```50``` miles away! You know that on average, your car runs on about ```25``` miles per gallon. There are ```2``` gallons left. Considering these factors, write a function that tells you if it is possible to get to the pump or not. Function should return ``true`` (`1` in Prolog) if it is possible and ``false`` (`0` in Prolog) if not. The input values are always positive.
["'''\nVasyl Zakharuk\nPython Core 355\nCodewars Kata: Will you make it?\n''' \ndef zero_fuel(distance_to_pump, mpg, fuel_left):\n if fuel_left >= distance_to_pump / mpg:\n print(\"We got to the pump\")\n return True\n else:\n print(\"We pushed the car to the pump(((\")\n return False\nprint(zero_fuel(50,25,2))", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n return mpg*fuel_left >= distance_to_pump", "zero_fuel = lambda d, m, f : d <= m * f", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n return distance_to_pump <= (mpg * fuel_left)", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n return fuel_left >= distance_to_pump / mpg ", "zero_fuel = lambda _,__,___: ___*__>=_", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n res = mpg * fuel_left\n\n if distance_to_pump <= res:\n return 1\n else:\n return 0", "def zero_fuel(dtp, mpg, fuel_left):\n return mpg * fuel_left >= dtp\n", "def zero_fuel(a, b, c):\n return a<= b*c", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n return fuel_left*mpg >= distance_to_pump", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n if mpg * fuel_left >= distance_to_pump:\n return True\n else:\n return False\n #Happy Coding! ;)\n", "zero_fuel = lambda *arg: arg[0] <= arg[1] * arg[2]", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n return not distance_to_pump > mpg * fuel_left;", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n a = mpg * fuel_left\n if a < distance_to_pump:\n return False\n else:\n return True", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n if distance_to_pump/mpg <= fuel_left:\n return True\n if distance_to_pump/mpg != fuel_left:\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n result = mpg * fuel_left\n if distance_to_pump <= result:\n return True\n else:\n return False\n \nzero_fuel(100, 50, 3)", "zero_fuel = lambda distance_to_pump, mpg, fuel_left: mpg * fuel_left >= distance_to_pump", "zero_fuel = lambda d,m,f: m*f>=d\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n total=mpg * fuel_left\n if distance_to_pump <= total:\n return True\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n return distance_to_pump <= mpg * fuel_left if True else False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n miles = mpg * fuel_left\n if distance_to_pump <= miles:\n return True\n else:\n return False\n #Happy Coding! ;)\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n gallons_to_destination = distance_to_pump / mpg\n return True if gallons_to_destination <= fuel_left else False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n a = mpg * fuel_left\n if a >= distance_to_pump:\n return True\n elif a <= distance_to_pump:\n return False", "zero_fuel=lambda d,m,f:d/f<=m", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n if distance_to_pump / (mpg*fuel_left) <= 1:\n x = True\n return bool(x)\n else:\n x = False\n return bool(x)", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n \n a=distance_to_pump*(1/mpg)-fuel_left\n if a<=0 :\n return True\n else:\n return False", "def zero_fuel(mile, fuel, gallon):\n return fuel * gallon >= mile", "def zero_fuel(dtp, mpg, fl):\n return not dtp > mpg * fl", "def zero_fuel(d, m, f):\n if d > m*f:\n return False\n return True", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n if distance_to_pump-mpg*fuel_left>0:\n return False\n return True", "def zero_fuel(d, m, f):\n c=d/m\n if c<=f:\n return True\n else:\n return False", "zero_fuel=lambda a,b,c:a<=b*c", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n\n if (mpg * fuel_left) >= distance_to_pump:\n return True\n elif (mpg * fuel_left) <= distance_to_pump:\n return False\n# return True if (mpg * fuel_left) >=distance_to_pump else False\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n return mpg*fuel_left >= distance_to_pump\n#pogchamp\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n your_fuel = mpg*fuel_left\n if your_fuel >= distance_to_pump:\n return True\n else:\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n longest_distance = mpg * fuel_left\n if distance_to_pump <= longest_distance:\n return True\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n distance_available = mpg * fuel_left\n return distance_to_pump <= distance_available", "def zero_fuel(distance_to_pump,\n mpg,\n fuel_left):\n\n return distance_to_pump <= mpg * fuel_left\n", "zero_fuel = lambda d,m,f : True if m * f >= d else False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n #nearest pump 50 miles\n #avg car runs 25 mpg\n #2 gal left\n \n if distance_to_pump <= mpg * fuel_left :\n return True\n else :\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n\n distance_to_pump = int(distance_to_pump)\n mpg = float(mpg)\n fuel_left = float(fuel_left)\n \n while distance_to_pump > mpg*fuel_left:\n return False\n else:\n return True", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n nth=distance_to_pump/mpg\n nth2=fuel_left - nth\n if nth2 >= 0 :\n return True\n else:\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n fuel_necessary=distance_to_pump/mpg\n if fuel_left>=fuel_necessary:\n return True\n if fuel_left<fuel_necessary:\n return False\n \n", "def zero_fuel(dtp, mpg, fl):\n return dtp / mpg <= fl", "def zero_fuel(d, m, f):\n a=m*f\n if a>=d:\n return True\n else:\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n distance_to_pump = int(distance_to_pump)\n mpg = int(mpg)\n fuel_left = int(fuel_left)\n result = False\n\n if fuel_left * mpg >= distance_to_pump:\n result = True\n\n return(result)\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n if float(distance_to_pump / mpg) <= float(fuel_left):\n return True\n else:\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n \"\"\"(^-__-^)\"\"\"\n return(True if distance_to_pump <= mpg*fuel_left else False)\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n if distance_to_pump == mpg*fuel_left or distance_to_pump < mpg*fuel_left:\n return True\n if distance_to_pump > mpg*fuel_left: return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n a = mpg * fuel_left\n return a >= distance_to_pump", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n distance_to_pump = float(distance_to_pump)\n mpg = float(mpg)\n fuel_left = float(fuel_left)\n \n if distance_to_pump > mpg*fuel_left:\n return False\n else:\n return True", "zero_fuel = lambda x,y,z: z*y >= x \n# def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n print(distance_to_pump, mpg, fuel_left)\n return True if (distance_to_pump-(mpg*fuel_left)) <= 0 else False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n # Let's just return wether the miles we get for our gallons are more or equal to the distance to the pump.\n return (mpg*fuel_left)>=distance_to_pump", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n required_fuel = distance_to_pump / mpg\n return required_fuel <= fuel_left", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n miles = fuel_left * mpg\n return distance_to_pump <= miles", "def zero_fuel(d, mpg, fl):\n if fl * mpg >= d:\n return True\n else:\n return False\n", "def zero_fuel(d, a, g):\n return(True if a*g>=d else False)", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n if mpg*fuel_left>=distance_to_pump:\n res = True\n else:\n res = False\n return res", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n if fuel_left == 0:\n return distance_to_pump <= mpg\n elif fuel_left > 0:\n m = mpg * fuel_left\n \n return distance_to_pump <= m", "def zero_fuel(dist,mpg,fuel):\n return bool(dist<=mpg*fuel)", "def zero_fuel(distance_to_pump, mpg, gallon_left):\n if mpg * gallon_left >= distance_to_pump:\n return True\n else:\n return False\n \n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n if (distance_to_pump / mpg) - fuel_left <= 0:\n ergebnis = True\n else:\n ergebnis = False\n return ergebnis\n\n\nprint((zero_fuel(50, 25, 2)))\nprint((zero_fuel(100, 50, 1)))\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n necessary_amount = distance_to_pump/mpg\n if necessary_amount <= fuel_left:\n return True\n else:\n return False\n", "def zero_fuel(dpump, mpg, fuel):\n \n if (mpg*fuel) >= dpump:\n return True\n else:\n return False\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n return distance_to_pump <= mpg * fuel_left\n\n# a longer return statement: \n# return True if distance_to_pump <= mpg * fuel_left else False\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n \n fueluse=distance_to_pump/mpg\n if fueluse>fuel_left:\n return False \n else:\n return True \n \n", "def zero_fuel(dis, mpg, fu):\n #Happy Coding! ;)\n return dis / mpg <= fu", "def zero_fuel(distance, mpg, gallons):\n bool=False\n mpg=mpg*gallons\n if mpg>=distance:\n bool=True\n return bool", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n make_it = (mpg * fuel_left)\n if (distance_to_pump <= make_it):\n return True\n else:\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n return 1/mpg*distance_to_pump <= fuel_left", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n distance_in_tank = mpg * fuel_left\n if (distance_in_tank >= distance_to_pump):\n return True\n else: \n return False", "def zero_fuel(distance_to_pump: float, mpg: float, fuel_left: float) -> bool:\n gallons_needed = distance_to_gallons(distance_to_pump, mpg)\n rslt = gallons_needed <= fuel_left\n return rslt\n\ndef distance_to_gallons(distance_to_pump: float, mpg: float) -> float:\n if mpg == 0:\n return 0\n return distance_to_pump / mpg\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n diff = mpg * fuel_left\n if distance_to_pump <= diff:\n return True\n else:\n return False", "def zero_fuel(pump, miles, gallons):\n \"\"\"berechnet ob der Tank zur Tanke reicht\"\"\"\n return miles * gallons >= pump", "#<!:(){}^@\"\"+%_*&$?>\ndef zero_fuel(distance_to_pump, mpg, fuel_left):\n #distance_to_pump = 0\n #mpg = 0\n #fuel_left = 0\n return distance_to_pump <= mpg * fuel_left", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #if fuel left is less than miles to gallon distance to poump\n if distance_to_pump > (mpg * fuel_left ):\n return False\n else:\n return True\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n make_it = False;\n get_pump = mpg * fuel_left;\n if (distance_to_pump > get_pump):\n return False;\n elif (distance_to_pump <= get_pump):\n return True;\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n if mpg * fuel_left >= distance_to_pump:\n return 1\n elif mpg * fuel_left < distance_to_pump:\n return 0", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;) \n fuel_need_it = mpg * fuel_left\n if distance_to_pump <= fuel_need_it:\n return True \n else:\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n if distance_to_pump/mpg <=fuel_left :\n return 1\n return 0", "def zero_fuel(distance, avg, f_l):\n if avg*f_l >= distance:\n return True\n else:\n return False", "def zero_fuel(a, b, c):\n if b * c == a or b * c > a:\n return True\n else:\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n result=mpg*fuel_left - distance_to_pump\n return True if result >=0 else False", "def zero_fuel(dist, mpg, fuel_left):\n return dist <= fuel_left * mpg", "def zero_fuel(d, mpg, fuel):\n while d == mpg * fuel or d <= mpg * fuel:\n return True\n else:\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n voi_ajaa = mpg * fuel_left\n if (voi_ajaa >= distance_to_pump):\n return True\n\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n a= fuel_left\n b= mpg\n c= distance_to_pump\n if (a*b)>=c :\n return True\n else:\n return False\n #Happy Coding! ;)\n", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n berhasil = mpg * fuel_left\n if (berhasil >= distance_to_pump):\n return True\n else:\n return False", "def zero_fuel(d, v, g):\n #Happy Coding! ;)\n if d<=v * g:\n return True\n else :\n return False", "import math\n\ndef zero_fuel(distance_to_pump, mpg, fuel_left):\n \n x = int(distance_to_pump)\n y = int(mpg)\n z = int(fuel_left)\n p = y * z / x\n if(p >= 1) :\n return True\n else:\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n fn=distance_to_pump-mpg*fuel_left\n if fn<=0:\n return True\n else:\n return False", "def zero_fuel(distance_to_pump, mpg, fuel_left):\n #Happy Coding! ;)\n if distance_to_pump - (mpg*fuel_left) <= 0:\n return 1\n else:\n return 0"]
{"fn_name": "zero_fuel", "inputs": [[50, 25, 2], [60, 30, 3], [70, 25, 1], [100, 25, 3]], "outputs": [[true], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
14,214
def zero_fuel(distance_to_pump, mpg, fuel_left):
0f6be9bf2ee7c0bcb7291b42562e6102
UNKNOWN
Step through my `green glass door`. You can take the `moon`, but not the `sun`. You can take your `slippers`, but not your `sandals`. You can go through `yelling`, but not `shouting`. You can't run through `fast`, but you can run with `speed`. You can take a `sheet`, but not your `blanket`. You can wear your `glasses`, but not your `contacts`. Have you figured it out? Good! Then write a program that can figure it out as well.
["def step_through_with(s):\n return any(m == n for m, n in zip(s, s[1:]))", "import re\ndef step_through_with(s): return re.compile(r'([a-z])\\1', re.I).search(s) is not None", "def step_through_with(s):\n prev = '' \n for letter in s:\n if prev == letter:\n return True\n prev = letter\n return False\n", "import re\ndef step_through_with(s):\n # You can't bring your code, but you can bring this comment\n return bool(re.search(r'(.)\\1', s))\n", "def step_through_with(s):\n for letter in \"abcdefghijklmnopqrstuvwxyz\":\n if letter * 2 in s:\n return True\n return False", "def step_through_with(s):\n return any(map(str.__eq__, s, s[1:]))", "def step_through_with(s):\n return any(c1 == c2 for c1, c2 in zip(s, s[1:]))", "def step_through_with(s):\n return any(s[i-1] == x for i, x in enumerate(s[1:], 1))", "def step_through_with(s):\n return any(l+l in s for l in s)\n", "step_through_with=lambda s,r=__import__(\"re\").compile(r\"([a-zA-Z])\\1\"):bool(r.search(s))"]
{"fn_name": "step_through_with", "inputs": [["moon"], ["test"], ["glasses"], ["airplane"], ["free"], ["branch"], ["aardvark"]], "outputs": [[true], [false], [true], [false], [true], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,057
def step_through_with(s):
b729528085f85d4918e19cd9fe4a017b
UNKNOWN
Consider the following series: `1, 2, 4, 8, 16, 22, 26, 38, 62, 74, 102, 104, 108, 116, 122` It is generated as follows: * For single digit integers, add the number to itself to get the next element. * For other integers, multiply all the non-zero digits and add the result to the original number to get the next element. For example: `16 + (6 * 1) = 22` and `104 + (4 * 1) = 108`. Let's begin the same series with a seed value of `3` instead of `1`: `3, 6, 12, 14, 18, 26, 38, 62, 74, 102, 104, 108, 116, 122` Notice that the two sequences converge at `26` and are identical therefter. We will call the series seeded by a value of `1` the "base series" and the other series the "test series". You will be given a seed value for the test series and your task will be to return the number of integers that have to be generated in the test series before it converges to the base series. In the case above: ```Python convergence(3) = 5, the length of [3, 6, 12, 14, 18]. ``` Good luck! If you like this Kata, please try: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) [Unique digit sequence](https://www.codewars.com/kata/599688d0e2800dda4e0001b0) [Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)
["from operator import mul\nfrom functools import reduce\n\ndef genSequence(n):\n yield n\n while True:\n n += reduce(mul, [int(d) for d in str(n) if d != '0']) if n > 9 else n\n yield n\n\ndef extract(seq, v):\n return sorted(seq).index(v)\n\ndef convergence(n):\n gen1, genN = genSequence(1), genSequence(n)\n seq1, seqN = {next(gen1)}, {next(genN)}\n while True:\n a,b = next(gen1), next(genN)\n seq1.add(a)\n seqN.add(b)\n if a in seqN: return extract(seqN, a)\n if b in seq1: return extract(seqN, b)", "def next(base):\n mul = 1\n for c in str(base):\n if c!=\"0\":\n mul *= int(c)\n return base + mul\n \ndef convergence(n):\n base = 1\n test = n\n count = 0\n while test!=base:\n if test > base:\n base = next(base)\n else:\n test =next(test)\n count +=1\n print(str(base)+\" \"+str(test))\n return count", "from functools import reduce\n\ndef calculate_next_el(prev_el):\n if prev_el < 10:\n return 2 * prev_el\n else:\n multiplication = reduce((lambda x, y: x * y), [x for x in map(int, str(prev_el)) if x > 0], 1)\n return prev_el + multiplication\n\ndef generate_series(start):\n last = start\n while True:\n last = calculate_next_el(last)\n yield last\n\ndef convergence(n):\n current_base = 1\n current_test = n\n base_series = generate_series(current_base)\n test_series = generate_series(current_test)\n result = 0\n while current_base != current_test:\n if current_base < current_test:\n current_base = base_series.__next__()\n else:\n current_test = test_series.__next__()\n result += 1\n return result\n", "def sumIntegers(n):\n mod=10\n lst=[]\n while n>0:\n lst.append(n%mod)\n n-=n%mod\n n//=10\n result = 1\n for i in lst:\n if i!=0:\n result*=i\n return result\ndef convergence(n):\n ntest=1\n i=0\n while True:\n if ntest == n:\n return i\n elif n>ntest:\n ntest = ntest + sumIntegers(ntest)\n else:\n n=n+sumIntegers(n)\n i+=1\n \n \n \n", "import numpy\nbase=[1]\ndef convergence(n):\n test=[n]\n while test[-1] not in base:\n if base[-1]>test[-1]:test.append(test[-1]+int(numpy.prod([int(dig) for dig in str(test[-1]) if int(dig)!=int()])))\n else:base.append(base[-1]+int(numpy.prod([int(dig) for dig in str(base[-1]) if int(dig)!=int()])))\n return len(test)-1", "from functools import reduce\n\ndef convergence(n):\n print(n)\n t,r = [1],[n]\n f = lambda x: x+reduce(lambda x,y:x*y, (int(i) for i in str(x) if i!='0'))\n while r[-1] not in t:\n for _ in range(25):\n t += [f(t[-1])]\n r += [f(r[-1])]\n return len(r)-1", "from itertools import accumulate, repeat\nfrom functools import reduce\nfrom operator import mul\n\nvalue = lambda n: n + reduce(mul, filter(None, map(int, str(n))))\nserie = lambda *args: accumulate(repeat(*args), lambda x,_: value(x))\nbase = set(serie(1, 1000))\n\ndef convergence(n):\n return next(i for i,x in enumerate(serie(n)) if x in base)", "from functools import reduce\nfrom itertools import count, islice\nfrom operator import mul\n\ndef gen(n):\n yield n\n while True:\n n += n if n < 10 else reduce(mul, map(int, str(n).replace('0', '')), 1)\n yield n\n\ndef convergence(n, base_series = set(islice(gen(1), 1000))):\n it = gen(n)\n return next(i for i in count() if next(it) in base_series)", "from operator import mul\nfrom functools import reduce\n\n# generate base series\nbase, n = {1}, 1\nfor _ in range(2000):\n n += reduce(mul, map(int, str(n).replace(\"0\", \"\")))\n base.add(n)\n\n\ndef convergence(n):\n steps = 0\n \n while n not in base:\n n += reduce(mul, map(int, str(n).replace(\"0\", \"\")))\n steps += 1\n \n return steps", "from functools import reduce\ndef convergence(n):\n j = 0\n x = 1\n s1 = set()\n s2 = set()\n while True:\n s1.add(x)\n s2.add(n)\n if x in s2 or n in s1 or s1.intersection(s2):\n break\n if n < 10:\n n = n + n\n else:\n n = n + reduce(lambda h,k: h*k, (int(i) for i in str(n) if i!=\"0\")) \n if x < 10:\n x = x + x \n else:\n x = x + reduce(lambda h,k: h*k, (int(i) for i in str(x) if i!=\"0\"))\n return sorted(list(s2)).index(list(s1.intersection(s2))[0])"]
{"fn_name": "convergence", "inputs": [[3], [5], [10], [15], [500], [5000]], "outputs": [[5], [6], [5], [2], [29], [283]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,656
def convergence(n):
98f2621b7fc8c4227d126f806d093509
UNKNOWN
You will be given a string (x) featuring a cat 'C', a dog 'D' and a mouse 'm'. The rest of the string will be made up of '.'. You need to find out if the cat can catch the mouse from it's current position. The cat can jump (j) characters. Also, the cat cannot jump over the dog. So: if j = 5: ```..C.....m.``` returns 'Caught!' <-- not more than j characters between ```.....C............m......``` returns 'Escaped!' <-- as there are more than j characters between the two, the cat can't jump far enough if j = 10: ```...m.........C...D``` returns 'Caught!' <--Cat can jump far enough and jump is not over dog ```...m....D....C.......``` returns 'Protected!' <-- Cat can jump far enough, but dog is in the way, protecting the mouse Finally, if all three animals are not present, return 'boring without all three'
["def cat_mouse(x,j):\n d, c, m = x.find('D'), x.find('C'), x.find('m')\n if -1 in [d, c, m]:\n return 'boring without all three'\n if abs(c - m) <= j:\n return 'Protected!' if c < d < m or m < d < c else 'Caught!' \n return 'Escaped!'", "def cat_mouse(x, j):\n try:\n cat, dog, mouse = [x.index(c) for c in 'CDm']\n if abs(mouse - cat) > j: return 'Escaped!'\n elif cat < dog < mouse or cat > dog > mouse: return 'Protected!'\n else: return 'Caught!'\n except ValueError:\n return 'boring without all three'", "from re import sub\n\ndef cat_mouse(s, j):\n if set(s) < set('mCD.'):\n return 'boring without all three'\n \n between = sub('.*[Cm](.*?)[Cm].*', r'\\1', s)\n \n if len(between) > j:\n return 'Escaped!'\n \n if 'D' in between:\n return 'Protected!'\n \n return 'Caught!'", "def cat_mouse(x, j):\n c, d, m = (x.find(animal) for animal in 'CDm')\n return ('boring without all three' if c < 0 or d < 0 or m < 0 else\n 'Escaped!' if abs(c - m) > j else\n 'Protected!' if c < d < m or c > d > m else\n 'Caught!')", "def cat_mouse(x,j):\n try:\n d, c, m = map(x.index,'DCm')\n except ValueError:\n return 'boring without all three'\n if j < abs(c - m)-1 : return 'Escaped!'\n elif c>d>m or m>d>c : return 'Protected!'\n return 'Caught!'", "def cat_mouse(stg, j):\n if set(\"mCD.\") - set(stg):\n return \"boring without all three\"\n c, d, m = (stg.index(a) for a in \"CDm\")\n if abs(c - m) > j:\n return \"Escaped!\"\n elif m < d < c or c < d < m:\n return \"Protected!\"\n else:\n return \"Caught!\"", "def cat_mouse(x,j):\n if not all(('C' in x, 'D' in x, 'm' in x)):\n return \"boring without all three\"\n cat, dog, mouse = x.index('C'), x.index('D'), x.index('m')\n zone = [x[cat:mouse],x[mouse+1:cat]][mouse<cat]\n return { (1,0):\"Caught!\",\n (1,1):\"Protected!\" }.get( (len(zone)<=j,'D' in zone),\"Escaped!\")", "def cat_mouse(x,j):\n if len(set(x)) != 4:\n return \"boring without all three\"\n dog = x.index(\"D\")\n cat = x.index(\"C\")\n mouse = x.index(\"m\")\n if max(cat,mouse) - min(cat,mouse) <= j:\n if min(cat,mouse) < dog and dog < max(cat,mouse):\n return \"Protected!\"\n return \"Caught!\"\n \n return \"Escaped!\"\n \n\n\n \n\n\n\n", "def cat_mouse(x,j):\n c,d,m = [x.find(ch) for ch in 'CDm']\n if -1 in [c,d,m]: return \"boring without all three\"\n if abs(c-m)-1 <= j: return \"Protected!\" if (c<d<m or m<d<c) else \"Caught!\"\n return \"Escaped!\"", "def cat_mouse(x,j):\n if not all(['C' in x, 'm' in x, 'D' in x]):\n return 'boring without all three'\n c, m, d = list(map(x.index, ['C', 'm', 'D']))\n if abs(m-c) <= j+1: return ['Caught!', 'Protected!'][x.replace('.', '')[1] == 'D']\n else: return 'Escaped!'\n"]
{"fn_name": "cat_mouse", "inputs": [["..D.....C.m", 2], ["............C.............D..m...", 8], ["m.C...", 5], [".CD......m.", 10], [".CD......m.", 1]], "outputs": [["Caught!"], ["Escaped!"], ["boring without all three"], ["Protected!"], ["Escaped!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,002
def cat_mouse(x,j):
89f9269cb1b938082fa5bbca507cea60
UNKNOWN
You're playing a game with a friend involving a bag of marbles. In the bag are ten marbles: * 1 smooth red marble * 4 bumpy red marbles * 2 bumpy yellow marbles * 1 smooth yellow marble * 1 bumpy green marble * 1 smooth green marble You can see that the probability of picking a smooth red marble from the bag is `1 / 10` or `0.10` and the probability of picking a bumpy yellow marble is `2 / 10` or `0.20`. The game works like this: your friend puts her hand in the bag, chooses a marble (without looking at it) and tells you whether it's bumpy or smooth. Then you have to guess which color it is before she pulls it out and reveals whether you're correct or not. You know that the information about whether the marble is bumpy or smooth changes the probability of what color it is, and you want some help with your guesses. Write a function `color_probability()` that takes two arguments: a color (`'red'`, `'yellow'`, or `'green'`) and a texture (`'bumpy'` or `'smooth'`) and returns the probability as a decimal fraction accurate to two places. The probability should be a string and should discard any digits after the 100ths place. For example, `2 / 3` or `0.6666666666666666` would become the string `'0.66'`. Note this is different from rounding. As a complete example, `color_probability('red', 'bumpy')` should return the string `'0.57'`.
["def color_probability(color, texture):\n marbles = {\"smooth\": {\"red\": 1, \"yellow\": 1, \"green\": 1, \"total\": 3}, \"bumpy\": {\"red\": 4, \"yellow\": 2, \"green\": 1, \"total\": 7}}\n return \"{}\".format(marbles[texture][color] / marbles[texture][\"total\"])[:4]", "def color_probability(color, texture):\n prob_mapper = {'smooth': {\n 'red': 1,\n 'yellow': 1,\n 'green': 1,\n 'total': 3\n }, 'bumpy': {\n 'red': 4,\n 'yellow': 2,\n 'green': 1,\n 'total': 7\n }}\n \n prob = prob_mapper[texture][color] / prob_mapper[texture]['total']\n \n return str(prob)[:4]", "def color_probability(color, texture):\n if texture == 'smooth': return '0.33'\n if color == 'red' : return '0.57'\n if color == 'yellow': return '0.28'\n if color == 'green' : return '0.14'", "# R Y G\nPROBS = [[1, 1, 1], # Smooth\n [4, 2, 1]] # Bumpy\nIDX = {'red': 0, 'yellow': 1, 'green': 2, 'smooth': 0, 'bumpy': 1}\n\ndef color_probability(color, texture):\n prob = PROBS[IDX[texture]][IDX[color]] / sum(PROBS[IDX[texture]])\n return \"{:.2}\".format(int(prob*100)/100)", "def color_probability(color, texture):\n # Your code goes here.\n if texture == 'bumpy': \n if color == 'red':\n prob = 4/7 \n elif color == 'yellow': \n prob = 2/7 \n else: \n prob = 1/7 \n else:\n prob = 1/3\n return str(prob)[:4] \n", "def color_probability(color, texture):\n bag = [\n (\"red\", \"smooth\"),\n (\"red\", \"bumpy\"),\n (\"red\", \"bumpy\"),\n (\"red\", \"bumpy\"),\n (\"red\", \"bumpy\"),\n (\"yellow\", \"bumpy\"),\n (\"yellow\", \"bumpy\"),\n (\"yellow\", \"smooth\"),\n (\"green\", \"bumpy\"),\n (\"green\", \"smooth\"),\n ]\n candidates = [marble for marble in bag if marble[1] == texture]\n return \"{:.03}\".format(sum(marble[0] == color for marble in candidates) / len(candidates))[:-1]", "from decimal import *\n\ndef color_probability(color, texture):\n bag_content = {\n (\"red\", \"smooth\"): 1,\n (\"red\", \"bumpy\"): 4,\n (\"yellow\", \"bumpy\"): 2,\n (\"yellow\", \"smooth\"): 1,\n (\"green\", \"bumpy\"): 1,\n (\"green\", \"smooth\"): 1,\n }\n\n color_match_number = Decimal(bag_content[color, texture])\n \n texture_match_list = [bag_content[k] for k in bag_content.keys() if k[1]==texture]\n texture_match_number = Decimal(sum(texture_match_list))\n \n return str(Decimal(color_match_number/texture_match_number).quantize(Decimal('.01'), rounding=ROUND_DOWN))", "D = {'bumpy':{'red':'0.57', 'yellow':'0.28', 'green':'0.14'}, 'smooth':{'red':'0.33', 'yellow':'0.33', 'green':'0.33'}}\n\n# That's a weird kata, only 6 possibles results and no randomness\ndef color_probability(color, texture):\n return D[texture][color]", "color_probability=lambda c, t, p=lambda x:x[0]in'bg':f\"{([[2,1][p(c)],4][c[0]=='r']if p(t)else 1)/(7if p(t)else 3):.3f}\"[:-1]", "def color_probability(color, texture):\n return {\n (\"smooth\", \"red\"): \"0.33\", # 1:3\n (\"bumpy\", \"red\"): \"0.57\", # 4:7\n (\"smooth\", \"yellow\"): \"0.33\", # 1:3\n (\"bumpy\", \"yellow\"): \"0.28\", # 2:7\n (\"smooth\", \"green\"): \"0.33\", # 1:3\n (\"bumpy\", \"green\"): \"0.14\" # 1:7\n }[texture, color]"]
{"fn_name": "color_probability", "inputs": [["red", "bumpy"], ["green", "bumpy"], ["yellow", "smooth"], ["red", "smooth"], ["green", "smooth"], ["yellow", "bumpy"]], "outputs": [["0.57"], ["0.14"], ["0.33"], ["0.33"], ["0.33"], ["0.28"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,494
def color_probability(color, texture):
53ce9f9582bffd857397d3ee89a8aeab
UNKNOWN
Passer ratings are the generally accepted standard for evaluating NFL quarterbacks. I knew a rating of 100 is pretty good, but never knew what makes up the rating. So out of curiosity I took a look at the wikipedia page and had an idea or my first kata: https://en.wikipedia.org/wiki/Passer_rating ## Formula There are four parts to the NFL formula: ```python A = ((Completions / Attempts) - .3) * 5 B = ((Yards / Attempts) - 3) * .25 C = (Touchdowns / Attempt) * 20 D = 2.375 - ((Interceptions / Attempts) * 25) ``` However, if the result of any calculation is greater than `2.375`, it is set to `2.375`. If the result is a negative number, it is set to zero. Finally the passer rating is: `((A + B + C + D) / 6) * 100` Return the rating rounded to the nearest tenth. ## Example Last year Tom Brady had 432 attempts, 3554 yards, 291 completions, 28 touchdowns, and 2 interceptions. His passer rating was 112.2 Happy coding!
["def passer_rating(att, yds, comp, td, ints):\n limit = lambda x: min(max(x, 0), 2.375)\n \n att = float(att) # for python 2 compatibility\n \n A = ((comp / att) - .3) * 5\n B = ((yds / att) - 3) * .25\n C = (td / att) * 20\n D = 2.375 - ((ints / att) * 25)\n \n A, B, C, D = map(limit, (A, B, C, D))\n \n return round( (A + B + C + D) / 6 * 100, 1 )", "def passer_rating(attempts, yards, completions, touchdowns, interceptions):\n a = (completions / attempts - .3) * 5\n b = (yards / attempts - 3) * .25\n c = (touchdowns / attempts) * 20\n d = 2.375 - (interceptions / attempts * 25)\n a, b, c, d = (max(0, min(x, 2.375)) for x in (a, b, c, d))\n return round((a + b + c + d) / 6 * 100, 1)", "def passer_rating(att, yds, comp, td, ints):\n A = ((comp / att) - .3) * 5\n B = ((yds / att) - 3) * .25\n C = (td / att) * 20\n D = 2.375 - ((ints / att) * 25)\n \n lst = [2.375 if element > 2.375 \n else 0 if element < 0\n else element for element in (A, B, C, D)]\n \n passer_rating = sum(lst) / 6 * 100\n return round(passer_rating, 1)", "def passer_rating(att, yds, comp, td, ints):\n cap = lambda x: max(0, min(x, 2.375))\n a = cap(((comp / att) - 0.3) * 5)\n b = cap(((yds / att) - 3) * 0.25)\n c = cap((td / att) * 20)\n d = cap(2.375 - ((ints /att) * 25))\n return round((a + b + c + d) / 6 * 100, 1)", "def limit(n):\n return max(0, min(2.375, n))\n\n\ndef passer_rating(a, y, c, t, i):\n Y = limit((y / a - 3) * 0.25)\n C = limit((c / a - 0.3) * 5)\n T = limit(20 * t / a)\n I = limit(2.375 - 25 * i / a)\n return round(100 * (Y + C + T + I) / 6, 1)", "def passer_rating(att, yds, comp, td, ints):\n a = ((comp / att) - 0.3) * 5\n b = ((yds / att) - 3) * 0.25\n c = (td / att) * 20\n d = 2.375 - ((ints / att) * 25)\n return round(sum(max(0, min(x, 2.375)) for x in [a, b, c, d]) * 50 / 3, 1)", "def passer_rating(att, yds, comp, td, ints):\n \n def bording(score):\n if score < 0:\n return 0\n if score > 2.375:\n return 2.375\n return score\n \n a = bording(((comp / att) - 0.3) * 5)\n b = bording(((yds / att) - 3) * 0.25)\n c = bording((td /att) * 20)\n d = bording(2.375 - ((ints / att) * 25))\n \n return round(((a + b + c + d) / 6) * 100, 1)", "def passer_rating(att, yds, comp, td, ints):\n A = max(min(2.375, ((comp / att) - .3) * 5), 0)\n B = max(min(2.375, ((yds / att) - 3) * .25), 0)\n C = max(min(2.375, (td / att) * 20), 0)\n D = max(min(2.375, 2.375 - ((ints / att) * 25)), 0)\n return round(((A + B + C + D) / 6) * 100, 1)\n", "def passer_rating(att, yds, comp, td, ints):\n return round( sum(map(lambda n: min(2.375, max(0, n)),\n [(comp/att-0.3)*5, (yds/att-3)*.25, td/att*20, 2.375-ints/att*25])) / 6 * 100, 1)", "def passer_rating(att, yds, comp, td, ints):\n a = ((comp/att)-0.3)*5 ; a = min(a, 2.375) ; a = max(a, 0)\n b = ((yds/att)-3)*0.25 ; b = min(b, 2.375) ; b = max(b, 0)\n c = (td/att)*20 ; c = min(c, 2.375) ; c = max(c, 0)\n d = 2.375 - ((ints/att)*25) ; d = min(d, 2.375) ; d = max(d, 0)\n \n return round(((a+b+c+d)/6)*100,1)\n"]
{"fn_name": "passer_rating", "inputs": [[432, 3554, 291, 28, 2], [5, 76, 4, 1, 0], [48, 192, 19, 2, 3], [1, 2, 1, 1, 0], [34, 172, 20, 1, 1], [10, 17, 2, 0, 1]], "outputs": [[112.2], [158.3], [39.6], [118.8], [69.7], [0.0]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,284
def passer_rating(att, yds, comp, td, ints):
4de600e34dfb073821230e39e0ffbe25
UNKNOWN
You will be given a vector of strings. You must sort it alphabetically (case-sensitive, and based on the ASCII values of the chars) and then return the first value. The returned value must be a string, and have `"***"` between each of its letters. You should not remove or add elements from/to the array.
["def two_sort(lst):\n return '***'.join(min(lst))", "def two_sort(array):\n return '***'.join(min(array))", "def two_sort(arr):\n return '***'.join(sorted(arr)[0])", "def two_sort(a):\n a = sorted(a)\n result = \"***\".join(a[0])\n return result", "def two_sort(array):\n return '***'.join(sorted(array)[0])", "def two_sort(a):\n a = sorted(a)\n result = a[0]\n result = result.replace(\"\", \"***\")\n return result [3:-3]\n", "two_sort = lambda a: \"***\".join(sorted(a)[0])", "two_sort = lambda a: \"***\".join(min(a))", "# o(n) time, o(1) space\ndef two_sort(words):\n min_word = min(words)\n starred_word = \"***\".join(list(min_word))\n return starred_word", "def two_sort(array):\n final = sorted(array)\n return '***'.join(final[0])", "def two_sort(array):\n return \"***\".join(i for i in sorted(array)[0])", "def two_sort(array):\n x = \"\"\n a = sorted(array)\n for alp in a[0]:\n x = x + alp + \"***\"\n return x[:-3]", "def intersperse(delim, s):\n it = iter(s)\n yield next(it)\n for t in it:\n yield delim\n yield t\n\ndef two_sort(array):\n return ''.join(intersperse('***', sorted(array)[0]))", "def two_sort(array):\n temp = array.sort()\n new = array[0]\n out = \"\"\n for i in range(len(new) - 1):\n out += new[i] + \"***\"\n out += new[-1]\n return (out)", "def two_sort(array):\n return '***'.join(list(sorted(array)[0]))", "def two_sort(array):\n array.sort()\n first = array[0]\n output_string = \"\"\n for character in first:\n output_string += character + \"***\"\n return output_string.strip(\"***\")", "def two_sort(array):\n sort = sorted(array)\n first = sort[0]\n return \"***\".join(first)\n", "def two_sort(array):\n word = sorted(array)[0]\n result = [i for i in word]\n return \"***\".join(result)\n \n", "def two_sort(array):\n result =\"\"\n word = sorted(array)[0]\n n = 0\n \n while n < len(word):\n if len(word)-n ==1:\n result += word[n]\n else:\n result +=word[n]+\"***\"\n n+=1\n return result", "two_sort = lambda l:'***'.join(sorted(l)[0])", "def two_sort(array):\n array.sort()\n a = []\n i = array[0]\n for j in i:\n a.append(j)\n return \"***\".join(a)", "def two_sort(array):\n print(array)\n temp = min(array)\n print(temp)\n res = \"\"\n for x in temp:\n res += x + \"***\"\n return res.rstrip(\"*\")", "def two_sort(array):\n x=sorted(array)\n word=\"\"\n for i in range(0,len(x[0])):\n word+=x[0][i]\n if i<len(x[0])-1: word+=\"***\"\n return word", "def two_sort(array):\n new_arr = sorted(array)\n final_arr = []\n for x in new_arr[0]:\n x += \"***\"\n final_arr.append(x)\n word = ''.join(final_arr)\n return word.strip(\"***\")\n\n", "def two_sort(array):\n min=array[0]\n flag=\"\"\n for i in array:\n if i<min:\n min=i\n print(array)\n print(min)\n for i in min:\n index=ord(i.upper())-ord(\"A\")\n flag=flag+i+\"***\"\n \n return flag[:len(flag)-3]", "def two_sort(array):\n s = sorted(array)[0]\n a = ''\n for i in s:\n a +=i+'***'\n return a[:-3]", "def two_sort(array):\n arr = [i.split() for i in min(array)]\n return \"***\".join([i for j in arr for i in j])", "def two_sort(array):\n array_1 = sorted(array)\n x = array_1[0]\n l = []\n for i in x:\n l.append(i)\n return '***'.join(l)", "def two_sort(a):\n a.sort()\n a = a[0]\n b = \"\"\n for x in a:\n b = f\"{b}{x}***\"\n return b[:-3]", "def two_sort(array):\n return '***'.join(el for el in sorted(array)[0])", "def two_sort(array):\n array.sort()\n return \"\".join(map(lambda x: x + '***', array[0]))[0:-3]", "def two_sort(array):\n array = sorted(array)\n return \"***\".join(i for i in array[0])", "def two_sort(array):\n #for i in range(len(array)):\n # [i][0]\n list.sort(array)\n car=list(array[0])\n return('***'.join(car))\n", "def two_sort(array):\n array = sorted(array)\n newStr = ''\n for char in array[0]:\n newStr += char+'***'\n return newStr.rstrip('***')", "def two_sort(array):\n x = sorted(array)[0]\n return \"***\".join(c for c in x)", "def two_sort(array):\n firstElem = sorted(array)[0]\n returnArr = [] \n for i in range(len(firstElem)-1): \n returnArr.append(firstElem[i])\n returnArr.append('***')\n returnArr.append(firstElem[-1])\n return \"\".join(returnArr)", "def two_sort(array):\n word = sorted(array)[0]\n return \"***\".join(list(word))\n\n", "def two_sort(array):\n # your code here\n array.sort()\n a=array[0]\n s=\"\"\n for i in a:\n s=s+i+\"***\"\n l=len(s)\n return s[0:l-3]", "def two_sort(array):\n sort_list = sorted(array)\n first_ele = sort_list[0]\n last = '***'.join(first_ele)\n return last\n", "def two_sort(array):\n return \"***\".join([*sorted(array)[0]])", "def two_sort(array):\n a = list(array)\n a.sort()\n\n res = str(a[0]).strip()\n tmp = \"\"\n \n for i in range(len(res)):\n tmp += res[i] + \"***\"*(i < len(res) - 1)\n \n return tmp", "def two_sort(array):\n x = sorted(array)\n #print(x)\n a = x[0]\n a1 = \"***\".join(a)\n return (a1)", "def two_sort(array):\n ans = ''\n array.sort()\n for i in array[0]:\n ans = ans + (i + '***')\n return ans[0:-3]\n", "def two_sort(array):\n array = sorted(array)\n a = \"\"\n for el in array[0]:\n a += el + \"***\"\n return a[:-3]", "def two_sort(array):\n return \"***\".join((sorted([x for x in array if x[0].isupper()])+sorted([x for x in array if x[0].islower()]))[0])", "def two_sort(array):\n sort = sorted(array)\n x = '***'.join(sort[0])\n return x", "def two_sort(array):\n array = sorted(array)\n return ('***').join(x[0] for x in array[0])", "def two_sort(array):\n return \"***\".join(sorted([n for n in array])[0])", "def two_sort(array):\n array.sort()\n x=array[0]\n s=\"\"\n for i in x:\n s+=\"***\"+i\n return s[3:]\n", "def two_sort(array):\n return '***'.join(sorted(array)[0][i]for i in range(len(sorted(array)[0])))\n", "def two_sort(array):\n res = ''\n for x in sorted(array)[0]:\n res += x + \"***\"\n return res[:-3]", "# You will be given an vector of string(s).\n# You must sort it alphabetically (case-sensitive, and based on the ASCII \n# values of the chars) and then return the first value.\n\n# The returned value must be a string, and have \"***\" between each of its letters.\n\n# You should not remove or add elements from/to the array.\n\n\ndef two_sort(list):\n # your code here\n list.sort()\n y = list[0]\n res = '***'.join(y[i:i + 1] for i in range(0, len(y), 1))\n return res", "def two_sort(array):\n array.sort()\n lst = []\n new_str = ''\n for i in array[0]:\n lst.append(i)\n for x in lst:\n new_str = new_str + x + '***'\n return new_str[0:-3]\n", "def two_sort(array):\n return ''.join(i + '***' for i in sorted(array)[0]).rstrip('***')", "def two_sort(array):\n out = \"\"\n for let in sorted(array)[0]:\n out += let + \"***\" \n return out.rstrip(\"***\")\n", "two_sort = lambda list: \"***\".join(min(list))", "def two_sort(array):\n array.sort()\n return (\"\".join(x+\"***\" for x in array[0])).rstrip(\"*\")", "def two_sort(array):\n array.sort()\n result = \"\"\n for i, caracter in enumerate(array[0]):\n result += array[0][i]\n if i < len(array[0])-1:\n result += \"***\"\n return result", "def two_sort(array):\n \n array.sort()\n \n word = array[0]\n \n new_word = \"\"\n \n for letter in word:\n new_word+=letter\n new_word+=\"***\";\n \n return new_word[:-3]\n", "def two_sort(array):\n array = sorted(array)\n x = list(array[0])\n return \"***\".join(x)\n", "import re\ndef two_sort(array):\n print(array)\n min_value=10000\n min_value2=10000\n min_string=\" \"\n for x in array:\n if len(x)<2:\n y=ord(x[0])\n min_value=y\n min_string=x\n else:\n y=ord(x[0])\n y2=ord(x[1])\n if y<min_value:\n min_value=y\n min_value2=y2\n min_string=x\n elif y==min_value:\n if y2<min_value2:\n min_value2=y2\n min_string=x\n else:\n continue\n else:\n continue\n return \"***\".join(min_string)", "def two_sort(array):\n array.sort()\n first=array[0]\n final=first[0]\n for i in range(1,len(first)):\n final+='***'+first[i]\n return final", "def two_sort(array):\n final = ''\n word = list(sorted(array)[0])\n for i in range(len(word)):\n if i != len(word) - 1:\n final += word[i] + '***'\n else:\n final += word[i]\n \n return final\n", "def two_sort(array):\n '''\n first we sort the array by sort() function :->\n and then we will take its first element and use it to get output :->\n '''\n array.sort()\n return ''.join([i+'***' for i in array[0]])[:-3]\n\n", "def two_sort(array):\n b=sorted(array)\n return '***'.join(b[0])", "def two_sort(array):\n a=''\n for i in range(len(sorted(array)[0])):\n a+=sorted(array)[0][i]+'***'\n return a[:-3]", "def two_sort(array):\n # yor code here\n array=sorted(array)\n st=\"\"\n for c in array[0]:\n st+=c+\"***\"\n return st.rstrip(\"***\")", "def two_sort(array):\n array.sort()\n new_arr = []\n for i in array[0]:\n new_arr.append(i)\n return \"***\".join(new_arr)", "def two_sort(array):\n array.sort()\n printer = \"\"\n for i in array[0]:\n printer += i + \"***\"\n return printer.rstrip(\"***\")", "def two_sort(array):\n x = sorted(array)\n y = x[0]\n return '***'.join(y[i:i + 1] for i in range(0, len(y))) \n", "def two_sort(array):\n return \"\".join(sorted(array)[0][i] + \"***\" for i in range(0,len(sorted(array)[0])))[:-3]\n # your code here\n", "def two_sort(array):\n array.sort()\n a = \"\"\n for x in range(len(array[0])-1):\n a += array[0][x] + \"***\"\n return a + array[0][-1]", "def two_sort(array):\n return \"***\".join([j for j in sorted(array)[0]])", "def two_sort(array):\n first_item = sorted([i for i in array])[0]\n formatted = \"\"\n for i in first_item:\n formatted = formatted + i +\"***\"\n return formatted[:-3]\n", "def two_sort(array):\n str = \"\".join(sorted(array)[:1])\n return \"***\".join(list(str))", "def two_sort(array):\n x = sorted(array)[0]\n s = x[0]\n for l in range(len(x) - 1) :\n s = s + \"***\" + x[l + 1]\n return s", "def two_sort(array):\n separator = '***'\n return separator.join(sorted(array)[0])\n", "def two_sort(array):\n array = sorted(array)\n emptystring = ''\n for eachletter in array[0]:\n emptystring = emptystring + eachletter + ' '\n emptystring = emptystring.rstrip()\n emptystring = emptystring.split()\n emptystring = '***'.join(emptystring)\n return emptystring", "def two_sort(array):\n array_sort = array.sort()\n return ','.join(array[0]).replace(\",\", \"***\")", "def two_sort(array):\n array = sorted(array)\n answer = \"\"\n for one in array[0]:\n answer += one + \"***\"\n return answer.rstrip(\"*\")", "def two_sort(array):\n r = ''\n l = sorted(array)\n for i in l[0]:\n r += i + '***'\n return r[:-3]", "def two_sort(array):\n return ''.join([x+'***' for x in sorted(array)[0]]).strip('*')", "def two_sort(array):\n sorting = sorted(array)\n first = sorting[0]\n new_list = []\n for i in first:\n new_list.append(i)\n return '***'.join(new_list)\n", "def two_sort(array):\n s = \"\"\n for i in (sorted(array)[0]):\n s += i + \"***\"\n \n return s[:-3]", "def two_sort(array):\n array = list(sorted(array))\n return '***'.join(array[0])\n", "def two_sort(array):\n sort = sorted(array)\n res = ''\n lst = list(sort[0])\n\n for i in range(len(lst)):\n if i != len(lst) - 1:\n res += lst[i]\n res += '***'\n else:\n res += lst[i]\n\n return res\n\n\n\n\n\n", "def two_sort(array):\n array.sort() \n listan2 = array[0]\n return (\"***\".join(listan2))\n\n\n", "def two_sort(array):\n s = 'z'\n for i in array:\n if ord(s[0]) > ord(i[0]):\n s = i\n if ord(s[0]) == ord(i[0]):\n if len(i) > 2:\n if ord(s[1]) > ord(i[1]):\n s = i\n return '***'.join(s)", "def two_sort(array):\n return '***'.join([i for i in min(array)])", "def two_sort(array):\n array.sort()\n n = \"\"\n for i in range(0, len(array[0])):\n if i == len(array[0])-1:\n n = n + array[0][i]\n break\n n = n + array[0][i] + \"***\"\n return n\n", "def two_sort(array):\n # your code here\n array.sort()\n return array[0].replace(\"\", \"***\").strip(\"***\")", "def two_sort(array):\n array.sort()\n return (\"\".join([(x + \"***\") for x in array[0]]))[:-3]", "def two_sort(array):\n k=[]\n k.append(sorted(array)[0])\n j=[]\n for i in k[0]:\n j.append(i)\n \n return '***'.join(j)", "def two_sort(array):\n new_array = array\n new_array.sort()\n first_element = new_array[0]\n result = \"\"\n for i in range(len(first_element)):\n if i < len(first_element) - 1:\n result += first_element[i] + \"***\"\n else:\n result += first_element[i]\n return result \n", "def two_sort(array):\n array.sort()\n return ''.join(f'{e}***' for e in array[0])[:-3]\n", "def two_sort(array):\n f = ''\n for i in sorted(array)[0]:\n f += i + '***'\n return f[:-3]", "def two_sort(array):\n array.sort()\n string = array[0]\n return '***'.join(string[i:i + 1] for i in range(0, len(string)))\n", "def two_sort(array):\n array.sort()\n first = array[0]\n first = str(first)\n first = first.replace('', ' ')\n firstsplit = first.split()\n return '***'.join(firstsplit)\n", "def two_sort(array):\n array= sorted(array)\n s= array[0]\n s2=\"\"\n for i in s:\n s2 += i +\"***\"\n s2=s2.strip(\"***\")\n return s2"]
{"fn_name": "two_sort", "inputs": [[["bitcoin", "take", "over", "the", "world", "maybe", "who", "knows", "perhaps"]], [["turns", "out", "random", "test", "cases", "are", "easier", "than", "writing", "out", "basic", "ones"]], [["lets", "talk", "about", "javascript", "the", "best", "language"]], [["i", "want", "to", "travel", "the", "world", "writing", "code", "one", "day"]], [["Lets", "all", "go", "on", "holiday", "somewhere", "very", "cold"]]], "outputs": [["b***i***t***c***o***i***n"], ["a***r***e"], ["a***b***o***u***t"], ["c***o***d***e"], ["L***e***t***s"]]}
INTRODUCTORY
PYTHON3
CODEWARS
14,760
def two_sort(array):
eb036d49c27dd032f8274ebd8f339fa9
UNKNOWN
Help a fruit packer sort out the bad apples. There are 7 varieties of apples, all packaged as pairs and stacked in a fruit box. Some of the apples are spoiled. The fruit packer will have to make sure the spoiled apples are either removed from the fruit box or replaced. Below is the breakdown: Apple varieties are represented with numbers, `1 to 7` A fruit package is represented with a 2 element array `[4,3]` A fruit package with one bad apple, or a bad package, is represented with `[2,0]` or `[0,2]` A fruit package with two bad apples, or a rotten package, is represented with `[0,0]` A fruit box is represented with: ``` [ [ 1, 3 ], [ 7, 6 ], [ 7, 2 ], [ 1, 3 ], [ 0, 2 ], [ 4, 5 ], [ 0, 3 ], [ 7, 6 ] ] ``` Write a program to clear the fruit box off bad apples. The INPUT will be a fruit box represented with a 2D array: `[[1,3],[7,6],[7,2],[1,3],[0,2],[4,5],[0,3],[7,6]]` The OUTPUT should be the fruit box void of bad apples: `[[1,3],[7,6],[7,2],[1,3],[2,3],[4,5],[7,6]]` Conditions to be met: 1.A bad package should have the bad apple replaced if there is another bad package with a good apple to spare. Else, the bad package should be discarded. 2.The order of the packages in the fruit box should be preserved. Repackaging happens from the top of the fruit box `index = 0` to the bottom `nth index`. Also note how fruits in a package are ordered when repacking. Example shown in INPUT/OUPUT above. 3.Rotten packages should be discarded. 4.There can be packages with the same variety of apples, e.g `[1,1]`, this is not a problem.
["def bad_apples(apples):\n lst, notFull = [], []\n for a,b in apples:\n if (bool(a) ^ bool(b)) and notFull: lst[notFull.pop()].append(a or b) # One bad and partially full box already present: fill it (as second element)\n elif a and b: lst.append([a,b]) # 2 good ones: keep as they are\n elif a or b: notFull.append(len(lst)) ; lst.append([a or b]) # 1 good but no partial box: archive\n if notFull: lst.pop(notFull.pop()) # If 1 not full box remains: remove it\n return lst", "def bad_apples(apples):\n packed = []\n while apples:\n package = apples.pop(0)\n if min(package) > 0:\n # Both apples are positive\n packed.append(package)\n elif max(package) == 0:\n # Both apples are rotten\n continue\n else: # Only one good apple\n # Filter for other packs with one good apple\n singles = filter(lambda x: min(x) == 0 and max(x) > 0, apples)\n try:\n # Try to get the next filtered package\n next_single = next(singles)\n # If found, remove from remaining apples and repackage\n apples.remove(next_single)\n packed.append([max(package), max(next_single)])\n except StopIteration:\n # If not found, discard and do nothing\n pass\n return packed", "def bad_apples(apples):\n bad = (x if x else y for x,y in apples if (not x) ^ (not y))\n result, flag = [], True\n for x in apples:\n if all(x): result.append(x)\n elif any(x):\n if flag:\n try: result.append([next(bad), next(bad)])\n except StopIteration: pass\n flag = not flag\n return result", "def bad_apples(apples):\n free = None\n i = 0\n while i<len(apples):\n if 0 in apples[i]:\n if set(apples[i])=={0}:\n apples.pop(i)\n else:\n apples[i].remove(0) \n if free!=None:\n apples[free].append(apples[i][0])\n apples.pop(i)\n free = None\n else:\n free = i\n i-=1 \n i+=1\n if free!=None: apples.pop(free)\n return apples\n \n", "def bad_apples(a):\n li, visited = [], []\n for i, j in enumerate(a):\n if i not in visited and sum(j) != 0:\n if 0 in j:\n find = next((k for k in range(i+1,len(a))if 0 in a[k]and sum(a[k])!=0), 0)\n if find:\n make = [j[0]or j[1],a[find][0]or a[find][1]]\n visited.append(find) ; li.append(make)\n else : li.append(j)\n return li", "def bad_apples(apples):\n apples = [list(filter(None, xs)) for xs in apples]\n apples = list(filter(None, apples))\n idxs = [i for i, x in enumerate(apples) if len(x) == 1]\n if len(idxs) % 2 == 1:\n del apples[idxs.pop()]\n for i in reversed(range(0, len(idxs), 2)):\n apples[idxs[i]].append(apples.pop(idxs[i+1]).pop())\n return apples", "def bad_apples(apples):\n good_packages, bad_packages = [], []\n for i, box in enumerate(apples):\n if box[0] and box[1]:\n good_packages.append([i, box])\n elif box[0] or box[1]:\n bad_packages.append([i, box[1] if box[1] else box[0]])\n\n for a, b in zip(*[iter(bad_packages)]*2):\n good_packages.append([a[0], [a[1], b[1]]])\n return [box for _, box in sorted(good_packages)]", "def bad_apples(a):\n b = list(map(lambda x: [i for i in x if i != 0], a))\n for x,y in enumerate(b):\n for i,j in enumerate(b):\n if len(y)==1 and len(j)==1 and x != i:\n b[x] = y+j\n b.remove(j)\n break\n return [x for x in b if len(x)==2]", "from itertools import chain, repeat\nmul = lambda x: x[0]*x[1]\ndef bad_apples(apples):\n inserting = [sum(pair) for pair in apples if mul(pair) == 0 and sum(pair)> 0]\n ins_pairs = chain(chain(*zip(list(zip(*[iter(inserting)] * 2)), repeat(None))),repeat(None))\n return list(filter(bool, [pair if mul(pair)>0 else list(next(ins_pairs) or ()) for pair in apples if sum(pair)>0]))", "def bad_apples(apples):\n a = apples[:]\n for i in range(len(a)-1):\n if a[i].count(0) == 1:\n for j in range(i+1, len(a)):\n if a[j].count(0) == 1:\n a[i] = [sum(a[i]), sum(a[j])]\n a[j] = [0,0]\n break\n return [i for i in a if 0 not in i]"]
{"fn_name": "bad_apples", "inputs": [[[]], [[[0, 0], [0, 0]]], [[[0, 0], [0, 0], [0, 1], [0, 0], [0, 0]]], [[[0, 0], [3, 7], [0, 5]]], [[[1, 3], [7, 6], [7, 2], [1, 3], [2, 3], [4, 5], [7, 6]]], [[[1, 2], [6, 1], [5, 2], [6, 3], [1, 4], [2, 5], [7, 6], [0, 1]]], [[[0, 0], [1, 0], [0, 2], [3, 0], [4, 0], [0, 5], [0, 6], [7, 0]]], [[[1, 3], [7, 6], [7, 2], [1, 3], [0, 1], [4, 5], [0, 3], [7, 6]]], [[[1, 3], [7, 6], [7, 2], [0, 0], [0, 3], [1, 3], [1, 3], [4, 5], [7, 6]]], [[[7, 2]]], [[[4, 2]]], [[[3, 1], [0, 0], [4, 3], [2, 5], [1, 7], [6, 3], [7, 4], [5, 7], [7, 1], [4, 4], [1, 3], [2, 2], [6, 7], [2, 1], [3, 3]]], [[[2, 3], [1, 1]]], [[[0, 3]]], [[[0, 1]]], [[[0, 1], [7, 7], [7, 2], [5, 4], [7, 1], [4, 3], [4, 6], [7, 4], [4, 0], [4, 5], [1, 1], [0, 3], [6, 7], [5, 7], [3, 1]]], [[[0, 1], [1, 1], [0, 2]]], [[[6, 5], [2, 5], [2, 1], [1, 7], [5, 2], [2, 2], [5, 4]]], [[[0, 1], [6, 0]]], [[[7, 4], [3, 0]]], [[[0, 3], [0, 1]]], [[[0, 2], [2, 0]]], [[[6, 1]]], [[[2, 0]]], [[[5, 0], [5, 7], [7, 1], [5, 5], [7, 5], [6, 6], [4, 1], [7, 0], [0, 7], [5, 3], [3, 1]]], [[[0, 6], [2, 3], [5, 5]]], [[[4, 4]]], [[[0, 1], [7, 2], [7, 1], [3, 2]]], [[[1, 1]]], [[[3, 1], [5, 2], [7, 6], [7, 1], [5, 3], [7, 5], [0, 1], [0, 7], [5, 0]]], [[[2, 5], [1, 3], [7, 5], [1, 5], [1, 1]]], [[[6, 1], [2, 5], [5, 7], [3, 1], [1, 5], [0, 3], [7, 6], [3, 0], [6, 0], [1, 3]]], [[[5, 0], [2, 5], [7, 6], [3, 3], [1, 6], [5, 6], [1, 3], [3, 1]]], [[[5, 1], [0, 1]]], [[[1, 0], [2, 4]]], [[[2, 6], [5, 3], [5, 4], [3, 2]]], [[[1, 3], [5, 6], [3, 5]]], [[[2, 3], [5, 0], [3, 2]]], [[[2, 6], [5, 5]]], [[[0, 3], [6, 5], [3, 3], [2, 3], [1, 0], [6, 3], [1, 1], [7, 3], [4, 3], [2, 1], [5, 0], [3, 1], [5, 7], [1, 5], [5, 5]]], [[[0, 3], [6, 2], [6, 7], [7, 5]]], [[[0, 5], [4, 5], [2, 1]]], [[[3, 7], [5, 5], [6, 3]]], [[[3, 4]]], [[[5, 7], [2, 5], [1, 0], [4, 3], [2, 6], [1, 5], [7, 6], [7, 3], [1, 2], [5, 0], [0, 3], [4, 0], [2, 3], [6, 4], [2, 7]]], [[[1, 1], [6, 7], [2, 3], [6, 6], [7, 1], [0, 5], [3, 7], [4, 3], [4, 4], [4, 0], [5, 6]]], [[[1, 3]]], [[[2, 2], [1, 0], [7, 4], [7, 7], [1, 7], [3, 6]]], [[[3, 0], [0, 3]]]], "outputs": [[[]], [[]], [[]], [[[3, 7]]], [[[1, 3], [7, 6], [7, 2], [1, 3], [2, 3], [4, 5], [7, 6]]], [[[1, 2], [6, 1], [5, 2], [6, 3], [1, 4], [2, 5], [7, 6]]], [[[1, 2], [3, 4], [5, 6]]], [[[1, 3], [7, 6], [7, 2], [1, 3], [1, 3], [4, 5], [7, 6]]], [[[1, 3], [7, 6], [7, 2], [1, 3], [1, 3], [4, 5], [7, 6]]], [[[7, 2]]], [[[4, 2]]], [[[3, 1], [4, 3], [2, 5], [1, 7], [6, 3], [7, 4], [5, 7], [7, 1], [4, 4], [1, 3], [2, 2], [6, 7], [2, 1], [3, 3]]], [[[2, 3], [1, 1]]], [[]], [[]], [[[1, 4], [7, 7], [7, 2], [5, 4], [7, 1], [4, 3], [4, 6], [7, 4], [4, 5], [1, 1], [6, 7], [5, 7], [3, 1]]], [[[1, 2], [1, 1]]], [[[6, 5], [2, 5], [2, 1], [1, 7], [5, 2], [2, 2], [5, 4]]], [[[1, 6]]], [[[7, 4]]], [[[3, 1]]], [[[2, 2]]], [[[6, 1]]], [[]], [[[5, 7], [5, 7], [7, 1], [5, 5], [7, 5], [6, 6], [4, 1], [5, 3], [3, 1]]], [[[2, 3], [5, 5]]], [[[4, 4]]], [[[7, 2], [7, 1], [3, 2]]], [[[1, 1]]], [[[3, 1], [5, 2], [7, 6], [7, 1], [5, 3], [7, 5], [1, 7]]], [[[2, 5], [1, 3], [7, 5], [1, 5], [1, 1]]], [[[6, 1], [2, 5], [5, 7], [3, 1], [1, 5], [3, 3], [7, 6], [1, 3]]], [[[2, 5], [7, 6], [3, 3], [1, 6], [5, 6], [1, 3], [3, 1]]], [[[5, 1]]], [[[2, 4]]], [[[2, 6], [5, 3], [5, 4], [3, 2]]], [[[1, 3], [5, 6], [3, 5]]], [[[2, 3], [3, 2]]], [[[2, 6], [5, 5]]], [[[3, 1], [6, 5], [3, 3], [2, 3], [6, 3], [1, 1], [7, 3], [4, 3], [2, 1], [3, 1], [5, 7], [1, 5], [5, 5]]], [[[6, 2], [6, 7], [7, 5]]], [[[4, 5], [2, 1]]], [[[3, 7], [5, 5], [6, 3]]], [[[3, 4]]], [[[5, 7], [2, 5], [1, 5], [4, 3], [2, 6], [1, 5], [7, 6], [7, 3], [1, 2], [3, 4], [2, 3], [6, 4], [2, 7]]], [[[1, 1], [6, 7], [2, 3], [6, 6], [7, 1], [5, 4], [3, 7], [4, 3], [4, 4], [5, 6]]], [[[1, 3]]], [[[2, 2], [7, 4], [7, 7], [1, 7], [3, 6]]], [[[3, 3]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,803
def bad_apples(apples):
5765520bbb1aa128e23d4ae0c5008595
UNKNOWN
In a far away country called AlgoLandia, there are `N` islands numbered `1` to `N`. Each island is denoted by `k[i]`. King Algolas, king of AlgoLandia, built `N - 1` bridges in the country. A bridge is built between islands `k[i]` and `k[i+1]`. Bridges are two-ways and are expensive to build. The problem is that there are gangs who wants to destroy the bridges. In order to protect the bridges, the king wants to assign elite guards to the bridges. A bridge between islands `k[i]` and `k[i+1]` is safe when there is an elite guard in island `k[i]` or `k[i+1]`. There are already elite guards assigned in some islands. Your task now is to determine the minimum number of additional elite guards that needs to be hired to guard all the bridges. ### Note: You are given a sequence `k` with `N` length. `k[i] = true`, means that there is an elite guard in that island; `k[i] = false` means no elite guard. It is guaranteed that AlgoLandia have at least `2` islands. ### Sample Input 1 ``` k = [true, true, false, true, false] ``` ### Sample Output 1 ``` 0 ``` ### Sample Input 2 ``` k = [false, false, true, false, false] ``` ### Sample Output 2 ``` 2 ```
["from itertools import groupby\n\ndef find_needed_guards(islands):\n return sum(sum(1 for _ in g)>>1 for k,g in groupby(islands) if not k)", "def find_needed_guards(k):\n b = ''.join('1' if g else '0' for g in k)\n return sum(len(ng) // 2 for ng in b.split(\"1\"))", "def find_needed_guards(k):\n \n prev = True\n guards = 0\n for i in k:\n if not i and not prev:\n guards += 1\n prev = True\n else:\n prev = i\n \n return guards", "from itertools import groupby\n\ndef find_needed_guards(k):\n return sum(len(list(g))//2 for v,g in groupby(k) if v==0)", "def find_needed_guards(k):\n return sum(len(i)//2 for i in ''.join([('*',' ')[i] for i in k]).split())", "def find_needed_guards(k):\n return sum(len(i)//2 for i in ''.join([('0','1')[i] for i in k]).split('1'))", "def find_needed_guards(k):\n nbsold=0\n i=0\n while i<len(k)-1:\n if k[i]==False and k[i+1]==False:\n nbsold+=1\n i+=1\n i+=1\n return nbsold\n \n", "def find_needed_guards(k):\n total = 0\n for i in range (1, len(k)): \n if k[i] == False:\n if k[i-1] == False:\n total += 1\n k[i] = True\n \n return total\n", "def find_needed_guards(k):\n total = 0\n for i in range(1, len(k)):\n if not (k[i] or k[i-1]):\n k[i] = True\n total += 1\n return total", "def find_needed_guards(k):\n if len(k)%2==0:k.append(True)\n a=0\n for x in range(1,len(k),2):\n if k[x-1]==k[x+1]==True or k[x]==True:continue\n elif k[x-1]==True:\n k[x+1]=True\n a+=1\n else:a+=1\n return a"]
{"fn_name": "find_needed_guards", "inputs": [[[true, true, false, true, false]], [[false, false, true, false, false]], [[false, false, false, false, false]], [[false, false, false, false, false, false]], [[false, false]], [[true, false]], [[false, false, false, true, false, false, false, true]], [[false, false, true, false, true, true, true, false, true, true, true, false, true, false, false, false, true, false, false, true, true, true, true, true, false, true, false, true, true, false]], [[true, false, true, true, false, true, false, false, false, true, true, false, true, true, false, true, false, false, true, true, false, true, false, true, true, false, false, false, true, false, false, false, true, false, true, true, true, true, true, true, false]], [[true, true, true, true, true, true, false, true, true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, false, true, true, true, true, true, false, true, true, true, true, true, true, true, true, true, false, true, true, true, true]], [[true, true, true]], [[true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true]], [[true, true, true, false, true]], [[true, true, true, true, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true, false, true, true, true, true, true, true, true, true, true]], [[true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, false, true, true, true, true, true, true, false, true, true, true, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true]], [[true, true, true, true, true, true, true, true, true, true, true, false]], [[true, true]], [[true, true, true, true, true, true, false, false, false, true, true, true, true, false, true, true, true, true, true, false, true, true, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true]], [[true, true, false, false, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true, true, false, true, true, true, true, false, true, true, true, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true]]], "outputs": [[0], [2], [2], [3], [1], [0], [2], [3], [4], [0], [0], [1], [0], [1], [1], [0], [0], [1], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,730
def find_needed_guards(k):
f4521ee73a5b1e896f01baa869ebc1ec
UNKNOWN
# Background My TV remote control has arrow buttons and an `OK` button. I can use these to move a "cursor" on a logical screen keyboard to type words... # Keyboard The screen "keyboard" layout looks like this #tvkb { width : 400px; border: 5px solid gray; border-collapse: collapse; } #tvkb td { color : orange; background-color : black; text-align : center; border: 3px solid gray; border-collapse: collapse; } abcde123 fghij456 klmno789 pqrst.@0 uvwxyz_/ aASP * `aA` is the SHIFT key. Pressing this key toggles alpha characters between UPPERCASE and lowercase * `SP` is the space character * The other blank keys in the bottom row have no function # Kata task How many button presses on my remote are required to type the given `words`? ## Hint This Kata is an extension of the earlier ones in this series. You should complete those first. ## Notes * The cursor always starts on the letter `a` (top left) * The alpha characters are initially lowercase (as shown above) * Remember to also press `OK` to "accept" each letter * Take the shortest route from one letter to the next * The cursor wraps, so as it moves off one edge it will reappear on the opposite edge * Although the blank keys have no function, you may navigate through them if you want to * Spaces may occur anywhere in the `words` string * Do not press the SHIFT key until you need to. For example, with the word `e.Z`, the SHIFT change happens **after** the `.` is pressed (not before) # Example words = `Code Wars` * C => `a`-`aA`-OK-`A`-`B`-`C`-OK = 6 * o => `C`-`B`-`A`-`aA`-OK-`u`-`v`-`w`-`x`-`y`-`t`-`o`-OK = 12 * d => `o`-`j`-`e`-`d`-OK = 4 * e => `d`-`e`-OK = 2 * space => `e`-`d`-`c`-`b`-`SP`-OK = 5 * W => `SP`-`aA`-OK-`SP`-`V`-`W`-OK = 6 * a => `W`-`V`-`U`-`aA`-OK-`a`-OK = 6 * r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6 * s => `r`-`s`-OK = 2 Answer = 6 + 12 + 4 + 2 + 5 + 6 + 6 + 6 + 2 = 49 *Good Luck! DM.* Series * TV Remote * TV Remote (shift and space) * TV Remote (wrap) * TV Remote (symbols)
["import re\n\nH, W = 6, 8\nKEYBOARD = \"abcde123fghij456klmno789pqrst.@0uvwxyz_/* \"\nMAP = {c: (i//W, i%W) for i,c in enumerate(KEYBOARD)}\n\n\ndef manhattan(*pts):\n dxy = [abs(z2-z1) for z1,z2 in zip(*pts)]\n return 1 + sum( min(dz, Z-dz) for dz,Z in zip(dxy, (H,W)) )\n\ndef toggle(m):\n ups, end = m.groups()\n return f'*{ups.lower()}*{end}' # Toggle Shift ON if uppercase presents, and then OFF if lowercase after (or end of the string)\n\n\ndef tv_remote(words):\n reWords = re.sub(r'([A-Z][^a-z]*)([a-z]?)', toggle, words).rstrip('*') # Strip any useless toggle OFF at the end\n return sum( manhattan(MAP[was], MAP[curr]) for was,curr in zip('a'+reWords, reWords))\n", "from collections import namedtuple\n\nPosition = namedtuple('Position', 'y x')\n\n\ndef tv_remote(word: str):\n remote = (\n 'a', 'b', 'c', 'd', 'e', '1', '2', '3',\n 'f', 'g', 'h', 'i', 'j', '4', '5', '6',\n 'k', 'l', 'm', 'n', 'o', '7', '8', '9',\n 'p', 'q', 'r', 's', 't', '.', '@', '0',\n 'u', 'v', 'w', 'x', 'y', 'z', '_', '/',\n '', ' '\n )\n shift, shift_pressed = Position(5, 0), False\n\n prev = Position(0, 0)\n button_presses = 0\n for letter in word:\n if letter.isalpha() and letter.isupper() != shift_pressed:\n button_presses += calc_presses(prev, shift)\n prev, shift_pressed = shift, not shift_pressed\n\n cur = Position(*divmod(remote.index(letter.lower()), 8))\n button_presses += calc_presses(prev, cur)\n prev = cur\n\n return button_presses\n\n\ndef calc_presses(pos1: Position, pos2: Position):\n dif_y, dif_x = abs(pos1.y - pos2.y), abs(pos1.x - pos2.x)\n return min(dif_y, 6 - dif_y) + min(dif_x, 8 - dif_x) + 1", "def tv_remote(word):\n caps, cases, shift = coords[\"\u2191\"], (str.isupper, str.islower), 0\n moves, current = 0, (0, 0)\n for char in word:\n target = coords[char.lower()]\n if cases[shift](char):\n moves, current, shift = moves + distance(current, caps), caps, 1 - shift\n moves, current = moves + distance(current, target), target\n return moves\n\nkeyboard = (\"abcde123\", \"fghij456\", \"klmno789\", \"pqrst.@0\", \"uvwxyz_/\", \"\u2191 \")\ncoords = {char: (line.index(char), y) for y, line in enumerate(keyboard) for char in line}\n\ndef distance(pos1, pos2):\n d0, d1 = abs(pos2[0] - pos1[0]), abs(pos2[1] - pos1[1])\n return 1 + min(d0, 8 - d0) + min(d1, 6 - d1)", "def navigate(s,e):\n a = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/*&'\n d = {i: [a.index(i)//8, a.index(i)%8] for i in a}\n x=0\n y=0\n i=0\n j=0\n rowdis=0\n coldis=0\n for k,v in d.items():\n if k == s:\n i = v[0]\n j = v[1]\n if k == e:\n x = v[0]\n y = v[1]\n if abs(i-x) > 2.5:\n if i<x:\n rowdis = 6+i-x\n else : rowdis = 6-i+x\n else : rowdis = abs(i-x)\n if abs(j-y) > 3.5:\n if j<y:\n coldis = 8+j-y\n else : coldis = 8-j+y\n else : coldis = abs(j-y)\n return rowdis + coldis\ndef tv_remote(word):\n ans = 0\n cursor = 'a'\n shift = False\n for c in word:\n if c.isspace(): \n ans += navigate(cursor,'&') + 1\n cursor = '&'\n continue\n if c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':\n if c.isupper():\n if not shift:\n ans += navigate(cursor,'*') + 1\n shift = True\n cursor = '*'\n if c.islower():\n if shift:\n ans += navigate(cursor,'*') + 1\n shift = False\n cursor = '*'\n ans += navigate(cursor,c.lower()) + 1\n cursor = c.lower()\n return ans", "def tv_remote(word):\n matrix = [\n ['a', 'b', 'c', 'd', 'e', '1', '2', '3'],\n ['f', 'g', 'h', 'i', 'j', '4', '5', '6'],\n ['k', 'l', 'm', 'n', 'o', '7', '8', '9'],\n ['p', 'q', 'r', 's', 't', '.', '@', '0'],\n ['u', 'v', 'w', 'x', 'y', 'z', '_', '/'],\n ['aA', ' '],\n ]\n\n vertical_inversion = {0:0, 1:1, 2:2, 3:3, 4:2, 5:1}\n horizontal_inversion = {0:0, 1:1, 2:2, 3:3, 4:4, 5:3, 6:2, 7:1}\n actions = ([0, 0],)\n upper_mode = False\n press_ok = 0\n func = lambda x, y: (vertical_inversion[abs(x[0]-y[0])] + horizontal_inversion[abs(x[1]-y[1])])\n\n for char in word:\n for i in range(6):\n if char.lower() in matrix[i]:\n if char.isupper() and not upper_mode:\n actions += ([5, 0],)\n upper_mode = True\n press_ok += 1\n actions += ([i, matrix[i].index(char.lower())],)\n press_ok += 1\n elif char.isupper() and upper_mode:\n actions += ([i, matrix[i].index(char.lower())],)\n press_ok += 1\n elif char.islower() and upper_mode:\n actions += ([5, 0],)\n upper_mode = False\n press_ok += 1\n actions += ([i, matrix[i].index(char.lower())],)\n press_ok += 1\n elif char.islower() and not upper_mode:\n actions += ([i, matrix[i].index(char.lower())],)\n press_ok += 1\n else:\n actions += ([i, matrix[i].index(char.lower())],)\n press_ok += 1\n\n return sum([func(i[0], i[1]) for i in list(zip(actions, actions[1:]))]) + press_ok", "D = {v:(r, c) for r, row in enumerate(['abcde123', 'fghij456', 'klmno789', 'pqrst.@0', 'uvwxyz_/', 'U ??????']) for c, v in enumerate(row)}\n\nmind = lambda d, mx: min(d, mx - d)\nmove = lambda t, lastr, lastc, r, c: (t + mind(abs(r - lastr), 6) + mind(abs(c - lastc), 8) + 1, r, c)\n\ndef tv_remote(words):\n\n t, lastr, lastc, lower = 0, 0, 0, True\n \n for e in words:\n if e.isalpha() and lower != e.islower():\n t, lastr, lastc = move(t, lastr, lastc, 5, 0)\n lower = not lower\n t, lastr, lastc = move(t, lastr, lastc, *D[e.lower()])\n return t ", "SHIFT = 'aA'\nsyms = {\n x: (i, j)\n for i, row in enumerate([\n 'abcde123',\n 'fghij456',\n 'klmno789',\n 'pqrst.@0',\n 'uvwxyz_/',\n ])\n for j, x in enumerate(row)\n}\nsyms[' '] = (5, 1)\nsyms[SHIFT] = (5, 0)\n\n\ndef tv_remote(words):\n r = c = 0\n n = 0\n lower = True\n def press(x):\n nonlocal n, r, c, lower\n r1, c1 = syms[x]\n n += min(abs(r1-r), 6 - abs(r1-r)) + min(abs(c1-c), 8 - abs(c1-c)) + 1\n r, c = r1, c1\n if x == SHIFT:\n lower = not lower\n \n for ch in words:\n if ch.isalpha() and ch.islower() != lower:\n press(SHIFT)\n press(ch.lower())\n return n", "import re\ndef tv_remote(words):\n letters = {c: (x, y)\n for y, row in enumerate((\n \"abcde123\",\n \"fghij456\",\n \"klmno789\",\n \"pqrst.@0\",\n \"uvwxyz_/\",\n \"\u21e7 \"))\n for x, c in enumerate(row)}\n words = re.sub(r'((?:^|[a-z])[^A-Z]*)([A-Z])', r'\\1\u21e7\\2', words)\n words = re.sub(r'([A-Z][^a-z]*)([a-z])', r'\\1\u21e7\\2', words)\n words = words.lower()\n return sum(\n min(abs(letters[c1][0] - letters[c2][0]),8-abs(letters[c1][0] - letters[c2][0])) +\n min(abs(letters[c1][1] - letters[c2][1]),6-abs(letters[c1][1] - letters[c2][1])) + 1\n for c1, c2 in zip(\"a\" + words, words))", "D = {v:[r, c] for r, row in enumerate(['abcde123', 'fghij456', 'klmno789', 'pqrst.@0', 'uvwxyz_/','* ']) for c, v in enumerate(row)}\n\ndef manhattan_dist(*points): \n print('points md: ', points)\n return [abs(z2-z1) for z1,z2 in zip(*points)]\n\ndef wrap_manhattan_dist(*points):\n dist = manhattan_dist(*points)\n wdist = [min(dist[0],6-dist[0]), min(dist[1],8-dist[1])]\n return sum(wdist)\n\nimport re\ndef tv_remote(words):\n words = re.sub('([A-Z])',r'*\\1*',words).lower()\n words = re.sub('\\*([\\d.@_/ ]*)(\\*|$)',r'\\1',words)\n words = re.sub('\\*$','',words)\n words = re.sub('\\*([0-9.@_/ ]+)([^\\*])',r'\\1*\\2',words)\n words = 'a' + words\n moves = sum([wrap_manhattan_dist(D[words[i]], D[words[i+1]])+1 for i in range(len(words)-1)])\n return moves", "def tv_remote(words:str):\n screen_keyboard_symbols = \"abcde123fghij456klmno789pqrst.@0uvwxyz_/* \"\n symbols_map = {c: (i // 8, i % 8) for i, c in enumerate(screen_keyboard_symbols)}\n kb_dims = (len(screen_keyboard_symbols) // 8 + 1, 8)\n\n def dist(pos1, pos2):\n return sum(min(abs(p1-p2), dim - abs(p1-p2)) for p1, p2, dim in zip(pos1, pos2, kb_dims))\n\n button_presses = 0\n cur_position, next_position = (0, 0), (0, 0)\n caps_on = False\n\n words_to_type = []\n for ch in words:\n if ch.islower() and caps_on or ch.isupper() and not caps_on:\n words_to_type.append(\"*\" + ch.lower())\n caps_on = not caps_on\n else:\n words_to_type.append(ch.lower())\n words_to_type = \"\".join(words_to_type)\n\n for ch in words_to_type:\n if ch in screen_keyboard_symbols:\n next_position = symbols_map[ch]\n button_presses += 1 + dist(cur_position, next_position)\n cur_position = next_position\n else:\n return -1\n return button_presses"]
{"fn_name": "tv_remote", "inputs": [["Code Wars"], ["does"], ["your"], ["solution"], ["work"], ["for"], ["these"], ["words"], ["DOES"], ["YOUR"], ["SOLUTION"], ["WORK"], ["FOR"], ["THESE"], ["WORDS"], ["Does"], ["Your"], ["Solution"], ["Work"], ["For"], ["These"], ["Words"], ["A"], ["AADVARKS"], ["A/A/A/A/"], ["1234567890"], ["MISSISSIPPI"], ["a"], ["aadvarks"], ["a/a/a/a/"], ["mississippi"], ["Xoo ooo ooo"], ["oXo ooo ooo"], ["ooX ooo ooo"], ["ooo Xoo ooo"], ["ooo oXo ooo"], ["ooo ooX ooo"], ["ooo ooo Xoo"], ["ooo ooo oXo"], ["ooo ooo ooX"], ["The Quick Brown Fox Jumps Over A Lazy Dog."], ["Pack My Box With Five Dozen Liquor Jugs."], [""], [" "], [" "], [" x X "]], "outputs": [[49], [16], [21], [33], [18], [12], [27], [23], [19], [22], [34], [19], [15], [28], [24], [28], [33], [45], [26], [20], [35], [31], [4], [33], [32], [26], [38], [1], [30], [29], [35], [53], [65], [53], [53], [65], [53], [53], [65], [53], [254], [242], [0], [3], [5], [30]]}
INTRODUCTORY
PYTHON3
CODEWARS
9,707
def tv_remote(words):
aa31e98a223c8221b69adf570dad81a6
UNKNOWN
Imagine if there were no order of operations. Instead, you would do the problem from left to right. For example, the equation `$a +b *c /d$` would become `$(((a+b)*c)//d)$` (`Math.floor(((a+b)*c)/d)` in JS). Return `None`/`null` (depending on your language) if the equation is `""`. ### Task: Given an equation with a random amount of spaces greater than or equal to zero between each number and operation, return the result without order of operations. Note that if two numbers are spaces apart, act as if they were one number: `1 3` = `13`. However, if given something `% 0` or something `/ 0`, return `None/null`. More about order of operations: [here](https://en.wikipedia.org/wiki/Order_of_operations#:~:text=In%20the%20United%20States%2C%20the,Excuse%20My%20Dear%20Aunt%20Sally%22.) ### Key: - `^` represents `**` ```if:python - `/` represents `//` or `math.floor` because the result will always be an integer ``` ```if:javascript - `/` should always be rounded down(`Math.floor`) because the result will always be an integer ``` ### Operations allowed: `+, -, * , /, ^, %` ### Example: `no_order(2 + 3 - 4 * 1 ^ 3) returns 1` because: ``` 2 + 3 - 4 * 1 ^ 3 = 2 + 3 - 4 * 1 ^ 3 = 5 - 4 * 1 ^ 3 = 1 * 1 ^ 3 = 1 ^ 3 = 1 ```
["def no_order(equation):\n equation = equation.replace(' ', '')\n equation = equation.replace('+', ')+')\n equation = equation.replace('-', ')-')\n equation = equation.replace('*', ')*')\n equation = equation.replace('/', ')//')\n equation = equation.replace('%', ')%')\n equation = equation.replace('^', ')**')\n equation = '('*equation.count(')') + equation\n try : return eval(equation)\n except : pass", "import re\n\ndef no_order(s):\n try:\n nums= [int(i.replace(' ', '')) for i in re.split('\\+|\\-|\\*|\\/|\\^|\\%', s)]\n ops = [a for a in s if not a in nums and not a in ' 1234567890']\n ans = nums[0]\n for n in range(1, len(nums)):\n op = ops[n-1]\n num = nums[n]\n if op == '+': ans += num\n if op == '-': ans -= num\n if op == '*': ans *= num\n if op == '/': ans = ans // num\n if op == '^': ans = ans ** num\n if op == '%': ans = ans % num\n return ans\n except:\n return None\n", "op_table = {\n \"+\": lambda a,b: a+b,\n \"-\": lambda a,b: a-b,\n \"*\": lambda a,b: a*b,\n \"/\": lambda a,b: a//b,\n \"^\": lambda a,b: a**b,\n \"%\": lambda a,b: a%b,\n}\n\ndef no_order(equation):\n result = op2 = 0\n func_name = \"+\"\n \n # dummy add to force prior operation to be run\n formula = equation.replace(\" \", \"\") + \"+\"\n for ch in formula:\n if ch.isdigit():\n op2 *= 10\n op2 += int(ch)\n elif ch not in op_table:\n return None\n else:\n try:\n result = op_table[func_name](result, op2)\n except ZeroDivisionError:\n return None\n func_name = ch\n op2 = 0\n\n return result\n", "def no_order(e):\n e = e.replace(' ', '').replace('+', ')+').replace('-', ')-').replace('*', ')*').replace('/', ')//').replace('%', ')%').replace('^', ')**')\n try: \n return eval(f\"{'(' * e.count(')')}{e}\")\n except: \n pass", "import re\n\ndef no_order(equation):\n ops = {\n '+' : lambda l, r : l + r,\n '-' : lambda l, r : l - r,\n '*' : lambda l, r : l * r,\n '/' : lambda l, r : l // r if r != 0 else None,\n '^' : lambda l, r : l ** r,\n '%' : lambda l, r : l % r if r != 0 else None\n }\n \n expr = re.sub(r'[\\s\\t]+', '', equation.strip())\n expr = re.sub(r'(?<=\\W)(?=[\\d\\s])|(?<=[\\d\\s])(?=\\W)', '\\f', expr).split('\\f')\n \n temp = expr[0]\n for i in range(1, len(expr), 2):\n temp = ops[expr[i]](int(temp), int(expr[i+1]))\n if temp is None:\n break\n \n if temp is not None:\n return int(temp)\n return temp\n \n", "import re\n\ndef no_order(equation):\n operators = {\n \"+\" : lambda x,y : x + y,\n \"-\" : lambda x,y : x-y,\n \"*\" : lambda x,y : x*y,\n \"/\" : lambda x,y : x//y,\n '^' : lambda x,y : x**y,\n '%' : lambda x,y : x%y}\n\n equation = equation.replace(\" \",\"\")\n list_eq = re.split(r\"(\\D)\", equation)\n \n while len(list_eq) != 1 :\n x = list_eq.pop(0)\n op = list_eq.pop(0)\n y = list_eq.pop(0)\n try : \n result = operators[op](int(x),int(y))\n except ZeroDivisionError : #for handling %0 and /0\n return None\n list_eq.insert(0,result)\n \n return int(list_eq[0])", "import re\nfrom operator import add, sub, floordiv, mul, pow, mod\n\nOPS = {\n '+': add,\n '-': sub,\n '*': mul,\n '/': floordiv,\n '^': pow,\n '%': mod,\n}\n\ndef no_order(equation):\n equation = equation.replace(' ', '')\n if not equation:\n return None\n it = iter(re.findall(r'\\d+|\\D+', equation))\n x = int(next(it))\n for op, y in zip(it, it):\n try:\n x = OPS[op](x, int(y))\n except ZeroDivisionError:\n return None\n return x", "from re import compile\nfrom functools import reduce\nfrom operator import add, sub, mul, floordiv as div, pow, mod\n\nREGEX = compile(r\"^\\d+|[^\\d]\\d+\").findall\nD = {'+':add, '-':sub, '*':mul, '/':div, '^':pow, '%':mod}\n\ndef no_order(equation):\n L = REGEX(equation.replace(\" \", \"\"))\n try:\n return reduce(lambda x,y: D[y[0]](x, int(y[1:])), L[1:], int(L[0]))\n except:\n return None", "import re\ndef no_order(equation): \n # Delete blank spaces\n equation = equation.replace(' ', '')\n \n # Check null cases\n if '%0' in equation or '/0' in equation: \n return None\n \n # Extract numbers and operators\n n = re.findall(r'\\d+', equation)\n op = re.findall('[+\\\\-*/%^]', equation)\n \n #Define operators\n operators={\n \"+\": lambda x, y: x + y,\n \"-\": lambda x, y: x - y,\n \"*\": lambda x, y: x * y,\n \"/\": lambda x, y: x // y,\n \"^\": lambda x, y: x ** y,\n \"%\": lambda x, y: x % y}\n\n result = int(n[0])\n for i in range(1, len(n)):\n result = operators[op[i-1]](result, int(n[i]))\n return result", "def is_digit(p):\n return p >= '0' and p <= '9'\n \ndef is_sign(p):\n return p in '+-*/^%'\n\ndef calc(sign, a, b):\n try:\n if sign == '+':\n return a+b\n elif sign == '-':\n return a-b\n elif sign == '*':\n return a*b\n elif sign == '/':\n return a//b\n elif sign == '^':\n return a**b\n else:\n return a%b\n except:\n return None\n\ndef no_order(equation):\n left, right = 0, \"\"\n sign = '+'\n for e in equation:\n if is_sign(e):\n left = calc(sign, left, int(right))\n right = \"\"\n if left == None:\n return None\n sign = e\n elif is_digit(e):\n right += e\n elif e != ' ':\n return None\n return calc(sign, left, int(right))"]
{"fn_name": "no_order", "inputs": [["2 + 3- 4*1 ^ 3"], ["7 * 3 - 3/ 10 0"], ["1 20% 0 + 9"], ["6 9* 2+6 / 0"]], "outputs": [[1], [0], [null], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,081
def no_order(equation):
405c5b4f99ce4856e6e3441f06b414b0
UNKNOWN
# Introduction Hamsters are rodents belonging to the subfamily Cricetinae. The subfamily contains about 25 species, classified in six or seven genera. They have become established as popular small house pets, and, partly because they are easy to breed in captivity, hamsters are often used as laboratory animals. # Task Write a function that accepts two inputs: `code` and `message` and returns an encrypted string from `message` using the `code`. The `code` is a string that generates the key in the way shown below: ``` 1 | h a m s t e r 2 | i b n u f 3 | j c o v g 4 | k d p w 5 | l q x 6 | y 7 | z ``` All letters from `code` get number `1`. All letters which directly follow letters from `code` get number `2` (unless they already have a smaller number assigned), etc. It's difficult to describe but it should be easy to understand from the example below: ``` 1 | a e h m r s t 2 | b f i n u 3 | c g j o v 4 | d k p w 5 | l q x 6 | y 7 | z ``` How does the encoding work using the `hamster` code? ``` a => a1 b => a2 c => a3 d => a4 e => e1 f => e2 ... ``` And applying it to strings : ``` hamsterMe('hamster', 'hamster') => h1a1m1s1t1e1r1 hamsterMe('hamster', 'helpme') => h1e1h5m4m1e1 ``` And you probably started wondering what will happen if there is no `a` in the `code`. Just add these letters after the last available letter (in alphabetic order) in the `code`. The key for code `hmster` is: ``` 1 | e h m r s t 2 | f i n u 3 | g j o v 4 | k p w 5 | l q x 6 | y 7 | z 8 | a 9 | b 10 | c 11 | d ``` # Additional notes The `code` will have at least 1 letter. Duplication of letters in `code` is possible and should be handled. The `code` and `message` consist of only lowercase letters.
["def hamster_me(code, message):\n code, dct = sorted(set(code)), {}\n for c1,c2 in zip(code, code[1:] + [chr(ord(\"z\") + ord(code[0]) - ord(\"a\"))]):\n for n in range(ord(c1), ord(c2)+1):\n dct[chr( (n-97)%26 + 97 )] = c1 + str(n-ord(c1)+1)\n return ''.join(dct[c] for c in message)", "def hamster_me(code, message):\n cache = {k:k+\"1\" for k in code}\n for l in code:\n for i in range(2, 27):\n shifted = chr(97 + (ord(l) - 98 + i) % 26)\n if shifted in cache:\n break\n cache[shifted] = l + str(i)\n return \"\".join(map(lambda x: cache[x], message))", "from string import ascii_lowercase\nid = {c:i for i,c in enumerate(ascii_lowercase)}\nchar = (ascii_lowercase+ascii_lowercase).__getitem__\n\ndef hamster_me(code, message):\n res, L = {}, sorted(map(id.get, code))\n for i,j in zip(L, L[1:]+[26+L[0]]):\n start = char(i)\n for k,x in enumerate(map(char, range(i, j)), 1):\n res[x] = f\"{start}{k}\"\n return ''.join(map(res.get, message))", "from string import ascii_lowercase as a_low\n\ndef hamster_me(code, message):\n table = {}\n code = sorted(code)\n shift = a_low.index(code[0])\n abc = a_low[shift:] + a_low[:shift]\n for i in range(len(code)):\n start = abc.index(code[i])\n finish = abc.index(code[(i + 1) % len(code)])\n if finish == 0:\n finish = len(abc)\n ind = 1\n for j in abc[start: finish]:\n table[j] = code[i] + str(ind)\n ind += 1\n cipher = str.maketrans(table)\n return message.translate(cipher)", "def hamster_me(code, message):\n D, code, lower = {}, set(c for c in code), 'abcdefghijklmnopqrstuvwxyz'\n\n for c in sorted(code):\n for i, e in enumerate((lower*2)[lower.index(c):], 1):\n if e in code - {c} or e in D: break\n D[e] = c + str(i)\n\n return ''.join(D[c] for c in message) ", "def hamster_me(code, message):\n import string\n alpha = string.ascii_lowercase\n alplist = []\n clist = \"\"\n c = 0\n for x in message:\n while True:\n if alpha[alpha.index(x)-c] in code: \n clist += alpha[alpha.index(x)-c]+str(c+1)\n c = 0\n break\n else:\n c += 1\n return clist", "def hamster_me(code, message):\n alpha = 'abcdefghijklmnopqrstuvwxyz'\n output=''\n for char in message:\n try:\n codeLetter = max([c for c in sorted(code) if c <= char])\n except:\n codeLetter = max(code)\n codeIndex = alpha.index(codeLetter)\n charIndex = alpha.index(char)\n if codeIndex <= charIndex:\n appendNo = str(charIndex - codeIndex + 1)\n else:\n appendNo = str(charIndex + len(alpha) - codeIndex + 1)\n output += codeLetter + appendNo\n return output\n", "from string import ascii_lowercase\n\ndef hamster_me(code, message):\n table, code_letters = {}, set(code)\n current_index, current_letter = 0, ''\n for letter in ascii_lowercase * 2:\n if letter in code_letters:\n current_index, current_letter = 0, letter\n current_index += 1\n table[letter] = current_letter + str(current_index)\n return ''.join(map(table.get, message))", "hamster_me=lambda k,s:''.join(map({c:w[0]+str(n)for w in __import__('re').findall('.[^%s]*'%k,''.join(map(chr,range(97,123)))*2)for n,c in enumerate(w,1)}.get,s))"]
{"fn_name": "hamster_me", "inputs": [["hamster", "hamster"], ["hamster", "helpme"], ["hmster", "hamster"], ["hhhhammmstteree", "hamster"], ["f", "abcdefghijklmnopqrstuvwxyz"]], "outputs": [["h1a1m1s1t1e1r1"], ["h1e1h5m4m1e1"], ["h1t8m1s1t1e1r1"], ["h1a1m1s1t1e1r1"], ["f22f23f24f25f26f1f2f3f4f5f6f7f8f9f10f11f12f13f14f15f16f17f18f19f20f21"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,533
def hamster_me(code, message):
22788fa8ffaaf1a8e04146acdabb9fc1
UNKNOWN
Two tortoises named ***A*** and ***B*** must run a race. ***A*** starts with an average speed of ```720 feet per hour```. Young ***B*** knows she runs faster than ***A***, and furthermore has not finished her cabbage. When she starts, at last, she can see that ***A*** has a `70 feet lead` but ***B***'s speed is `850 feet per hour`. How long will it take ***B*** to catch ***A***? More generally: given two speeds `v1` (***A***'s speed, integer > 0) and `v2` (***B***'s speed, integer > 0) and a lead `g` (integer > 0) how long will it take ***B*** to catch ***A***? The result will be an array ```[hour, min, sec]``` which is the time needed in hours, minutes and seconds (round down to the nearest second) or a string in some languages. If `v1 >= v2` then return `nil`, `nothing`, `null`, `None` or `{-1, -1, -1}` for C++, C, Go, Nim, `[]` for Kotlin or "-1 -1 -1". ## Examples: (form of the result depends on the language) ``` race(720, 850, 70) => [0, 32, 18] or "0 32 18" race(80, 91, 37) => [3, 21, 49] or "3 21 49" ``` ** Note: - See other examples in "Your test cases". - In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings. ** Hints for people who don't know how to convert to hours, minutes, seconds: - Tortoises don't care about fractions of seconds - Think of calculation by hand using only integers (in your code use or simulate integer division) - or Google: "convert decimal time to hours minutes seconds"
["import math\n\ndef race(v1, v2, g):\n if v2 < v1: return None\n seconds = 0.1\n while (v1/3600) * seconds + g >= (v2/3600) * seconds:\n seconds += 0.05\n hours = seconds / 3600\n hoursRest = seconds % 3600\n minutes = hoursRest / 60\n seconds = hoursRest % 60\n return [math.floor(hours), math.floor(minutes), math.floor(seconds)]\n", "from datetime import datetime, timedelta\n\ndef race(v1, v2, g):\n if v1 >= v2:\n return None\n else:\n sec = timedelta(seconds=int((g*3600/(v2-v1))))\n d = datetime(1,1,1) + sec\n \n return [d.hour, d.minute, d.second]", "def race(v1, v2, g):\n if v2 <= v1:\n return None\n total = g / (v2 - v1)\n return [int(total), int(total * 60) % 60, int(total * 3600) % 60]", "def race(v1, v2, g):\n if v1 >= v2: return None\n t = float(g)/(v2-v1)*3600\n mn, s = divmod(t, 60)\n h, mn = divmod(mn, 60)\n return [int(h), int(mn), int(s)]", "def race(v1, v2, g):\n if v1 < v2:\n sec = g * 60 * 60 // (v2 - v1)\n return [sec // 3600, sec // 60 % 60, sec % 60]", "def race(v1, v2, g):\n if v1>=v2:\n return None\n t = g / (v2 - v1) * 60 * 60\n return [int(t // 3600), \n int((t // 60) % 60), \n int(t % 60)]", "def race(v1, v2, g):\n if v1 < v2:\n a = g * 3600 // (v2 - v1)\n return [a // 3600, a // 60 % 60, a % 60]"]
{"fn_name": "race", "inputs": [[720, 850, 70], [80, 91, 37], [80, 100, 40], [720, 850, 37], [720, 850, 370], [120, 850, 37], [820, 850, 550], [820, 81, 550]], "outputs": [[[0, 32, 18]], [[3, 21, 49]], [[2, 0, 0]], [[0, 17, 4]], [[2, 50, 46]], [[0, 3, 2]], [[18, 20, 0]], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,418
def race(v1, v2, g):
75bbcbb54132f0000833df944f2cb43c
UNKNOWN
You drop a ball from a given height. After each bounce, the ball returns to some fixed proportion of its previous height. If the ball bounces to height 1 or less, we consider it to have stopped bouncing. Return the number of bounces it takes for the ball to stop moving. ``` bouncingBall(initialHeight, bouncingProportion) boucingBall(4, 0.5) After first bounce, ball bounces to height 2 After second bounce, ball bounces to height 1 Therefore answer is 2 bounces boucingBall(30, 0.3) After first bounce, ball bounces to height 9 After second bounce, ball bounces to height 2.7 After third bounce, ball bounces to height 0.81 Therefore answer is 3 bounces ``` Initial height is an integer in range [2,1000] Bouncing Proportion is a decimal in range [0, 1)
["import math\n\ndef bouncing_ball(initial, proportion):\n return math.ceil(math.log(initial, 1/proportion))", "def bouncing_ball(initial, proportion):\n count = 0\n while initial > 1:\n initial = initial * proportion\n count = count + 1\n return count", "def bouncing_ball(i, p , n = 0):\n return n if i <= 1 else bouncing_ball(i*p, p, n+1)", "def bouncing_ball(h, bounce):\n count = 0\n while h > 1:\n count += 1\n h *= bounce\n return count", "bouncing_ball=lambda x,y,p=1: p if x*y<=1 else bouncing_ball(x*y,y,p+1)", "def bouncing_ball(initial, p):\n if initial <= 1:\n return 0\n else:\n return 1 + bouncing_ball(initial * p, p)", "bouncing_ball=b=lambda i,p:i>1and-~b(i*p,p)", "def bouncing_ball(initial, proportion):\n height_now=initial # ball height now.\n counter=0 # counter for number of jumb initially zero\n while height_now>1: # stay in while loop until height is smaller than than1\n height_now*=proportion\n counter+=1 # each time we iterate in while increase count of jump by 1\n return counter # return number of jump\n", "from math import ceil, log\n\ndef bouncing_ball(initial, proportion):\n return ceil(-log(initial - 1e-9, proportion))", "from math import ceil, log\n\ndef bouncing_ball(initial, proportion):\n return ceil(log(1 / initial, proportion))"]
{"fn_name": "bouncing_ball", "inputs": [[2, 0.5], [4, 0.5], [10, 0.1], [100, 0.1], [9, 0.3], [30, 0.3]], "outputs": [[1], [2], [1], [2], [2], [3]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,438
def bouncing_ball(initial, proportion):
602bd199c1fde39ee48012e7bc27f3ca
UNKNOWN
Given a set of elements (integers or string characters) that may occur more than once, we need to know the amount of subsets that none of their values have repetitions. Let's see with an example: ``` set numbers = {1, 2, 3, 4} ``` The subsets are: ``` {{1}, {2}, {3}, {4}, {1,2}, {1,3}, {1,4}, {2,3}, {2,4},{3,4}, {1,2,3}, {1,2,4}, {1,3,4}, {2,3,4}, {1,2,3,4}} (15 subsets, as you can see the empty set, {}, is not counted) ``` Let's see an example with repetitions of an element: ``` set letters= {a, b, c, d, d} ``` The subsets for this case will be: ``` {{a}, {b}, {c}, {d}, {a,b}, {a,c}, {a,d}, {b,c}, {b,d},{c,d}, {a,b,c}, {a,b,d}, {a,c,d}, {b,c,d}, {a,b,c,d}} (15 subsets, only the ones that have no repeated elements inside) ``` The function ```est_subsets()``` (javascript: ``estSubsets()```) will calculate the number of these subsets. It will receive the array as an argument and according to its features will output the amount of different subsets without repetitions of its elements. ```python est_subsets([1, 2, 3, 4]) == 15 est_subsets(['a', 'b', 'c', 'd', 'd']) == 15 ``` Features of the random tests: ``` Low Performance Tests: 40 Length of the arrays between 6 and 15 High Performance Tests: 80 Length of the arrays between 15 and 100 (Python an Ruby) and between 15 and 50 javascript) ``` Just do it!
["def est_subsets(arr):\n return 2**len(set(arr)) - 1", "est_subsets = lambda a: 2 ** len(set(a)) - 1", "est_subsets=lambda n:2 ** len(set(n)) - 1", "from math import factorial\nfrom collections import Counter\n\ndef C(n, r):\n return factorial(n) // factorial(r) // factorial(n-r)\n \ndef est_subsets(arr):\n s = set(arr)\n return sum(C(len(s), i) for i in range(1, len(s)+1))", "def est_subsets(arr):\n # your code here\n return 2**len(set(arr)) - 1 # n: amount of subsets that do not have repeated elements ", "def est_subsets(arr):\n # we first count the number of unique elements m\n # then we use the mathematical property that there is 2**m - 1 non-empty\n # sets that can be created by combination of m elements\n m = len(set(arr))\n return 2**m - 1", "def est_subsets(arr):\n arr = list(set(arr))\n return 2 ** len(arr) - 1", "def est_subsets(arr):\n # your code here\n\n s = set(arr)\n\n return 2**(len(s)) - 1 # n: amount of subsets that do not have repeated elements ", "def est_subsets(arr):\n return 2**len(dict.fromkeys(arr))-1", "def est_subsets(arr):\n s = set(arr)\n n = (2 ** len(s)) - 1\n return n # n: amount of subsets that do not have repeated elements "]
{"fn_name": "est_subsets", "inputs": [[[1, 2, 3, 4]], [["a", "b", "c", "d", "d"]]], "outputs": [[15], [15]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,247
def est_subsets(arr):
ca6245798ed7f557d3dda32a4e95546a
UNKNOWN
It's tricky keeping track of who is owed what when spending money in a group. Write a function to balance the books. * The function should take one parameter: an object/dict with two or more name-value pairs which represent the members of the group and the amount spent by each. * The function should return an object/dict with the same names, showing how much money the members should pay or receive. **Further points:** * The values should be positive numbers if the person should receive money from the group, negative numbers if they owe money to the group. * If value is a decimal, round to two decimal places. Translations and comments (and upvotes!) welcome. ### Example 3 friends go out together: A spends £20, B spends £15, and C spends £10. The function should return an object/dict showing that A should receive £5, B should receive £0, and C should pay £5.
["def split_the_bill(x):\n diff = sum(x.values())/float(len(x))\n return {k: round(x[k]-diff, 2) for k in x}", "def split_the_bill(spendings):\n fair_amount = sum(spendings.values()) / float(len(spendings))\n return {name: round(amount - fair_amount, 2) for name, amount in spendings.items()}\n", "def split_the_bill(d):\n avg = sum(d.values())/len(d)\n return {n: round(v-avg,2) for n,v in d.items()}", "def split_the_bill(x):\n bill = float(sum(amount for amount in x.values())) / len(x)\n return {person : round(amount - bill, 2) for person, amount in x.items()}", "def split_the_bill(group):\n mean = sum(group.values()) / float(len(group))\n return {k: round(v - mean, 2) for k, v in group.items()}", "def split_the_bill(x):\n m = sum(x.values()) / float(len(x))\n return {k:round(v-m, 2) for k, v in x.items()}", "def split_the_bill(x):\n avg = 1.0 * sum(x.values()) / len(x)\n return {key: round(value - avg, 2) for key, value in x.items()}", "def split_the_bill(x):\n perperson = 1.0 * sum(x.values()) / len(x)\n \n for name, val in x.items():\n x[name] = round(val - perperson, 2)\n \n return x", "def split_the_bill(x):\n # Good Luck!\n avg = sum(x.values())/float(len(x))\n group = {}\n for key in x:\n group[key] = round(x[key] - avg, 2)\n return group"]
{"fn_name": "split_the_bill", "inputs": [[{"A": 20, "B": 15, "C": 10}], [{"A": 40, "B": 25, "X": 10}], [{"A": 40, "B": 25, "C": 10, "D": 153, "E": 58}], [{"A": 475, "B": 384, "C": 223, "D": 111, "E": 19}], [{"A": 20348, "B": 493045, "C": 2948, "D": 139847, "E": 48937534, "F": 1938724, "G": 4, "H": 2084}]], "outputs": [[{"A": 5.0, "B": 0.0, "C": -5.0}], [{"A": 15.0, "B": 0.0, "X": -15.0}], [{"A": -17.2, "B": -32.2, "C": -47.2, "D": 95.8, "E": 0.8}], [{"A": 232.6, "B": 141.6, "C": -19.4, "D": -131.4, "E": -223.4}], [{"A": -6421468.75, "B": -5948771.75, "C": -6438868.75, "D": -6301969.75, "E": 42495717.25, "F": -4503092.75, "G": -6441812.75, "H": -6439732.75}]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,352
def split_the_bill(x):
7323b0da72eeb2a9ae41c4e05b99b354
UNKNOWN
## Witamy! You are in Poland and want to order a drink. You need to ask "One beer please": "Jedno piwo poprosze" ``` java Translator.orderingBeers(1) = "Jedno piwo poprosze" ``` But let's say you are really thirsty and want several beers. Then you need to count in Polish. And more difficult, you need to understand the Polish grammar and cases (nominative, genitive, accustative and more). ## The grammar In English, the plural of "beer" is simply "beers", with an "s". In Polish, the plural of "piwo" (nominative singular) is "piw" (genitive plural) or "piwa" (nominative plural). It depends! The rules: * usually the plural is genitive: "piw" * but after the numerals 2, 3, 4, and compound numbers ending with them (e.g. 22, 23, 24), the noun is plural and takes the same case as the numeral, so nominative: "piwa" * and exception to the exception: for 12, 13 and 14, it's the genitive plural again: "piw" (yes, I know, it's crazy!) ## The numbers From 0 to 9: "zero", "jeden", "dwa", "trzy", "cztery", "piec", "szesc" , "siedem", "osiem", "dziewiec" From 10 to 19 it's nearly the same, with "-ascie" at the end: "dziesiec", "jedenascie", "dwanascie", "trzynascie", "czternascie", "pietnascie", "szesnascie", "siedemnascie", "osiemnascie", "dziewietnascie" Tens from 10 to 90 are nearly the same, with "-ziesci" or "ziesiat" at the end: "dziesiec", "dwadziescia", "trzydziesci", "czterdziesci", "piecdziesiat", "szescdziesiat", "siedemdziesiat", "osiemdziesiat", "dziewiecdziesiat" Compound numbers are constructed similarly to English: tens + units. For example, 22 is "dwadziescia dwa". "One" could be male ("Jeden"), female ("Jedna") or neuter ("Jedno"), which is the case for "beer" (piwo). But all other numbers are invariant, even if ending with "jeden". Ah, and by the way, if you don't want to drink alcohol (so no beers are ordered), ask for mineral water instead: "Woda mineralna". Note: if the number of beers is outside your (limited) Polish knowledge (0-99), raise an error! --- More about the crazy polish grammar: https://en.wikipedia.org/wiki/Polish_grammar
["def ordering_beers(beers):\n assert 0 <= beers < 100\n \n units = [\"\", \"jeden\", \"dwa\", \"trzy\", \"cztery\", \"piec\", \"szesc\" , \"siedem\", \"osiem\", \"dziewiec\",\n \"dziesiec\", \"jedenascie\", \"dwanascie\", \"trzynascie\", \"czternascie\", \"pietnascie\", \"szesnascie\", \"siedemnascie\", \"osiemnascie\", \"dziewietnascie\"]\n tens = [\"\", \"\", \"dwadziescia\", \"trzydziesci\", \"czterdziesci\", \"piecdziesiat\", \"szescdziesiat\", \"siedemdziesiat\", \"osiemdziesiat\", \"dziewiecdziesiat\"]\n \n if beers == 0:\n order = \"Woda mineralna\"\n elif beers == 1:\n order = \"Jedno piwo\"\n elif beers < 20:\n order = units[beers] + \" piw\"\n else:\n order = tens[beers // 10] + \" \" * bool(beers % 10) + units[beers % 10] + \" piw\"\n \n if beers % 10 in [2, 3, 4] and beers not in [12, 13, 14]:\n order += \"a\"\n \n return order.capitalize() + \" poprosze\"", "def ordering_beers(beers):\n one_to_ten = {1: \"jeden\", 2: \"dwa\", 3: \"trzy\", 4: \"cztery\", 5: \"piec\", 6: \"szesc\", 7: \"siedem\", 8: \"osiem\", 9: \"dziewiec\"}\n ten_to_nineteen = {10: \"dziesiec\", 11: \"jedenascie\", 12: \"dwanascie\", 13: \"trzynascie\", 14: \"czternascie\", 15: \"pietnascie\", 16: \"szesnascie\", 17: \"siedemnascie\", 18: \"osiemnascie\", 19: \"dziewietnascie\"}\n twenty_to_ninety = {20: \"dwadziescia\", 30: \"trzydziesci\", 40: \"czterdziesci\", 50: \"piecdziesiat\", 60: \"szescdziesiat\", 70: \"siedemdziesiat\", 80: \"osiemdziesiat\", 90: \"dziewiecdziesiat\"}\n if 99 > beers < 0:\n raise Exception()\n if beers == 0:\n return \"Woda mineralna poprosze\"\n else:\n beers_str = list(str(beers))\n piwa = [2, 3, 4]\n if len(beers_str) > 1:\n if 10 <= beers <= 19:\n return ten_to_nineteen[beers].capitalize() + \" piw poprosze\"\n if beers >= 20:\n result = twenty_to_ninety[int(beers_str[0] + \"0\")].capitalize()\n return result + \" piw poprosze\" if beers_str[1] == '0' else result + \" \" + one_to_ten[int(beers_str[1])] + \" piwa poprosze\" if int(beers_str[1]) in piwa else result + \" \" + one_to_ten[int(beers_str[1])] + \" piw poprosze\"\n else:\n ones = one_to_ten[int(beers_str[0])]\n return (\"Jedno piwo poprosze\" if beers == 1 else str(ones).capitalize() + \" piwa poprosze\" if beers in piwa else str(ones).capitalize() + \" piw poprosze\")", "ones = {0:\"Woda\", 1:\"Jeden\", 2:\"dwa\", 3:\"trzy\", 4:\"cztery\", 5:\"piec\", 6:\"szesc\" , 7:\"siedem\", 8:\"osiem\", 9:\"dziewiec\"}\ntwos = {10:\"dziesiec\", 11:\"jedenascie\", 12:\"dwanascie\", 13:\"trzynascie\", 14:\"czternascie\", 15:\"pietnascie\", 16:\"szesnascie\", 17:\"siedemnascie\", 18:\"osiemnascie\", 19:\"dziewietnascie\"}\ntens = {10:\"dziesiec\", 20:\"dwadziescia\", 30:\"trzydziesci\", 40:\"czterdziesci\", 50:\"piecdziesiat\", 60:\"szescdziesiat\", 70:\"siedemdziesiat\", 80:\"osiemdziesiat\", 90:\"dziewiecdziesiat\"}\n\nordering_beers=lambda n:[ones.get(n,twos.get(n,tens.get(n,tens[(n//10or 1)*10]+' '+ones[n%10]))),'Jedno'][n==1].capitalize() + ' ' +\\\n ['mineralna',['piwo',['piw','piwa'][n in[2,3,4]or(n//10in[2,3,4]and n%10 in[2,3,4])]][n!=1]][n!=0] + ' ' +\\\n 'poprosze'", "UNITS = \" jeden dwa trzy cztery piec szesc siedem osiem dziewiec\".split(\" \")\nTENS = \"dziesiec jedenascie dwanascie trzynascie czternascie pietnascie szesnascie siedemnascie osiemnascie dziewietnascie\".split(\" \")\nTENTH = \" dwadziescia trzydziesci czterdziesci piecdziesiat szescdziesiat siedemdziesiat osiemdziesiat dziewiecdziesiat\".split(\" \")\n\ndef ordering_beers(n):\n if not 0 <= n < 100: raise ValueError(\"Nie wiem\")\n t, u = divmod(n, 10)\n number = {0: UNITS[u], 1: TENS[u]}.get(t, TENTH[t] + \" \" * (u > 0) + UNITS[u])\n plural = \"piwa\" if t != 1 and 1 < u < 5 else \"piw\"\n order = {0: \"woda mineralna\", 1: \"jedno piwo\"}.get(n, number + \" \" + plural)\n return \"{} poprosze\".format(order).capitalize()", "def ordering_beers(beers):\n assert 0 <= beers < 100\n \n units = [\"\", \"jeden\", \"dwa\", \"trzy\", \"cztery\", \"piec\", \"szesc\" , \"siedem\", \"osiem\", \"dziewiec\",\n \"dziesiec\", \"jedenascie\", \"dwanascie\", \"trzynascie\", \"czternascie\", \"pietnascie\", \"szesnascie\", \"siedemnascie\", \"osiemnascie\", \"dziewietnascie\"]\n tens = [\"dwadziescia\", \"trzydziesci\", \"czterdziesci\", \"piecdziesiat\", \"szescdziesiat\", \"siedemdziesiat\", \"osiemdziesiat\", \"dziewiecdziesiat\"]\n \n order = [\"Woda mineralna\", \"Jedno piwo\"]\n \n for i, num in enumerate(units[2:], 2):\n order.append(\"%s piw%s\" % (num, \"a\" if i in [2, 3, 4] else \"\"))\n \n for n in tens:\n for i in range(10):\n order.append(\"%s%s%s piw%s\" % (n, \" \" * bool(i), units[i], \"a\" if i in [2, 3, 4] else \"\"))\n \n return order[beers].capitalize() + \" poprosze\"", "singleNums = [\"zero\", \"jeden\", \"dwa\", \"trzy\", \"cztery\", \"piec\", \"szesc\" , \"siedem\", \"osiem\", \"dziewiec\"]\ntenth = [\"dziesiec\", \"jedenascie\", \"dwanascie\", \"trzynascie\", \"czternascie\", \"pietnascie\", \"szesnascie\", \"siedemnascie\", \"osiemnascie\", \"dziewietnascie\"] \ntens = [\"dziesiec\", \"dwadziescia\", \"trzydziesci\", \"czterdziesci\", \"piecdziesiat\", \"szescdziesiat\", \"siedemdziesiat\", \"osiemdziesiat\", \"dziewiecdziesiat\"]\n\ndef ordering_beers(beers):\n \n if beers < 0:\n raise ValueError('No negative values')\n elif beers < 1:\n return \"Woda mineralna poprosze\"\n elif beers == 1:\n return \"Jedno piwo poprosze\"\n \n \n whole = beers // 10\n modulo = beers % 10\n \n if beers > 10 and beers < 15:\n noun = 'piw'\n elif modulo > 1 and modulo < 5:\n noun = 'piwa'\n else:\n noun = 'piw'\n \n if beers < 10:\n numeral = singleNums[beers]\n elif beers > 9 and beers < 20:\n numeral = tenth[modulo]\n elif modulo == 0 and beers > 19:\n numeral = tens[whole-1]\n else:\n numeral = tens[whole-1] + ' ' + singleNums[modulo]\n \n return numeral.capitalize() + ' ' + noun + ' poprosze'", "ones = [\"jeden\", \"dwa\", \"trzy\", \"cztery\", \"piec\", \"szesc\" , \"siedem\", \"osiem\", \"dziewiec\"]\nteens = [\"dziesiec\", \"jedenascie\", \"dwanascie\", \"trzynascie\", \"czternascie\", \"pietnascie\", \"szesnascie\", \"siedemnascie\", \"osiemnascie\", \"dziewietnascie\"]\ntens = [\"dziesiec\", \"dwadziescia\", \"trzydziesci\", \"czterdziesci\", \"piecdziesiat\", \"szescdziesiat\", \"siedemdziesiat\", \"osiemdziesiat\", \"dziewiecdziesiat\"]\n\ndef ordering_beers(beers):\n if beers < 0: raise 'No negative beers'\n if not beers: return 'Woda mineralna poprosze'\n output = ''\n ending = 'o' if beers == 1 else 'a' if (beers % 10) in (2, 3, 4) and not beers in (12, 13, 14) else ''\n if beers > 19:\n output = tens[beers // 10 - 1]\n beers %= 10\n elif beers > 9:\n output = teens[beers - 10]\n beers = 0\n if beers:\n if output: output += ' '\n output += 'jedno' if beers == 1 and not ' ' in output else ones[beers - 1]\n return f'{output} piw{ending} poprosze'.capitalize()", "def ordering_beers(beers):\n oneToTwenty = ['zero','jeden','dwa','trzy','cztery','piec','szesc','siedem','osiem',\n 'dziewiec','dziesiec','jedenascie','dwanascie','trzynascie','czternascie',\n 'pietnascie','szesnascie','siedemnascie','osiemnascie','dziewietnasce','dwadziescia']\n tens = [\"dziesiec\", \"dwadziescia\", \"trzydziesci\", \"czterdziesci\", \"piecdziesiat\", \"szescdziesiat\", \n \"siedemdziesiat\", \"osiemdziesiat\", \"dziewiecdziesiat\"]\n \n if beers < 0:\n raise Exception(\"Only positive numbers!\")\n elif beers == 0:\n return \"Woda mineralna poprosze\"\n elif beers == 1:\n return \"Jedno piwo poprosze\"\n elif beers <= 20:\n order = oneToTwenty[beers]\n order = order[:1].upper() + order[1:]\n else:\n order = tens[int(beers/10)-1] + \" \" + oneToTwenty[beers%10]\n order = order[:1].upper() + order[1:]\n \n if beers in [12,13,14]:\n order = order + \" piw\"\n elif beers%10 in [2,3,4]:\n order = order + \" piwa\"\n else:\n order = order + \" piw\"\n \n return order + \" poprosze\"", "dict_units={\n 0:\"Woda\",\n 1:\"jeden\",\n 2:\"dwa\",\n 3:\"trzy\",\n 4:\"cztery\",\n 5:\"piec\",\n 6:\"szesc\",\n 7:\"siedem\",\n 8:\"osiem\",\n 9:\"dziewiec\"\n}\n\n\ndict_units_1={\n 10:\"dziesiec\",\n 11:\"jedenascie\",\n 12:\"dwanascie\",\n 13:\"trzynascie\",\n 14:\"czternascie\",\n 15:\"pietnascie\",\n 16:\"szesnascie\",\n 17:\"siedemnascie\",\n 18:\"osiemnascie\",\n 19:\"dziewietnascie\"\n}\n\n\n\ndict_dec={\n 10:\"dziesiec\",\n 20:\"dwadziescia\",\n 30:\"trzydziesci\",\n 40:\"czterdziesci\",\n 50:\"piecdziesiat\",\n 60:\"szescdziesiat\",\n 70:\"siedemdziesiat\",\n 80:\"osiemdziesiat\",\n 90:\"dziewiecdziesiat\"\n}\n\ndef ordering_beers(beers):\n\n if beers > 99:\n raise Exception\n\n length=len(str(beers))\n digit_l=None\n digit_r=None\n beer_word=None\n please=\"poprosze\"\n\n if length > 1:\n\n if beers in [10,20,30,40,50,60,70,80,90]:\n return \"{} {} {}\".format(dict_dec[beers].capitalize(), \"piw\", please)\n elif beers in [11,12,13,14,15,16,17,18,19]:\n return \"{} {} {}\".format(dict_units_1[beers].capitalize(), \"piw\", please)\n\n digit_l=int((str(beers))[0])\n digit_r=int((str(beers))[1])\n\n\n\n if digit_r in [2,3,4]:\n beer_word=\"piwa\"\n\n elif digit_r==1:\n beer_word=\"piw\"\n\n elif digit_r==0:\n beer_word=\"mineralna\"\n\n else:\n beer_word=\"piw\"\n\n return \"{} {} {} {}\".format(dict_dec[digit_l*10].capitalize(),dict_units[digit_r] , beer_word, please)\n\n\n\n else:\n\n\n\n\n digit_r=int(beers)\n\n if digit_r in [2,3,4]:\n beer_word=\"piwa\"\n elif digit_r==1:\n beer_word=\"piwo\"\n\n elif digit_r==0:\n beer_word=\"mineralna\"\n\n else:\n beer_word=\"piw\"\n\n if beers==1:\n return \"{} {} {}\".format(\"Jedno\".capitalize(), beer_word, please)\n\n return \"{} {} {}\".format(dict_units[digit_r].capitalize(), beer_word, please)\n\n\n\n", "def ordering_beers(beers):\n num_0_to_19_in_polish=(\"zero\", \"jeden\", \"dwa\", \"trzy\", \"cztery\", \"piec\", \"szesc\" , \"siedem\", \"osiem\", \"dziewiec\",\"dziesiec\", \"jedenascie\", \"dwanascie\", \"trzynascie\", \"czternascie\", \"pietnascie\", \"szesnascie\", \"siedemnascie\", \"osiemnascie\", \"dziewietnascie\")\n tens_10_to_90_in_polish=(\"dziesiec\", \"dwadziescia\", \"trzydziesci\", \"czterdziesci\", \"piecdziesiat\", \"szescdziesiat\", \"siedemdziesiat\", \"osiemdziesiat\", \"dziewiecdziesiat\")\n if beers==0:\n number=\"Woda\"\n beverage=\"mineralna\"\n elif beers==1:\n number=\"Jedno\"\n beverage=\"piwo\"\n elif beers<=19 and beers>0:\n number=num_0_to_19_in_polish[beers]\n if beers in (2,3,4):\n beverage=\"piwa\"\n else:\n beverage=\"piw\"\n elif beers<=99 and beers>0:\n tens=beers//10\n remains=beers%10\n if remains==0:\n number=tens_10_to_90_in_polish[tens-1]\n else:\n number=tens_10_to_90_in_polish[tens-1]+\" \"+num_0_to_19_in_polish[remains]\n if remains in (2,3,4):\n beverage=\"piwa\"\n else:\n beverage=\"piw\"\n else:\n raise Exception(\"\u8f93\u5165\u53d8\u91cf\u8d8a\u754c\")\n number1=number.capitalize()\n return number1+\" \"+beverage+\" poprosze\""]
{"fn_name": "ordering_beers", "inputs": [[0], [1], [2], [3], [4], [5], [8], [10], [11], [12], [13], [14], [15], [16], [20], [21], [22], [28], [33], [44], [55], [98], [99]], "outputs": [["Woda mineralna poprosze"], ["Jedno piwo poprosze"], ["Dwa piwa poprosze"], ["Trzy piwa poprosze"], ["Cztery piwa poprosze"], ["Piec piw poprosze"], ["Osiem piw poprosze"], ["Dziesiec piw poprosze"], ["Jedenascie piw poprosze"], ["Dwanascie piw poprosze"], ["Trzynascie piw poprosze"], ["Czternascie piw poprosze"], ["Pietnascie piw poprosze"], ["Szesnascie piw poprosze"], ["Dwadziescia piw poprosze"], ["Dwadziescia jeden piw poprosze"], ["Dwadziescia dwa piwa poprosze"], ["Dwadziescia osiem piw poprosze"], ["Trzydziesci trzy piwa poprosze"], ["Czterdziesci cztery piwa poprosze"], ["Piecdziesiat piec piw poprosze"], ["Dziewiecdziesiat osiem piw poprosze"], ["Dziewiecdziesiat dziewiec piw poprosze"]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,092
def ordering_beers(beers):
aa7c573f84d96991134578ef413d1c68
UNKNOWN
Third day at your new cryptoanalyst job and you come across your toughest assignment yet. Your job is to implement a simple keyword cipher. A keyword cipher is a type of monoalphabetic substitution where two parameters are provided as such (string, keyword). The string is encrypted by taking the keyword, dropping any letters that appear more than once. The rest of the letters of the alphabet that aren't used are then appended to the end of the keyword. For example, if your string was "hello" and your keyword was "wednesday", your encryption key would be 'wednsaybcfghijklmopqrtuvxz'. To encrypt 'hello' you'd substitute as follows, ``` abcdefghijklmnopqrstuvwxyz hello ==> |||||||||||||||||||||||||| ==> bshhk wednsaybcfghijklmopqrtuvxz ``` hello encrypts into bshhk with the keyword wednesday. This cipher also uses lower case letters only. Good Luck.
["abc = \"abcdefghijklmnopqrstuvwxyz\"\n\ndef keyword_cipher(s, keyword, key=\"\"):\n for c in keyword + abc:\n if c not in key:\n key += c\n return s.lower().translate(str.maketrans(abc, key))", "from string import ascii_lowercase\n\ndef keyword_cipher(a, b):\n return a.lower().translate(str.maketrans(ascii_lowercase, \"\".join(dict.fromkeys(b + ascii_lowercase))))", "from string import ascii_lowercase as low\nfrom itertools import filterfalse, chain\n\ndef keyword_cipher(msg, keyword):\n D = dict.fromkeys(keyword)\n cypher = ''.join(chain(D.keys(), filterfalse(D.__contains__, low)))\n return msg.lower().translate(str.maketrans(low, cypher))", "keyword_cipher=lambda m,k,s='abcdefghijklmnopqrstuvwxyz':m.lower().translate(str.maketrans(s,''.join(sorted(set(k),key=k.index)+[i for i in s if i not in k])))", "from string import ascii_lowercase\n\ndef keyword_cipher(msg, keyword):\n key = list(dict.fromkeys(keyword + ascii_lowercase).keys())\n return ''.join(key[ascii_lowercase.index(c)] if c in key else c for c in msg.lower())\n", "def keyword_cipher(msg, keyword):\n abc = 'abcdefghijklmnopqrstuvwxyz'\n return msg.lower().translate(str.maketrans(abc, ''.join(dict.fromkeys(keyword)) + ''.join(c for c in abc if c not in keyword)))", "from string import ascii_lowercase\n\ndef keyword_cipher(msg, keyword):\n msg = msg.lower()\n keyword = keyword.lower()\n subs = ''.join(dict.fromkeys(keyword)) + ''.join(c for c in ascii_lowercase if c not in keyword)\n tbl = str.maketrans(ascii_lowercase, subs)\n return msg.translate(tbl)", "lowers = \"abcdefghijklmnopqrstuvwxyz \"\n\ndef keyword_cipher(msg, keyword):\n key = \"\".join(sorted(lowers, key=f\"{keyword.lower()}{lowers}\".index))\n return \"\".join(key[lowers.index(char)] for char in msg.lower())", "from string import ascii_lowercase\nfrom collections import OrderedDict\n\ndef keyword_cipher(msg,keyword):\n return msg.lower().translate(str.maketrans(ascii_lowercase,''.join(OrderedDict.fromkeys(keyword.lower()+ascii_lowercase).keys())))", "import string\ndef keyword_cipher(msg, keyword):\n s = []\n for i in keyword.lower():\n if i not in s:\n s.append(i)\n return msg.lower().translate(str.maketrans(string.ascii_lowercase, ''.join(s + [i for i in string.ascii_lowercase if i not in keyword]).lower()))"]
{"fn_name": "keyword_cipher", "inputs": [["Welcome home", "secret"], ["hello", "wednesday"], ["HELLO", "wednesday"], ["HeLlO", "wednesday"], ["WELCOME HOME", "gridlocked"], ["alpha bravo charlie", "delta"], ["Home Base", "seven"], ["basecamp", "covert"], ["one two three", "rails"], ["Test", "unbuntu"]], "outputs": [["wticljt dljt"], ["bshhk"], ["bshhk"], ["bshhk"], ["wlfimhl kmhl"], ["djofd eqdvn lfdqjga"], ["dlja esqa"], ["ocprvcil"], ["mks twm tdpss"], ["raqr"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,373
def keyword_cipher(msg, keyword):
6b5a34b08672f3dd6461d574c600b742
UNKNOWN
Create a function that takes a string as a parameter and does the following, in this order: 1. replaces every letter with the letter following it in the alphabet (see note below) 2. makes any vowels capital 3. makes any consonants lower case **Note:** the alphabet should wrap around, so `Z` becomes `A` So, for example the string `"Cat30"` would return `"dbU30"` (`Cat30 --> Dbu30 --> dbU30`)
["def changer(s):\n return s.lower().translate(str.maketrans('abcdefghijklmnopqrstuvwxyz', 'bcdEfghIjklmnOpqrstUvwxyzA'))", "changer=lambda s: \"\".join([a if not a.isalpha() else chr((ord(a)-96)%26+97).upper() if a in \"zdhnt\" else chr(ord(a)+1) for a in s.lower()])", "table = str.maketrans(\"abcdefghijklmnopqrstuvwxyz\", \"bcdEfghIjklmnOpqrstUvwxyzA\")\n\n\ndef changer(stg):\n return stg.lower().translate(table)", "from string import ascii_lowercase\ntrans = str.maketrans(ascii_lowercase, \"bcdEfghIjklmnOpqrstUvwxyzA\")\n\ndef changer(string):\n return string.lower().translate(trans)", "def changer(string):\n return string.lower().translate(str.maketrans('abcdeffghijklmnopqrstuvwxyz', 'bcdEffghIjklmnOpqrstUvwxyzA'))", "from string import ascii_lowercase as al\n\nxs = ''.join(c.upper() if c in 'aeiou' else c for c in al) * 2\ntbl = str.maketrans(al + al.upper(), xs[1:] + xs[0])\ndef changer(s):\n return s.translate(tbl)", "def changer(string):\n d = str.maketrans('abcdefghijklmnopqrstuvwxyz',\n 'bcdEfghIjklmnOpqrstUvwxyzA')\n return string.lower().translate(d)", "import re\ndef changer(st):\n st = st.lower().translate(st.maketrans('abcdefghijklmnopqrstuvwxyz','bcdefghijklmnopqrstuvwxyza'))\n return re.sub('[aeiou]',lambda m: m.group().upper(),st)", "def changer(string):\n string = \"\".join(chr(ord(letter) + 1).upper() if chr(ord(letter) + 1) in \"aeiouAEIOU\"\n else letter if letter in \" 0123456789\"\n else 'A' if letter.lower() == 'z'\n else chr(ord(letter) + 1).lower() for letter in string)\n return string \n", "from string import ascii_letters\n\ntr=str.maketrans(ascii_letters,'bcdEfghIjklmnOpqrstUvwxyzA'*2)\n\ndef changer(s):\n return s.translate(tr)"]
{"fn_name": "changer", "inputs": [["Cat30"], ["Alice"], ["sponge1"], ["Hello World"], ["dogs"], ["z"]], "outputs": [["dbU30"], ["bmjdf"], ["tqpOhf1"], ["Ifmmp xpsmE"], ["Epht"], ["A"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,890
def changer(string):
ef5677b1bd05b7ea70366deac7fcc7b5
UNKNOWN
Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. The method takes in an array of strings and returns a single formatted string. Empty string values should be ignored. Empty arrays or null/nil values being passed into the method should result in an empty string being returned. ```Python format_words(['ninja', 'samurai', 'ronin']) # should return "ninja, samurai and ronin" format_words(['ninja', '', 'ronin']) # should return "ninja and ronin" format_words([]) # should return "" ``` ```Haskell formatWords ["ninja", "samurai", "ronin"] -- should return "ninja, samurai and ronin" formatWords ["ninja", "", "ronin"] -- should return "ninja and ronin" formatWords [] -- should return "" ```
["def format_words(words):\n return ', '.join(word for word in words if word)[::-1].replace(',', 'dna ', 1)[::-1] if words else ''", "def format_words(words):\n # reject falsey words\n if not words: return \"\"\n \n # ignoring empty strings\n words = [word for word in words if word]\n \n number_of_words = len(words)\n if number_of_words <= 2:\n # corner cases:\n # 1) list with empty strings\n # 2) list with one non-empty string\n # 3) list with two non-empty strings\n joiner = \" and \" if number_of_words == 2 else \"\"\n return joiner.join(words)\n \n return \", \".join(words[:-1]) + \" and \" + words[-1]", "def format_words(words):\n words = [w for w in words if w] if words else ''\n if not words:\n return ''\n return '{seq} and {last}'.format(seq=', '.join(words[:-1]), last=words[-1]) if len(words) !=1 else '{0}'.format(words[0])", "def format_words(words):\n return \" and \".join(\", \".join(filter(bool, words or [])).rsplit(\", \", 1))", "from itertools import chain\n\ndef format_words(words):\n if not words: return ''\n \n filtered = [s for s in words if s]\n nCommas = len(filtered)-2\n nAnd = min(1,len(filtered)-1)\n chunks = [', '] * nCommas + [' and '] * nAnd + ['']\n \n return ''.join(chain(*zip(filtered, chunks)))", "def format_words(words):\n if not words or words == ['']:\n return ''\n words = [i for i in words if i != '']\n if len(words) == 1:\n return words[0]\n return ', '.join(words[:-1]) + ' and ' + words[-1]", "def format_words(w=None):\n return ', '.join(filter(lambda _:bool(_),w))[::-1].replace(',','dna ',1)[::-1] if w else ''", "def format_words(words):\n return ', '.join([word for word in words if word] if words else [])[::-1].replace(' ,', ' dna ', 1)[::-1]", "def format_words(words):\n if words!=[\"\"] and words!=[] and words is not None:\n l=[word for word in words if word!='']\n return \", \".join(l[:-1])+' and '+l[-1:][0] if len(l)>1 else l[0]\n return ''\n", "def format_words(words):\n words = [w for w in words if w] if words else ''\n if not words:\n return ''\n return f'{\", \".join(words[:-1])} and {words[-1]}' if len(words) !=1 else words[-1]"]
{"fn_name": "format_words", "inputs": [[["one", "two", "three", "four"]], [["one"]], [["one", "", "three"]], [["", "", "three"]], [["one", "two", ""]], [[]], [null], [[""]]], "outputs": [["one, two, three and four"], ["one"], ["one and three"], ["three"], ["one and two"], [""], [""], [""]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,306
def format_words(words):
95f1d1fffabe1c409c2f269c94a4b48a
UNKNOWN
# Task let F(N) be the sum square of digits of N. So: `F(1) = 1, F(3) = 9, F(123) = 14` Choose a number A, the sequence {A0, A1, ...} is defined as followed: ``` A0 = A A1 = F(A0) A2 = F(A1) ... ``` if A = 123, we have: ``` 123 → 14(1 x 1 + 2 x 2 + 3 x 3) → 17(1 x 1 + 4 x 4) → 50(1 x 1 + 7 x 7) → 25(5 x 5 + 0 x 0) → 29(2 x 2 + 5 x 5) → 85(2 x 2 + 9 x 9) → 89(8 x 8 + 5 x 5) --- → 145(8 x 8 + 9 x 9) |r → 42(1 x 1 + 4 x 4 + 5 x 5) |e → 20(4 x 4 + 2 x 2) |p → 4(2 x 2 + 0 x 0) |e → 16(4 x 4) |a → 37(1 x 1 + 6 x 6) |t → 58(3 x 3 + 7 x 7) | → 89(5 x 5 + 8 x 8) --- → ...... ``` As you can see, the sequence repeats itself. Interestingly, whatever A is, there's an index such that from it, the sequence repeats again and again. Let `G(A)` be the minimum length of the repeat sequence with A0 = A. So `G(85) = 8` (8 number : `89,145,42, 20,4,16,37,58`) Your task is to find G(A) and return it. # Input/Output - `[input]` integer `a0` the A0 number - `[output]` an integer the length of the repeat sequence
["from itertools import count\n\n# Couldn't find the pattern of why it's 1 or 8, I'm sad :(\ndef repeat_sequence_len(n):\n memo = {}\n for i in count():\n if n in memo: return i - memo[n]\n memo[n] = i\n n = sum(d*d for d in map(int, str(n)))", "def F(n):\n return sum(int(d)**2 for d in str(n))\n\ndef repeat_sequence_len(n):\n seq = [n]\n c = F(n)\n while c not in seq:\n seq.append(c)\n c = F(c)\n return len(seq) - seq.index(c)", "digits = lambda n: map(int, str(n))\n\ndef repeat_sequence_len(n):\n seen = []\n \n while n not in seen:\n seen.append(n)\n n = sum(x*x for x in digits(n))\n \n return len(seen) - seen.index(n)", "def repeat_sequence_len(n):\n s = []\n\n while True:\n n = sum(int(i) ** 2 for i in str(n))\n if n not in s:\n s.append(n)\n else:\n return len(s[s.index(n):])", "def f(n):\n return sum(int(x) ** 2 for x in str(n))\n \ndef repeat_sequence_len(n):\n d, i = {}, 0\n while n not in d:\n d[n] = i\n i += 1\n n = f(n)\n return i - d[n]", "def repeat_sequence_len(n):\n f = lambda n: sum(int(c) ** 2 for c in str(n))\n tortoise = n\n rabbit = f(n)\n while tortoise != rabbit:\n tortoise = f(tortoise)\n rabbit = f(f(rabbit))\n rabbit = f(rabbit)\n result = 1\n while tortoise != rabbit:\n rabbit = f(rabbit)\n result += 1\n return result", "tr = lambda n: sum(int(i) ** 2 for i in str(n))\n\ndef repeat_sequence_len(n):\n if n < 10: return n\n tmp = []\n n = tr(n)\n while n not in tmp:\n tmp.append(n)\n n = tr(n)\n return len(tmp) - tmp.index(n)", "def repeat_sequence_len(n):\n a = [n]\n while a.count(a[-1]) == 1:\n a.append(sum(int(c)**2 for c in str(a[-1])))\n return len(a) - a.index(a[-1]) - 1", "f = lambda n: sum(int(d)**2 for d in str(n))\n\ndef repeat_sequence_len(n):\n S=[]\n while n not in S:\n S.append(n)\n n = f(n)\n return len(S)-S.index(n)", "def repeat_sequence_len(n):\n seen,i={},0\n n=sum([int(x)**2 for x in str(n)])\n while n not in seen:\n seen[n]=i\n n=sum([int(x)**2 for x in str(n)])\n i+=1\n return i-seen[n]\n\n#89,145,42, 20,4,16,37,58\n"]
{"fn_name": "repeat_sequence_len", "inputs": [[1], [85], [810], [812], [818], [833]], "outputs": [[1], [8], [8], [8], [1], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,321
def repeat_sequence_len(n):
494072e07e0d306096e8474836fc74f8
UNKNOWN
You get a new job working for Eggman Movers. Your first task is to write a method that will allow the admin staff to enter a person’s name and return what that person's role is in the company. You will be given an array of object literals holding the current employees of the company. You code must find the employee with the matching firstName and lastName and then return the role for that employee or if no employee is not found it should return "Does not work here!" The array is preloaded and can be referenced using the variable `employees` (`$employees` in Ruby). It uses the following structure. ```python employees = [ {'first_name': "Dipper", 'last_name': "Pines", 'role': "Boss"}, ...... ] ``` There are no duplicate names in the array and the name passed in will be a single string with a space between the first and last name i.e. Jane Doe or just a name.
["employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]\ndef find_employees_role(name):\n \n for employee in employees:\n if employee['first_name'] + ' ' + employee['last_name'] == name:\n return employee['role']\n \n return \"Does not work here!\"", "employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]\ndef find_employees_role(name):\n try: (first, last) = name.split(' ')\n except: return 'Does not work here!'\n for e in employees:\n if e['first_name'] == first and e['last_name'] == last: return e['role']\n return 'Does not work here!'", "employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]\ndef find_employees_role(name):\n for e in employees:\n if '{} {}'.format(e['first_name'], e['last_name']) == name:\n return e['role']\n return 'Does not work here!'\n", "employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]\ndef find_employees_role(name):\n for e in employees:\n if e['first_name'] + ' ' + e['last_name'] == name:\n return e['role']\n else:\n return 'Does not work here!'", "employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]\nEMPLOYEES_ROLES = {'{} {}'.format(dct['first_name'], dct['last_name']): dct['role'] for dct in employees}\n\ndef find_employees_role(name):\n return EMPLOYEES_ROLES.get(name, \"Does not work here!\")", "employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]\ndef find_employees_role(name):\n ns = name.split() # it's stupid, isn't it?\n fn,ln = ns if len(ns) == 2 else ('', '') # omfg\n return next(\n (e['role'] for e in employees if e['first_name'] == fn and e['last_name'] == ln),\n \"Does not work here!\")", "employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]\ndef find_employees_role(name):\n for i in employees:\n if i.get(\"first_name\") + \" \" + i.get(\"last_name\") == name: return i[\"role\"]\n return \"Does not work here!\"", "employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]\nD = {f\"{d['first_name']} {d['last_name']}\":d['role'] for d in employees}\n\ndef find_employees_role(name):\n return D.get(name, \"Does not work here!\")", "employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]\ndef find_employees_role(name):\n return next((employee['role'] for employee in employees if name == '{first_name} {last_name}'.format(**employee)), \"Does not work here!\") ", "employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]\ndef find_employees_role(name):\n return next(\n (d['role'] for d in employees if '{0[first_name]} {0[last_name]}'.format(d) == name),\n 'Does not work here!'\n )"]
{"fn_name": "find_employees_role", "inputs": [["Dipper Pines"], ["Morty Smith"], ["Anna Bell"], ["Anna"], ["Bell Anna"], ["Jewel Bell"], ["Bell Jewel"]], "outputs": [["Does not work here!"], ["Truck Driver"], ["Admin"], ["Does not work here!"], ["Does not work here!"], ["Receptionist"], ["Does not work here!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
11,257
employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}] def find_employees_role(name):
e5b1bb9b0e8ea13f8a15e292ac8ab8ea
UNKNOWN
Remove the parentheses = In this kata you are given a string for example: ```python "example(unwanted thing)example" ``` Your task is to remove everything inside the parentheses as well as the parentheses themselves. The example above would return: ```python "exampleexample" ``` Other than parentheses only letters and spaces can occur in the string. Don't worry about other brackets like ```"[]"``` and ```"{}"``` as these will never appear.
["def remove_parentheses(s):\n lvl,out = 0,[]\n for c in s:\n lvl += c=='('\n if not lvl: out.append(c)\n lvl -= c==')' \n return ''.join(out)", "import re\n\ndef remove_parentheses(s):\n while (t := re.sub(r'\\([^()]*\\)', '', s)) != s:\n s = t\n return s", "def remove_parentheses(s):\n para = ('(',')')\n stack = []\n string = []\n \n for char in s:\n if char in para:\n stack.append(char) if char == para[0] else stack.pop()\n \n elif len(stack) == 0:\n string.append(char)\n \n return ''.join(string)", "import re\ndef remove_parentheses(s):\n ret, count = \"\", 0\n for letter in s:\n if letter == \"(\": count +=1\n elif letter == \")\": count -=1\n elif count == 0: ret += letter\n return ret", "def remove_parentheses(s):\n def f():\n paren = 0\n for c in s:\n if c == '(':\n paren += 1\n elif c == ')':\n paren -= 1\n elif not paren:\n yield c\n return ''.join(f())", "def remove_parentheses(s):\n nested = 0\n result = []\n for c in s:\n if c == \"(\":\n nested += 1\n elif c == \")\":\n nested -= 1\n elif nested == 0:\n result.append(c)\n return \"\".join(result)", "def remove_parentheses(s):\n stack = []\n for i in range(len(s)):\n if s[i] is not ')':\n stack.append(s[i])\n else:\n while(stack[-1]!='('):\n stack.pop()\n stack.pop()\n return ''.join(stack)", "import re\nP = re.compile('\\([^\\(\\)]*\\)')\ndef remove_parentheses(s):\n if '(' in s: \n return remove_parentheses(P.sub('', s))\n return s", "import re;f=remove_parentheses=lambda s:f(re.sub(r'\\([^\\(\\)]*\\)','',s))if'('in s else s", "def remove_parentheses(s):\n s2 = s.replace('(','|').replace(')','|')\n level = 0\n start = 0\n i = s2.find('|')\n while i != -1:\n if s[i] == '(':\n if (level == 0):\n start = i\n level += 1\n elif s[i] == ')':\n level -= 1\n if (level == 0):\n s = s[0:start]+s[i+1:]\n s2 = s2[0:start]+s2[i+1:]\n i = -1\n i = s2.find('|',i+1)\n return s\n\n\nprint((remove_parentheses(\"example(unwanted thing)example\")))\n"]
{"fn_name": "remove_parentheses", "inputs": [["example(unwanted thing)example"], ["example (unwanted thing) example"], ["a (bc d)e"], ["a(b(c))"], ["hello example (words(more words) here) something"], ["(first group) (second group) (third group)"]], "outputs": [["exampleexample"], ["example example"], ["a e"], ["a"], ["hello example something"], [" "]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,469
def remove_parentheses(s):
eff6c56f00df7a1d032642033574d67b
UNKNOWN
In this Kata, you will be given a string that has lowercase letters and numbers. Your task is to compare the number groupings and return the largest number. Numbers will not have leading zeros. For example, `solve("gh12cdy695m1") = 695`, because this is the largest of all number groupings. Good luck! Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)
["import re\n\n\ndef solve(s):\n return max(map(int,re.findall(r\"(\\d+)\", s)))", "def solve(s):\n largest = 0\n number = 0\n \n for char in s:\n if char.isdigit():\n number = number * 10 + int(char)\n if largest < number:\n largest = number\n else:\n number = 0\n \n return largest", "import re\n\ndef solve(s):\n return max(map(int, re.findall(r'\\d+', s)), default=0)", "def solve(s):\n return max(map(int,\"\".join(\" \" if x.isalpha() else x for x in s).split()))", "def solve(s):\n result = [0]\n for c in s:\n if '0' <= c <= '9':\n result[-1] = result[-1] * 10 + int(c)\n elif result[-1] > 0:\n result.append(0)\n return max(result)", "import re\n\ndef solve(s):\n return max(map(int, re.findall(\"\\d+\", s)));", "def solve(s):\n breakdown = [0]\n for i in s:\n if i in [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]:\n breakdown[-1] = breakdown[-1]*10 + int(i)\n elif breakdown[-1] != 0:\n breakdown.append(0)\n breakdown.sort()\n return(breakdown[-1])", "import re\ndef solve(s):\n g = re.findall(r'\\d+',s)\n return max(map(int,g))", "import re\ndef solve(s):\n return max([int(i) for i in re.compile('[a-z]').split(s) if i != ''])", "import re\nP = re.compile('\\d+')\nsolve = lambda s: max(map(int, (P.findall(s))))", "import re\ndef solve(s): \n reg = r\"(\\+?\\-?\\ *\\d+\\.?\\d*)\" \n return max(map(float, re.findall(reg, s)))", "import re\n\ndef solve(s):\n return max(int(x) for x in re.findall(r'[\\d]+',s))", "solve = lambda s:max(map(int,''.join(c if c in '0123456789' else ' ' for c in s).split()))", "import re\ndef solve(s):\n return max(map(int, re.findall(r'[0-9]+', s)))", "def solve(s):\n new_list=[]\n number = ''\n for characters in s:\n if characters.isdigit():\n number += characters\n elif number != \"\":\n new_list.append(int(number))\n number = \"\"\n if number != \"\":\n new_list.append(int(number))\n return max(new_list)", "solve=lambda s:max(map(int,__import__('re').findall('\\d+',s)))", "def solve(s):\n #assumes no negatives, per problem statement\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n ans = \"\"\n \n for char in s:\n if char in alphabet:\n ans += \" \"\n else:\n ans += char\n ans = ans.split(\" \")\n \n return max(int(x) for x in ans if x) #0 will eval false", "def solve(s):\n w=''.join(['*' if i.isalpha() else i for i in s])\n num=[int(i) for i in w.split('*') if i]\n return max(num)", "import re\ndef solve(s):\n return max([int(d) for d in re.findall(r'\\d{1,}', s)])", "def solve(s):\n k=0\n a=''\n talha=[]\n for i in s:\n if i.isalpha() == True :\n a=a+'x'\n else:\n a=a+i\n b=a.split('x')\n for i in b:\n if i.isdigit() == True:\n talha.append(int(i))\n return(max(talha))", "def solve(s):\n return max([ int(i) for i in ''.join([i if i.isdigit()else' 'for i in s]).split() ])", "def solve(s):\n return max(map(int,[c for c in \"\".join([v if not v.isalpha() else '|' for v in s ]).split('|') if c!='']))", "def solve(s):\n max = num = 0\n \n for char in s:\n if char.isdigit():\n num = num * 10 + int(char)\n if max < num:\n max = num\n else:\n num = 0\n \n return max", "from re import findall; solve=lambda s: max(int(m) for m in findall(r\"\\d+\",s))", "def solve(s):\n for i in s:\n if i.isalpha():\n s = s.replace(i, \" \")\n lst = s.split()\n largest = 0\n for w in lst:\n if int(w) > largest:\n largest = int(w)\n return largest", "def solve(s):\n for i in s:\n if i not in '0123456789':\n s = s.replace(i,' ')\n s = s.split()\n return sorted([int(i) for i in s])[-1]", "def solve(s):\n \"\"\"\n result = ''\n for char in s: \n if char in '0123456789': \n result += char\n else: \n result += ' '\n return max(int(x) for x in result.split())\n \"\"\"\n\n return max(int(x) for x in ''.join(c if c in '0123456789' else ' ' for c in s).split())\n", "def solve(s):\n return max(find_numbers(s))\n\n\ndef find_numbers(chaos):\n numbers = []\n buffer = []\n for char in chaos:\n if char.isnumeric():\n buffer.append(char)\n elif char.isalpha() and buffer:\n numbers.append(int(\"\".join(buffer)))\n buffer = []\n if buffer:\n numbers.append(int(\"\".join(buffer)))\n return numbers", "def solve(s):\n return max(list(map(int, ''.join([c if not c.isalpha() else ' ' for c in s]).split())))\n", "import re\ndef solve(s):\n s = re.sub('[^0-9]+', 'x', s)\n l = s.split('x')\n res = []\n for i in l:\n if(i is ''):\n pass\n elif i.isnumeric:\n res.append(int(i))\n return(max(res))\n \n", "import re\ndef solve(s):\n x = re.findall('[0-9]+', s)\n result=list(map(int,x))\n return(max(result))", "def solve(s):\n s += 'a'\n digits = list('0123456789')\n biggest = 0\n current = ''\n list_of_numbers = []\n for i in range(len(s)):\n if s[i] in digits:\n current += s[i]\n else:\n list_of_numbers.append(current)\n current = ''\n \n while '' in list_of_numbers:\n list_of_numbers.remove('')\n list_of_ints = []\n for j in range(len(list_of_numbers)):\n list_of_numbers[j] = int(list_of_numbers[j])\n list_of_ints.append(list_of_numbers[j])\n biggest = max(list_of_ints)\n return biggest\npass\n", "def solve(s):\n highest = 0\n temp = ''\n for char in s:\n if char.isnumeric():\n temp += char\n else:\n if temp != '' and int(temp) >= highest:\n highest = int(temp)\n temp = ''\n return highest if temp == '' or highest > int(temp) else int(temp)", "import re;\n\ndef solve(s):\n \n zahlen = re.findall('([0-9]*)', s);\n\n liste = [feld for feld in zahlen if feld != ''];\n results = list(map(int, liste))\n\n return (max(results));\n \n \n \n \n \n", "from re import findall\n\ndef solve(s):\n return max(map(int, findall(r\"[\\d]{1,}\", s)))", "import re\ndef solve(s):\n \n array = re.findall(r'[0-9]+', s)\n x = [int(i) for i in array]\n x.sort()\n return x[-1] ", "import re\n\n\ndef solve(s):\n list_numbers = re.sub(\"[^0-9]\", \" 0 \", s)\n return max([int(i) for i in list_numbers.split()])", "import re\ndef solve(s):\n kill = [int(x) for x in re.findall(\"[0-9]*\", s) if x != \"\"]\n return sorted(kill, reverse=True)[0]", "def solve(s):\n max_int = -1\n current_num = ''\n for char in s:\n if char in '0123456789':\n current_num += char\n max_int = max(max_int, int(current_num))\n else:\n current_num = ''\n return max_int", "def solve(s):\n arr = []\n for i in s:\n if i.isalpha():\n arr.append('*')\n else:\n arr.append(i)\n\n strr = ''.join(arr)\n\n arr = strr.split('*')\n\n return max([int(i) for i in arr if i != ''])\n \n", "def solve(s):\n max = float('-inf')\n s = list(s)\n word = ' '\n for ch in s:\n if ch.isnumeric():\n word += ch\n if not ch.isnumeric():\n word += ' '\n lists = word.split(' ')\n for value in lists:\n if value.isnumeric():\n if int(value) > max:\n max = int(value)\n else:\n pass\n return max\n", "import re\n\ndef solve(string):\n return max(map(int, re.findall(r'[\\d]+', string)))", "def solve(s):\n max = 0\n \n for i in range(len(s)):\n if s[i].isnumeric():\n k = \"\"\n for j in range(i, len(s)):\n if s[j].isnumeric():\n k+=s[j]\n if max < int(k):\n max = int(k)\n else:\n if max < int(k):\n max = int(k)\n break\n return max ", "import re\ndef solve(s):\n return max([int(i) for i in re.split('[^0-9]', s) if i != ''])", "import re\n\ndef solve(s):\n x = re.findall(\"\\d+\", s)\n x = list(map(int, x))\n return max(x)\n", "def solve(s):\n end = \"\"\n for i in range(1, len(s)):\n if s[i-1].isdigit():\n end += s[i-1]\n if s[i].isalpha():\n end += \",\"\n if i == len(s)-1 and s[i].isdigit():\n end += s[i]\n return max(sorted([int(i) for i in end.split(\",\") if i != \"\"]))", "def solve(s):\n numbers=\"0123456789\"\n num = []\n str = \"\"\n for i in s:\n if i in numbers:\n str += i\n elif str != \"\":\n num.append(str)\n str = \"\"\n if str != \"\":\n num.append(str)\n return max([int(i) for i in num])", "import re\ndef solve(s):\n nums = re.findall('\\d+', s )\n nums = [int(i) for i in nums]\n return max(nums)", "def solve(s): \n for letter in s:\n if letter.isdigit():\n pass\n else:\n s = s.replace(letter,\" \")\n numberList =map(int,s.split())\n return max(numberList)", "def solve(s):\n number = 0\n largest = 0\n for char in s:\n if char.isdigit():\n number = number * 10 + int(char)\n if number > largest:\n largest = number\n else: \n number = 0\n \n return largest\n", "def solve(s):\n ans = [0]\n for char in s:\n if '0' <= char <= '9':\n ans[-1] = ans [-1] * 10 + int(char)\n elif ans[-1] > 0:\n ans.append(0)\n return max(ans)\n\n", "def solve(s):\n import re\n \n numbers = re.findall(r\"\\d+\",s)\n int_numbers = [int(i) for i in numbers]\n return max(int_numbers)", "def solve(number):\n numb_list = []\n temp = ''\n int_mun = []\n for numb in number:\n if not numb.isdigit():\n numb_list.append(' ')\n elif numb.isdigit():\n numb_list.append(numb)\n temp = sorted(''.join(numb_list).split())\n\n for el in temp:\n el = int(el)\n int_mun.append(el)\n return sorted(int_mun)[-1]", "def solve(s):\n str_num = \"\"\n num_fin = 0 \n j_count = 0 \n len_s = len(s)\n for a in s :\n if a.isdigit() :\n str_num = str_num + a\n \n if ((not a.isdigit()) or j_count==(len_s - 1)) and str_num != '' :\n \n num_fin = max(int(str_num),num_fin)\n str_num = \"\"\n j_count = j_count + 1 \n return num_fin", "def solve(s):\n outl = []\n s += \" \"\n for el in s:\n if el.isdecimal():\n outl.append(el) \n else:\n outl.append(\" \")\n\n temp = ''\n lis = []\n for i in range(len(outl)-1):\n if outl[i].isdecimal():\n temp += outl[i]\n if outl[i+1] == \" \":\n lis.append(int(temp))\n temp = \"\"\n return max(lis)", "def solve(s):\n r=[',' if x in 'qwertyuioplkjhgfdsazxcvbnm' else x for x in s]\n t=list(filter(lambda x: x!='', (''.join(r)).split(',')))\n return max(list(map(lambda x: int(x), t)))", "import re\n\ndef solve(s):\n return max(int(x) for x in re.split(r'\\D+', s) if x.isnumeric())", "def solve(s):\n t=''.join([i if i.isnumeric() else ' ' for i in s])\n return max([int(i) for i in t.split(' ') if i])", "def solve(s):\n for n in s:\n if n.isnumeric()==False:\n s = s.replace(n,' ')\n lst = s.split()\n lst = [int(x) for x in lst]\n return max(lst)", "def solve(s):\n number = 0\n lst = []\n last = 0\n for i in range(len(s)):\n if s[i].isnumeric():\n if last == i-1:\n number = number*10 + int(s[i])\n last = i\n else:\n lst.append(number)\n number = int(s[i])\n last = i\n lst.append(number)\n return max(lst)", "def solve(s):\n substr = \"\"\n sub_list = []\n prev_digit = s[0].isdigit()\n \n for char in s:\n this_digit = char.isdigit()\n if this_digit != prev_digit:\n sub_list.append(substr)\n substr = \"\"\n prev_digit = this_digit\n \n substr += char\n\n sub_list.append(substr)\n\n list_of_numbers = []\n \n final_list = [s for s in sub_list if s.isdigit()]\n \n high = max(map(int,final_list))\n \n return high", "import re\n\ndef solve(s):\n temp = re.findall(r'\\d+', s)\n erg = list(map(int, temp))\n return int(max(erg))", "def solve(s):\n str_lst = []\n temp = \"\"\n for elem in s:\n if elem.isdigit():\n temp += elem\n elif not elem.isdigit() and temp != \"\":\n str_lst.append(temp)\n temp = \"\"\n\n str_lst.append(temp) if temp != \"\" else False\n\n maximum = max( [int(elem) for elem in str_lst] )\n return maximum", "def solve(s):\n n = ''\n ls = []\n for i in s:\n if i.isnumeric():\n n+=i\n else:\n if n !='':\n ls.append(n)\n n = ''\n if n !='':\n ls.append(n)\n return max(map(float,ls))", "def solve(s):\n clean = \"\".join([str(c) if c.isdigit() else \" \" for c in s])\n return max(list([int(x) for x in list([_f for _f in clean.split(\" \") if _f])]))\n\n \n", "def solve(s):\n a = ''\n b = 0\n for i in s:\n if i.isdigit():\n a += i\n if not i.isdigit():\n if not a == '':\n b = max(int(a),int(b))\n a = ''\n if not a == '':\n return max(int(a), int(b))\n else:\n return int(b)", "import re #Jai Shree Ram!!!\ndef solve(s):\n l=[int(i) for i in re.findall(r'(\\d+)',s)]\n return max(l)", "def solve(s):\n int_temp = []\n int_store = []\n for i in range(len(s)): \n try:\n int(s[i])\n int_temp.append(s[i])\n if i == len(s) - 1:\n int_store.append(''.join(int_temp))\n except:\n if int_temp == '':\n int_temp = []\n else:\n int_store.append(''.join(int_temp))\n int_temp = []\n int_clean = [int(x) for x in int_store if x not in '']\n return int(sorted(int_clean, reverse=True)[0])", "import re\n\ndef solve(s):\n elements = re.split('[azertyuiopqsdfghjklmwxcvbn]',s)\n return max([int(coordinates) for coordinates in elements if len(coordinates) > 0 ])", "def solve(s):\n string = ''\n for i, item in enumerate(s):\n if item.isalpha():\n string += ' '\n else:\n string += item\n numbers = string.split()\n numbers = [int(i) for i in numbers]\n return max(numbers)", "def solve(s):\n longest_number = \"0\"\n number_sequence = \"0\"\n for x in s:\n if x.isalpha() is False:\n number_sequence = number_sequence + x\n if int(number_sequence) > int(longest_number):\n longest_number = number_sequence\n else:\n number_sequence = \"\"\n return(int(longest_number))\n \n", "def solve(s):\n return max(map(int, (''.join(elem if elem.isdigit() else ' ' for elem in s)).split()))", "import re\n\ndef solve(s):\n return max(int(n or '0') for n in re.split('[a-z]+', s))", "def solve(s) -> str:\n naujas_listas = split(s)\n return max(naujas_listas)\n\n\ndef split(tekstas) -> list:\n groups = []\n newword = \"\"\n for x, i in enumerate(tekstas[0:]):\n if i.isnumeric():\n newword += i\n\n else:\n if newword != \"\":\n groups.append(int(newword))\n newword = \"\"\n\n if newword != \"\":\n groups.append(int(newword))\n\n return groups", "def solve(s):\n return max([int(s) for s in \"\".join([c if '9'>=c>='0' else ' ' for c in s]).split()])", "def solve(arr):\n l = len(arr)\n integ = []\n i = 0\n while i < l:\n s_int = ''\n a = arr[i]\n while '0' <= a <= '9':\n s_int += a\n i += 1\n if i < l:\n a = arr[i]\n else:\n break\n i += 1\n if s_int != '':\n integ.append(int(s_int))\n\n return max(integ)", "import re\n\n\ndef solve(s):\n reg = re.compile(\"\\d+\")\n ans = reg.findall(s)\n val =0\n \n holder = [int( x) for x in ans]\n\n \n for ele in holder:\n \n if ele > val:\n val = ele \n return val\n pass", "def solve(s):\n digits = '0123456789'\n res = []\n temp_nums = ''\n for i in s:\n if i in digits:\n temp_nums += i\n if i not in digits:\n if len(temp_nums) > 0:\n res += [int(temp_nums)]\n temp_nums = ''\n if len(temp_nums) > 0:\n res += [int(temp_nums)]\n return max(res)\n", "def solve(s):\n nums=[]\n num=''\n for letter in s+'k':\n if letter.isalpha():\n print(num, letter)\n if num !='':\n nums.append(int(num))\n num=''\n if letter.isalpha()==False:\n print(letter)\n num+=letter\n return max(nums)", "import re\n\ndef solve(s):\n temp = re.findall(r'\\d+', s)\n res = max(list(map(int, temp)))\n return res\n", "def solve(s):\n l = []\n num = ''\n alp = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'\n for i in s:\n if i not in alp:\n num += i\n if i in alp:\n if len(num) == 0:\n continue\n else:\n l.append(int(num))\n num = ''\n if len(num) > 0:\n l.append(int(num))\n return max(l)", "def solve(s):\n s=s+'d'\n t=[]\n d=''\n for i in range(len(s)-1):\n if s[i].isdigit():\n d=d+s[i]\n if s[i+1].isalpha():\n t.append(int(d))\n d=''\n return max(t)\n\n", "def solve(s):\n max_num = float('-inf')\n temp = ''\n \n for i in s:\n if i.isdigit():\n temp += i\n max_num = max(max_num, int(temp))\n else:\n temp = ''\n \n return max_num", "def solve(s):\n lst = []\n i = 0\n while len(s) > i:\n if s[i].isdigit():\n lst.append(s[i])\n i += 1\n else:\n lst.append('*')\n i += 1\n lst = ''.join(lst)\n lst = lst.replace('*', ' ')\n lst = lst.split()\n lst = list(map(int, lst))\n return max(lst)\n", "import re\ndef solve(var):\n return max(int(x) for x in re.findall(r'\\d+', var))", "def solve(a):\n b = [0] * len(a)\n c = 0\n for i in a:\n if i.isalpha():\n a = a.replace(i, \" \")\n a = a.split()\n for x in range(len(a)):\n b[x] = int(a[x])\n c += 1\n return max(b)", "def solve(s):\n mas2=['0','1','2','3','4','5','6','7','8','9']\n mas=[]\n k=''\n for i in range(len(s)):\n if s[i] in mas2:\n k=k+s[i]\n if i == len(s)-1:\n mas.append(int(k))\n else:\n if k!='':\n mas.append(int(k))\n k=''\n return max(mas)", "import re\ndef solve(s):\n return max([int(x) for x in re.compile('\\D').split(s) if x != ''])", "def solve(s):\n import re\n return max(int(el) for el in re.findall(r'\\d+', s))", "def solve(s):\n char='abcdefghijklmnopqrstuvwxyz'\n ans=''\n answer=[]\n for i in s:\n if i in char:\n ans+=' '\n else:\n ans+=i\n ans = ans.split(' ')\n while ans.count('')!=0:\n ans.remove('')\n for i in ans:\n i = int(i)\n answer.append(i)\n return max(answer)\n", "def solve(s):\n res = []\n temp = list(s)\n max = 0\n\n for item in temp:\n if(item.isalpha()):\n res.append(\" \")\n else:\n res.append(item)\n res = (\"\".join(res)).split(\" \")\n\n for item in res:\n\n if((item != \"\") and (int(item) > max)):\n max = int(item)\n \n return max", "def solve(s):\n import re\n return max([int(i) for i in re.split('(\\d+)',s) if i.isnumeric()])", "def solve(s):\n import re\n lst = [i for i in re.split('(\\d+)',s) if i.isnumeric()]\n \n max_num = 0\n for l in lst:\n if int(l) > max_num:\n max_num = int(l)\n return max_num", "def solve(s):\n next_number = 0\n largest_number = 0\n for char in s:\n if str.isnumeric(char) :\n next_number = int(str(next_number) + str(char))\n else:\n if next_number > largest_number:\n largest_number = next_number\n next_number = 0\n \n if next_number > largest_number:\n largest_number = next_number\n return largest_number\n\nprint (solve('lu1j8qbbb85'))", "def isNumber(char):\n if char in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:\n \n return True\n else:\n return False\n\ndef solve(s):\n \n max_number = 0\n \n new_number = []\n \n for char in s:\n \n if isNumber(char):\n \n new_number.append(char)\n \n else:\n\n if new_number != []: # if there is a number to be compared: \n k = int(''.join(new_number))\n if k > max_number:\n max_number = k\n \n new_number = []\n \n\n # and for the last char:\n if new_number != []: # if there is a number to be compared: \n k = int(''.join(new_number))\n if k > max_number:\n max_number = k\n \n return max_number", "def solve(s):\n s+=\".\"\n arr=[]\n num=\"\"\n for i in s:\n if i.isnumeric():\n num+=i\n else:\n if num!=\"\":\n arr.append(int(num))\n num=\"\"\n arr.sort()\n \n return arr[-1]\n", "import re\ndef solve(s):\n b=re.findall('[0-9]+',s)\n return max([int(i) for i in b])", "import re\n\ndef solve(s):\n x = re.findall('[0-9]+', s)\n list = []\n for i in x:\n list.append(int(i))\n return max(list)", "def solve(s):\n nums = 0\n for char in s:\n if char.isdigit():\n pass\n else:\n s = s.replace(char,' ')\n result_list = s.split()\n for i in range(len(result_list)):\n result_list[i] = int(result_list[i])\n return (max(result_list))", "def solve(s):\n numbers = []\n temp = ''\n for char in s:\n if char.isnumeric():\n temp += char\n numbers.append(int(temp))\n else:\n try:\n numbers.append(int(temp))\n temp = ''\n except:\n continue \n return max(numbers)"]
{"fn_name": "solve", "inputs": [["gh12cdy695m1"], ["2ti9iei7qhr5"], ["vih61w8oohj5"], ["f7g42g16hcu5"], ["lu1j8qbbb85"]], "outputs": [[695], [9], [61], [42], [85]]}
INTRODUCTORY
PYTHON3
CODEWARS
23,578
def solve(s):
074a731ac350db44801e04ed949f8af6
UNKNOWN
#Bubbleing around Since everybody hates chaos and loves sorted lists we should implement some more sorting algorithms. Your task is to implement a Bubble sort (for some help look at https://en.wikipedia.org/wiki/Bubble_sort) and return a list of snapshots after **each change** of the initial list. e.g. If the initial list would be l=[1,2,4,3] my algorithm rotates l[2] and l[3] and after that it adds [1,2,3,4] to the result, which is a list of snapshots. ``` [1,2,4,3] should return [ [1,2,3,4] ] [2,1,4,3] should return [ [1,2,4,3], [1,2,3,4] ] [1,2,3,4] should return [] ```
["def bubble(l):\n ret = []\n for i in range(len(l) - 1, 0, -1):\n for j in range(i):\n if l[j] > l[j + 1]:\n l[j], l[j + 1] = l[j + 1], l[j]\n ret.append(l[:])\n return ret", "def bubble(l):\n bubbling,bubbles = True, []\n while bubbling :\n bubbling = False\n for i in range(len(l)-1) :\n if l[i] > l[i+1] : \n l[i],l[i+1] = l[i+1],l[i]\n bubbling = True\n bubbles.append( l[:] )\n return bubbles\n", "def bubble(l):\n arr = []\n for j in range(len(l)-1,0,-1):\n for i in range(j):\n if l[i]>l[i+1]:\n temp = l[i]\n l[i] = l[i+1]\n l[i+1] = temp\n arr.append(l[:])\n return arr", "def bubble(lst):\n result = []\n mod = lst.copy()\n swap = True\n while swap:\n swap = False\n for i in range(len(mod) - 1):\n if mod[i] > mod[i+1]:\n mod[i], mod[i+1] = mod[i+1], mod[i]\n swap = True\n result.append(mod.copy())\n return result\n", "def bubble(l):\n snapshots = []\n for i in range(len(l), 1, -1):\n for j in range(1, i):\n if l[j-1] > l[j]:\n l[j-1], l[j] = l[j], l[j-1]\n snapshots.append(l[:])\n return snapshots", "def swap(l, aindex, bindex):\n tmp = l[bindex]\n l[bindex] = l[aindex]\n l[aindex] = tmp\n\ndef bubble(l):\n result = []\n for _ in range(len(l) - 1):\n for i in range(len(l) - 1):\n if l[i] > l[i+1]:\n swap(l,i , i+1) \n result.append(list(l))\n return result\n \n", "def bubble(l):\n n, permutations = len(l), []\n while n:\n m = 0\n for i in range(1, n):\n if l[i-1] > l[i]:\n l[i-1], l[i] = l[i], l[i-1]\n permutations.append(l[:])\n m = i\n n = m\n return permutations", "def bubble(l):\n output, toChange = [], True\n while toChange:\n toChange = False\n for i, x in enumerate(l[:-1]):\n if l[i + 1] < l[i]:\n l[i], l[i + 1] = l[i + 1], l[i]\n output.append(l[:])\n toChange = True\n return output", "def bubble(l):\n r=[]\n for i in range(0,len(l)):\n for j in range(1,len(l)):\n if l[j]<l[j-1]: t=l[j]; l[j]=l[j-1]; l[j-1]=t; r.append(l[:])\n return r", "def bubble(a):\n if a == None or len(a) < 2 : \n return []\n swapped = True\n i = 0\n r = []\n while i < len(a) - 1 and swapped:\n swapped = False\n for j in range(len(a) - i - 1):\n if a[j] > a[j + 1]: \n a[j], a[j+1] = a[j+1], a[j]\n r.append(list(a))\n swapped = True\n i += 1\n return r"]
{"fn_name": "bubble", "inputs": [[[]], [[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[1, 3, 3, 7, 4, 2]]], "outputs": [[[]], [[]], [[[1, 3, 3, 4, 7, 2], [1, 3, 3, 4, 2, 7], [1, 3, 3, 2, 4, 7], [1, 3, 2, 3, 4, 7], [1, 2, 3, 3, 4, 7]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,881
def bubble(l):
efc343cd2ec0e956727e2cc2d7fd490a
UNKNOWN
Paul is an excellent coder and sits high on the CW leaderboard. He solves kata like a banshee but would also like to lead a normal life, with other activities. But he just can't stop solving all the kata!! Given an array (x) you need to calculate the Paul Misery Score. The values are worth the following points: kata = 5 Petes kata = 10 life = 0 eating = 1 The Misery Score is the total points gained from the array. Once you have the total, return as follows: <40 = 'Super happy!'<70 >=40 = 'Happy!'<100 >=70 = 'Sad!'\>=100 = 'Miserable!'
["def paul(x):\n points = {'life': 0, 'eating': 1, 'kata': 5, 'Petes kata': 10}\n misery = sum(map(points.get, x))\n return ['Miserable!', 'Sad!', 'Happy!', 'Super happy!']\\\n [(misery<40)+(misery<70)+(misery<100)]", "def paul(x):\n val = x.count(\"kata\")*5 + x.count(\"Petes kata\")*10 + x.count(\"eating\")\n return 'Super happy!' if val<40 else 'Happy!' if 40<=val<70 else 'Sad!' if 70<=val<100 else 'Miserable!'", "points = {\"life\": 0, \"eating\": 1, \"kata\": 5, \"Petes kata\": 10}\n\ndef paul(lst):\n score = sum(points[activity] for activity in lst)\n return \"Super happy!\" if score < 40 else \"Happy!\" if score < 70 else \"Sad!\" if score < 100 else \"Miserable!\"", "PTS = {'kata':5, 'Petes kata':10, 'life':0, 'eating':1}\nOUTS = ((100,'Miserable!'), (70,'Sad!'), (40,'Happy!'), (0,'Super happy!'))\n\ndef paul(lst):\n v = sum(map(PTS.__getitem__, lst))\n return next(s for limit,s in OUTS if v>=limit)", "def paul(x):\n dict = {'kata':5, 'Petes kata': 10, 'life': 0, 'eating': 1}\n res = sum(dict.get(i, 0) for i in x)\n \n return 'Super happy!' if res < 40 else 'Happy!' if res < 70 else 'Sad!' if res <100 else 'Miserable!'\n", "paul=lambda x:(lambda y:['Super happy!','Happy!','Sad!','Miserable!'][(y>39)+(y>69)+(y>99)])(sum('le k P'.find(e[0])for e in x)) ", "points = {'kata': 5, 'Petes kata': 10, 'life': 0, 'eating': 1}\n\ndef paul(x):\n score = sum(map(points.get, x))\n return (\n 'Super happy!' if score < 40 else\n 'Happy!' if score < 70 else\n 'Sad!' if score < 100 else\n 'Miserable!'\n )", "def paul(x):\n vals = {'kata':5,'Petes kata':10,'life':0,'eating':1}\n score = 0\n for item in x:\n score += vals[item]\n if score < 40:\n return \"Super happy!\"\n elif score < 70:\n return \"Happy!\"\n elif score < 100:\n return \"Sad!\"\n else:\n return \"Miserable!\"", "def paul(a):\n s = sum(5 if x=='kata' else 10 if x=='Petes kata' else 1 if x=='eating' else 0 for x in a)\n return 'Super happy!' if s<40 else 'Happy!' if s<70 else 'Sad!' if s<100 else 'Miserable!'", "def paul(x):\n points=sum({\"kata\":5,\"Petes kata\":10,\"life\":0,\"eating\":1}[v] for v in x)\n return [[[\"Miserable!\",\"Sad!\"][points<100],\"Happy!\"][points<70],\"Super happy!\"][points<40]"]
{"fn_name": "paul", "inputs": [[["life", "eating", "life"]], [["life", "Petes kata", "Petes kata", "Petes kata", "eating"]], [["Petes kata", "Petes kata", "eating", "Petes kata", "Petes kata", "eating"]]], "outputs": [["Super happy!"], ["Super happy!"], ["Happy!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,373
def paul(x):
707f15645066c71b5a7357bdf4f78e8b
UNKNOWN
# Task Yesterday you found some shoes in your room. Each shoe is described by two values: ``` type indicates if it's a left or a right shoe; size is the size of the shoe. ``` Your task is to check whether it is possible to pair the shoes you found in such a way that each pair consists of a right and a left shoe of an equal size. # Example For: ``` shoes = [[0, 21], [1, 23], [1, 21], [0, 23]] ``` the output should be `true;` For: ``` shoes = [[0, 21], [1, 23], [1, 21], [1, 23]] ``` the output should be `false.` # Input/Output - `[input]` 2D integer array `shoes` Array of shoes. Each shoe is given in the format [type, size], where type is either 0 or 1 for left and right respectively, and size is a positive integer. Constraints: `2 ≤ shoes.length ≤ 50, 1 ≤ shoes[i][1] ≤ 100.` - `[output]` a boolean value `true` if it is possible to pair the shoes, `false` otherwise.
["def pair_of_shoes(a):\n return sorted(s for lr, s in a if lr == 1) == sorted(s for lr, s in a if lr == 0)", "from collections import defaultdict\ndef pair_of_shoes(shoes):\n sz = defaultdict(list)\n for i in shoes:\n sz[i[1]].append(i[0])\n return all( (i[1].count(1) == i[1].count(0)) for i in sz.items())", "from collections import defaultdict\n\n\ndef pair_of_shoes(shoes):\n shoe_counts = defaultdict(int)\n for shoe_type, shoe_size in shoes:\n shoe_counts[shoe_size] += 1 if shoe_type else -1\n return all(a == 0 for a in shoe_counts.values())\n", "from collections import defaultdict\n\ndef pair_of_shoes(shoes):\n D = defaultdict(lambda:defaultdict(int))\n for type, size in shoes: D[size][type] += 1\n return all(v[0] == v[1] for v in D.values())", "pair_of_shoes=lambda s:all([s.count([i[0]^1,i[1]])==s.count(i)for i in s])", "def pair_of_shoes(shoes):\n return not sum((size * (-1)**side) for side, size in shoes)", "from collections import Counter\n\ndef pair_of_shoes(shoes):\n c = Counter()\n for lr, size in shoes:\n c[size] += 1 if lr else -1\n return not any(c.values())", "def pair_of_shoes(shoes):\n l = [i for i, j in shoes]\n m = [j for i, j in shoes]\n return sum(m.count(i) % 2 == 0 for i in set(m)) == len(set(m)) and l.count(0) == l.count(1)\n", "from collections import Counter\n\ndef pair_of_shoes(shoes):\n def count_of_type(type_):\n return Counter(n for t, n in shoes if t == type_)\n return count_of_type(0) == count_of_type(1)", "S,pair_of_shoes=lambda a,T:sorted(s for t,s in a if t-T),lambda a:S(a,0)==S(a,1)"]
{"fn_name": "pair_of_shoes", "inputs": [[[[0, 21], [1, 23], [1, 21], [0, 23]]], [[[0, 21], [1, 23], [1, 21], [1, 23]]], [[[0, 23], [1, 21], [1, 23], [0, 21], [1, 22], [0, 22]]], [[[0, 23], [1, 21], [1, 23], [0, 21]]], [[[0, 23], [1, 21], [1, 22], [0, 21]]], [[[0, 23]]], [[[0, 23], [1, 23]]], [[[0, 23], [1, 23], [1, 23], [0, 23]]], [[[0, 23], [1, 22]]], [[[0, 23], [1, 23], [1, 23], [0, 23], [0, 23], [0, 23]]]], "outputs": [[true], [false], [true], [true], [false], [false], [true], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,630
def pair_of_shoes(shoes):
dcbff2ceafa291ed7180c5a76a01c375
UNKNOWN
# Task The string is called `prime` if it cannot be constructed by concatenating some (more than one) equal strings together. For example, "abac" is prime, but "xyxy" is not("xyxy"="xy"+"xy"). Given a string determine if it is prime or not. # Input/Output - `[input]` string `s` string containing only lowercase English letters - `[output]` a boolean value `true` if the string is prime, `false` otherwise
["def prime_string(s):\n return (s + s).find(s, 1) == len(s)", "import re\ndef prime_string(s):\n return not not re.sub(r\"^(.+)\\1+$\",\"\",s)", "def prime_string(s):\n n=len(s)\n return all(s!= s[:i]*(n//i) for i in range(1,n//2 +1))\n \n \n \n \n", "def prime_string(s):\n n = len(s)\n return n == 1 or all(s != s[:i] * (n//i) for i in range(1, n//2 +1))", "def prime_string(s):\n return (s*2).find(s, 1) == len(s)", "def prime_string(s):\n l = len(s)\n return not any( s == s[:l//n]*n for n in range(2, l+1) if l%n == 0 )", "def prime_string(s):\n l=len(s)\n for i in range(1,len(s)//2+1):\n a=s[:i]\n b=l//i\n if a*b==s:return False\n return True\n", "def prime_string(s):\n for i in range(len(s) // 2):\n if s[:i + 1] * (len(s)//len(s[:i+1])) == s : return 0\n return 1", "def prime_string(s):\n return True if (s+s).find(s, 1, -1) == -1 else False", "def prime_string(s):\n for i in range(1,len(s) // 2 + 1):\n if len(s) % i == 0 and (len(s) // i) * s[:i] == s:\n return False\n return True"]
{"fn_name": "prime_string", "inputs": [["abac"], ["abab"], ["aaaa"], ["x"], ["abc"], ["fdsyffdsyffdsyffdsyffdsyf"], ["utdutdtdutd"], ["abba"]], "outputs": [[true], [false], [false], [true], [true], [false], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,096
def prime_string(s):
ada4e2f9aa172c08fbc28d8686baa0fd
UNKNOWN
Your task is to create a function called ```sum_arrays()``` in Python or ```addArrays``` in Javascript, which takes two arrays consisting of integers, and returns the sum of those two arrays. The twist is that (for example) ```[3,2,9]``` does not equal ``` 3 + 2 + 9```, it would equal ```'3' + '2' + '9'``` converted to an integer for this kata, meaning it would equal ```329```. The output should be an array of the the sum in a similar fashion to the input (for example, if the sum is ```341```, you would return ```[3,4,1]```). Examples are given below of what two arrays should return. ```python [3,2,9],[1,2] --> [3,4,1] [4,7,3],[1,2,3] --> [5,9,6] [1],[5,7,6] --> [5,7,7] ``` If both arrays are empty, return an empty array. In some cases, there will be an array containing a negative number as the first index in the array. In this case treat the whole number as a negative number. See below: ```python [3,2,6,6],[-7,2,2,8] --> [-3,9,6,2] # 3266 + (-7228) = -3962 ```
["def sum_arrays(*args):\n if all(x == [] for x in args) or all(x == [0] for x in args):\n return []\n elif any(x == [] for x in args):\n return max(args)\n else:\n s = sum(int(''.join(map(str, x))) for x in args)\n minus = s < 0\n return [int(x) * -1 if minus and i == 0 else int(x)\n for i, x in enumerate(list(str(abs(s))))]\n", "def sum_arrays(array1,array2):\n number1 = 0\n number2 = 0\n b1 = False\n b2 = False\n if len(array1) == 0:\n return array2\n if len(array2) == 0:\n return array1\n if array1[0] < 0:\n array1[0] *= -1\n b1 = True\n if array2[0] < 0:\n array2[0] *= -1\n b2 = True\n for i in array1:\n number1 = number1 * 10 + i\n for i in array2:\n number2 = number2 * 10 + i\n if b1:\n number1 *= -1\n if b2:\n number2 *= -1\n number = number1 + number2\n array = []\n if number == 0:\n return []\n if number < 0:\n b = True\n number *= -1\n else:\n b = False\n number = str(number)\n for i in range(len(number)):\n array.append(int(number[i]))\n if b:\n array[0] *= -1\n return array\n return array", "def sum_arrays(ar1,ar2):\n answ = []\n if not ar1 and not ar2: return []\n if not ar1: return ar2\n if not ar2: return ar1\n if ar1[0] == 0 and ar2[0] == 0 : return []\n sa1 = \"\".join([str(k) for k in ar1])\n sa2 = \"\".join([str(j) for j in ar2])\n r = int(sa1) + int(sa2)\n if str(r)[0] == '-':\n for s in str(r)[1:]:\n answ.append(int(s))\n answ[0] *= -1\n return answ\n for s in str(r):\n answ.append(int(s))\n return answ\n", "def sum_arrays(array1,array2):\n if array1 and not array2:\n return array1\n elif not array1 and array2:\n return array2\n if array1 or array2:\n a=''.join(map(str,array1))if array1 else '0'\n b=''.join(map(str,array2)) if array2 else '0'\n c=str(int(a)+int(b))\n c=[-int(v) if i==0 else int(v) for i,v in enumerate(c[1:])] if '-' in c else c\n return list(map(int,c)) if list(map(int,c))!=[0] else []\n \n return []", "def sum_arrays(array1,array2):\n arr = []\n if array1 == [0] and array2 == [0]:\n return arr\n if not array1 and not array2:\n return arr\n if len(array1) == 0:\n return array2\n if len(array2) == 0:\n return array1\n str1, str2 = '', ''\n for i in array1:\n str1 += str(i)\n for i in array2:\n str2 += str(i)\n res = str(int(str1) + int(str2))\n i = 0\n while i < len(res):\n if res[i] == '-':\n temp = res[i] + res[i+1]\n arr.append(int(temp))\n i += 2\n else:\n arr.append(int(res[i]))\n i += 1\n return arr", "def sum_arrays(A, B):\n if A == B == [0]: return []\n if not (A and B): return A or B\n S = sum(int(''.join(map(str, arr))) for arr in (A, B))\n res = [int(d) for d in str(abs(S))]\n return [-res[0] if S < 0 else res[0]] + res[1:]", "def sum_arrays(array1,array2):\n if(not array1 and not array2):\n return array1\n elif(not array1):\n return array2\n elif(not array2):\n return array1\n elif(array1==0 and array2==0):\n nu=[]\n return nu\n \n else:\n nu=[]\n if(len(array1)==1 and len(array2)==1):\n if(array1[0]==0 and array2[0]==0):\n return nu\n print(array1)\n print(array2)\n number1=0\n number2=0\n num3=0\n for x in range(0, len(array1)):\n if(array1[0] <0):\n if(x==0):\n number1+=((array1[x])* (10**((len(array1)-1)-x)))\n else:\n number1-=((array1[x])* (10**((len(array1)-1)-x)))\n else:\n number1+=(array1[x] * (10**((len(array1)-1)-x)))\n for x in range(0, len(array2)):\n if(array2[0] <0):\n if(x==0):\n number2+=((array2[x])* (10**((len(array2)-1)-x)))\n else:\n number2-=((array2[x]) * (10**((len(array2)-1)-x)))\n else:\n number2+=(array2[x] * (10**((len(array2)-1)-x)))\n num3= number1+number2\n strnum=str(num3)\n answer=[]\n if(strnum[0]==0):\n return nu\n if(strnum[0]=='-'):\n for x in range(1, len(strnum)):\n if(x==1):\n answer.append(-1 * int(strnum[x]))\n else:\n answer.append(int(strnum[x]))\n else:\n for x in range(0, len(strnum)):\n answer.append(int(strnum[x]))\n return answer", "def sum_arrays(arr1, arr2):\n if not arr1 and not arr2: return []\n if any([not arr1, not arr2]): return arr1 if not arr2 else arr2\n a = str(int(\"\".join([str(x) for x in arr1])) + int(\"\".join([str(x) for x in arr2])))\n if a == \"0\": return []\n return [-int(a[1])] + [int(a[k]) for k in range(2, len(a))] if a[0] == \"-\" else [int(a[k]) for k in range(len(a))]", "def sum_arrays(array1,array2):\n if array1 == [0] and array2 == [0]: return []\n if array1 == [-4] and array2 == [4]: return []\n if not (array1 or array2): return []\n if not array1 or not array2: return array1 if array1 else array2\n sum = str(int(''.join(list(map(str, array1)))) + int(''.join(list(map(str, array2)))))\n if sum[0] == \"-\":\n return list(map(int, [sum[0] + sum[1]] + list(sum[2:])))\n else:\n return list(map(int, sum))", "def sum_arrays(array1, array2):\n if len(array1) == 0:\n return array2\n elif len(array2) == 0:\n return array1\n else:\n num1 = int(''.join([str(x) for x in array1]))\n num2 = int(''.join([str(x) for x in array2]))\n result = str(num1 + num2)\n if result == '0':\n return []\n if result[0] == '-':\n lst = ['-' + result[1]]\n lst.extend(result[2:])\n return [int(x) for x in lst]\n else:\n return [int(x) for x in list(result)]\n"]
{"fn_name": "sum_arrays", "inputs": [[[3, 2, 9], [1, 2]], [[4, 7, 3], [1, 2, 3]], [[1], [5, 7, 6]], [[3, 2, 6, 6], [-7, 2, 2, 8]], [[-4, 5, 7, 3, 6], [5, 3, 4, 5]], [[], []], [[0], []], [[], [1, 2]], [[1, 4, 5], []], [[0], [0]]], "outputs": [[[3, 4, 1]], [[5, 9, 6]], [[5, 7, 7]], [[-3, 9, 6, 2]], [[-4, 0, 3, 9, 1]], [[]], [[0]], [[1, 2]], [[1, 4, 5]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,283
def sum_arrays(array1,array2):
b3274d470b978f70f87904e158f17e9f
UNKNOWN
Create a function that transforms any positive number to a string representing the number in words. The function should work for all numbers between 0 and 999999. ### Examples ``` number2words(0) ==> "zero" number2words(1) ==> "one" number2words(9) ==> "nine" number2words(10) ==> "ten" number2words(17) ==> "seventeen" number2words(20) ==> "twenty" number2words(21) ==> "twenty-one" number2words(45) ==> "forty-five" number2words(80) ==> "eighty" number2words(99) ==> "ninety-nine" number2words(100) ==> "one hundred" number2words(301) ==> "three hundred one" number2words(799) ==> "seven hundred ninety-nine" number2words(800) ==> "eight hundred" number2words(950) ==> "nine hundred fifty" number2words(1000) ==> "one thousand" number2words(1002) ==> "one thousand two" number2words(3051) ==> "three thousand fifty-one" number2words(7200) ==> "seven thousand two hundred" number2words(7219) ==> "seven thousand two hundred nineteen" number2words(8330) ==> "eight thousand three hundred thirty" number2words(99999) ==> "ninety-nine thousand nine hundred ninety-nine" number2words(888888) ==> "eight hundred eighty-eight thousand eight hundred eighty-eight" ```
["words = \"zero one two three four five six seven eight nine\" + \\\n\" ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty\" + \\\n\" thirty forty fifty sixty seventy eighty ninety\"\nwords = words.split(\" \")\n\ndef number2words(n):\n if n < 20:\n return words[n]\n elif n < 100:\n return words[18 + n // 10] + ('' if n % 10 == 0 else '-' + words[n % 10])\n elif n < 1000:\n return number2words(n // 100) + \" hundred\" + (' ' + number2words(n % 100) if n % 100 > 0 else '')\n elif n < 1000000:\n return number2words(n // 1000) + \" thousand\" + (' ' + number2words(n % 1000) if n % 1000 > 0 else '')", "d={0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',\n6:'six',7:'seven',8:'eight',9:'nine',10:'ten',\n11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fifteen',\n16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen',\n20:'twenty',30:'thirty',40:'forty',50:'fifty',\n60:'sixty',70:'seventy',80:'eighty',90:'ninety',\n100:'hundred',1000:'thousand'}\ndef number2words(n):\n \"\"\" works for numbers between 0 and 999999 \"\"\"\n if 0<=n<=20:return d[n]\n if 20<n<=99 and n%10:return d[10*(n//10)]+'-'+d[n%10]\n if 20<n<99:return d[10*(n//10)]\n if n<1000 and n%100==0:return d[n//100]+' '+d[100]\n if 100<n<=999:return d[n//100]+' '+d[100]+' '+number2words(n%100)\n if n%1000==0:return d[n//1000]+' '+d[1000]\n return number2words(n//1000)+' '+d[1000]+' '+number2words(n%1000)", "def number2words(n):\n \"\"\" works for numbers between 0 and 999999 \"\"\"\n b=[\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\",\"eleven\",\"twelve\",\"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"]\n b2=[\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"]\n if 0 <= n <= 19:\n return b[n]\n elif 20 <= n <= 99:\n return \"{}{}\".format(b2[int(str(n)[0])-2],\"\" if int(str(n)[1]) == 0 else \"-\" + number2words(int(str(n)[1])))\n elif 100 <= n <= 999:\n return \"{}{}\".format(number2words(int(str(n)[0])) + \" hundred\",\"\" if int(str(n)[1:]) == 0 else \" \" + number2words(int(str(n)[1:])))\n else:\n return \"{}{}\".format(number2words(int(str(n)[:-3])) + \" thousand\",\"\" if int(str(n)[-3:]) == 0 else \" \" + number2words(int(str(n)[-3:])))", "UNITS = ' one two three four five six seven eight nine ten '\\\n 'eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen'.split(' ')\nTENS = ' ten twenty thirty forty fifty sixty seventy eighty ninety'.split(' ')\nUNITS += [TENS[n//10] + '-' + UNITS[n%10] if n%10 else TENS[n//10] for n in range(20, 100)]\n\ndef number2words(n):\n if n == 0:\n return 'zero'\n \n text = []\n \n if n >= 1000:\n text.append(number2words(n//1000) + ' thousand')\n n %= 1000\n \n hundred, unit = divmod(n, 100)\n if hundred:\n text.append(UNITS[hundred] + ' hundred')\n if unit:\n text.append(UNITS[unit])\n \n return ' '.join(text)", "def number2words(n):\n if n == 0: return \"zero\"\n if n == 10: return \"ten\"\n \n numbers_11_19={\n \"0\":\"ten\",\n \"1\":\"eleven\",\n \"2\":\"twelve\",\n \"3\":\"thirteen\",\n \"4\":\"fourteen\",\n \"5\": \"fifteen\",\n \"6\":\"sixteen\",\n \"7\":\"seventeen\",\n \"8\":\"eighteen\",\n \"9\":\"nineteen\"\n }\n numbers_1_9={\n \"0\":\"\",\n '1':'one',\n '2':'two',\n \"3\":\"three\",\n \"4\":\"four\",\n \"5\":\"five\",\n \"6\":\"six\",\n \"7\":\"seven\",\n \"8\":\"eight\",\n \"9\":\"nine\",\n }\n numbers_20_100={\n \"0\":\"\",\n \"2\":\"twenty\",\n \"3\":\"thirty\",\n \"4\":\"forty\",\n \"5\":\"fifty\",\n \"6\":\"sixty\",\n \"7\":\"seventy\",\n \"8\":\"eighty\",\n \"9\":\"ninety\",\n }\n \n nStr=str(n)\n print (nStr)\n s=\"\"\n L=len(nStr)\n pos=0\n if pos==L-6:#4 simvol sotni tisyzcg\n s+=numbers_1_9.get(nStr[pos])\n if nStr[pos]!=\"0\":s+=\" hundred \"\n pos+=1\n if pos==L-5:#4simvol - desytki ticych\n if nStr[pos]==\"1\": #11 - 19\n s+=numbers_11_19.get(nStr[pos+1])\n pos=+1\n else:\n s+=numbers_20_100.get(nStr[pos])\n if nStr[pos+1]!=\"0\" and nStr[pos]!=\"0\" : s+=\"-\"\n pos+=1\n if pos==L-4:#3 simvol - tisycha\n if nStr[pos-1]!=\"1\": s+=numbers_1_9.get(nStr[pos])\n s+=\" thousand \"\n pos+=1\n if pos==L-3:#2 simbol - sotka\n s+=numbers_1_9.get(nStr[pos])\n if nStr[pos]!=\"0\":s+=\" hundred \"\n pos+=1\n if pos==L-2: #1 simvol, desytok\n if nStr[pos]==\"1\": #11 - 19\n s+=numbers_11_19.get(nStr[pos+1])\n pos=-1\n else:\n s+=numbers_20_100.get(nStr[pos])\n if nStr[pos+1]!=\"0\" and nStr[pos]!=\"0\" : s+=\"-\"\n pos+=1\n if pos==L-1: #0 simvol, edinici\n s+=numbers_1_9.get(nStr[pos]) \n return s.strip()", "nums = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \n \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\",\n \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\",\n \"seventeen\", \"eighteen\", \"nineteen\"]\n \ntens = [\"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n\n\n\ndef number2words(n):\n if n < 20:\n return nums[n]\n if n < 100:\n nn = (n-20)%10\n return \"%s%s\" % (tens[int((n-20)/10)], (\"-\"+nums[nn] if nn else \"\"))\n if n < 1000:\n nh = int(n / 100)\n nt = n % 100\n return (\"%s hundred %s\" % (number2words(nh), number2words(nt) if nt else \"\")).strip()\n nto = int(n / 1000)\n nh = n % 1000\n return (\"%s thousand %s\" % (number2words(nto), number2words(nh) if nh else \"\")).strip()\n \n", "d = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',\n 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',\n 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen',\n 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', \n 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', \n 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', \n 90: 'ninety', 0:''}\n\ndef number2words(n): \n s = (htu(n // 1000) + ' thousand ' if n // 1000 else '') + htu(n % 1000)\n \n return ' '.join(s.split()) if s else 'zero'\n\n \ndef htu(n):\n h, tu, u = n//100, n % 100, n % 10\n t = (d[tu] if tu in d else d[tu//10*10] + '-' + d[u]).strip('-')\n return d[h] + ' hundred ' + t if h else t", "base = ' thousand million billion trillion quadrillion quintillion sextillion septillion'.split(' ')\nALL = {int(i):x for i,x in zip('0 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 10 20 30 40 50 60 70 80 90 100'.split(),'zero one two three four five six seven eight nine eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen ten twenty thirty forty fifty sixty seventy eighty ninety'.split(' ')+['one hundred'])}\nparse=lambda n:(ALL.get(n,ALL[n//10*10]+'-'+ALL[n%10] if n<100 else ALL[n//100]+' hundred '+parse(n%100)).strip()) if n else ''\nnumber2words=lambda n:' '.join([parse(int(i))+' '+j if int(i) else '' for i,j in zip(format(n, ',').split(',')[::-1], base)][::-1]).strip() or 'zero' # SUPPORT UPTO SEPTILLION...", "special = {\n '0': 'zero',\n '1': 'one',\n '2': 'two',\n '3': 'three',\n '4': 'four',\n '5': 'five',\n '6': 'six',\n '7': 'seven',\n '8': 'eight',\n '9': 'nine',\n '10': 'ten',\n '11': 'eleven',\n '12': 'twelve',\n '13': 'thirteen',\n '14': 'fourteen',\n '15': 'fifteen',\n '16': 'sixteen',\n '17': 'seventeen',\n '18': 'eighteen',\n '19': 'nineteen',\n '20': 'twenty',\n '30': 'thirty',\n '40': 'forty',\n '50': 'fifty',\n '60': 'sixty',\n '70': 'seventy',\n '80': 'eighty',\n '90': 'ninety'\n}\ndef three_digits2words(s):\n ''' len of s should <= 3 '''\n s = str(int(s)) # remove leading 0s\n if s in special:\n return special[s]\n if len(s) == 2:\n return '{}-{}'.format(special[s[0]+'0'], special[s[1]])\n else:\n lower2 = three_digits2words(s[1:])\n return '{} hundred'.format(special[s[0]]) + ((\" \" + lower2) if lower2 != 'zero' else '')\n\ndef number2words(n):\n \"\"\" works for numbers between 0 and 999999 \"\"\"\n s = str(n)\n lower3 = three_digits2words(s[-3:])\n if len(s) > 3:\n return \"{} thousand\".format(three_digits2words(s[:-3])) + ((\" \" + lower3) if lower3 != 'zero' else '')\n else:\n return lower3", "X = (\"zero\", \"one\", \"two\", \"three\", \"four\",\n \"five\", \"six\", \"seven\", \"eight\", \"nine\",\n \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\",\n \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\")\nY = (None, None, \"twenty\", \"thirty\", \"forty\",\n \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\")\n\n\ndef number2words(n):\n if n < 20: return X[n]\n if n < 100: return f\"{Y[n//10]}-{X[n%10]}\" if n%10 else Y[n//10]\n if n < 1000: return f\"{X[n//100]} hundred{f' {number2words(n%100)}' if n%100 else ''}\"\n return f\"{number2words(n//1000)} thousand{f' {number2words(n%1000)}' if n%1000 else ''}\""]
{"fn_name": "number2words", "inputs": [[0], [1], [8], [5], [9], [10], [19], [20], [22], [54], [80], [98], [100], [301], [793], [800], [650], [1000], [1003], [3052], [7300], [7217], [8340], [99997], [888887]], "outputs": [["zero"], ["one"], ["eight"], ["five"], ["nine"], ["ten"], ["nineteen"], ["twenty"], ["twenty-two"], ["fifty-four"], ["eighty"], ["ninety-eight"], ["one hundred"], ["three hundred one"], ["seven hundred ninety-three"], ["eight hundred"], ["six hundred fifty"], ["one thousand"], ["one thousand three"], ["three thousand fifty-two"], ["seven thousand three hundred"], ["seven thousand two hundred seventeen"], ["eight thousand three hundred forty"], ["ninety-nine thousand nine hundred ninety-seven"], ["eight hundred eighty-eight thousand eight hundred eighty-seven"]]}
INTRODUCTORY
PYTHON3
CODEWARS
9,503
def number2words(n):
8b02f30ebca48d51f13153b549ca13c8
UNKNOWN
## Your Story "A *piano* in the home meant something." - *Fried Green Tomatoes at the Whistle Stop Cafe* You've just realized a childhood dream by getting a beautiful and beautiful-sounding upright piano from a friend who was leaving the country. You immediately started doing things like playing "Heart and Soul" over and over again, using one finger to pick out any melody that came into your head, requesting some sheet music books from the library, signing up for some MOOCs like Developing Your Musicianship, and wondering if you will think of any good ideas for writing piano-related katas and apps. Now you're doing an exercise where you play the very first (leftmost, lowest in pitch) key on the 88-key keyboard, which (as shown below) is white, with the little finger on your left hand, then the second key, which is black, with the ring finger on your left hand, then the third key, which is white, with the middle finger on your left hand, then the fourth key, also white, with your left index finger, and then the fifth key, which is black, with your left thumb. Then you play the sixth key, which is white, with your right thumb, and continue on playing the seventh, eighth, ninth, and tenth keys with the other four fingers of your right hand. Then for the eleventh key you go back to your left little finger, and so on. Once you get to the rightmost/highest, 88th, key, you start all over again with your left little finger on the first key. Your thought is that this will help you to learn to move smoothly and with uniform pressure on the keys from each finger to the next and back and forth between hands. You're not saying the names of the notes while you're doing this, but instead just counting each key press out loud (not starting again at 1 after 88, but continuing on to 89 and so forth) to try to keep a steady rhythm going and to see how far you can get before messing up. You move gracefully and with flourishes, and between screwups you hear, see, and feel that you are part of some great repeating progression between low and high notes and black and white keys. ## Your Function The function you are going to write is not actually going to help you with your piano playing, but just explore one of the patterns you're experiencing: Given the number you stopped on, was it on a black key or a white key? For example, in the description of your piano exercise above, if you stopped at 5, your left thumb would be on the fifth key of the piano, which is black. Or if you stopped at 92, you would have gone all the way from keys 1 to 88 and then wrapped around, so that you would be on the fourth key, which is white. Your function will receive an integer between 1 and 10000 (maybe you think that in principle it would be cool to count up to, say, a billion, but considering how many years it would take it is just not possible) and return the string "black" or "white" -- here are a few more examples: ``` 1 "white" 12 "black" 42 "white" 100 "black" 2017 "white" ``` Have fun! And if you enjoy this kata, check out the sequel: Piano Kata, Part 2
["def black_or_white_key(key_press_count):\n return \"black\" if (key_press_count - 1) % 88 % 12 in [1, 4, 6, 9, 11] else \"white\"\n", "w, b = \"white\", \"black\"\nkeyboard = [w, b, w, w, b, w, b, w, w, b, w, b]\n\ndef black_or_white_key(count):\n return keyboard[(count - 1) % 88 % 12]", "def black_or_white_key(c):\n i = int('010100101010'[((c - 1) % 88 - 3) % 12])\n return ['white', 'black'][i]", "keyboard = [(\"white\", \"black\")[int(n)] for n in \"010010100101\"]\n\n\ndef black_or_white_key(key_press_count):\n return keyboard[(key_press_count - 1) % 88 % 12]\n \n", "def black_or_white_key(keycount):\n black=2,5,7,10,12\n x=keycount%88\n if x==0:\n return \"white\"\n else: \n if x%12 in black or x%12==0:\n return \"black\"\n else:\n return \"white\"", "def black_or_white_key(key_press_count):\n k=['white','black','white','white','black','white',\n 'black','white','white','black','white','black']\n return k[(key_press_count-1)%88%12]\n", "def black_or_white_key(key_press_count):\n w = \"white\"\n b = \"black\"\n repetitive_keyboard_layout = [w, b, w, w, b, w, b, w, w, b, w, b,]\n return repetitive_keyboard_layout[(key_press_count - 1) % 88 % 12]\n", "def black_or_white_key(key_press_count):\n # your code here\n w,b = 'white','black'\n keyboard = [w,b,w,w,b,w,b,w,w,b,w,b]\n return keyboard[(key_press_count - 1) % 88 % 12]\n", "black_or_white_key=lambda n:'bwlhaictke'[13>>~-n%88%12%5&1::2]", "black_or_white_key=lambda n:'bwlhaictke'[1453>>~-n%88%12&1::2]"]
{"fn_name": "black_or_white_key", "inputs": [[1], [5], [12], [42], [88], [89], [92], [100], [111], [200], [2017]], "outputs": [["white"], ["black"], ["black"], ["white"], ["white"], ["white"], ["white"], ["black"], ["white"], ["black"], ["white"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,588
def black_or_white_key(key_press_count):
35949138265dcd0af705ffdd3273276d
UNKNOWN
# A History Lesson Tetris is a puzzle video game originally designed and programmed by Soviet Russian software engineer Alexey Pajitnov. The first playable version was completed on June 6, 1984. Pajitnov derived its name from combining the Greek numerical prefix tetra- (the falling pieces contain 4 segments) and tennis, Pajitnov's favorite sport. # About scoring system The scoring formula is built on the idea that more difficult line clears should be awarded more points. For example, a single line clear is worth `40` points, clearing four lines at once (known as a Tetris) is worth `1200`. A level multiplier is also used. The game starts at level `0`. The level increases every ten lines you clear. Note that after increasing the level, the total number of cleared lines is not reset. For our task you can use this table: .demo { width:70%; border:1px solid #C0C0C0; border-collapse:collapse; padding:5px; } .demo th { border:1px solid #C0C0C0; padding:5px; } .demo td { border:1px solid #C0C0C0; padding:5px; } Level Points for 1 line Points for 2 lines Points for 3 lines Points for 4 lines 0 40 100 300 1200 1 80 200 600 2400 2 120 300 900 3600 3 160 400 1200 4800 ... 7 320 800 2400 9600 ... For level n you must determine the formula by yourself using given examples from the table. # Task Calculate the final score of the game using original Nintendo scoring system # Input Array with cleaned lines. Example: `[4, 2, 2, 3, 3, 4, 2]` Input will always be valid: array of random length (from `0` to `5000`) with numbers from `0` to `4`. # Ouput Calculated final score. `def get_score(arr) -> int: return 0` # Example ```python get_score([4, 2, 2, 3, 3, 4, 2]); # returns 4900 ``` Step 1: `+1200` points for 4 lines (current level `0`). Score: `0+1200=1200`;\ Step 2: `+100` for 2 lines. Score: `1200+100=1300`;\ Step 3: `+100`. Score: `1300+100=1400`;\ Step 4: `+300` for 3 lines (current level still `0`). Score: `1400+300=1700`.\ Total number of cleaned lines 11 (`4 + 2 + 2 + 3`), so level goes up to `1` (level ups each 10 lines);\ Step 5: `+600` for 3 lines (current level `1`). Score: `1700+600=2300`;\ Step 6: `+2400`. Score: `2300+2400=4700`;\ Step 7: `+200`. Total score: `4700+200=4900` points. # Other If you like the idea: leave feedback, and there will be more katas in the Tetris series. * 7 kyuTetris Series #1 — Scoring System * 6 kyuTetris Series #2 — Primitive Gameplay * 6 kyuTetris Series #3 — Adding Rotation (TBA) * 5 kyuTetris Series #4 — New Block Types (TBA) * 4 kyuTetris Series #5 — Complex Block Types (TBA?)
["points = [0, 40, 100, 300, 1200]\n\ndef get_score(arr) -> int:\n cleared = 0\n score = 0\n for lines in arr:\n level = cleared // 10\n score += (level+1) * points[lines]\n cleared += lines\n return score", "def get_score(arr) -> int:\n return sum([0, 40, 100, 300, 1200][n] * (1 + (sum(arr[:i]) // 10)) for i, n in enumerate(arr))", "points = [0, 40, 100, 300, 1200]\n\ndef get_score(arr):\n done, score = 0, 0\n for lines in arr:\n score += (done // 10 + 1) * points[lines]\n done += lines\n return score", "def get_score(arr) -> int:\n points = [0, 40, 100, 300, 1200]\n done = 0\n score = 0\n for lines in arr:\n level = done // 10\n score += (level+1) * points[lines]\n done += lines\n return score", "d = {0: 0, 1: 40, 2: 100, 3: 300, 4: 1200}\n\ndef get_score(arr) -> int:\n level, score, line = 0, 0, 0\n for n in arr:\n score += d[n] * (level + 1)\n line += n\n level = line // 10\n return score", "def get_score(arr):\n score = 0\n level = 0\n lines = 0\n for i in arr:\n if i == 4:\n score += 1200*(level+1)\n lines += 4\n elif i == 3:\n score += 300*(level+1)\n lines += 3\n elif i == 2:\n score += 100*(level+1)\n lines += 2\n elif i == 1:\n score += 40*(level+1)\n lines += 1\n else:\n continue\n \n if lines >= 10:\n level += 1\n lines -= 10\n \n return score", "class Score:\n def __init__(self):\n self.default = {'points': tuple([40, 100, 300, 1200]),'line': int(10)}\n self.current = {'level': int(1), 'lines': int(0), 'point': int(0), 'new_line': int(0)}\n\n def line__(self):\n self.current['lines'] += self.current['new_line'] \n if self.current['lines'] >= self.default['line']:\n self.current['level'] += 1\n self.current['lines'] -= self.default['line']\n \n def points__(self):\n self.current['point'] = self.default['points'][self.current['new_line']-1] * (self.current['level'])\n \n def update__(self, current) -> int:\n self.current['new_line'] = current\n self.points__()\n self.line__()\n return self.current['point']\n\ndef get_score(arr) -> int:\n score = Score()\n return sum([(score.update__(current)) for current in arr if (current > 0 & current <= 4)])", "points = {\n 0:0,\n 1:40,\n 2:100,\n 3:300,\n 4:1200\n}\n\ndef get_score(arr) -> int:\n sum = 0\n level = 0\n for i in arr:\n sum += points[i] * (int(level / 10) + 1)\n level += i\n return sum", "get_score = lambda arr, acc=__import__(\"itertools\").accumulate: sum(map(lambda ln, lv: [0, 40, 100, 300, 1200][ln] * (lv//10 + 1), arr, acc([0] + arr)))", "from math import floor\n\ndef get_score(arr) -> int:\n level = 1\n score = []\n counter = 0\n points = {0:0, 1:40, 2:100, 3:300, 4:1200}\n for i in arr:\n score.append(points[i]*level)\n counter += i\n level = floor(counter/10) + 1\n return sum(score)"]
{"fn_name": "get_score", "inputs": [[[0, 1, 2, 3, 4]], [[0, 1, 1, 3, 0, 2, 1, 2]], [[2, 0, 4, 2, 2, 3, 0, 0, 3, 3]], [[0]], [[]]], "outputs": [[1640], [620], [3300], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,216
def get_score(arr) -> int:
26570fd53c60cb0ed4382258fc560f89
UNKNOWN
# Task You are given two strings s and t of the same length, consisting of uppercase English letters. Your task is to find the minimum number of "replacement operations" needed to get some `anagram` of the string t from the string s. A replacement operation is performed by picking exactly one character from the string s and replacing it by some other character. About `anagram`: А string x is an anagram of a string y if one can get y by rearranging the letters of x. For example, the strings "MITE" and "TIME" are anagrams, so are "BABA" and "AABB", but "ABBAC" and "CAABA" are not. # Example For s = "AABAA" and t = "BBAAA", the output should be 1; For s = "OVGHK" and t = "RPGUC", the output should be 4. # Input/Output - `[input]` string `s` Constraints: `5 ≤ s.length ≤ 35`. - `[input]` string `t` Constraints: `t.length = s.length`. - `[output]` an integer The minimum number of replacement operations needed to get an anagram of the string t from the string s.
["from collections import Counter\n\ndef create_anagram(s, t):\n return sum((Counter(s) - Counter(t)).values())", "def create_anagram(s, t):\n return sum(max(0, s.count(c) - t.count(c)) for c in set(s))", "def create_anagram(s, t):\n for c in s: t = t.replace(c, \"\", 1)\n return len(t)", "def create_anagram(s, t):\n \n return sum([s.count(x)- t.count(x) if s.count(x)> t.count(x) else 0 for x in set(s)])", "def create_anagram(s, t):\n return sum(max(t.count(c) - s.count(c), 0) for c in set(t))", "def create_anagram(s, t):\n return sum(abs(s.count(c)-t.count(c))for c in set(s+t))/2", "def create_anagram(s, t):\n for a in s:\n t = t.replace(a, '', 1)\n return len(t)", "def create_anagram(s, t):\n s = list(s)\n for letter in t:\n if letter in s:\n s.remove(letter)\n return len(s)", "from collections import Counter\ndef create_anagram(s,t):\n c_s,c_t=Counter(s),Counter(t)\n return min(sum((c_s-c_t).values()),sum((c_t-c_s).values()))", "from collections import Counter\n\ndef create_anagram(s, t):\n cs, ct = Counter(s), Counter(t)\n return sum(n for _, n in (ct - cs).items())"]
{"fn_name": "create_anagram", "inputs": [["AABAA", "BBAAA"], ["OVGHK", "RPGUC"], ["AAAAAAAAAAAAAAAAAAAAAAAAAAAAAB", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAC"]], "outputs": [[1], [4], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,164
def create_anagram(s, t):
056e3ab1adf3ec59e8d336be820a0a12
UNKNOWN
Complete the square sum function so that it squares each number passed into it and then sums the results together. For example, for `[1, 2, 2]` it should return `9` because `1^2 + 2^2 + 2^2 = 9`. ```if:racket In Racket, use a list instead of an array, so '(1 2 3) should return 9. ```
["def square_sum(numbers):\n return sum(x ** 2 for x in numbers)", "def square_sum(numbers):\n return sum(x * x for x in numbers) ", "def square_sum(numbers):\n return sum(map(lambda x: x**2,numbers))", "def square_sum(numbers):\n res = 0\n for num in numbers:\n res = res + num*num\n return res", "def square_sum(numbers):\n return sum([x**2 for x in numbers])", "def square_sum(numbers):\n return sum([i * i for i in numbers])", "def square_sum(numbers):\n res=0\n for key in numbers:\n res+=key**2\n return res", "def square_sum(numbers):\n result = []\n for sqr in numbers:\n result.append(sqr ** 2)\n return sum(result)", "import numpy\n\ndef square_sum(numbers):\n return sum(numpy.array(numbers) ** 2)", "def square_sum(numbers):\n return sum(map(lambda x: x*x, numbers))", "def square_sum(numbers):\n return sum(n ** 2 for n in numbers)", "import functools\ndef square_sum(numbers):\n return functools.reduce(lambda x, y: x + y**2, numbers, 0)", "def square_sum(numbers):\n return sum([i**2 for i in numbers])", "def square_sum(numbers):\n #your code here\n li = []\n for number in numbers:\n li.append(number**2)\n return(sum(li))\n", "square_sum = lambda n: sum(e**2 for e in n)", "def square_sum(numbers):\n return sum(i**2 for i in numbers)", "from itertools import repeat\n\ndef square_sum(numbers):\n return sum(map(pow, numbers, repeat(2)))", "import math\n\ndef square_sum(numbers):\n result = 0\n for c in numbers:\n result += math.pow(c, 2) \n return result ", "def square_sum(numbers):\n #your code here\n s = [] #empty list to store the result from loop below\n for x in numbers: #loop through argument value\n x = x**2 #square value and assign\n s.append(x) #append new value to list s\n return sum(s) #sum of list after loop finishes", "def square_sum(x):\n L=[]\n for i in x:\n L.append(i**2)\n return sum(L)", "def square_sum(numbers):\n i = 0\n sum = 0\n while i < len(numbers):\n sum = sum + (numbers[i] ** 2)\n i = i + 1\n return sum", "def square_sum(numbers):\n new_lst = []\n for i in numbers:\n i = i*i\n new_lst.append(i)\n\n return sum(new_lst)", "def square_sum(numbers):\n #your code here\n g=0\n for i in range(len(numbers)):\n g+=pow(int(numbers[i]),2)\n return g ", "def square_sum(numbers):\n counter = 0\n for num in numbers:\n counter += pow(num, 2)\n return counter", "def square_sum(numbers):\n #your code here\n s = 0\n for i in numbers:\n s += i*i\n return s\n", "def square_sum(numbers):\n return sum(list(map(lambda x : x*x, numbers)))", "def square_sum(n):\n return sum(map(lambda x: x*x, n))", "def square_sum(numbers):\n return sum(pow(i, 2) for i in numbers)", "def square_sum(numbers):\n return sum([l ** 2 for l in numbers])", "square_sum=lambda n:sum(a**2 for a in n)", "def square_sum(numbers):\n return sum(i*i for i in numbers)", "import numpy as np\n\ndef square_sum(numbers):\n array_sum = np.array(numbers)\n result = np.sum(array_sum**2)\n return result", "def square_sum(numbers):\n lista = []\n for i in numbers:\n i = i**2\n lista.append(i)\n return sum(lista)", "def square_sum(numbers):\n lol = 0\n hassu = len(numbers)\n while hassu > 0:\n lol = numbers[hassu - 1] ** 2 + lol\n hassu = hassu - 1\n return lol\n", "def square_sum(numbers):\n r= [number*number for number in numbers]\n return(sum(r))", "def square_sum(numbers):\n return sum(list(map(lambda i:i**2,numbers)))", "from functools import reduce\ndef square_sum(numbers):\n if(len(numbers) == 0): return 0\n else:\n squared = [n**2 for n in numbers]\n return reduce(lambda x, y: x + y, squared)", "def square_sum(numbers):\n total = 0\n for i in numbers:\n total += i**2\n return total", "def square_sum(nums):\n return sum(i**2 for i in nums)", "def square_sum(numbers):\n output = 0\n for x in numbers:\n output += x**2\n \n return output\n \n", "def square_sum(numbers):\n li = []\n for x in numbers:\n x2 = x**2\n li.append(x2)\n add = sum(li[:])\n return add", "def square_sum(numbers):\n return sum(int(a)**2 for a in numbers)", "def square_sum(numbers):\n lista=[]\n for valor in numbers:\n valor1=valor*valor\n lista.append(valor1)\n lista=sum(lista)\n return lista\n", "def square_sum(numbers):\n n=0\n for m in numbers:\n n+=m**2\n return n", "def square_sum(num):\n sum1=0\n for i in num:\n sum1=sum1+i**2\n return sum1", "def square_sum(numbers):\n sum = 0\n for nb in numbers:\n sum = sum + nb**2\n return sum", "def square_sum(numbers):\n number = 0\n for x in numbers:\n number += x ** 2\n return number", "def square_sum(numbers):\n b=0\n for i in range(len(numbers)):\n b=b+(numbers[i]**2)\n return b", "def square_sum(numbers):\n tmp = 0\n for i in numbers:\n tmp += (i ** 2)\n return tmp", "#lambda inception\nsquare_sum = lambda numbers: sum(list(map(lambda arr: arr ** 2, numbers)))", "def square_sum(numbers):\n \n sum = 0\n \n for number in numbers:\n \n sum = sum + abs(number**2)\n \n return sum\n \n \n \n \n \n \n \n \n", "def square_sum(nums):\n return sum(n**2 for n in nums)", "def square_sum(numbers):\n y = 0\n for each in numbers:\n x = each**2\n y = y + x\n return y", "def square_sum(numbers):\n #your code here\n sq_nums = []\n for num in numbers:\n sq_nums.append(num**2)\n return sum(sq_nums)\n", "def square_sum(num):\n return sum([el ** 2 for el in num])", "def square_sum(numbers):\n numbers = [el * el for el in numbers]\n return sum(numbers)", "def square_sum(numbers):\n return sum([el * el for el in numbers])", "def square_sum(num):\n return sum([num[i]*num[i] for i in range(0,len(num))]) ", "def square_sum(numbers):\n sum1 = sum(list([pow(x,2) for x in numbers]))\n return sum1\n", "def square_sum(numbers):\n squared = [num**2 for num in numbers]\n return sum(squared)", "def square_sum(numbers):\n sq = 0\n for i in numbers:\n sq = sq + i**2\n return sq\n", "def square_sum(numbers):\n result = list()\n for i in numbers:\n result.append(i**2)\n return sum(result)", "def square_sum(numbers):\n print(numbers)\n sqrtNum = [x*x for x in numbers]\n return sum(sqrtNum)", "\n\ndef square_sum(numbers):\n sum=0\n x=len(numbers)\n for i in range(x):\n a=pow(numbers[i], 2)\n sum=a+sum\n return sum", "def square_sum(numbers):\n sum = 0\n for number in numbers:\n sum = sum + number*number\n return sum\n \n# Iterate through each number in the array\n# For each number, square it's value\n# Add the result to the sum\n", "def square_sum(n):\n return pow(n.pop(0), 2) + square_sum(n) if len(n) > 0 else 0", "def square_sum(numbers):\n return sum(map(lambda elem : elem ** 2, numbers))", "def square_sum(numbers):\n return sum(list(map(lambda elem : elem**2, numbers)))", "def square_sum(numbers):\n sums = 0\n for num in range(len(numbers)):\n sums += pow(numbers[num], 2)\n return sums", "def square_sum(n):\n a=0\n for x in n:\n a+=x**2\n return a", "def square_sum(numbers):\n res = []\n for i in numbers:\n res.append(i * i)\n return sum(res)", "def square_sum(numbers):\n sum = 0\n for i in numbers:\n n = i ** 2\n sum += n\n return sum\nsquare_sum([1,2,2]) \n #your code here\n", "square_sum=lambda n:sum(map((2).__rpow__,n))", "def square_sum(numbers):\n list = [item**2 for item in numbers]\n return sum(list)\n", "def square_sum(numbers):\n sum = 0\n def square(number):\n return pow(number, 2)\n for number in numbers:\n sum += square(number)\n return sum\n", "def square_sum(n):\n a = 0\n for x in n:\n a += x*x\n return a \n \n\n \n \n \n", "def square_sum(n):\n n=list([x**2 for x in n])\n return sum(n)\n \n \n \n #your code here\n", "def square_sum(numbers):\n res = 0\n for i in numbers:\n a = i * i\n res += a\n return res", "def square_sum(numbers):\n sum = 0\n if numbers:\n for num in numbers:\n sum += num*num\n return sum\n #your code here\n", "def square_sum(numbers):\n x = len(numbers)\n z = 0\n for k in range(0,x):\n z += numbers[k]**2\n return z\n #your code here\n", "def square_sum(numbers):\n #your code here\n sq_sum = 0\n for square in numbers:\n sq_sum = sq_sum + square**2\n return(sq_sum)\n", "def square_sum(numbers):\n ss = sum([n**2 for n in numbers])\n return ss", "def square_sum(numbers):\n arr = list()\n for i in numbers:\n arr.append(i*i)\n return sum(arr)", "def square_sum(numbers, t=0):\n for i in numbers:\n t += i**2\n return t", "def square_sum(numbers, t=0):\n for i in numbers:\n t += i**2\n return t\n\n", "def square_sum(n):\n a=[i*i for i in n]\n return sum(a)", "def square_sum(numbers):\n suma = 0\n for i in numbers:\n i = i ** 2\n suma += i\n return suma\n", "def square_sum(numbers):\n summer = [x ** 2 for x in numbers]\n return sum(summer)", "def square_sum(numbers):\n sum = 0 \n for i in numbers:\n square = i * i\n sum = sum + square\n return sum\n \n", "def square_sum(numbers):\n i = 0\n for x in numbers:\n i = i + x**2\n return i", "def square_sum(numbers):\n squared = []\n for i in numbers:\n x = i ** 2\n squared.append(x)\n y = sum(squared)\n return y\n\nsquare_sum([0, 3, 4, 5])", "def square_sum(numbers):\n resultado = 0\n for x in numbers:\n resultado += x**2\n return resultado\n \n\n", "def square_sum(numbers):\n sum = 0\n for i in numbers:\n squr = i ** 2\n sum += squr\n return sum\n", "def square_sum(numbers):\n final_answer = 0\n for number in numbers:\n square = number ** 2\n final_answer += square\n return final_answer", "def square_sum(numbers):\n resulting_sum = 0\n for i in numbers: resulting_sum += i**2\n return resulting_sum", "def square_sum(numbers):\n total = 0\n for n in range(0, len(numbers)): \n total = total + numbers[n]**2 \n return total", "def square_sum(numbers):\n numbers_ = 0\n for i in range(0,len(numbers)):\n numbers_ += numbers[i]**2\n return numbers_", "def square_sum(numbers):\n return sum([no ** 2 for no in numbers])"]
{"fn_name": "square_sum", "inputs": [[[1, 2]], [[0, 3, 4, 5]], [[]], [[-1, -2]], [[-1, 0, 1]]], "outputs": [[5], [50], [0], [5], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
10,977
def square_sum(numbers):
0e7c2dd1f5a3bcc68bcb643dd91c2ffb
UNKNOWN
# Task Given a `sequence` of integers, check whether it is possible to obtain a strictly increasing sequence by erasing no more than one element from it. # Example For `sequence = [1, 3, 2, 1]`, the output should be `false`; For `sequence = [1, 3, 2]`, the output should be `true`. # Input/Output - `[input]` integer array `sequence` Constraints: `2 ≤ sequence.length ≤ 1000, -10000 ≤ sequence[i] ≤ 10000.` - `[output]` a boolean value `true` if it is possible, `false` otherwise.
["def almost_increasing_sequence(sequence):\n save, first = -float('inf'), True\n for i,x in enumerate(sequence):\n if x > save: save = x\n elif first:\n if i == 1 or x > sequence[i-2]: save = x\n first = False\n else: return False\n return True", "is_increasing_sequence = lambda a: all(x < y for x, y in zip(a, a[1:]))\nalmost_increasing_sequence = lambda a: any(is_increasing_sequence(a[:i] + a[i+1:]) for i in range(len(a)))", "def almost_increasing_sequence(sequence):\n \n for n,i in enumerate(sequence):\n lis = sequence.copy()\n del(lis[n])\n if len(lis) == len(set(lis)): \n if sorted(lis) == lis :\n return True\n\n return False", "def almost_increasing_sequence(arr):\n li,i = [],0\n while i < len(arr):\n temp = []\n while i + 1 < len(arr) and arr[i] < arr[i + 1]:\n temp.append(arr[i]) ; i += 1\n li.append(temp) ; i += 1\n return len(li) <= 2 and all(j[-1]<li[i+1][0] for i,j in enumerate(li[:-1]) if j and li[i+1])", "def almost_increasing_sequence(sequence):\n prev = sequence[0] - 1\n n = 0\n for i, x in enumerate(sequence):\n if x <= prev:\n if n:\n return False\n n = 1\n if i > 1 and sequence[i-2] >= x:\n continue\n prev = x\n return True", "def almost_increasing_sequence(seq):\n l = [ i for i,(a,b) in enumerate(zip(seq[:-1], seq[1:])) if a >= b ]\n return not l or len(l) == 1 and ( l[0] == 0 or l[0] == len(seq)-2 or seq[l[0]-1] < seq[l[0]+1] or seq[l[0]] < seq[l[0]+2])", "def almost_increasing_sequence(s):\n p=-1\n l=len(s)\n for i in range(l-1):\n if s[i]>=s[i+1]:\n if p>=0: return False\n p=i\n return p<=0 or p==l-2 or s[p-1]<=s[p+1]", "almost_increasing_sequence=lambda a:sum((y>=z)*(2-(x<z))for x,y,z in zip([a[1]-1]+a[:-3]+[a[-1]-1],a,a[1:]))<2", "def almost_increasing_sequence(sequence):\n to_remove = 0\n min_ = sequence[0]\n for i in range(len(sequence)-1):\n if sequence[i] >= sequence[i+1]:\n to_remove += 1\n if sequence[i+1] < min_ and min_ != sequence[i]:\n return False\n if to_remove == 2:\n return False\n min_ = sequence[i+1]\n return True", "def almost_increasing_sequence(sequence):\n if len(sequence)>2:\n for i in range(len(sequence)-1):\n if sequence[i]>=sequence[i+1] and sequence[i+1]!=sequence[-1]:\n sequence.remove(sequence[i])\n for j in range(len(sequence)-1):\n if sequence[j]>=sequence[j+1]:\n return False\n return True\n return True"]
{"fn_name": "almost_increasing_sequence", "inputs": [[[1, 3, 2, 1]], [[1, 3, 2]], [[1, 2, 3]], [[1, 2, 3, 1]], [[1, 4, 10, 4, 2]], [[10, 1, 2, 3, 4, 5]], [[1, 1, 1, 2, 3]], [[0, -2, 5, 6]], [[1, 1]], [[4, 5, 6, 1, 2, 3]], [[149, 15, 23, 32, 41, 48, 58, 66, 69, 75, 81, 91, 178, 100, 109, 118, 128, 134, 143]]], "outputs": [[false], [true], [true], [true], [false], [true], [false], [true], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,788
def almost_increasing_sequence(sequence):
a1c7f2ab78f3f9bb8c05315530a8a17a
UNKNOWN
## Task Write a function that accepts two arguments and generates a sequence containing the integers from the first argument to the second inclusive. ## Input Pair of integers greater than or equal to `0`. The second argument will always be greater than or equal to the first. ## Example ```python generate_integers(2, 5) # --> [2, 3, 4, 5] ```
["def generate_integers(m, n): \n return list(range(m,n+1))", "def generate_integers(m, n): \n return [*range(m, n + 1)]", "def generate_integers(m, n):\n return [i for i in range(m,n+1)]\n", "def generate_integers(m, n):\n ans = []\n for each in range(m,n+1):\n ans.append(each)\n return ans", "def generate_integers(m, n): \n return [_ for _ in range(m, n + 1)]", "def generate_integers(m, n):\n return [num for num in range(m, n+1)]", "def generate_integers(m, n): \n c = []\n for i in range (m,n+1):\n c.append (i)\n return c", "def generate_integers(m, n): \n numeros=[]\n for x in range(m,n+1):\n numeros.append(x)\n return numeros\n pass", "def generate_integers(m, n): \n nums = list()\n while(m <= n):\n nums.append(m)\n m += 1\n return(nums)\n", "def generate_integers(m, n): \n list = []\n for x in m, n:\n while m <= x <= n:\n x = x + 1\n list.append(x - 1)\n return list\n \n"]
{"fn_name": "generate_integers", "inputs": [[2, 5]], "outputs": [[[2, 3, 4, 5]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,030
def generate_integers(m, n):
f4871c39039da88117347362c1c7d001
UNKNOWN
# Story&Task There are three parties in parliament. The "Conservative Party", the "Reformist Party", and a group of independants. You are a member of the “Conservative Party” and you party is trying to pass a bill. The “Reformist Party” is trying to block it. In order for a bill to pass, it must have a majority vote, meaning that more than half of all members must approve of a bill before it is passed . The "Conservatives" and "Reformists" always vote the same as other members of thier parties, meaning that all the members of each party will all vote yes, or all vote no . However, independants vote individually, and the independant vote is often the determining factor as to whether a bill gets passed or not. Your task is to find the minimum number of independents that have to vote for your party's (the Conservative Party's) bill so that it is passed . In each test case the makeup of the Parliament will be different . In some cases your party may make up the majority of parliament, and in others it may make up the minority. If your party is the majority, you may find that you do not neeed any independants to vote in favor of your bill in order for it to pass . If your party is the minority, it may be possible that there are not enough independants for your bill to be passed . If it is impossible for your bill to pass, return `-1`. # Input/Output - `[input]` integer `totalMembers` The total number of members. - `[input]` integer `conservativePartyMembers` The number of members in the Conservative Party. - `[input]` integer `reformistPartyMembers` The number of members in the Reformist Party. - `[output]` an integer The minimum number of independent members that have to vote as you wish so that the bill is passed, or `-1` if you can't pass it anyway. # Example For `n = 8, m = 3 and k = 3`, the output should be `2`. It means: ``` Conservative Party member --> 3 Reformist Party member --> 3 the independent members --> 8 - 3 - 3 = 2 If 2 independent members change their minds 3 + 2 > 3 the bill will be passed. If 1 independent members change their minds perhaps the bill will be failed (If the other independent members is against the bill). 3 + 1 <= 3 + 1 ``` For `n = 13, m = 4 and k = 7`, the output should be `-1`. ``` Even if all 2 independent members support the bill there are still not enough votes to pass the bill 4 + 2 < 7 So the output is -1 ```
["def pass_the_bill(total, conservative, reformist):\n ind = total - conservative - reformist\n majority = total//2 + 1\n if conservative > majority:\n return 0\n elif conservative + ind < majority:\n return -1\n else:\n return majority - conservative", "def pass_the_bill(t, c, r):\n return -1 if t < 2*r + 1 else max(0, t//2 + 1 - c)", "def pass_the_bill(par, con, ref):\n return -1 if ref >= (par / 2) else max(0, par // 2 + 1 - con)\n", "def pass_the_bill(t, c, r):\n return 0 if c>=(t>>1)+1 else -1 if r>=(t>>1)+1 or r==t>>1 and t%2==0 else (t>>1)+1-c", "pass_the_bill = lambda t, c, r: -1 if r / t >= 0.5 else max(0,int(t/2)+1-c)", "import math \ndef pass_the_bill(total_members, conservative_party_members, reformist_party_members):\n avg = total_members / 2\n count = 0\n if reformist_party_members >= avg: return -1\n while avg >= conservative_party_members:\n count += 1\n conservative_party_members +=1\n return count", "import math\n\ndef pass_the_bill(total_members, conservative_party_members, reformist_party_members):\n if reformist_party_members >= total_members / 2: return -1\n return max(0, math.ceil(total_members / 2 + .5) - conservative_party_members)", "def pass_the_bill(total_members, conservative_party_members, reformist_party_members):\n independants = total_members - conservative_party_members - reformist_party_members\n majority = total_members // 2 + 1\n needed = max(0, majority - conservative_party_members)\n return -1 if needed > independants else needed", "def pass_the_bill(total, cons, refs):\n inds = total - cons - refs\n boundary = total // 2 + 1\n if cons + inds < boundary:\n return -1\n if cons > boundary:\n return 0\n return boundary - cons", "def pass_the_bill(t,c,r):\n i=t//2-c+1\n return max(i,0) if t-r-c>=i else -1"]
{"fn_name": "pass_the_bill", "inputs": [[8, 3, 3], [13, 4, 7], [7, 4, 3], [11, 4, 1], [11, 5, 1], [11, 6, 1], [11, 4, 4], [11, 5, 4], [11, 5, 5], [11, 4, 6], [11, 4, 5], [15, 9, 3], [16, 7, 8], [16, 8, 7], [16, 1, 8]], "outputs": [[2], [-1], [0], [2], [1], [0], [2], [1], [1], [-1], [2], [0], [-1], [1], [-1]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,898
def pass_the_bill(total_members, conservative_party_members, reformist_party_members):
1254d3e76ce1e3239bb125a3d4e66d45
UNKNOWN
*This kata is based on [Project Euler Problem 539](https://projecteuler.net/problem=539)* ##Object Find the last number between 1 and `n` (inclusive) that survives the elimination process ####How It Works Start with the first number on the left then remove every other number moving right until you reach the the end, then from the numbers remaining start with the first number on the right and remove every other number moving left, repeat the process alternating between left and right until only one number remains which you return as the "last man standing" ##Example given an input of `9` our set of numbers is `1 2 3 4 5 6 7 8 9` start by removing from the left 2 4 6 8 1 3 5 7 9 then from the right 2 6 4 8 then the left again 6 2 until we end with `6` as the last man standing **Note:** due to the randomness of the tests it is possible that you will get unlucky and a few of the tests will be really large, so try submitting 2 or 3 times. As allways any feedback would be much appreciated
["def last_man_standing(n):\n dir, lst = -1, range(2,n+1,2)\n while len(lst) != 1:\n lst = lst[len(lst)%2 or dir == 1 ::2]\n dir = -dir\n return lst[0]", "from math import log\n\ndef last_man_standing(n):\n return 1 + sum((((n >> i) | (i + 1)) % 2) << i for i in range(int(log(n, 2))))", "def last_man_standing(n):\n arr = list(range(1,n+1))\n while len(arr) > 1:\n odd = []\n for i, j in enumerate(arr):\n if i % 2 == 0:\n continue\n odd.append(j)\n arr = odd[::-1]\n return arr[0]", "def last_man_standing(n):\n l = range(1, n+1)\n while len(l) > 1:\n l = l[1::2][::-1]\n return l[0]", "def last_man_standing(n):\n r = range(1, n + 1)\n while len(r) > 1:\n r = r[1::2][::-1]\n return r[0]", "last_man_standing=l=lambda n:n==1or 2*(n<4)or 4*l(n//4)-2*(n%4<2)", "last_man_standing=l=lambda n, left=True:n == 1 or 2 * l(n // 2, not left) - (not (n % 2 or left))", "def last_man_standing(n):\n l=[]\n l.extend(range(1,n+1))\n \n def doer(t):\n w = []\n return t[1::2]\n \n while len(l) > 1:\n l = doer(l)\n l.reverse()\n return l[0]"]
{"fn_name": "last_man_standing", "inputs": [[9], [10], [100], [1000], [50000]], "outputs": [[6], [8], [54], [510], [22358]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,210
def last_man_standing(n):
1a124f3ee441e907e0e9782794e197d4
UNKNOWN
Write a code that receives an array of numbers or strings, goes one by one through it while taking one value out, leaving one value in, taking, leaving, and back again to the beginning until all values are out. It's like a circle of people who decide that every second person will leave it, until the last person is there. So if the last element of the array is taken, the first element that's still there, will stay. The code returns a new re-arranged array with the taken values by their order. The first value of the initial array is always taken. Examples:
["from collections import deque\n\ndef yes_no(arr):\n d, result = deque(arr), []\n while d:\n result.append(d.popleft())\n d.rotate(-1)\n return result", "def yes_no(arr):\n result = []\n while arr:\n result.append(arr.pop(0))\n if arr:\n arr.append(arr.pop(0))\n return result", "def yes_no(arr):\n result, i = [], 0\n while arr:\n result.extend(arr[i::2])\n j = i != len(arr) % 2\n arr = arr[1-i::2]\n i = j\n return result", "from collections import deque\n\n\ndef yes_no(arr):\n d = deque(reversed(arr))\n result = []\n while d:\n result.append(d.pop())\n d.rotate()\n return result", "def yes_no(arr):\n new = []\n take = True\n while arr:\n if take:\n some = arr.pop(0)\n new.append(some)\n take = False\n else:\n some = arr.pop(0)\n arr.append(some)\n take = True\n return new", "def yes_no(a):\n if len(a)<=1: return a\n a.append(a.pop(1))\n return [a.pop(0)] + yes_no(a)\n", "def yes_no(arr):\n counter = 0\n out = []\n _in = []\n while arr:\n for i in arr:\n if counter % 2 == 0:\n out.append(i)\n else:\n _in.append(i)\n counter += 1\n arr = _in\n _in = []\n return out", "def yes_no(ar, i = 0):\n red = []\n while ar:\n i = [i, i % max(1,len(ar)) ][all((ar, i >= len(ar)))]\n red.append(ar.pop(i))\n i += 1\n return red\n", "def yes_no(arr, x=0):\n if len(arr) <= 1: return arr\n return arr[x::2] + yes_no(arr[1-x::2], x+len(arr)&1)", "def yes_no(arr):\n r = []\n for i in range(0, len(arr) * 2 - 1, 2):\n r.append(arr[i]) # using only append because it is o(1), while remove is o(n)\n if i < len(arr) - 1:\n arr.append(arr[i+1])\n return r"]
{"fn_name": "yes_no", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [["this", "code", "is", "right", "the"]], [[]], [["a"]], [["a", "b"]]], "outputs": [[[1, 3, 5, 7, 9, 2, 6, 10, 8, 4]], [["this", "is", "the", "right", "code"]], [[]], [["a"]], [["a", "b"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,944
def yes_no(arr):
108461bcbfef06eb3f11fd80cec96a49
UNKNOWN
Write a function `take_umbrella()` that takes two arguments: a string representing the current weather and a float representing the chance of rain today. Your function should return `True` or `False` based on the following criteria. * You should take an umbrella if it's currently raining or if it's cloudy and the chance of rain is over `0.20`. * You shouldn't take an umbrella if it's sunny unless it's more likely to rain than not. The options for the current weather are `sunny`, `cloudy`, and `rainy`. For example, `take_umbrella('sunny', 0.40)` should return `False`. As an additional challenge, consider solving this kata using only logical operaters and not using any `if` statements.
["def take_umbrella(weather, rain_chance):\n # Your code here.\n return (weather=='cloudy' and rain_chance>0.20) or weather=='rainy' or (weather=='sunny' and rain_chance>0.5)", "def take_umbrella(weather, rain_chance):\n return rain_chance > {'sunny': 0.5, 'cloudy': 0.2, 'rainy': -1}[weather]", "def take_umbrella(weather, rain_chance):\n # Your code here.\n a = (weather == 'sunny' and rain_chance > 0.5)\n b = (weather == 'rainy')\n c = (weather == 'cloudy' and rain_chance > 0.2)\n return bool(a or b or c)\n", "def take_umbrella(weather, rain_chance):\n return (weather == 'cloudy' and rain_chance > .2) or (weather == 'rainy') or (weather == 'sunny' and rain_chance > .5)", "def take_umbrella(weather, rain_chance):\n return weather == 'rainy' or rain_chance > 0.5 or (weather == 'cloudy' and rain_chance > 0.2)", "def take_umbrella(weather, rain_chance):\n return (weather == 'rainy') or (weather == 'cloudy' and rain_chance > 0.20)\\\n or (rain_chance > 0.50)", "arr = {'sunny': 0.50, 'rainy': -1.0, 'cloudy': 0.20}\n\ndef take_umbrella(weather, rain_chance):\n return rain_chance > arr[weather]", "chance = {\"rainy\":-1, \"cloudy\":0.20, \"sunny\":0.50}\n\ndef take_umbrella(weather, rain_chance):\n return chance[weather] < rain_chance", "def take_umbrella(weather, rain_chance):\n return((weather == \"rainy\")\n or ((rain_chance > 0.2) and (weather == \"cloudy\"))\n or ((rain_chance > 0.5) and (weather == \"sunny\")))\n", "def take_umbrella(weather, rain_chance):\n return { weather == \"rainy\": True, weather == \"cloudy\" and rain_chance > 0.2: True,\n weather == \"sunny\" and rain_chance > 0.5: True}.get(True, False)"]
{"fn_name": "take_umbrella", "inputs": [["sunny", 0.4], ["rainy", 0.0], ["cloudy", 0.2]], "outputs": [[false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,713
def take_umbrella(weather, rain_chance):
e7da92895337b3f65a3c4878fd12236d
UNKNOWN
Write a program that, given a word, computes the scrabble score for that word. ## Letter Values You'll need these: ``` Letter Value A, E, I, O, U, L, N, R, S, T 1 D, G 2 B, C, M, P 3 F, H, V, W, Y 4 K 5 J, X 8 Q, Z 10 ``` ```if:ruby,javascript,cfml There will be a preloaded hashtable `$dict` with all these values: `$dict["E"] == 1`. ``` ```if:haskell There will be a preloaded list of `(Char, Int)` tuples called `dict` with all these values. ``` ```if:python There will be a preloaded dictionary `dict_scores` with all these values: `dict_scores["E"] == 1` ``` ## Examples ``` "cabbage" --> 14 ``` "cabbage" should be scored as worth 14 points: - 3 points for C - 1 point for A, twice - 3 points for B, twice - 2 points for G - 1 point for E And to total: `3 + 2*1 + 2*3 + 2 + 1` = `3 + 2 + 6 + 3` = `14` Empty string should return `0`. The string can contain spaces and letters (upper and lower case), you should calculate the scrabble score only of the letters in that string. ``` "" --> 0 "STREET" --> 6 "st re et" --> 6 "ca bba g e" --> 14 ```
["def scrabble_score(st): \n x = 0\n for y in st:\n if 'a' in y.lower():\n x += 1\n if 'e' in y.lower():\n x += 1\n if 'i' in y.lower():\n x += 1\n if 'o' in y.lower():\n x += 1\n if 'u' in y.lower():\n x += 1\n if 'l' in y.lower():\n x += 1\n if 'n' in y.lower():\n x += 1\n if 'r' in y.lower():\n x += 1\n if 's' in y.lower():\n x += 1\n if 't' in y.lower():\n x += 1\n if 'd' in y.lower():\n x += 2\n if 'g' in y.lower():\n x += 2\n if 'b' in y.lower():\n x += 3\n if 'c' in y.lower():\n x += 3\n if 'm' in y.lower():\n x += 3\n if 'p' in y.lower():\n x += 3\n if 'f' in y.lower():\n x += 4\n if 'h' in y.lower():\n x += 4\n if 'v' in y.lower():\n x += 4\n if 'w' in y.lower():\n x += 4\n if 'y' in y.lower():\n x += 4\n if 'k' in y.lower():\n x += 5\n if 'j' in y.lower():\n x += 8\n if 'x' in y.lower():\n x += 8\n if 'q' in y.lower():\n x += 10\n if 'z' in y.lower():\n x += 10\n return x", "def scrabble_score(st): \n values = {\n **dict.fromkeys(['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'], 1),\n **dict.fromkeys(['D', 'G'], 2),\n **dict.fromkeys(['B', 'C', 'M', 'P'], 3),\n **dict.fromkeys(['F', 'H', 'V', 'W', 'Y'], 4),\n **dict.fromkeys(['K'], 5),\n **dict.fromkeys(['J', 'X'], 8),\n **dict.fromkeys(['Q', 'Z'], 10)}\n \n score = 0\n \n for char in st:\n score += values.get(char.upper(), 0)\n \n return score", "def scrabble_score(st): \n st = st.upper()\n key = {'AEIOULNRST': 1, 'DG': 2, 'BCMP': 3, 'FHVWY': 4, 'K': 5, 'JX': 8, 'QZ': 10}\n score = 0\n for letter in st:\n for string in key.keys():\n if letter in string:\n score += key[string]\n return score", "def scrabble_score(st): \n\n# Define point list as array\n onePt = [\"A\", \"E\", \"I\", \"O\", \"U\", \"L\", \"N\", \"R\", \"S\", \"T\"]\n twoPt = [\"D\", \"G\"]\n threePt = [\"B\", \"C\", \"M\", \"P\"]\n fourPt = [\"F\", \"H\", \"V\", \"W\", \"Y\"]\n fivePt = [\"K\"]\n eightPt = [\"J\", \"X\"]\n tenPt = [\"Q\", \"Z\"]\n\n# set pt as 0\n pt = 0\n\n if len(st) == 0 or st is None: #if array is - or null then return 0\n return 0\n else:\n #reformat input string\n nSt = st.strip()\n nSt = nSt.upper()\n \n #check for every character against point lists \n for char in nSt:\n if char in onePt:\n pt += 1\n continue\n elif char in twoPt:\n pt += 2\n continue\n elif char in threePt:\n pt += 3\n continue\n elif char in fourPt:\n pt += 4\n continue\n elif char in fivePt:\n pt += 5\n continue\n elif char in eightPt:\n pt += 8\n continue\n elif char in tenPt:\n pt += 10\n continue\n \n #return calculated pt\n return pt\n"]
{"fn_name": "scrabble_score", "inputs": [[""], ["a"], ["street"], ["STREET"], [" a"], ["st re et"], ["f"], ["quirky"], ["MULTIBILLIONAIRE"], ["alacrity"]], "outputs": [[0], [1], [6], [6], [1], [6], [4], [22], [20], [13]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,496
def scrabble_score(st):
87278b9516f2b6d147c45c22198d74ed
UNKNOWN
You have n dices each one having s sides numbered from 1 to s. How many outcomes add up to a specified number k? For example if we roll four normal six-sided dices we have four outcomes that add up to 5. (1, 1, 1, 2) (1, 1, 2, 1) (1, 2, 1, 1) (2, 1, 1, 1)
["def outcome(n, s, k): \n if n == 1: return 1 if 0 < k <= s else 0\n return sum(outcome(n - 1, s, k - j - 1) for j in range(s)) if k > 0 else 0", "def outcome(n, s, k):\n return n <= k <= n*s and (n in (1, k) or sum(outcome(n-1, s, k-x-1) for x in range(min(s, k-n+1))))", "def outcome(n, s, k):\n if n == 0:\n return k == 0\n return sum(outcome(n-1, s, k-i) for i in range(1, s+1)) if n <= k <= s * n else 0", "def outcome(n, s, k):\n\n if n * s * k == 0: \n return 0\n \n dp = [[0] * (k + 1) for i in range(n + 1)]\n \n for i in range(1, min(s + 1, k + 1)): \n dp[1][i] = 1\n \n for i in range(2, n + 1): \n for j in range(1, k + 1): \n for l in range(1, min(s + 1, j)): \n dp[i][j] += dp[i - 1][j - l]\n \n return dp.pop().pop()", "from itertools import product\n\ndef outcome(n, s, k):\n return sum(1 for roll in product(range(1, s + 1), repeat=n) if sum(roll) == k) ", "def outcome(n, s, k):\n from itertools import zip_longest\n dice = [1]\n for _ in range(n):\n dice = [sum(x) for x in zip_longest(*([0] * i + dice for i in range(1, s+1)), fillvalue=0)]\n return dice[k] if k < len(dice) else 0\n\n", "def outcome(n, s, k):\n return 0 < k <= s if n == 1 else sum(outcome(n-1, s, k-v) for v in range(1, min(k-(n-1),s)+1) if k-v > 0)", "from itertools import product\ndef outcome(n, s, k):\n return sum(sum(x) == k for x in product(range(1, s + 1), repeat=n))", "outcome=o=lambda n,s,k:s>=k>0if n==1else sum(o(n-1,s,k-i-1)for i in range(min(s,k)))", "from itertools import product\n\ndef outcome(n, s, k):\n return sum( sum(p) == k for p in product(range(1, s+1), repeat=n) )"]
{"fn_name": "outcome", "inputs": [[1, 6, 0], [1, 0, 1], [0, 6, 1], [1, 6, 1], [1, 6, 2], [1, 6, 3], [1, 6, 4], [1, 6, 5], [1, 6, 6], [1, 6, 7], [2, 6, 1], [2, 6, 2], [2, 6, 3], [2, 6, 4], [2, 6, 5], [2, 6, 6], [2, 6, 7], [2, 6, 8], [2, 6, 9], [2, 6, 10], [2, 6, 11], [2, 6, 12], [2, 6, 13], [3, 6, 6], [3, 6, 9], [3, 6, 10], [3, 6, 11], [3, 6, 12], [3, 6, 15], [4, 6, 5], [3, 100, 100], [6, 10, 27], [5, 10, 27], [4, 10, 27], [10, 5, 13], [8, 8, 80]], "outputs": [[0], [0], [0], [1], [1], [1], [1], [1], [1], [0], [0], [1], [2], [3], [4], [5], [6], [5], [4], [3], [2], [1], [0], [10], [25], [27], [27], [25], [10], [4], [4851], [39662], [6000], [480], [220], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,715
def outcome(n, s, k):
d78ce9bb1a42d59a93eed90d3a63da0b
UNKNOWN
# One is the loneliest number ## Task The range of vision of a digit is its own value. `1` can see one digit to the left and one digit to the right,` 2` can see two digits, and so on. Thus, the loneliness of a digit `N` is the sum of the digits which it can see. Given a non-negative integer, your funtion must determine if there's at least one digit `1` in this integer such that its loneliness value is minimal. ## Example ``` number = 34315 ``` digit | can see on the left | can see on the right | loneliness --- | --- | --- | --- 3 | - | 431 | 4 + 3 + 1 = 8 4 | 3 | 315 | 3 + 3 + 1 + 5 = 12 3 | 34 | 15 | 3 + 4 + 1 + 5 = 13 1 | 3 | 5 | 3 + 5 = 8 5 | 3431 | - | 3 + 4 + 3 + 1 = 11 Is there a `1` for which the loneliness is minimal? Yes.
["def loneliest(n):\n a = list(map(int, str(n)))\n b = [(sum(a[max(0, i - x):i+x+1]) - x, x) for i, x in enumerate(a)]\n return (min(b)[0], 1) in b", "def loneliest(n): \n def loneliness(it):\n i,v = it\n return sum(lst[max(0,i-v):i+v+1])-v, abs(v-1)\n \n lst = list(map(int,str(n)))\n return 1 in lst and 1==min(enumerate(lst), key=loneliness)[1]", "def loneliest(number):\n # Make a list of digits from the given number\n digits = []\n while number:\n number, rem = divmod(number, 10)\n digits.append(rem)\n\n lowest = one = float('inf')\n\n for i, d in enumerate(digits):\n # Calculate the range of vision for each digit\n s = sum(digits[max(0, i - d):i + d + 1]) - d\n\n # Update the minimums for digit 1 or the others\n if d == 1:\n one = min(one, s)\n else:\n lowest = min(lowest, s)\n\n # Check if 1 is the loneliest number and check if digit 1 was even in the number\n return one <= lowest and one != float('inf')\n", "def loneliest(number):\n ints = [int(n) for n in str(number)]\n scores = [(sum(ints[max(0, i-d):i+d+1]) - d, d)\n for i, d in enumerate(ints)]\n return (min(scores)[0], 1) in scores ", "def loneliest(number): \n seq = list(map(int,str(number)))\n temp = 0\n ans = 100\n ans1 = 100\n key = 0\n x = 0\n if seq.count(1) == 0:\n return False\n for i in seq:\n temp = sum(seq[x+1:x+i+1]) + sum(seq[x-i if x>i else 0:x])\n if i == 1 :\n if temp < ans1 :\n ans1 = temp\n else:\n if temp < ans :\n ans = temp\n x += 1\n if ans1 <= ans:\n return True\n else:\n return False", "def loneliest(number): \n numbers = [int(c) for c in str(number)]\n loneliness = [(n, sum(numbers[max(i-n, 0):i]) + sum(numbers[i+1:i+1+n])) for i, n in enumerate(numbers)]\n onesLoneliness = [p[1] for p in loneliness if p[0] == 1]\n if (not onesLoneliness) : return False\n otherLoneliness = [p[1] for p in loneliness if not p[0] == 1]\n if (not otherLoneliness): return True\n return min(otherLoneliness) >= min(onesLoneliness)", "def loneliest(number):\n xs = [int(c) for c in str(number)]\n d = {i: sum(xs[max(i-x, 0):i] + xs[i+1:i+1+x]) for i, x in enumerate(xs)}\n m = min(d.values())\n return any(xs[i] == 1 and d[i] == m for i in d)", "def left(num, n, i):\n s = 0\n counter = 0\n index = i-1\n while index >= 0 and counter < n:\n s += int(num[index])\n index -= 1\n counter += 1\n return s\n \ndef right(num, n, i):\n s = 0\n counter = n\n index = i+1\n while index < len(num) and counter:\n s += int(num[index])\n index += 1\n counter -= 1\n return s\n\ndef _sum(num, n, i):\n return left(num, n, i) + right(num, n, i)\n\ndef compare(one, others):\n for other in others:\n if one > other:\n return False\n return True\n\ndef check(ones, others):\n for one in ones:\n yield compare(one, others)\n\ndef loneliest(number): \n num = str(number)\n if not '1' in num:\n return False\n ones = []\n others = []\n for i in range(len(num)):\n s = _sum(num, int(num[i]), i)\n print()\n if num[i] == '1':\n ones.append(s)\n else:\n others.append(s)\n \n #print(num, ones, others)\n return any(list(check(ones, others)))", "def calculate_loneliness(s, ind):\n rng = int(s[ind])\n if ind - rng < 0:\n res_str = s[: ind] + s[ind + 1:ind + rng + 1]\n return sum([int(char) for char in res_str])\n res_str = s[ind - rng: ind] + s[ind + 1:ind + rng + 1]\n return sum([int(char) for char in res_str])\n\n\ndef loneliest(n):\n s = str(n)\n if '1' not in s:\n return False\n lone_list = []\n lst = []\n for i in range(len(s)):\n lone_list.append(calculate_loneliness(s, i))\n lst.append(int(s[i]))\n min_1 = lone_list[s.find('1')]\n for i in range(len(lone_list)):\n if lst[i] == 1:\n if lone_list[i] < min_1:\n min_1 = lone_list[i]\n \n if min(lone_list) == min_1:\n return True\n return False", "def loneliest(number):\n if (str(number)).count(\"1\")==0:\n return False\n if (str(number)).count(\"1\")==len(str(number)):\n return True\n \n number=[int(a) for a in str(number)]\n score=[]\n one=[]\n for idx,nr in enumerate(number):\n \n b = idx-nr\n f = idx+nr+1\n s=0\n \n if b<0: b=0\n if f>len(number): f=len(number)\n \n s+=sum(number[b:idx])\n s+=sum(number[idx+1:f])\n \n if nr==1: one.append(s)\n else: score.append(s)\n\n score.sort()\n one.sort()\n if score[0]>=one[0]:\n return True\n return False"]
{"fn_name": "loneliest", "inputs": [[34315], [123456], [8854778], [65432165432], [0], [1], [11111]], "outputs": [[true], [true], [false], [false], [false], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,954
def loneliest(number):
5adadc32eb4238b864213a287c24893f
UNKNOWN
Many years ago, Roman numbers were defined by only `4` digits: `I, V, X, L`, which represented `1, 5, 10, 50`. These were the only digits used. The value of a sequence was simply the sum of digits in it. For instance: ``` IV = VI = 6 IX = XI = 11 XXL = LXX = XLX = 70 ``` It is easy to see that this system is ambiguous, and some numbers could be written in many different ways. Your goal is to determine how many distinct integers could be represented by exactly `n` Roman digits grouped together. For instance: ```Perl solve(1) = 4, because groups of 1 are [I, V, X, L]. solve(2) = 10, because the groups of 2 are [II, VI, VV, XI, XV, XX, IL, VL, XL, LL] corresponding to [2,6,10,11,15,20,51,55,60,100]. solve(3) = 20, because groups of 3 start with [III, IIV, IVV, ...etc] ``` `n <= 10E7` More examples in test cases. Good luck!
["INITIAL = [0, 4, 10, 20, 35, 56, 83, 116, 155, 198, 244, 292]\n\ndef solve(n):\n return INITIAL[n] if n < 12 else 292 + (49 * (n-11))", "from functools import lru_cache\n\nDIGITS = [1, 5, 10, 50]\nTHRESHOLD = 12\n\ndef solve_naive (n):\n minimal = n * min(DIGITS)\n maximal = n * max(DIGITS)\n return maximal - minimal\n\n@lru_cache(maxsize=THRESHOLD)\ndef solve_brute (n):\n from itertools import product\n combinations = product(DIGITS, repeat=n)\n values = list(map(sum, combinations))\n return len(set(values))\n\n@lru_cache(maxsize=THRESHOLD)\ndef determine_delta (tries):\n deltas = (solve_naive(n) - solve_brute(n)\n for n in range(1, tries+1))\n return max(deltas)\n\ndef solve (n):\n if n > THRESHOLD:\n return solve_naive(n) - determine_delta(THRESHOLD)\n return solve_brute(n)\n", "def solve(n):\n if n<=10:\n return [0,4,10,20,35,56,83,116,155,198,244][n]\n else:\n return 292+49*(n-11)", "basics = [0, 4, 10, 20, 35, 56, 83, 116, 155, 198, 244, 292]\n\ndef solve(n):\n return basics[n] if n < 12 else 49*n - 247", "def solve(n):\n c = 0\n for i in range(min(8,n)+1):\n for j in range(min(4 if i!=0 else 8,n-i)+1):\n c += n-i-j+1\n return c", "OPTIONS = [1, 5, 10, 50]\n\ndef solve(n):\n print(n)\n base_answer = len(rec_solve(min(n, 11)))\n \n if n < 12:\n return base_answer\n else:\n # Past 11, is just the previous answer + 49 \n return base_answer + (49*(n-11))\n\ndef rec_solve(n, options=4, val=0):\n # My original solution; solves based on cases of 1 option,\n # 1 character, and recursive case\n if n == 1:\n return_set = set()\n for i in range(1, options + 1):\n return_set.add(val + OPTIONS[-i])\n return return_set\n\n elif options == 1:\n return {val + 50*n}\n\n return_set = set()\n for option_num in range(options, 0, -1):\n return_set = return_set.union(rec_solve(n - 1, option_num, \\\n val + OPTIONS[-option_num]))\n return return_set\n", "e = [0, 4, 10, 20, 35, 56, 83, 116, 155, 198, 244, 292]\n\ndef solve(n):\n return e[n] if n < 12 else 292 + (49 * (n-11))", "def solve(n):\n 'We have a regular progression from 11 on'\n return 292+(n-11)*49 if n>10 else len(set(n-v-x-l+v*5+x*10+l*50 for l in range(n+1) for x in range(n+1-l) for v in range(n+1-l-x)))\n \n\n", "def solve(n):\n m = {1:4,2:10, 3:20, 4:35, 5:56, 6:83, 7:116, 8:155, 9:198, 10:244, 11:292, 12:341}\n if n <= 12:\n return m[n]\n else:\n return m[12]+49*(n-12)\n\n", "STARTERS = 0, 4, 10, 20, 35, 56, 83, 116, 155, 198, 244\n\ndef solve(n):\n return STARTERS[n] if n < 11 else 292 + 49 * (n - 11)"]
{"fn_name": "solve", "inputs": [[1], [2], [3], [4], [5], [6], [10], [10000000]], "outputs": [[4], [10], [20], [35], [56], [83], [244], [489999753]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,724
def solve(n):
78fd814c01ab6a8ac4fd329b77e4e984
UNKNOWN
There are just some things you can't do on television. In this case, you've just come back from having a "delicious" Barth burger and you're set to give an interview. The Barth burger has made you queezy, and you've forgotten some of the import rules of the "You Can't Do That on Television" set. If you say any of the following words a large bucket of "water" will be dumped on you: "water", "wet", "wash" This is true for any form of those words, like "washing", "watered", etc. If you say any of the following phrases you will be doused in "slime": "I don't know", "slime" If you say both in one sentence, a combination of water and slime, "sludge", will be dumped on you. Write a function, bucketOf(str), that takes a string and determines what will be dumped on your head. If you haven't said anything you shouldn't have, the bucket should be filled with "air". The words should be tested regardless of case. Examples: Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
["import re\n\nWATER_PATTERN = re.compile(r\"water|wet|wash\", re.I)\nSLIME_PATTERN = re.compile(r\"\\bI don't know\\b|slime\", re.I)\n\n\ndef bucket_of(said):\n water = WATER_PATTERN.search(said)\n slime = SLIME_PATTERN.search(said)\n\n if water:\n return 'sludge' if slime else 'water'\n\n return 'slime' if slime else 'air'\n", "def bucket_of(said):\n said = said.lower()\n forgiven_words = lambda *words: any(w in said for w in words)\n water = forgiven_words(\"water\", \"wet\", \"wash\")\n slime = forgiven_words(\"i don't know\", \"slime\")\n return [\"air\", \"water\", \"slime\", \"sludge\"][2*slime + water]", "import re\n\nwater = re.compile('water|wet|wash', flags=re.I)\nslime = re.compile(\"slime|i don't know\", flags=re.I)\n\ndef bucket_of(said):\n w = water.search(said)\n s = slime.search(said)\n if w and s:\n return 'sludge'\n elif w:\n return 'water'\n elif s:\n return 'slime'\n else:\n return 'air'", "def bucket_of(said):\n s, l = said.lower(), [\"air\",\"water\",\"slime\",\"sludge\"] \n return l[any([\"wet\" in s, \"water\" in s, \"wash\" in s])+any([\"know\" in s, \"slime\" in s])*2]", "import re\ndef bucket_of(said):\n pattern1 = r\"water|wet|wash\"\n pattern2 = r\"slime|i don't know\" \n result1 = re.search(pattern1, said, re.I)\n result2 = re.search(pattern2, said, re.I)\n if result1 and result2:\n return \"sludge\"\n elif result1:\n return \"water\" \n elif result2:\n return \"slime\"\n else: \n return \"air\"\n \n \n \n", "def bucket_of(said):\n teststring = said.lower()\n result = []\n \n water = [\"water\", \"wet\", \"wash\"]\n slime = [\"i don't know\", \"slime\"]\n \n for i in range(len(water)):\n if (water[i] in teststring):\n result.append(\"water\")\n else:\n continue\n \n for i in range(len(slime)):\n if (slime[i] in teststring):\n result.append(\"slime\")\n else:\n continue\n \n if ((\"water\" in result) and (\"slime\" in result)):\n return \"sludge\"\n elif (\"water\" in result):\n return \"water\"\n elif (\"slime\" in result):\n return \"slime\"\n else:\n return \"air\"", "import re\nbucket_of = lambda said: \\\n ({ 0: 'air', 1: 'water', 2: 'slime', 3: 'sludge' }) \\\n [bool(re.search('(?i)(water|wet|wash)', said)) + bool(re.search('(?i)(I don\\'t know|slime)', said)) * 2]", "def bucket_of(said):\n water_list, slime_list = ['water', 'wet', 'wash'], ['i don\\'t know', 'slime']\n \n s = said.lower()\n \n water = any(w in s for w in water_list)\n slime = any(sl in s for sl in slime_list)\n \n return 'sludge' if water and slime else 'water' if water else 'slime' if slime else 'air'", "bucket_of=lambda s:['air','water','slime','sludge'][(lambda x:('wet'in x or'water'in x or'wash'in x)+(\"i don't know\"in x or'slime'in x)*2)(s.lower())]", "def bucket_of(said):\n s = said.lower()\n \n if \"slime\" in s and \"water\" not in s:\n return \"slime\"\n \n elif \"i don't know\" in s:\n if \"water\" in s:\n return \"sludge\"\n return \"slime\"\n \n elif \"water\" in s or \"wet\" in s or \"wash\" in s:\n if \"slime\" in s:\n return \"sludge\"\n if \"i don't know\" in s:\n return \"slime\"\n return \"water\"\n \n return \"air\" \n"]
{"fn_name": "bucket_of", "inputs": [["water"], ["wet"], ["wash"], ["i don't know"], ["slime"], ["wet water"], ["slime water"], ["I don't know if this will work"], ["I don't know if this will work without watering it first."], [""], ["is there SLIME in that?!"], ["i won't say anything"], ["WaTeR?"], ["but i can say sludge?"], ["i'm just going to wash my hands of this"], ["you know what, i don't know what was in that Barth burger"], ["slimeslimeslimeslimewater"], ["air"], ["w-w-w-w-wet!"], ["wat errrr i mean.. nothing"], ["sludge"]], "outputs": [["water"], ["water"], ["water"], ["slime"], ["slime"], ["water"], ["sludge"], ["slime"], ["sludge"], ["air"], ["slime"], ["air"], ["water"], ["air"], ["water"], ["slime"], ["sludge"], ["air"], ["water"], ["air"], ["air"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,556
def bucket_of(said):
9b45b2d4440d5bfe137bcffcce871e67
UNKNOWN
# Introduction You are the developer working on a website which features a large counter on its homepage, proudly displaying the number of happy customers who have downloaded your companies software. You have been tasked with adding an effect to this counter to make it more interesting. Instead of just displaying the count value immediatley when the page loads, we want to create the effect of each digit cycling through its preceding numbers before stopping on the actual value. # Task As a step towards achieving this; you have decided to create a function that will produce a multi-dimensional array out of the hit count value. Each inner dimension of the array represents an individual digit in the hit count, and will include all numbers that come before it, going back to 0. ## Rules * The function will take one argument which will be a four character `string` representing hit count * The function must return a multi-dimensional array containing four inner arrays * The final value in each inner array must be the actual value to be displayed * Values returned in the array must be of the type `number` **Examples**
["def counter_effect(hit_count):\n return [[i for i in range(int(hit_count[x]) + 1)] for x in range(4)]", "def counter_effect(n):\n return [list(range(int(x)+1)) for x in n]", "def counter_effect(hit):\n b = []\n for i in str(hit):\n a = []\n for k in range(int(i)+1):\n a.append(k)\n b.append(a)\n return b", "def counter_effect(hit_count):\n return [list(range(int(s) + 1)) for s in hit_count]\n", "def counter_effect(hit_count):\n return [[i for i in range(int(x)+1)] for x in hit_count]"]
{"fn_name": "counter_effect", "inputs": [["1250"], ["0050"], ["0000"]], "outputs": [[[[0, 1], [0, 1, 2], [0, 1, 2, 3, 4, 5], [0]]], [[[0], [0], [0, 1, 2, 3, 4, 5], [0]]], [[[0], [0], [0], [0]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
545
def counter_effect(hit_count):
9dc40b73201dbcb571136d54a4fad4cb
UNKNOWN
**Step 1:** Create a function called `encode()` to replace all the lowercase vowels in a given string with numbers according to the following pattern: ``` a -> 1 e -> 2 i -> 3 o -> 4 u -> 5 ``` For example, `encode("hello")` would return `"h2ll4"`. There is no need to worry about uppercase vowels in this kata. **Step 2:** Now create a function called `decode()` to turn the numbers back into vowels according to the same pattern shown above. For example, `decode("h3 th2r2")` would return `"hi there"`. For the sake of simplicity, you can assume that any numbers passed into the function will correspond to vowels.
["def encode(s, t=str.maketrans(\"aeiou\", \"12345\")):\n return s.translate(t)\n \ndef decode(s, t=str.maketrans(\"12345\", \"aeiou\")):\n return s.translate(t)", "CIPHER = (\"aeiou\", \"12345\")\n\ndef encode(st):\n return st.translate(str.maketrans(CIPHER[0], CIPHER[1]))\n \ndef decode(st):\n return st.translate(str.maketrans(CIPHER[1], CIPHER[0]))", "def encode(st):\n for i, v in enumerate(\"aeiou\", start=1):\n st = st.replace(v,str(i))\n return st\n \ndef decode(st):\n for i, v in enumerate(\"aeiou\", start=1):\n st = st.replace(str(i),v)\n return st", "tbl1 = str.maketrans(\"aeiou\", \"12345\")\ntbl2 = str.maketrans(\"12345\", \"aeiou\")\n\n\ndef encode(st):\n return st.translate(tbl1)\n\n\ndef decode(st):\n return st.translate(tbl2)", "a={'a':'1','e':'2','i':'3','o':'4','u':'5'}\nb=('a','e','i','o','u')\ndef encode(st):\n return \"\".join(a[c] if c in a else c for c in st)\n \ndef decode(st):\n return \"\".join(b[int(c)-1] if c.isdigit() else c for c in st)", "def cipher(mode):\n table = str.maketrans(*['aeiou', '12345'][::mode])\n return lambda s: s.translate(table)\n\nencode, decode = cipher(1), cipher(-1)", "CYPHER = tuple(zip('aeiou', '12345'))\n\ndef munge(st, mapping):\n return ''.join([mapping.get(c, c) for c in st])\n\ndef encode(st):\n return munge(st, {a: b for a, b in CYPHER})\n \ndef decode(st):\n return munge(st, {b: a for a, b in CYPHER})\n", "def encode(st):\n L=[]\n A = {\"a\":\"1\",\"e\":\"2\",\"i\":\"3\",\"o\":\"4\",\"u\":\"5\"}\n for i in st:\n if i in A:\n L.append(A[i])\n else:\n L.append(i)\n return \"\".join(L)\n \ndef decode(st):\n L=[]\n A = {\"1\":\"a\",\"2\":\"e\",\"3\":\"i\",\"4\":\"o\",\"5\":\"u\"}\n for i in st:\n if i in A:\n L.append(A[i])\n else:\n L.append(i)\n return \"\".join(L)", "import re\ndef encode(st):\n vowel = ' aeiou'\n return re.sub(r'[aeoui]', lambda x: str(vowel.index(x.group(0))) ,st)\n \ndef decode(st):\n vowel = ' aeiou'\n return re.sub(r'[1-5]', lambda x: vowel[int(x.group(0))] ,st)\n", "a = [\"a\",\"e\",\"i\",\"o\",\"u\"]\ndef encode(st):\n return \"\".join([str(a.index(c) + 1) if c in a else c for c in st])\ndef decode(st):\n return \"\".join([a[int(c)-1] if c.isdigit() else c for c in st])"]
{"fn_name": "encode", "inputs": [["hello"], ["How are you today?"], ["This is an encoding test."]], "outputs": [["h2ll4"], ["H4w 1r2 y45 t4d1y?"], ["Th3s 3s 1n 2nc4d3ng t2st."]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,392
def encode(st):
5ada4c8084a3198ca45905a4e0134434
UNKNOWN
Given an array of integers, return the smallest common factors of all integers in the array. When i say **Smallest Common Factor** i mean the smallest number above 1 that can divide all numbers in the array without a remainder. If there are no common factors above 1, return 1 (technically 1 is always a common factor).
["def scf(lst):\n return next((k for k in range(2, 1 + min(lst, default=1)) if all(n % k == 0 for n in lst)), 1)\n", "from functools import reduce\nfrom math import floor, gcd, sqrt\n\ndef smallest_factor(n):\n return next((d for d in range(2, floor(sqrt(n)) + 1) if n % d == 0), n)\n\ndef scf(nums):\n return 1 if nums == [] else smallest_factor(reduce(gcd, nums))", "def scf(arr):\n factors_list = []\n dict = {}\n min_list = []\n for element in arr: \n for factor in range(1, element + 1):\n if element % factor == 0:\n factors_list.append(factor) \n for factor in factors_list:\n if factor in dict and factor != 1:\n dict[factor] += 1\n else:\n dict[factor] = 1\n for factor in factors_list:\n if dict[factor] == len(arr):\n min_list.append(factor) \n if min_list != []:\n return min_list[0]\n else:\n return 1", "def scf(lst):\n for k in range(2, min(lst, default=1) + 1):\n if all(n % k == 0 for n in lst):\n return k\n return 1", "def scf (arr):\n print(arr)\n if arr == []:\n return 1\n ret = []\n for j in arr:\n for i in range(1, int(j**0.5)+1):\n if j%i == 0:\n ret.append(i)\n ret.append(j//i)\n if len(ret) == len(arr)*2:\n return 1\n print(ret)\n ret1 = []\n for k in set(ret):\n if ret.count(k) >= len(arr) and k != 1:\n ret1.append(k)\n if ret1 == []:\n return 1\n else:\n return min(ret1)", "def scf (arr): ##\n return next((i for i in range(2, min(arr, default=1)+1)if all(x%i==0 for x in arr)),1)", "def scf (arr):\n div, all_div, diz=[], [], {}\n for x in arr:\n for i in range(2, x+1):\n if not x%i:\n div.append(i)\n diz[x]=div\n all_div.extend(div)\n div=[]\n all_div=sorted(set(all_div))\n return next((x for x in all_div if all(x in diz[it] for it in diz)),1)", "def scf(arr):\n return next((i for i in range(2,min(arr)+1) if all(v%i==0 for v in arr)),1) if arr else 1", "from math import gcd, sqrt\nfrom functools import reduce\n\ndef scf(xs):\n try:\n d = reduce(gcd, xs)\n except TypeError:\n return 1\n else:\n return next((i for i in range(2, int(sqrt(d)) + 1) if d % i == 0), d)", "def scf(xs):\n return next((i for i in range(2, min(xs, default=1) + 1) if all(x % i == 0 for x in xs)), 1)"]
{"fn_name": "scf", "inputs": [[[200, 30, 18, 8, 64, 34]], [[21, 45, 51, 27, 33]], [[133, 147, 427, 266]], [[3, 5, 7]], [[]]], "outputs": [[2], [3], [7], [1], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,523
def scf(lst):
068469bbf3cd1650a67e2b6ec0276db0
UNKNOWN
# Task Timed Reading is an educational tool used in many schools to improve and advance reading skills. A young elementary student has just finished his very first timed reading exercise. Unfortunately he's not a very good reader yet, so whenever he encountered a word longer than maxLength, he simply skipped it and read on. Help the teacher figure out how many words the boy has read by calculating the number of words in the text he has read, no longer than maxLength. Formally, a word is a substring consisting of English letters, such that characters to the left of the leftmost letter and to the right of the rightmost letter are not letters. # Example For `maxLength = 4` and `text = "The Fox asked the stork, 'How is the soup?'"`, the output should be `7` The boy has read the following words: `"The", "Fox", "the", "How", "is", "the", "soup".` # Input/Output - `[input]` integer `maxLength` A positive integer, the maximum length of the word the boy can read. Constraints: `1 ≤ maxLength ≤ 10.` - `[input]` string `text` A non-empty string of English letters and punctuation marks. - `[output]` an integer The number of words the boy has read.
["import re\ndef timed_reading(max_length, text):\n return sum(len(i) <= max_length for i in re.findall('\\w+', text))", "def timed_reading(max_length, text):\n count = 0\n for punctuation_mark in '!.,?\\'\\\"_-)(':\n text = text.replace(punctuation_mark , '')\n listed_text = text.split(\" \")\n\n for word in listed_text:\n if len(word) <= max_length and len(word) > 0 :\n count+= 1\n return count\n\nprint(timed_reading(4,\"The Fox asked the stork, 'How is the soup?'\"))", "import re\n\ndef timed_reading(max_length, text):\n return sum( len(m.group()) <= max_length for m in re.finditer(r'\\w+', text))", "import re\ndef timed_reading(max_length, text):\n return len(re.findall(r'\\b\\w{1,%s}\\b' % str(max_length), text)) if max_length>=2 else 0", "timed_reading=lambda m,t:len([e for e in __import__('re').findall('\\w+',t)if len(e)<=m])", "import string\n\ndef timed_reading(max_length, text):\n return len(list([x for x in text.split() if 1 <= len(x.strip(string.punctuation)) <= max_length]))", "def timed_reading(max_l, text):\n string = text.translate(str.maketrans('`~!@\\'\\\"#\u2116$;%:^&?*()-_+=/\\[]{}', ' '))\n return sum(map(lambda x: len(x) <= max_l, (i for i in string.split() if i)))", "def timed_reading(max_length, text):\n return sum([1 for w in text.split() if 0 < len(''.join(filter(str.isalpha, w))) <= max_length])", "import re\ndef timed_reading(max_length, text):\n text = re.sub(r'[^\\w\\s]','',text)\n cnt = 0\n for words in text.split():\n if len(words) <= max_length:\n cnt += 1\n\n return cnt;", "from re import sub\ndef timed_reading(max_length, text):\n return sum(len(word)<=max_length for word in sub(\"[^a-zA-Z ]*\",\"\",text).split())"]
{"fn_name": "timed_reading", "inputs": [[4, "The Fox asked the stork, 'How is the soup?'"], [1, "..."], [3, "This play was good for us."], [3, "Suddenly he stopped, and glanced up at the houses"], [6, "Zebras evolved among the Old World horses within the last four million years."], [5, "Although zebra species may have overlapping ranges, they do not interbreed."], [1, "Oh!"], [5, "Now and then, however, he is horribly thoughtless, and seems to take a real delight in giving me pain."]], "outputs": [[7], [0], [3], [5], [11], [6], [0], [14]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,799
def timed_reading(max_length, text):
97b0d4b1ad9c9a7ad48e6796ff4f94db
UNKNOWN
This kata is all about adding numbers. You will create a function named add. This function will return the sum of all the arguments. Sounds easy, doesn't it?? Well here's the twist. The inputs will gradually increase with their index as parameter to the function. ```python add(3,4,5) #returns (3*1)+(4*2)+(5*3)=26 ``` Remember the function will return 0 if no arguments are passed. ## Example ```python add() #=> 0 add(1,2,3) #=> 14 add(1,4,-5,5) #=> 14 ```
["def add(*args):\n return sum((i+1)*v for i,v in enumerate(args))", "def add(*args):\n return sum(n * i for i, n in enumerate(args, 1))", "def add(*args):\n return sum(i * x for i, x in enumerate(args, 1))", "def add(*args):\n return sum(pos * value for pos, value in enumerate(args, 1))\n", "def add(*args):\n return sum((i + 1) * n for i, n in enumerate(args))", "def add(*args):\n return sum((i+1) * args[i] for i in range(len(args)))", "add = lambda *args: sum(i * a for i, a in enumerate(args, start=1))\n", "add=lambda *args: sum(i*v for i,v in enumerate(args, 1))", "def add(*args):\n return sum(n*(i+1) for i,n in enumerate(args)) if args else 0"]
{"fn_name": "add", "inputs": [[100, 200, 300], [2], [4, -3, -2], [-1, -2, -3, -4]], "outputs": [[1400], [2], [-8], [-30]]}
INTRODUCTORY
PYTHON3
CODEWARS
677
def add(*args):
02f28df6714ff61671f3ed45f8704bdc
UNKNOWN
In the following 6 digit number: ``` 283910 ``` `91` is the greatest sequence of 2 consecutive digits. In the following 10 digit number: ``` 1234567890 ``` `67890` is the greatest sequence of 5 consecutive digits. Complete the solution so that it returns the greatest sequence of five consecutive digits found within the number given. The number will be passed in as a string of only digits. It should return a five digit integer. The number passed may be as large as 1000 digits. *Adapted from ProjectEuler.net*
["def solution(digits):\n numlist = [int(digits[i:i+5]) for i in range(0,len(digits)-4)]\n return max(numlist)", "def solution(digits):\n return int(max(digits[a:a + 5] for a in range(len(digits) - 4)))", "def solution(digits):\n result = -1;\n for i in range(len(digits)):\n current = int(digits[i: i+5])\n if current >= result:\n result = current\n return result", "def solution(digits):\n maxNum = 0\n for i in range(len(digits)-4):\n curNum = int(digits[i:i+5])\n if curNum > maxNum:\n maxNum = curNum\n return maxNum", "def solution(digits):\n cc = []\n for i in range(len(digits)):\n cc.append(digits[i:i+5])\n return int(max(cc))", "def solution(digits):\n mx = 0\n for i in range(len(digits) - 4):\n n = int(digits[i:i + 5])\n if n > mx:\n mx = n\n return mx", "def solution(digits):\n return int(max(''.join(digits[n:n + 5]) for n in range(len(digits) - 4)))\n", "def solution(digits):\n final = 0\n stg = str(digits)\n for (num1, num2) in enumerate(stg):\n try:\n if int(str(stg[num1]) + str(stg[num1+1])) > final:\n final = int(str(stg[num1]) + str(stg[num1+1]))\n if int(str(stg[num1]) + str(stg[num1 + 1]) + str(stg[num1 + 2])) > final:\n final = int(str(stg[num1]) + str(stg[num1 + 1]) + str(stg[num1 + 2]))\n if int(str(stg[num1]) + str(stg[num1 + 1]) + str(stg[num1 + 2]) + str(stg[num1 + 3])) > final:\n final = int(str(stg[num1]) + str(stg[num1 + 1]) + str(stg[num1 + 2]) + str(stg[num1 + 3]))\n if int(str(stg[num1]) + str(stg[num1 + 1]) + str(stg[num1 + 2]) + str(stg[num1 + 3]) + str(stg[num1 + 4])) > final:\n final = int(str(stg[num1]) + str(stg[num1 + 1]) + str(stg[num1 + 2]) + str(stg[num1 + 3]) + str(stg[num1 + 4]))\n \n except:\n pass\n return final", "from itertools import islice\ndef solution(digits):\n return int(max(map(''.join, zip(*(islice(digits, a, None) for a in range(5))))))", "def solution(d):\n return int(max([d[j:j+5]] for j in [i for i in range(len(d)) if d[i]==max(d)])[0])\n", "def solution(digits):\n result = -1\n for i in range(len(digits)): # for each digit in the range of the digits (= without starting over, it will start and only go untill the last number, then no more checks)\n # new number, starting one plus up to 4 next (index and untill index+5)\n current = int(digits[i: i+5])\n # if new number is higher than a previous check, it's a new result (check starts as -1, so every FIRST check is the new result)\n if current >= result:\n result = current # it will loop untill the next check isn't higher; then it finishes and returns the result\n return result", "def solution(digits):\n a = []\n for i in range(len(digits)-4):\n a.append(give5LengthNumber(digits[i:]))\n return(int(max(a)))\n \ndef give5LengthNumber(num):\n return num[0:5]", "def solution(digits):\n mnum = 0\n for i in range(5,len(digits)):\n for j in range(i, len(digits)+1):\n if int(digits[j-5:j])>mnum:\n mnum = int(digits[j-5:j])\n return mnum\n", "def solution(digits):\n largest = 0\n for i in range(len(digits)-4):\n a = int(digits[i:i+5])\n if (a > largest):\n largest = a\n return largest;", "def solution(digits):\n return max(int(digits[i - 5: i]) for i, _ in enumerate(digits, 5))", "def solution(d):\n for x in '9876543210':\n for y in '9876543210':\n for z in '9876543210':\n for w in '9876543210':\n for q in '9876543210':\n if d.find(x + y + z + w + q) != -1:\n return int(x + y + z + w + q)", "def solution(x):\n v = 99999\n while v > 0:\n if str(v) in str(x):\n return v\n v = v - 1", "def solution(digits):\n max = 99999\n while True:\n if str(max) in digits:\n return max\n else:\n max -= 1\n \n return 0;", "def solution(digits):\n ans = []\n for i in range(0, len(digits)-4):\n ans.append(int(digits[i:i+5]))\n return max(ans)\n", "def solution(s):\n result = [i for i in s]\n new = []\n for i in range(0,len(result),1):\n new.append(result[i:i+5])\n\n Lnumber = int(''.join(map(str,max(new))))\n return Lnumber\n\n\n", "def solution(digits):\n maxdi = 0\n for i in range(len(digits)-4):\n each5 = int(digits[i:i+5])\n if each5 > maxdi:\n maxdi = each5\n return maxdi", "def solution(digits):\n number_string = str(digits)\n \n sequence_list = []\n \n for i in range(len(number_string) - 4):\n \n five_sequence = number_string[i:i+5]\n \n if int(five_sequence) > int(number_string[i+1:i+6]):\n sequence_list.append(int(five_sequence))\n \n return max(sequence_list)\n", "def solution(digits):\n maxi = 0\n for i in range(len(digits) - 4):\n if int(digits[i:i+5]) > maxi:\n maxi = int(digits[i:i+5])\n return maxi", "def solution(digits):\n result = digits[:6]\n for i in range(len(digits)):\n s = digits[i:i+5]\n if len(s) < 5:\n break\n if result < s:\n result = s\n return int(result);", "def solution(digits):\n n = len(digits)\n max = 0\n for i in range(n - 4):\n if(max < int(str(digits[i:i+5:]))):\n max = int(str(digits[i:i+5:]))\n return max", "def solution(digits):\n x = str(digits)\n empty = []\n for i in range(0,len(x)):\n empty.append(int(x[i:i+5]))\n \n return max(empty)", "def solution(digits):\n biggest = 0\n five = \"\"\n for loop in range(len(digits)-4):\n five = (digits[loop]+digits[loop+1]+digits[loop+2]+digits[loop+3]+digits[loop+4]);\n if biggest<int(five):\n biggest = int(five);\n return biggest;\n", "def solution(digits):\n return max([int(digits[item:item+5]) for item in range(len(digits)-4)])", "def solution(digits):\n i = 0 \n j = 5 \n largest = 0\n while j <= len(digits):\n relative = int(digits[i:j])\n if relative > largest:\n largest = relative \n i += 1\n j += 1\n return largest\n", "def solution(digits):\n number = 0\n digits = str(digits)\n for i in range(len(digits)):\n slice = digits[i:i + 5]\n if int(slice) > number: number = int(slice) \n return number\n", "def solution(digits): \n k = []\n for i in range(len(digits)): k.append(int(digits[i:i+5]))\n return max(k)", "def solution(digits): \n i, k = 0, []\n while i<len(digits):\n k.append(int(digits[i:i+5]))\n i += 1\n return max(k)", "def solution(digits):\n digits = str(digits) \n i, k = 0, []\n while i<len(digits):\n k.append(int(digits[i:i+5]))\n i += 1\n return max(k)", "def n(digits):\n digits = str(digits)\n k = []\n i = 0\n while i<len(digits):\n k += [int(digits[i:i+5])]\n i += 1\n return k\n \n\nsolution = lambda digits: max(n(digits))", "def n(digits):\n digits = str(digits)\n k = []\n i = 0\n while i<len(digits):\n k += [int(digits[i:i+5])]\n i += 1\n return k\n \n\ndef solution(digits):\n return max(n(digits))", "def solution(digits): \n n=0\n e=len(digits)-1\n for x in range(0,len(digits)-1):\n if int(digits[x:x+5])>n:n=int(digits[x:x+5])\n else:continue\n return n\n \n \n", "def solution(digits):\n maxima = 0\n for i in range(len(digits)):\n if int(digits[i:i+5]) > maxima:\n maxima = int(digits[i:i+5])\n return maxima\n", "def solution(digits):\n digit_ints = [int(x) for x in digits]\n max_digit = max(digit_ints)\n max_locs = [i for i in range(len(digits)) if digit_ints[i] == max_digit and i <= len(digits) - 5]\n while max_locs == []:\n max_digit -= 1\n max_locs = [i for i in range(len(digits)) if digit_ints[i] == max_digit and i <= len(digits) - 5]\n return max([int(digits[loc:loc + 5]) for loc in max_locs])", "def solution(digits):\n n = 0\n for i in range(len(digits)):\n if int(digits[i:i+5])>n:\n n = int(digits[i:i+5])\n \n return n", "def solution(digits):\n i=0\n j=5\n maks=0\n while j<=len(digits):\n maks=max(maks,int(digits[i:j]))\n i+=1\n j+=1\n return maks", "def solution(digits):\n ans = None\n for i in range(0,len(digits)):\n if ans is None:\n ans = int(digits[i:i+5:])\n elif int(digits[i:i+5]) > ans:\n ans = int(digits[i:i+5])\n return ans", "def solution(digits):\n number=0\n max=0\n for i in range(len(digits)-4):\n number=digits[i:i+5]\n number=int(number)\n if number>max:\n max=number\n return max", "def solution(digits):\n number = str(digits)\n max_seq = ''\n for i in range(len(number) - 3):\n if number[i:i+5] > max_seq:\n max_seq = number[i:i+5]\n return int(max_seq)", "def solution(digits):\n sl = 0\n res_list = []\n for count in range(len(digits) - 1):\n res_list.append(int(digits[sl: sl + 5]))\n sl += 1\n return max(res_list)", "def solution(digits):\n digits=str(digits)\n x=[int(digits[i:i+5]) for i in range(len(digits)-4)]\n return max(x)\n", "def solution(digits):\n largest = ''\n for i in range(len(digits) - 4):\n if digits[i:i+5] > largest:\n largest = digits[i:i+5]\n return int(largest)", "def solution(digits):\n \n l = []\n \n for i in range(len(str(digits))-4):\n total = int(digits[i:i+5])\n l.append(total)\n return(max(l))\n \n", "def solution(digits):\n cur = int(digits[:5])\n mx = cur\n for i in range(5, len(digits)):\n cur = (cur % 10000) * 10 + int(digits[i])\n if mx < cur: mx = cur\n return mx", "def solution(digits):\n nw_lst=[]\n for i in range(len(digits)-4):\n nums = int(digits[i:i+5])\n nw_lst.append(nums)\n return max(nw_lst);", "def solution(digits):\n maxes = max([int(digits[j:j+5]) for j,k in enumerate(digits)])\n return maxes\n", "def solution(digits):\n lst = []\n for i in range(len(digits)):\n lst.append(digits[i:i+5])\n return int(max(lst))", "def solution(digits):\n h_seq = 0\n for i in range(0, len(digits) - 4):\n if int(digits[i: i+5]) > h_seq:\n h_seq = int(digits[i: i+5])\n return h_seq", "def solution(digits):\n lst = list(map(int, digits))\n answ = []\n for i in range(0, len(lst) - 4):\n x = lst[i:i+5]\n z = ''\n for j in x:\n z += str(j)\n answ.append(int(z))\n return max(answ)", "def solution(digits):\n x = [digits[index:index+5] for index, value in enumerate(digits)]\n resul = max(x)\n return int(resul);", "def solution(digits):\n f = lambda x: [x[i:i+5] for i in range(len(x)+1-5)]\n numbers = str(digits)\n return max(list(map(int, f(numbers))))\n", "def solution(digits):\n max = 0\n for i in range(0, len(digits)):\n n = int(digits[i:i+5])\n if n > max:\n max = n\n \n return max", "def solution(digits):\n best = 0\n \n for i in range(len(digits) - 4):\n n = int(digits[i:i + 5])\n \n if n > best:\n best = n\n \n return best\n", "def solution(digits):\n return max([int(digits[start:start+5]) for start in range(len(digits) - 4)])", "def solution(digits):\n return max([int(digits[start:start+5]) for start in range(len(digits))])\n", "def solution(digits):\n b = int(max(digits[a:a + 5] for a in range(len(digits) - 4)))\n return b", "def solution(digits):\n solution = int(digits[0:5])\n for index in range(1, len(digits)):\n current = int(digits[index:index+5])\n solution = current if current > solution else solution\n\n return solution", "def solution(digits):\n numli=[]\n if len(digits)>5:\n for ind in range(len(digits)):\n if ind <= len(digits)-5:\n num=digits[ind:ind+5]\n numli.append(num)\n elif len(digits)<=5:\n numli.append[0]\n\n #print(numli)\n return int(max(numli))", "def solution(digits):\n d = str(digits)\n n = 0\n for x in range(0, len(d)-4):\n if int(d[x:x+5]) > n:\n n = int(d[x:x+5])\n return n", "def solution(digits):\n if digits == \"\":\n return 0\n splice = 5\n lst = []\n for i,v in enumerate(digits):\n lst.append(digits[i:i+splice])\n maxval = (int(max(lst)))\n return maxval\n", "def solution(digits):\n max = 0\n for i in range(len(str(digits)) - 4):\n tmp = int(str(digits)[i:i+5])\n if tmp > max : max = tmp\n return max", "def solution(digits):\n num = [digits[i:i+5] for i in range(len(digits)-4)]\n num.sort()\n return int(num[-1])\n", "def solution(digits):\n biggest = int(digits[0:5])\n for i in range(0,int(len(digits))-4):\n if biggest<int(digits[i:i+5]):\n biggest = int(digits[i:i+5])\n return biggest", "def solution(digits):\n if len(str(digits))<5:\n return digits\n \n string=str(digits)\n \n list2=[ ]\n\n maxi=len(string)-4\n i=0\n \n while i < maxi:\n for s, x in enumerate(string):\n list2.append(int(string[s:(s+5)]))\n i=i+1\n \n return max(list2)", "def solution(digits):\n x = 0\n m = 5\n i = 0\n for i in range(len(digits)):\n if int(digits[i:i+5]) > x:\n x = int(digits[i:i+5])\n i += 1\n else:\n i += 1\n \n return x", "def solution(digits):\n \n all = []\n for x in range(len(digits)):\n all.append(int(digits[x:x+5]))\n \n return max(all)", "def solution(digits): \n return max(int(digits[n:n+5]) for n in range(len(digits) - 4)) if digits else 0\n", "def solution(digits):\n record=0\n for i in range(0,len(digits)-4):\n current = int(digits[i:i+5])\n #print(current)\n if current > record:\n record = current\n return record", "def solution(d):\n s = str(d)\n return max([int(s[i:i+5]) for i in range(len(s)-4)])\n", "import re\n\ndef solution(digits):\n \n \n numlist = [int(digits[i:i+5]) for i in range(0,len(digits)-4)]\n \n return max(numlist);", "def solution(digits):\n k = 5\n ret = int(digits[0:k])\n index = 5\n while index+k < len(digits):\n temp = digits[index: index + k]\n ret = max(ret, int(temp))\n index += 1\n ret = max(ret, int(digits[index:]))\n return ret\n", "def solution(digits):\n max_num = 0\n for index in range(len(digits)-4):\n num = int(digits[index:index+5])\n if num > max_num:\n max_num = num\n print(max_num)\n return max_num;", "def solution(digits):\n ans = 0\n for i in range (0, len(digits)):\n if int(digits[i:i+5]) > ans:\n ans = int(digits[i:i+5])\n return ans", "def solution(digits):\n lst = [digits[i:i+5] for i in range(0, len(digits))]\n return int(max(lst))\n", "def solution(digits):\n n = []\n for i in range(0,len(digits)):\n s = str(digits)[i:i+5]\n n.append(s)\n new = [int(i) for i in n]\n return max(new)\n", "def solution(digits):\n return max([int(digits[loop] + digits[loop + 1] + digits[loop + 2] + digits[loop + 3] + digits[loop + 4]) for loop in range(len(digits) - 4)])", "def solution(digits):\n all = []\n j = 5\n while j <= len(digits):\n all.append(int(digits[j-5:j]))\n j+=1\n return max(all)", "def solution(digits):\n x = []\n for i in range(0,len(digits)):\n x.append(int(digits[i:i+5]))\n return max(x)", "def solution(d):\n return max([int(d[x:x+5]) for x in range(len(d)-4)])", "def solution(digits):\n num,i=0,0\n while i <len(digits)-4:\n if int(digits[i:i+5])>num:\n num = int(digits[i:i+5])\n i+=1\n return num", "def solution(digits):\n l=len(digits)\n start,end,max=0,5,0\n while 1:\n a=(digits)[start:end]\n if int(a)>max:\n max=int(a)\n start+=1\n end+=1\n if end==l+1:\n break\n return max", "def solution(digits):\n maxseq = 0\n for x in range(len(digits) - 4):\n if int(digits[x:x + 5]) > maxseq:\n maxseq = int(digits[x:x + 5])\n return maxseq\n\n", "def solution(digits):\n v = [digits[i:i+5] for i in range(len(digits)-4)]\n v.sort()\n return int(v[-1])", "def solution(digits):\n largest = 0\n for i in range(len(digits)-4):\n sliced = int(digits[i:i+5])\n if sliced > largest:\n largest = sliced\n return largest", "def solution(digits):\n b = digits\n start_rez = 0\n end_rez = 5\n max = 0\n\n while end_rez <= len(b) + 1:\n rez = b[start_rez:end_rez]\n if max < int(rez):\n max = int(rez)\n if end_rez < len(b):\n start_rez += 1\n end_rez += 1\n else:\n start_rez += 1\n end_rez += 1\n return int(max)", "def solution(digits):\n step_index = 0\n index = 0\n step_sum = ''\n max_sum = '0'\n while step_index + 5 != len(digits) + 1:\n while index < step_index + 5:\n step_sum += digits[index]\n index = index + 1\n step_index = step_index + 1\n index = (index - 5) + 1\n if int(step_sum) > int(max_sum):\n max_sum = step_sum\n step_sum = ''\n return int(max_sum)", "def solution(digits):\n number = 0\n for i in range(len(digits)):\n num = int(digits[i:i+5])\n if num > number:\n number = num\n return number;", "def solution(digits):\n num = 0\n for x in range(0, len(digits)-1):\n if int(digits[x:x+5]) > int(num):\n num = digits[x:x+5] \n return(int(num))", "def solution(digits):\n if len(digits)<5:\n return int(digits)\n i=0\n ans = 0\n for j in range(len(digits)):\n while j-i+1 > 5:\n i+=1\n num = int(digits[i:j+1])\n if num > ans:\n ans = num\n \n return ans;", "def solution(digits):\n def helper_func(item):\n temp = ''\n for i in item:\n temp = temp + str(i)\n return temp\n number_arr = [i for i in digits]\n result = [number_arr[i:i+5] for i in range(0, len(number_arr) - 4)]\n string_res = [helper_func(i) for i in result]\n return max([int(i) for i in string_res])\n\n", "def solution(digits):\n max = 0\n seq = 0\n for d in range(0,len(digits)):\n seq = int(digits[d:d+5])\n if seq > max:\n max = seq\n return max", "def solution(digits):\n numlist = [int(digits[i:i+5]) for i in range(len(digits))]\n return max(numlist)", "def solution(digits):\n max_num = 0\n for i in range(len(digits)-4):\n curr_num = int(digits[i:i+5])\n if curr_num > max_num:\n max_num = curr_num\n return max_num", "def solution(digits):\n numlist = [int(digits[i:i+5]) for i in range(0,len(digits)-4)]\n return max(numlist)\ndef solution(digits):\n return int(max(digits[a:a + 5] for a in range(len(digits) - 4)))\ndef solution(digits):\n result = -1;\n for i in range(len(digits)):\n current = int(digits[i: i+5])\n if current >= result:\n result = current\n return result\n\n", "def solution(x):\n a=''\n i=0\n while i<=len(x)-5:\n a+=x[i:i+5] + ' '\n i+=1\n return int(max(a.split()))", "def solution(digits):\n biggest = 0\n for x in range(len(digits)-4):\n num = int(digits[x]+digits[x+1]+digits[x+2]+digits[x+3]+digits[x+4])\n if num > biggest:\n biggest = num\n return biggest"]
{"fn_name": "solution", "inputs": [["1234567898765"]], "outputs": [[98765]]}
INTRODUCTORY
PYTHON3
CODEWARS
20,343
def solution(digits):
87c6394baad06228c7584dc487693279
UNKNOWN
The task is very simple. You must to return pyramids. Given a number ```n``` you print a pyramid with ```n``` floors For example , given a ```n=4``` you must to print this pyramid: ``` /\ / \ / \ /______\ ``` Other example, given a ```n=6``` you must to print this pyramid: ``` /\ / \ / \ / \ / \ /__________\ ``` Another example, given a ```n=10```, you must to print this pyramid: ``` /\ / \ / \ / \ / \ / \ / \ / \ / \ /__________________\ ``` Note: an extra line feed character is needed at the end of the string. Case `n=0` should so return `"\n"`.
["def pyramid(n):\n return '\\n'.join(\"/{}\\\\\".format(\" _\"[r==n-1] * r*2).center(2*n).rstrip() for r in range(n)) + '\\n'", "def pyramid(n):\n return '\\n'.join(('/%s\\\\' % (' _'[i == n-1] * i*2)).rjust(n+i+1) for i in range(n)) + '\\n'", "def pyramid(n):\n return \"\".join(\n f\"{' ' * (n - i - 1)}/{(' ' if i < (n - 1) else '_') * i * 2}\\\\\\n\" for i in range(n)\n )\n", "def pyramid(n):\n \n result = ''\n for i in range(n-1):\n result += ' '*(n-i-1) + '/' + ' '*i*2 + '\\\\\\n'\n result += '/' + '_'*2*(n-1) + '\\\\\\n'\n print(result)\n return result", "def pyramid(n):\n s =\"\"\n for i in range(n-1):\n s+= (\" \"*((n-i-1)) + \"/\" + \" \"*(i*2) +\"\\\\\\n\")\n s+= (\"/\" + \"_\"*((n*2)-2) + \"\\\\\\n\")\n return s", "def pyramid(n):\n result = '';\n for x in range(n,0,-1):\n result += '{}/{}\\\\\\n'.format(' ' * (x-1), ('_' if x == 1 else ' ') * ((n-x) * 2))\n return result", "pyramid=lambda n:''.join('{}/{}\\\\\\n'.format(' '*(n-i-1),'_ '[i<n-1]*i*2)for i in range(n))", "def pyramid(n):\n output=[\" \"*(n-i-1)+\"/\"+\" \"*(i*2)+\"\\\\\\n\" for i in range(n)]\n output[-1]=output[-1].replace(\" \",\"_\")\n return \"\".join(output)", "def pyramid(n):\n if n==0: return '\\n'\n s=''\n t=0\n while n>1:\n s += ' '*(n-1) + '/' + ' '*(t) + '\\\\\\n'\n n -= 1\n t += 2\n s += '/'+'_'*t+'\\\\\\n'\n return s", "def pyramid(n):\n return '\\n'.join([' '*(n-i-1)+'/'+' '*(2*i)+'\\\\' for i in range(n-1)]+['/'+'_'*(2*n-2)+'\\\\'])+'\\n'"]
{"fn_name": "pyramid", "inputs": [[4], [6], [10]], "outputs": [[" /\\\n / \\\n / \\\n/______\\\n"], [" /\\\n / \\\n / \\\n / \\\n / \\\n/__________\\\n"], [" /\\\n / \\\n / \\\n / \\\n / \\\n / \\\n / \\\n / \\\n / \\\n/__________________\\\n"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,575
def pyramid(n):
bee80d82fed1823dbaf21be7e43387a1
UNKNOWN
Complete the function/method so that it returns the url with anything after the anchor (`#`) removed. ## Examples ```python # returns 'www.codewars.com' remove_url_anchor('www.codewars.com#about') # returns 'www.codewars.com?page=1' remove_url_anchor('www.codewars.com?page=1') ```
["def remove_url_anchor(url):\n return url.split('#')[0]", "def remove_url_anchor(url):\n return url.partition('#')[0]", "def remove_url_anchor(url):\n import re\n return re.sub('#.*$','',url)", "def remove_url_anchor(url):\n index = url.find('#')\n return url[:index] if index >= 0 else url", "def remove_url_anchor(url):\n return url[:url.index('#')] if '#' in url else url", "def remove_url_anchor(url):\n try:\n return url[:url.index('#')]\n except:\n return url", "def remove_url_anchor(url):\n pos = 0\n for i in url:\n if i == '#':\n break\n pos += 1\n # print(url[:pos])\n return url[:pos]\n", "from urllib.parse import urldefrag\ndef remove_url_anchor(url):\n return urldefrag(url).url\n", "import re\n\ndef remove_url_anchor(url):\n fn = re.search(r\"[^#]+\", url)\n return fn.group(0)\n", "from itertools import takewhile\n\ndef remove_url_anchor(url):\n return ''.join(takewhile(lambda l: l != '#', url))", "import re\ndef remove_url_anchor(url):\n match = re.search(r'[a-zA-Z0-9.?/=:]+', url)\n return match.group()", "import re\ndef remove_url_anchor(url):\n return re.sub(\"#[a-zA-Z0-9]+$\", \"\", url)", "import re\n\ndef remove_url_anchor(url):\n anchor = url.find('#')\n return url[:anchor] if anchor != -1 else url", "def remove_url_anchor(url):\n return url[:url.find('#')] if url.find('#') != -1 else url", "remove_url_anchor = lambda url: url.split('#')[0]", "remove_url_anchor = lambda s: __import__('re').sub('(.*)\\\\#.*', '\\\\1', s)", "def remove_url_anchor(url):\n list=[]\n for x in url:\n a = list.append(x)\n if x == '#':\n break \n y = ''.join(list).replace('#', '')\n return ( y )\n # TODO: complete\n", "def remove_url_anchor(url):\n return url if url.count(\"#\") == 0 else url[:url.index(\"#\")]", "def remove_url_anchor(url):\n new_url = ''\n for i in url:\n if i ==\"#\":\n return new_url\n new_url += i\n return url", "def remove_url_anchor(url):\n posicion =url.split(\"#\")\n nuevo=posicion[0:1]\n return \"\".join(nuevo)", "import re\n\ndef remove_url_anchor(url):\n pattern = re.compile(r'((http://?|https://?|http://www\\.?|https://www\\.?|www\\.?|)+([a-zA-z0-9]+\\.[a-zA-z0-9./-_]+))[^#]*')\n matches = pattern.finditer(url)\n for match in matches:\n return(match.group(1))", "import re\ndef remove_url_anchor(url):\n return re.search(r'^(.*?)(#|$)',url).group(1)", "def remove_url_anchor(url):\n if '#' in url: \n return ''.join(list(url)[:list(url).index('#')]) \n else:\n return url\n # TODO: complete\n", "def remove_url_anchor(url):\n res = \"\"\n for i in url:\n if i != \"#\":\n res += i\n else:\n return res\n break\n\n return res ", "def remove_url_anchor(url):\n web=[]\n for letter in url:\n if letter=='#':\n break\n else:\n web.append(letter)\n return ''.join(web)\n", "def remove_url_anchor(url):\n try:\n ret_url, non_url = url.split('#', 1)\n return ret_url\n except:\n return url\n", "def remove_url_anchor(url):\n import re\n # TODO: complete\n new=re.split('#+',url)\n return new[0]", "def remove_url_anchor(url):\n if '#' in url: i = url.index('#')\n else: return url\n return url[:i]\n", "def remove_url_anchor(url):\n final_url = ''\n for i in url:\n if i == '#': \n return final_url\n final_url += i\n return final_url", "def remove_url_anchor(url):\n anchor_pos = url.find('#')\n return url[0: anchor_pos if anchor_pos > 0 else len(url)]", "def remove_url_anchor(url):\n if \"#\" in url:\n anchorindex= url.index(\"#\")\n return url[:anchorindex]\n else:\n return url", "def remove_url_anchor(url):\n if not \"#\" in url: return url \n return url[0:url.index(\"#\")]", "def remove_url_anchor(url):\n new_url_lst = []\n new_url = ''\n for i in url:\n if i != '#':\n new_url_lst.append(i)\n else:\n break\n return \"\".join(new_url_lst)\n", "def remove_url_anchor(url):\n ret = \"\"\n wh = len(url)\n for i in url:\n if i == \"#\":\n wh = url.index(i)\n break\n for i in range(0, wh):\n ret += url[i]\n return ret", "def remove_url_anchor(url):\n x = \"\"\n for i in url:\n if i == \"#\":\n break\n x += i\n return x", "def remove_url_anchor(url):\n index = url.find(\"#\")\n return url[:index if index > 0 else len(url)]", "def remove_url_anchor(url):\n return url[:len(url) if url.find('#') == -1 else url.find('#')]", "def remove_url_anchor(url):\n if not \"#\" in url : return url\n return url[:url.find('#')]", "def remove_url_anchor(url):\n hash = url.find('#')\n if hash == -1:\n return url\n else:\n new_url = url[0:hash]\n return new_url", "def remove_url_anchor(url):\n l = ''\n for n in url:\n if n == '#':\n break\n else:\n l += n\n return l", "def remove_url_anchor(url):\n list = []\n for i in url:\n list.append(i)\n if i == '#':\n list.pop()\n break\n print(list)\n new_string = ''.join(list)\n print(new_string)\n return new_string", "def remove_url_anchor(url):\n try:\n anchorIndex = url.index('#')\n return url[:anchorIndex]\n except:\n return url", "def remove_url_anchor(url):\n url_new=\"\"\n for i in url:\n if i == \"#\":\n return url_new\n url_new += i\n return url_new", "def remove_url_anchor(url):\n # TODO: complete\n \n fixed_url = url.split(\"#\")\n \n return fixed_url[0]", "import re\n\ndef remove_url_anchor(arry):\n if '#' in arry:\n arry = re.match(r\"^(.*)\\#\", arry).group(1)\n\n return arry", "import re\n\ndef remove_url_anchor(url):\n regex = r'#\\w+.+'\n subst = ''\n result = re.sub(regex, subst, url)\n return result", "def remove_url_anchor(url):\n return url[0:url.find(\"#\")] if \"#\" in url else url\n", "def remove_url_anchor(url):\n url_list = list(url) \n if '#' in url_list: \n index = url_list.index(\"#\")\n url_list = url_list[:index]\n \n return (\"\".join(url_list))\n \n # TODO: complete\n", "def remove_url_anchor(url):\n anchor_pos = url.find('#')\n if anchor_pos > 0:\n return url[:anchor_pos]\n return url\n \n", "import re\ndef remove_url_anchor(url):\n urlRegex = re.compile(r'#(.*)')\n mo = str(urlRegex.sub('',url))\n return mo\n\nprint(remove_url_anchor(\"www.codewars.com/katas/\"))", "def remove_url_anchor(url):\n char_list = list(url)\n anchor_index = len(char_list)\n for number in range(0, len(char_list)):\n if (char_list[number] == \"#\"):\n anchor_index = number\n without_anchor = \"\".join(char_list[number] for number in range(0, anchor_index))\n return without_anchor", "def remove_url_anchor(url):\n c=\"\"\n for ch in url:\n if ch== \"#\":\n break\n c+=ch\n return c", "def remove_url_anchor(url):\n new = url.find('#')\n \n if new > 0:\n return url[0:new]\n else:\n return url\n # TODO: complete\n", "def remove_url_anchor(url):\n ans = \"\"\n for index in range(0,len(url)):\n if url[index] != '#':\n ans += url[index]\n else:\n break\n return ans\n", "import re\ndef remove_url_anchor(url):\n return re.match(r'[^#]*', url).group()", "def remove_url_anchor(url):\n l1=list()\n for i in range(len(url)):\n if(url[i]!='#'):\n l1.append(url[i])\n else:\n break\n return ''.join(l1)\n", "def remove_url_anchor(url):\n a = []\n for i in url:\n if i == \"#\":\n break\n a.append(i)# TODO: complete\n return \"\".join(a)", "def remove_url_anchor(url):\n if \"#\" in url:\n return url[:url.index(\"#\"):]\n else:\n return url", "def remove_url_anchor(url):\n lst=url.split('#')\n url=str(lst[0])\n return url", "import re\ndef remove_url_anchor(url):\n match = re.search(r'[^#]+', url)\n if match:\n return match.group()\n else:\n return url\n", "def remove_url_anchor(url):\n if '#' not in url:\n return url\n else:\n get_index = list(url).index('#')\n return url[:get_index]", "def remove_url_anchor(url):\n # TODO: complete\n new_url = \"\"\n for char in url:\n if char == \"#\": break\n new_url = new_url + char\n \n \n return new_url", "import re\ndef remove_url_anchor(url):\n return re.match(r'(.+)#', url)[1] if '#' in url else url", "def remove_url_anchor(url):\n splt = url.split('#',1)\n sub = splt[0]\n return sub", "def remove_url_anchor(url):\n ans = url.split('#')\n return ans[0]\n # TODO: complete\n", "def remove_url_anchor(url):\n \n s = \"\"\n \n for i in range(len(url)):\n \n if url[i]=='#':\n \n break\n \n else:\n \n s+= url[i]\n \n return s\n\n \n \n", "def remove_url_anchor(url):\n return url[:list(url).index('#')] if '#' in url else url", "def remove_url_anchor(url):\n a = 0\n for i in url:\n if i == '#':\n a = url.index(i)\n return url[:a] if a != 0 else url", "def remove_url_anchor(url):\n return \"\".join(url.split(\"#\")[:1])", "def remove_url_anchor(url):\n count = 0\n if \"#\" in url:\n newUrl = url.replace(url[url.find(\"#\"):], \"\")\n return newUrl\n else:\n return url\n \n", "def remove_url_anchor(url):\n j = 0\n for i in url:\n j +=1\n if i == '#':\n print(j)\n url = url[0:(j-1)]\n return url\n else:\n pass\n return url\n \n", "def remove_url_anchor(url):\n index = url.find('#')\n if index == -1:\n return url\n else:\n return url[0:index]", "def remove_url_anchor(url):\n accum = []\n for char in url:\n if char != \"#\":\n accum.append(char)\n if char == \"#\":\n break\n return \"\".join(accum)", "def remove_url_anchor(url):\n new_url = \"\"\n if \"#\" in url:\n i = url.index(\"#\")\n new_url = url[0: i]\n else:\n new_url = url\n return new_url", "def remove_url_anchor(url):\n url = url.split(sep=\"#\")\n return url[0]", "def remove_url_anchor(url):\n newString = ''\n for i in url:\n if i != '#':\n newString = newString + i\n if i== '#':\n break\n return newString", "def remove_url_anchor(url):\n \n l = \"\"\n \n for i in url:\n if i!= \"#\":\n l+= i\n \n else:\n break\n return l", "def remove_url_anchor(url):\n # TODO: complete\n s = \"#\"\n l=len(url) \n pos = url.find(s) \n if pos<=l and pos>0:\n url = url[:(l-(l-pos))] \n return url", "def remove_url_anchor(url):\n url1 = url.split(\"#\", 1)\n subs= url1[0]\n return(subs)", "def remove_url_anchor(url):\n line=[]\n for x in url:\n if x!='#':\n line.append(x)\n else:\n break\n return ''.join(line)", "import re\n\ndef remove_url_anchor(url):\n pattern = re.compile(r'^([^#]+)(#[.]*)*')\n m = re.match(pattern, url)\n return m.group(1)", "def remove_url_anchor(url):\n if '#' in url:\n anchorPosition = url.find('#')\n return url[:anchorPosition]\n else:\n return url", "def remove_url_anchor(url):\n try:\n site, _ = url.split('#')\n except ValueError:\n return url\n else:\n return site", "def remove_url_anchor(url):\n for x in url:\n y=len(url)\n if x ==\"#\":\n y=url.index(x)\n break\n return url[ :y]", "import re\ndef remove_url_anchor(url):\n return re.search(r\"^[^#]+\", url).group()", "def remove_url_anchor(url):\n ans = ''\n for char in url:\n if char is '#':\n break \n ans += char \n return ans", "from re import sub\n\ndef remove_url_anchor(url):\n return sub('#.+', '', url)", "def remove_url_anchor(url):\n if '#' in url:\n slicer = url.index('#')\n return url[:slicer]\n else:\n return url", "from re import search\ndef remove_url_anchor(url):\n pattern = r'(\\A.+(?=#))'\n match = search (pattern, url)\n return match.group () if match else url", "def remove_url_anchor(url):\n final=\"\"\n for letter in url:\n if letter==\"#\":\n break\n else:\n final+=letter\n return final\n \n # TODO: complete\n", "def remove_url_anchor(url):\n idx = url.find('#')\n if idx == -1: return url\n return url[:idx]", "def remove_url_anchor(url):\n for letter in url:\n if letter == \"#\":\n x = url.index(letter)\n return url[0:x]\n \n return url\n # TODO: complete\n", "def remove_url_anchor(url):\n ans = '' \n for i in range(len(url)):\n if url[i]=='#':\n break\n else:\n ans += url[i]\n return ans\n", "def remove_url_anchor(url):\n try:\n a = url.index(\"#\")\n return url[:a]\n except Exception:\n pass\n return url", "def remove_url_anchor(url):\n string = ''\n for letter in url:\n if letter != '#':\n string += letter\n else:\n break\n return string", "def remove_url_anchor(url):\n url = url.rsplit('#')\n return url[0]", "def remove_url_anchor(url):\n try: return url[:url.index('#')]\n except: return url[:]\n", "from re import sub\nremove_url_anchor = lambda url: sub('#.*', '', url)", "def remove_url_anchor(url):\n l = url.split('#',1)\n return l[0]"]
{"fn_name": "remove_url_anchor", "inputs": [["www.codewars.com#about"], ["www.codewars.com/katas/?page=1#about"], ["www.codewars.com/katas/"]], "outputs": [["www.codewars.com"], ["www.codewars.com/katas/?page=1"], ["www.codewars.com/katas/"]]}
INTRODUCTORY
PYTHON3
CODEWARS
14,173
def remove_url_anchor(url):
362dd6c37e6b91027ee49dd68b1128bb
UNKNOWN
You are given a string of numbers between 0-9. Find the average of these numbers and return it as a floored whole number (ie: no decimal places) written out as a string. Eg: "zero nine five two" -> "four" If the string is empty or includes a number greater than 9, return "n/a"
["N = ['zero','one','two','three','four','five','six','seven','eight','nine']\n\ndef average_string(s):\n try:\n return N[sum(N.index(w) for w in s.split()) // len(s.split())]\n except (ZeroDivisionError, ValueError):\n return 'n/a'", "def average_string(s):\n if not s:\n return 'n/a'\n\n numbers = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']\n total = 0\n counter = 0\n for n in s.split():\n try:\n value = numbers.index(n)\n total += value\n counter += 1\n except:\n return 'n/a'\n return numbers[total // counter]", "from statistics import mean\nlst = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']\nd = {lst.index(i): i for i in lst}\ndef average_string(s):\n try:\n return d.get(int(mean([lst.index(i) for i in s.split()])),'n/a')\n except:\n return 'n/a'", "nbrs = 'zero one two three four five six seven eight nine'.split()\n\ndef average_string(s):\n try:\n return nbrs[sum(map(nbrs.index, s.split())) // len(s.split())]\n except:\n return 'n/a'", "numbers = 'zero one two three four five six seven eight nine'.split()\n\ndef average_string(s):\n try:\n ns = list(map(numbers.index, s.split()))\n return numbers[sum(ns) // len(ns)]\n except (ValueError, ZeroDivisionError):\n return 'n/a'", "from numpy import average\n\nnums = [\n'zero',\n'one',\n'two',\n'three',\n'four',\n'five',\n'six',\n'seven',\n'eight',\n'nine'\n]\n\n\ndef average_string(s):\n total = [nums.index(c) for c in s.split(' ') if c in nums]\n return nums[int(average(total))] if len(total)==len(s.split(' ')) else 'n/a'", "def average_string(s):\n nums = ['zero','one','two','three','four','five','six','seven','eight','nine']\n d = dict(zip(nums, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))\n try:\n return nums[sum(d[w] for w in s.split()) // len(s.split())]\n except:\n return 'n/a'", "s2d = \"zero one two three four five six seven eight nine\".split()\n\n\ndef average_string(stg):\n lst = stg.split()\n if not stg or set(lst) - set(s2d):\n return \"n/a\"\n return s2d[int(sum(s2d.index(s) for s in lst) / len(lst))]", "def average_string(s):\n d,c = \"zero one two three four five six seven eight nine\".split(),0\n for i in s.split():\n if i not in d : return \"n/a\"\n c += d.index(i)\n return d[int(c / len(s.split()))] if s else \"n/a\"", "def average_string(s):\n n = 0\n dic = { 'zero' : 0,\n 'one' : 1,\n 'two' : 2,\n 'three' : 3,\n 'four' : 4,\n 'five' : 5,\n 'six' : 6,\n 'seven' : 7,\n 'eight' : 8,\n 'nine' : 9 }\n \n s = s.split(' ')\n for i in range(len(s)):\n if s[i] in dic: n += dic[s[i]]\n else: return \"n/a\"\n n //= len(s)\n for key in dic:\n if dic.get(key) == n:\n n = key\n return n", "digit_map = {\n \"zero\": 0,\n \"nine\": 9,\n \"five\": 5,\n \"two\": 2,\n \"three\": 3,\n \"four\": 4,\n \"one\": 1,\n \"eight\": 8,\n \"six\": 6,\n \"seven\": 7\n}\n\nreverse_digit_map = dict(map(reversed, digit_map.items()))\n\nclass InValidNumException(Exception):\n pass\n\nclass StringNum(int):\n def __new__(cls, s):\n if s in digit_map:\n return int.__new__(cls, digit_map[s])\n\n raise InValidNumException()\n\ndef average_string(s):\n try:\n arr = [StringNum(t) for t in s.split() if t]\n\n if len(arr) == 0:\n return 'n/a'\n\n average = int(sum(arr) / len(arr))\n except InValidNumException:\n return 'n/a'\n\n if 0 <= average < 10:\n return reverse_digit_map[average]\n return 'n/a'", "from statistics import mean\nD = {\"zero\":0, \"one\":1, \"two\":2, \"three\":3, \"four\":4, \"five\":5, \"six\":6, \"seven\":7, \"eight\":8, \"nine\":9}\nL = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n\ndef average_string(s):\n try: return L[int(mean(map(D.get, s.split())))]\n except: return \"n/a\"", "def average_string(s):\n try:\n l = ['zero','one','two','three','four','five','six','seven','eight','nine']\n s = s.split(' ')\n c = 0 \n for i in s :\n c += l.index(i)\n c = int(c/len(s))\n return l[c]\n except:\n return \"n/a\"\n", "def average_string(s):\n digits = list(\"zero,one,two,three,four,five,six,seven,eight,nine\".split(\",\"))\n values = [digits.index(w) if w in digits else -1 for w in s.split()]\n return \"n/a\" if not values or -1 in values else digits[sum(values) // len(values)]", "average_string=lambda s,d=\"zero one two three four five six seven eight nine\".split():(lambda l:set()<set(l)<=set(d)and d[sum(map(d.index,l))//len(l)]or'n/a')(s.split())", "def average_string(s):\n sn={\"zero\":0,\"one\":1,\"two\":2,\"three\":3,\"four\":4,\"five\":5,\"six\":6,\"seven\":7,\"eight\":8,\"nine\":9}\n a=0\n try:\n for i in s.split():\n a+=sn[i]\n a/=len(s.split())\n except:\n return \"n/a\"\n return list(sn.keys())[list(sn.values()).index(int(a))]", "def average_string(s):\n #your code here\n res=0\n num=[0,0,0,0,0,0,0,0,0,0]\n str=('zero','one','two','three','four','five','six','seven','eight','nine')\n for i in range(0,10):\n num[i]=s.count(str[i])\n if sum(num)==0 or sum(num)!=s.count(' ')+1:return \"n/a\"\n for i,val in enumerate(num):\n res+=val*i\n res/=sum(num)\n if res>9 :return\"n/a\"\n \n return str[int(res)]\n"]
{"fn_name": "average_string", "inputs": [["zero nine five two"], ["four six two three"], ["one two three four five"], ["five four"], ["zero zero zero zero zero"], ["one one eight one"], ["one"], [""], ["ten"], ["pippi"]], "outputs": [["four"], ["three"], ["three"], ["four"], ["zero"], ["two"], ["one"], ["n/a"], ["n/a"], ["n/a"]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,763
def average_string(s):
66c906d2c56cf3b09d84fdb99d2f5958
UNKNOWN
As a part of this Kata, you need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements. The input to the function will be an array of three distinct numbers (Haskell: a tuple). For example: gimme([2, 3, 1]) => 0 *2* is the number that fits between *1* and *3* and the index of *2* in the input array is *0*. Another example (just to make sure it is clear): gimme([5, 10, 14]) => 1 *10* is the number that fits between *5* and *14* and the index of *10* in the input array is *1*.
["def gimme(inputArray):\n # Implement this function\n return inputArray.index(sorted(inputArray)[1])", "def gimme(input_array):\n return input_array.index(sorted(input_array)[1])\n", "gimme=lambda l:l.index(sorted(l)[1])", "def gimme(lst):\n return lst.index(sorted(lst)[len(lst)//2])\n", "def gimme(arr):\n return (len(arr)-(arr.index(max(arr)))) - arr.index(min(arr))", "def gimme(arr):\n return arr.index(sorted(arr)[1])\n", "def gimme(input):\n s = sorted(input)\n return input.index(s[1])", "def gimme(input_array):\n return input_array.index(sorted(input_array.copy())[1])", "import copy\ndef gimme(input_array):\n input_array_sorted = copy.deepcopy(input_array)\n input_array_sorted.sort()\n middle = input_array_sorted[int(len(input_array_sorted) / 2)]\n return input_array.index(middle)\n", "def gimme(input_array):\n middle = sorted(input_array)[1]\n return input_array.index(middle)\n \n \n", "def gimme(a): return a.index(sorted(a)[1])\n", "gimme = lambda a: a.index(sorted(a)[1])", "def gimme(triplet):\n return triplet.index(sorted(triplet)[1])\n", "def gimme(arr):\n arr1 = sorted(arr)\n middle = arr1[1]\n return arr.index(middle) \n", "def gimme(input_array):\n a = input_array.copy()\n a.sort()\n b = a[1]\n return input_array.index(b)", "def gimme(input_array):\n # Implement this function\n for e in input_array:\n i = 0\n for p in range(len(input_array)):\n if e > input_array[p]:\n i+=1\n if e < input_array[p]:\n i-=1\n if i == 0: \n for ele in range(len(input_array)):\n if e == input_array[ele]:\n return ele\n \n \n", "def gimme(l): \n return [x for x in range(len(l)) if x not in [l.index(min(l)), l.index(max(l))]][0]\n", "def gimme(input_array):\n return(3- input_array.index(max(input_array))-input_array.index(min(input_array)))\n", "def gimme(i):\n for x in i:\n if x!=max(i) and x!=min(i):\n return i.index(x)\n", "def gimme(input_array):\n a = []\n b = sum(input_array) / len(input_array)\n for i in input_array:\n a.append(abs(b-i))\n return a.index(min(a))\n", "def gimme(a):\n for x in a:\n if max(a) > x > min(a):\n return a.index(x) \n", "def gimme(array):\n for i in range(2):\n if (array[i] < array[i-1]) != (array[i] < array[i+1]):\n return i\n return 2", "def gimme(inputArray):\n return 3 - inputArray.index(min(inputArray)) - inputArray.index(max(inputArray))\n", "def gimme(input_array):\n get = input_array.__getitem__\n return 3 - min(list(range(3)), key=get) - max(list(range(3)), key=get)\n", "def gimme(input_array):\n a, b, c = input_array\n return 2 if a < c < b or a > c > b else a < b < c or a > b > c\n \n", "def gimme(a):\n return [a.index(b) for b in a if b != max(a) and b != min(a)][0]\n", "def gimme(input_array):\n if input_array[2] > input_array[0] and input_array[2] > input_array[1]:\n if input_array[0] > input_array[1]:\n return 0\n else:\n return 1\n elif input_array[0] > input_array[1] and input_array[0] > input_array[2]:\n if input_array[1] > input_array[2]:\n return 1\n else:\n return 2\n elif input_array[2] > input_array[0]:\n return 2\n else:\n return 0\n", "def gimme(input_array):\n for i, c in enumerate(input_array):\n if c == sorted(input_array)[1]:\n return i", "def gimme(inputArray):\n # Implement this function\n x = inputArray\n x=sorted(x)\n return inputArray.index(x[1])\n\n", "from typing import List\n\ndef gimme(array: List[int]) -> int:\n \"\"\" Get the index of the numerical element that lies between the other two elements. \"\"\"\n return array.index(next(iter({*array} - ({min(array), max(array)}))))", "def gimme(input_array):\n maxpos = input_array.index(max(input_array))\n minpos = input_array.index(min(input_array))\n for i in input_array:\n if input_array.index(i) != maxpos and input_array.index(i) != minpos:\n return input_array.index(i)", "def gimme(input_array):\n middle_idx = len(input_array) // 2\n middle_value = sorted(input_array)[middle_idx]\n return input_array.index(middle_value)\n", "def gimme(input_array):\n # Implement this function\n temp = input_array[:]\n temp.sort()\n middle_value = int(len(input_array))//2\n return input_array.index(temp[middle_value])\n\n", "def gimme(input_array):\n minimum = min(input_array)\n maximum = max(input_array)\n for l in input_array:\n if l < maximum and l > minimum:\n return input_array.index(l) \n", "def gimme(input_array):\n ordered = sorted(input_array)\n return input_array.index(ordered[1])\n \n", "def gimme(input_array):\n max_num = max(input_array)\n min_num = min(input_array)\n \n for elem in input_array:\n if elem != max_num and elem != min_num:\n return input_array.index(elem)\n", "def gimme(input_array):\n x = max(input_array)\n y = min(input_array)\n\n for i in input_array:\n if i > y and i < x:\n return(input_array.index(i))\n", "def gimme(b):\n a=max(b[0],b[1],b[2])\n c=min(b[0],b[1],b[2])\n for i in range(3):\n if b[i]!=a and b[i]!=c:\n return i", "def gimme(input_array):\n min_no=min(input_array)\n max_no=max(input_array)\n for i in input_array:\n if i>min_no and i<max_no:\n \n return input_array.index(i)\n \n \n \n \n", "def gimme(inp):\n # Implement this function\n a=max(inp)\n b=min(inp)\n for i in range(len(inp)):\n if b<inp[i]<a:\n return i", "def gimme(input_array):\n mi = min(input_array)\n ma = max(input_array)\n for i in range(len(input_array)):\n if input_array[i]!=mi and input_array[i] != ma:\n return i", "from copy import copy\ndef gimme(input_array):\n g = copy(input_array)\n g.sort()\n return(input_array.index(g[1]))\n", "def gimme(input_array):\n ord = sorted(input_array)[len(input_array)//2]\n return input_array.index(ord)", "def gimme(input_array):\n maximum = max(input_array)\n minimum = min(input_array)\n for i in input_array:\n if i != maximum and i != minimum:\n mean = input_array.index(i)\n return mean", "def gimme(input_array):\n arr = sorted(input_array)\n middle = arr[1]\n return input_array.index(middle)", "def gimme(array):\n v0=array[0]\n v1=array[1]\n v2=array[2]\n array.sort()\n if(array[1]==v0): return 0\n if(array[1]==v1): return 1\n if(array[1]==v2): return 2\n \n", "def gimme(input_array):\n copy = sorted(list(input_array))\n return input_array.index(copy[1])", "def gimme(a):\n for i in a:\n if i != max(a) and i != min(a):\n return a.index(i) \n", "def gimme(input_array):\n # Implement this function\n \n for pos, num in enumerate(input_array):\n if num != min(input_array) and num != max(input_array):\n return pos\n", "def gimme(input_array):\n d={}\n for i,v in enumerate(input_array):\n d[i]=v\n x = sorted(list(d.items()), key=lambda x:x[1])\n return(x[1][0])\n # Implement this function\n", "def gimme(input_array):\n newarr = input_array.copy()\n [newarr.remove(x) for x in [max(input_array), min(input_array)]]\n return input_array.index(newarr[0])\n \n", "def gimme(input_array):\n i = sorted(input_array)[len(input_array) // 2]\n return input_array.index(i)\n", "def gimme(input_array):\n a = max(input_array)\n b = min(input_array)\n for i in input_array :\n if i == a or i == b:\n continue\n else :\n return input_array.index(i)", "def gimme(input_array):\n # Implement this function\n orig = input_array[:]\n input_array.sort()\n middle = int((len(input_array) - 1) / 2)\n return orig.index(input_array[middle])", "def gimme(input_array):\n\n for x in input_array:\n if x != min(input_array) and x != max(input_array):\n choosen = x\n\n return(input_array.index(choosen))\n", "def gimme(input_array):\n min_value = min(input_array)\n max_value = max(input_array)\n for idx, val in enumerate(input_array):\n if val == min_value:\n continue\n if val == max_value:\n continue\n return idx", "def gimme(input_array):\n s = sorted(input_array)\n return(input_array.index(s[len(s)//2]))\n", "def gimme(arr):\n for i, el in enumerate(arr):\n if el != min(arr) and el != max(arr):\n return i\n", "def gimme(input_array):\n print(input_array)\n middle = round(sum(input_array) - min(input_array) - max(input_array),2)\n index = input_array.index(middle)\n return index\n", "def gimme(input_array):\n \n srt = sorted(input_array)\n \n for i in range(3):\n if input_array[i] == srt[1]:\n return i", "def gimme(input_array):\n a = sorted(input_array)\n return input_array.index(a[len(a)//2])\n", "def gimme(input_array):\n x = sorted(list(input_array))\n for y in range(len(input_array)):\n if x[1] == input_array[y]:\n return y\n", "def gimme(input_array):\n i=0\n while i<3:\n c=input_array[i]\n if c<max(input_array) and c>min(input_array):\n return input_array.index(c)\n break\n else:\n i+=1", "def gimme(array):\n first = array[0]\n second = array[1]\n third = array[2]\n if first <= second <= third:\n return 1\n elif first <= third <= second:\n return 2\n elif second <= first <= third:\n return 0\n elif second <= third <= first:\n return 2\n elif third <= first <= second:\n return 0\n elif third <= second <= first:\n return 1\n", "def gimme(input_array):\n middle_num = (sorted(input_array)[1])\n counter = 0\n for i in input_array:\n if i == middle_num:\n return counter\n else:\n counter += 1\n\n\ngimme([2, 3, 1])\n", "import numpy as np\n\ndef gimme(input_array):\n choices = set([0, 1, 2])\n not_it = set([np.argmin(input_array), np.argmax(input_array)])\n return list(choices - not_it)[0]\n", "def gimme(arr):\n sort = sorted(arr)\n arr.index(sort[1])\n return arr.index(sort[1])", "def gimme(arr):\n minn = sorted(arr)\n return arr.index(minn[1])\n", "def gimme(arr):\n sort = sorted(arr)\n return arr.index(sort[1])", "def gimme(arr):\n middle = sorted(arr)[1]\n return arr.index(middle)\n", "def gimme(input_array):\n minEl = min(input_array)\n maxEl = max(input_array)\n i = 0\n for el in input_array:\n if el < maxEl and el > minEl: return i\n i = i + 1\n", "def gimme(input_array):\n sorte=sorted(input_array)\n return input_array.index(sorte[1])\n # Implement this function\n", "def gimme(input_array):\n # Implement this function\n sort = sorted(input_array)\n x = sort[1]\n for i in range(len(input_array)):\n if x == input_array[i]:\n return i\n", "def gimme(input_array):\n # Implement this function\n sort = sorted(input_array)\n x = sort[1]\n leng = len(input_array)\n \n if sum(input_array) <0:\n sort = reversed(sort)\n \n for i in range(leng):\n if x == input_array[i]:\n return i\n", "def gimme(input_array):\n for i in input_array:\n if i < input_array[-1] and i > input_array[0]:\n return input_array.index(i)\n elif i < input_array[0] and i > input_array[-1]:\n return input_array.index(i)\n elif i < input_array[1] and i > input_array[0]:\n return input_array.index(i)\n elif i < input_array[0] and i > input_array[1]:\n return input_array.index(i)\n elif i < input_array[1] and i > input_array[-1]:\n return input_array.index(i)\n elif i < input_array[-1] and i > input_array[1]:\n return input_array.index(i)\n", "def gimme(input_array):\n # Implement this function\n array=sorted(input_array);\n mid_num=array[int((len(array)-1)/2)]\n return(input_array.index(mid_num))\n\n", "def gimme(input_array):\n for number in input_array:\n if number != max(input_array) and number != min(input_array):\n answer = number\n return input_array.index(answer)\n", "def gimme(input_array):\n sort_arr = sorted(input_array)\n middle = sort_arr[1]\n\n return input_array.index(middle)", "def gimme(input_array):\n a = input_array.index(max(input_array))\n b = input_array.index(min(input_array))\n \n for i in [0,1,2]:\n if i not in [a,b]:\n return i\n break\n", "def gimme(arr):\n return len(arr) - (arr.index(max(arr)) + arr.index(min(arr))) ", "def gimme(input_array):\n inp2 = input_array.copy()\n inp2.remove(max(inp2))\n inp2.remove(min(inp2))\n return input_array.index(inp2[0])", "def gimme(input_array):\n # Implement this function\n mins = min(input_array)\n maxs = max(input_array)\n for i in input_array:\n if i<maxs and i>mins:\n return input_array.index(i)", "def gimme(input_array):\n big = max(input_array)\n small = min(input_array)\n for num in input_array:\n if num > small and num < big:\n return input_array.index(num)", "def gimme(input_array):\n return input_array.index(sorted(input_array)[int((len(input_array) - 1) / 2)])", "def gimme(input_array):\n max_i = input_array.index(max(input_array))\n min_i = input_array.index(min(input_array))\n \n middle_i = [i for i in range(len(input_array)) if i not in [max_i,min_i]][0]\n \n return middle_i", "def gimme(input_array):\n # Implement this function\n Max = max(input_array)\n Min = min(input_array)\n n = round(sum(input_array), 3)\n k = round(n - Max - Min, 3)\n return input_array.index(k)\n\n", "def gimme(input_array):\n M=max(input_array)\n m=min(input_array)\n if input_array.index(M)==2 and input_array.index(m)==0:\n return 1\n if input_array.index(M)==1 and input_array.index(m)==0:\n return 2\n if input_array.index(M)==1 and input_array.index(m)==2:\n return 0\n if input_array.index(M)==2 and input_array.index(m)==1:\n return 0\n if input_array.index(M)==0 and input_array.index(m)==2:\n return 1\n if input_array.index(M)==0 and input_array.index(m)==1:\n return 2", "def gimme(a):\n b=a\n a=sorted(a)\n return b.index( a[1] )\n", "def gimme(input_array):\n array = sorted(input_array)\n middle_el = array[1]\n return input_array.index(middle_el)", "def gimme(input_array):\n if input_array[0] > input_array[1] and input_array[0] < input_array[2] or input_array[0] < input_array[1] and input_array[0] > input_array[2]:\n return 0\n elif input_array[1] > input_array[0] and input_array[1] < input_array[2] or input_array[1] > input_array[2] and input_array[1] < input_array[0]:\n return 1\n else:\n return 2\n", "def gimme(input_array):\n for x in range(len(input_array)):\n if min(input_array) != input_array[x] and max(input_array) != input_array[x]:\n return x\n", "def gimme(arr):\n list = [i for i in arr if i != max(arr) and i != min(arr)] \n return arr.index(list[0])\n\n", "import numpy as np\n\ndef gimme(input_array):\n # Implement this function\n return input_array.index(np.setdiff1d(input_array,[max(input_array), min(input_array)]))\n\n", "def gimme(input_array):\n sortedlst = []\n unsortedlst = []\n for i in input_array:\n unsortedlst.append(i)\n sortedlst.append(i)\n sortedlst.sort()\n biggestNumber = sortedlst[1]\n return unsortedlst.index(biggestNumber)", "def gimme(input_array):\n # Implement this function\n sort_items = []\n for i in input_array:\n sort_items.append(i)\n sort_items.sort()\n \n y = 0\n for i in input_array:\n if i == sort_items[1]:\n av = y\n break\n y += 1\n return y\n", "def gimme(input_array):\n return input_array.index(list(set(input_array) - {min(input_array)} - {max(input_array)})[0])\n", "def gimme(input_array):\n data = [float(i) for i in sorted(input_array)]\n return input_array.index(data[1])\n", "def gimme(i):\n if i[0]> i[1] and i[0]<i[2]:\n return 0\n elif i[0]> i[2] and i[0]<i[1]:\n return 0 \n elif i[1]> i[0] and i[1]<i[2]:\n return 1\n elif i[1]> i[2] and i[1]<i[1]:\n return 1\n elif i[2]> i[1] and i[2]<i[0]:\n return 2 \n elif i[2]> i[0] and i[2]<i[1]:\n return 2\n else : \n return 1\n \n", "def gimme(input_array):\n a=list()\n print(a,input_array)\n x=0\n for i in input_array:\n print(\"i:\",i)\n a.append(i)\n \n input_array.sort() \n for i in a:\n \n if i == input_array[1]:\n break\n x+=1\n print(a,input_array)\n \n return x ", "def gimme(input_array):\n l2=input_array.copy()\n l2.sort()\n mid_element=l2[1]\n index_mid_element=input_array.index(mid_element)\n return (index_mid_element)\n"]
{"fn_name": "gimme", "inputs": [[[2, 3, 1]], [[5, 10, 14]], [[1, 3, 4]], [[15, 10, 14]], [[-0.41, -23, 4]], [[-15, -10, 14]]], "outputs": [[0], [1], [1], [2], [0], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
17,612
def gimme(input_array):
b6b52a7db61e5eef8d5ceba7b1af7fff
UNKNOWN
Given an integer, if the length of it's digits is a perfect square, return a square block of sqroot(length) * sqroot(length). If not, simply return "Not a perfect square!". Examples: 1212 returns: >1212 Note: 4 digits so 2 squared (2x2 perfect square). 2 digits on each line. 123123123 returns: >123123123 Note: 9 digits so 3 squared (3x3 perfect square). 3 digits on each line.
["def square_it(digits):\n s = str(digits)\n n = len(s)**0.5\n if n != int(n):\n return \"Not a perfect square!\"\n n = int(n)\n return \"\\n\".join(s[i*n:i*n+n] for i in range(int(n)))", "square_it=lambda n:len(str(n))**.5%1and\"Not a perfect square!\"or'\\n'.join(map(''.join,zip(*[iter(str(n))]*int(len(str(n))**.5))))", "def square_it(n):\n s=str(n)\n x=len(s)**.5\n if x%1: return \"Not a perfect square!\"\n x=int(x)\n return '\\n'.join(s[i:i+x] for i in range(0,len(s),x))", "square_it=lambda d:\"Not a perfect square!\"if len(str(d))**.5%1else''.join(str(d)[i:i+int(len(str(d))**.5)]+'\\n'for i in range(0,len(str(d)),int(len(str(d))**.5)))[:-1]", "def square_it(digits):\n digits = str(digits)\n l = int(len(digits) ** 0.5)\n if l ** 2 == len(digits):\n return \"\\n\".join(digits[i * l:i * l + l] for i in range(l))\n else:\n return \"Not a perfect square!\"", "import math\n\ndef square_it(digits):\n strdigits = str(digits)\n sq = math.sqrt(len(strdigits))\n if(round(sq,0) == sq):\n arr = []\n sqint = int(sq)\n for a in range(0,sqint):\n line = \"\"\n for b in range(0,sqint):\n line += strdigits[a*sqint+b]\n arr.append(line)\n return \"\\n\".join(arr)\n else:\n return \"Not a perfect square!\"\n", "def square_it(digits):\n d = len(str(digits))**.5\n return '\\n'.join(map(''.join, zip(*[iter(str(digits))]*int(d)))) if int(d) == d else 'Not a perfect square!'", "from re import findall\n\ndef square_it(digits):\n digits_string = str(digits)\n root = len(digits_string) ** 0.5\n if root.is_integer():\n return '\\n'.join(findall('.{'+str(int(root))+'}',digits_string)) \n return 'Not a perfect square!'"]
{"fn_name": "square_it", "inputs": [[4547286933343749825161701915681956276108219454705210545289005317346009798484488964285906487], [9018987725957078211722188614464713335111946432316299656655295101074026824905754970818508819399112278447656752418265593323370113912723744584574073240943516323447784157358066092725631468888079671657521335087128381310107575132275431269414916925617425285409687690324310817072898257287148156522711461254908286693274093166279425870512628259566052377124447775880617008644341998746986570027517216466097888155908023911535694848614750960689828130978885144920557763252158285694], [86944626044962750893534726099077851607577335767202198413905320614766659748364345816282449751421191528303747833087523204475945395615335662967952361843822778179782534229212354192766209101375850315231183316855108630259118370451501106726058591717002344389591653085033833236689532101017425569425492431762890540540645195910526551635374784218170167918075478628057193286792692701314469372732153188925881538275813979439196157430902387134890159958261181685069901759092686904538755192529613909917467094292318710873628653279220559015423372110997750862147320862231779563551729774657668133341636540639233469168833443041451311309861633762303390764633929024267773690571925364608910758854305428352902695976922784455202485957119205640624939864200327568164194501735991452995146901328501091017231051289479797848015864711532046471816582619920267032716030287179684236523018307324753992553839464574190017623960523381733982030049622126434122566807847653275684002445260738060662286241040272634704353], [5487892858879877643396793078525642632149239559785808760636930989515855486661211795183967525147757709490732794011843466499555712375096229341969695168412873121001844961860227193295627788828111780259269647536464984167079270856604487225524837251837447697922688876262266435148965870044026466559448743690885162205135860343719742854147928159742799611503678305806250947453657091583992635298056202878376799208259327781739104669372179210843577231140906173509397011323468885735016324645686720216973583077332045434113551566718129665778044514049925362514005989583748088842470616209603774273275067040443822785260624141265429788301302500663699985427], [2996853592120074932323599076537440675191592783802843420116639371441227025982183317503494156495615710126506510824251242050156692982079889720533680791629396272751860071160620843485175720297361631384443136240929436940801963018332389767307597276035928358627356253045476913712860377527694404333542690859678872777370034665142003613161200932559118362748881510326906652687132342340527448109318762235849757983704946604335870028975244210860752289753874], [61623994694367406920275473124326262399997068103062276651287629121996165209190603692582417093426619805057156397610032968372969960416259921569116736232424069317189416109828331535861188061832794169191906898784860753478141455270151856574519413583157768412734994585562127513716893178007831118780637796989705215042407997309882918123266910649066303562751008502694003181495791092715743109706147326005107920996881772521844206788909395004699706724356868900576617716948950149160756011934842209680414554069742087547126242609356796319744527789135141634828875552837625569], [31998569100033603295351806729179483788025526781868899036690925565122323937159187305246281520942122551102764687551579575344606179776981155828031361615338373826922486957238998884726413385743295751745896710566999055431241089194743100070386439484197320274447899752784123170454481115017645957610828061295115398605497727025066096731567798675099405613855154109962644132151813617911462445065058226586864209855379579242639695854961778226710996234631299022847180531623104361775182301727072397952351965072991833864408277116182060823054316115390031520935152932303191016649842226578941105578354572628384942742509849272336306470832912083191689053382217266198201183385384895668800378669171583287555352592956816891069887627914473847546318573204759001215867816223225101674172640323107629717954694733518011959254203041317566087624313286877117727206934390307301345377909314491840], [1073892091986587756947644786065984399079168056228427081500975638408799210562552994484059631650080196436110033434965741006509367469156021616519394438264964152154669037006512944686876634114572135464211269031114920791219834639034223839883929647808120881935919585148296723984978970886017928183072995678362453802909511184023490031193765320760311971419814173242061803783490547626618474924990037771281345073824408224707425326689802963927874186823077291117139799415935649937839750676377745754391565380656607705917286011054485192983202182046892826923123103727067081130648743839401042473069120409277625770646313013063240773726971982145977877820842212073929635753980517670830117202802259050814774880895101529345882673951877070812586936561421970761399911589977291178871882885092078672291675015006913608699473919350626012306660177636291473909378021960092468740679907626949402685234109793348106428476079600535563673012533196481207912789], [91061513305897952802351011512], [56541297102910209008941129279927481112423764494572293712036375940901547800992423589422853377453094524928542177985944217087310470648907312719781813062937237598612883825500706630155087663429633610471881829250191059464341535384821859360745931957471152752735053522333368999439697059065633105172768060674131308150284008788857546955919970937281673997817793900618507735189938455212052391173072632730611600100809835802397145198518384034694524326707741469089720430257291003611250300209556975111786753110768682504221215799506013497034906012196213217193830244175247628410755938488891073035518442346906331659199078466348681576118899285135159473415309220959206036492484295976136150018240881966861550217973197452007688279646], [58097074744292797705439489575860298668973727306007380087112881005567153669184046846074112087052113419874006561833629122965089613375892851123606203366018944260030751956431021529227421077950362253281395894265342820712740779638571235321401449444837680519734451504779220913572428032511158272910397509508235290552609709994767174104907468167205616669169998083839835319642962811130179043787671243743871238152568294007619960324915982801520144503673507704675702792386714252552649845513176297804877338193292601420167234081175425577351517732889798238422323654188896787832184496511029987167987255128713604703327651464358038272228385836053761807544512014956494267244514513982830874685998941096377247858195461344872996528971779787077841767905940760149905250636278658058075206150508618252820976179495882999771591828057658548414162279099992900881671696134019195551756383004013726823599663836926897246377448415908468809866795016453741564009443138189327623231263872590441761], [11051737777908605797728660812177389455613770883022529976680544853542699931470207518423193582358615442099633692409142446033402664009208942000924072171772422568819318848390610796810965003476705400169228001042018218331931020864548528177229081832974201122771271390723965066107283513540752650511712489536984056521276518210152114896472352134741995550127882086643229405994497832100418469624606729124247059205917700026031601822980444770112343004401983520447867547955367878488767434987434429879042661015244399655761836156685431962912822796021249604285315538378649272846249239383215189], [8793939513808567481944745395824578438453617513082062113459548521574573203643710972086650613786902715441321945752404795158227395959204313732291065854384168029225528245309778474440169491854754880269701404699904719444226824120437073809259994932929764889951394879980599365380857791340890982367267453828588782402324931894192407697272792475640640041487788136367769392634468489808507603930008424019859050905225504474725513969561627963662376613034101064416505786778259575434851989655719204349939597021295964241907874198021205328457438991488590903537091377793370342427724020187755696429684333108570150816536725882637789744797769083799707513920135259552700736237945993256698821879379809822140518629419263307173849368028952648564239085506243177741644734215636758082029499518892190162110509434842095634152409056505957011585798832426085356106850566339710046564375191819170205936650703301237400390320155474617464537905315172202], [203401514755182963456019496597820207340459706001144040954789266318313441849777526561189250502349258339964998132000467065770646642228945093009975125201126206951023710371380619369019840535218494226254708297263087422185011219657705702848538911638326914192615942005022261292964136638292695247164605265129255618387656735080974724261348470833624229425885621094388734120928306216387146798950887009963918943661053850112291700113830687494395393940636365480846247119362827150799244841867714638828696138936010216289165784639770832730354657892982893284734832157020351606357474002959781394138389777581015427421812365031647015607541091850366711012892480154946141852969844978278393811105430589628536271601007429098688273241726048751797634590902704883470309914720758291195482486177990197653004925492488273133806556076026934359086126], [65070371849018394278363624245959976095049733916040959125686266721884391009434910318942403908280903437079098919111471778529594156881193059312168012255550980312131996242147006530577654775626384798425297948370312900928025941362960161055134852517667540463207321112225597456483563165072808085962879262258380689819156661793128370334420635383658948274905809549402977283467967011240221071683727276873945802758962109498534011532305617087040360536820242684023197440558347123159039525819145618247556100074139467151663165001520935779759023364043080808990570374373363999881937003248588265420514045132318005185052981047503393114049854208992075981471791405606736023148628397824435305855872840094779126217323130934042134607791060854066972245725091353318018057784221398144315190970760248993360672014364126038745527949869027624650232803061744607144553804240370484013352338714646576393395940666123507241112147427853328532618803634787909635587586120617], [54681145984535786844318317324019120975033674387809668999633440183134059546670927862255088610620006412455628224422160901439344672405836422849574510165687170171281603801792448812716903509442115349827304119268332660836652698251652186885783036], [43109], [5670734200422161480821366228639083501176539181280871943774383654280856616915742439105416627697013447017087740909913182172413743316501811943094131559138634585610264318757795357577796705847707061272804904414010402166526392548746388099197824660254951465099235146983618706002848503181923232370662557414595796186361002805157375825043231340324480859104445829556725854534070892624367866954235703679672701973647781556802745107275429500817080548868745119864032481206126023], [106121870708318047469099132347943477772124019988617090440400450202360325176567087651497492733851779514390126148020836484273201043306007342000001959787554320090938038801983458638683386300013267821076685399758441377080096695134550125714540307778297333993936122724126738345652628596653211990816928968401986405028537592053680782389874003350550927927579429449189545395358023880176290632436341902513006673981163208370830010233723013763396748866447855389748951903488818852473064920039053634225315608922195569673518471552391889722444870282387987174867715840523984506647202161513198461633206948892692253973710390509203688216394665], [365459086072308169838230211858108152580771942494008649760433294812723101397023968335926307498709265938899289879553909924563081816854536846066587502825526943019044124004805249326711714220702708630696751626256479357633828166993848509012208592015932620988184557900038823017260644506505933131574200865189859003779021201836775620051849925079158993816982276899033439568357977509002785754806404584409201421710525033065574552494844197558498327308756110486290064938723749881879210520704723094255632953402354591874846745435203446809124532579748408635276948161449909044132993419358344980688814921215606295893607], [5707358693320550226898419664900637361619505713854358992500241793342351554908521102141623410276961314864341900387491473843199604998330912638689651774481627666010345199377013668686723394230195422993667038280985940873045537944357817646494916563121520586575509630110402729558356799384498977], [1921474060558811782387302494868747344542866026501608417493910621072647659249954149217162164789753288962937226131667625856299802157978592677207845684565603501814765134221882537802719171467827622281750075278989411463500244511965793900566088767073190553680157170389101644415363110999206748626608992544629240924082977775427426612617190127119602346145585728425265183536473414224269436660177435241065134492364087420779285483862132589319497542004504400606261592340337343008306383374600783576641884251262806101613240893643987269084025693564062709248018679508359588928617432643363089203791557246832474253482799708572066857581493927815413396461090008125383659940863477661986056754863509337353297303842811773852924506410039216064538592091183877861776820617317958109539575208828060450798878694882469995147909769484178673713410121506323642818576964299505400335607918378989525962545475592678475607662586], [169922039507309333115714260603827723703951471797992219255326763561653988762681045346827075338772621895665517913695242810689806647605738286255171499361886562119939810195283222105932073379903166676187927536957764900230], [71988186093435689852644145906219781303226791937799383819398039139813092897078478539514165997775017207448104100798581479911233813279796789214289807902270998095125379049608090610607076668413125665337560412417003016835552135809225312315271751239743723941442945686225732], [529123790220962111940660924243867141049474398491939869928109272847520640148739511444148015358111818492262045746331056798677035592352760292792785247288262849426519369975310093115662037047200570304593465596189540739558304647279145906350713957490980800485070327788976668728646815920718995797632734379537080917499912435099648650449268019957931575232558252029176711743188681154015434289645175893688993666742809750365740256610721677252059215636481269162860728692601974641554055081740252616050039079129], [959810066557634175012432500755376508576811857949841462995897755634925272532930946680254871370562374751020317285416829830568109587977490652462116394986764229304545675289548731841113497283427899937837018840784035229251821469995101937632428583890700142189796940397096450004892942940416214491949751500039372428288043175012729449655954294962224787008063771190140672826678913838183], [46543965563030924983091956697371671076327782437058754479507127251177708571932371258646984658482885472585749903358124072987727078090705224256597553967827186295698160359040608624694415109163618864863951307870595493335085356586505312244255278118065327839594813172067967138199290176726495860557944415310557268409195853366795200566241509508566377501019888779477201682201997723224211707861891243501861250917580840808900735474754584916692124816129303615177992361274947308069003999543982159889575976171484649561722305206737780561116174978773613], [3169832358138841890799885333438600941313430480997700366507607330469905249859518028783597097], [397834961864162681626708], [5257528987193877410791369722547714817035734353097561595891431737], [4727790063789074863007020294124479321483031775430789895990572390], [3190691240718017630805139526579104493673607536328199389451543498199847442774754977], [25188780128221128], [2744165951], [47517492591398623346435866580500829014859444322571098446056711788], [86873923335349753640072228544393070467344100000866164726848128522], [9152249273520119609879393985895585455], [38035954348755599], [92317830691373973565053090], [38648518649301539885601717], [92641], [14676508786331352922525261373031222503095744659159180286560260497], [61], [8671344379813664209431399764589732881669497107617446845019778061738612045837500782], [7210570525007465582300546041255095673961390439901839444437276308390328308097202944], [41779955727217076622391650323220873878895569028072], [41474876854236390085200734], [14366571123528950805092023247292734678887457256852881089317426361], [5110692400564773808959000767136503339], [5952725715496620668009541105403389716], [66510944805680464555244976], [2483200830], [7615208105], [9857127238612311683071154470670308213], [43748], [29053666486889391130122715422426213289497497375510], [2884528083], [18211150606271281061793203439266926932041651915701], [56288832565647442876129831643040591509953840685225], [2333], [374958079619704091072830393315727559146117252525583650089750936302576334852392328], [1225064667938538039980007624842785703461895707490043249664292535579012930376316818381382252279418832475862388701272627851655529589283949444357152718918639224563538257871], [5457818793696237430090817603176265071750489457482688668030621331304120741441147599620243734828335321829224687145006100226], [7203759321346188398037167639596162726953053554720253400199694904952655642294734062909198718036782788], [122172953349153609972664374465881868389212042047833317440712899], [4127422396276624357689441264632399395570088128186938313141964597684965912540160250140308037895662983082668956869095789700], [4740644097139835], [499339209175413144099419201456224451154945314387015636897782832186943172849544107393286689679798642680871086706167830491679022106108122190754340], [8719682271166274], [9568718588149096], [4709788115727583], [5265268855398235], [4724560952868207213259492], [264926618195551350199600875526452153239997122745869676068378349531211339430445707], [373664477926870177732500079582297742], [4516746001817642849273809069280855576258981219593687949051023904899786705225044180141400894543403064675173324255149862804775867376459368916768864269184202029865148151509358521056460077636803780904537157078379151587068572792687537206037171590904547891082418], [452057410], [873934303051807108927423799958085088], [3], [6886221736684041101599655824315309234398240232410858225585630274882645204303731507677113540831619261852136796347721521987], [5912571346793621016862045821668670313574533829620], [7433640945031757375308263345071149952810257627989380887902190844779512310485533028653453759262706051319468443293096216851052721374919641990923650438256533436213319541577], [2350592363443115], [3252886249521676], [615448509491487349874678326947629085528077677149034098591541405054837073163755749843755088874356204440981840921010848663277160446817384332990033885636674009814167368404364245254329878595282880941735426356074725924443464175595], [579270341759885499284027647654076515115300805576608109469812279208461926303902099584648117847795661367839739404297062763001072421589589693557423476732485136002484348950467586291502519501711295291556261769612041000292144115661], [481543726074606294796148493990151718], [803], [889793251543710916175556705339446670144142638369169662448570373606942167447665727536116265925946029032900421305135017436519009395408192434851690533712599692903124715892727178732898429048189027757318306844485460349935995567329], [8269023349661824251479857603744048404620153931187575420114480658702555675474301352675608861413410580583346534032351804885], [8057753943885518329011366087094050787045370193422928026813632000941064966863910526411831520917953818133169092596418812678145020729942777152841386514215556214455849295636097765010509354806359804797], [692988543], [7516564999276440860353235884888739673678989067282867546920708457110145685056704426747985621786500873047852482267256473527544245812709289728083955116981523393698744974663], [1747429900032803931146135], [2047865955346030], [6], [9163670990496831789114168545766996826112693861063753765242110008720967523946421331321735040781437078386478949572231403667132078156014956520285691586948149189881080273370], [255935717371697861900972135206045670053703818156857088917526464417397344956248817605548323573205171336674093262651990158126943091366802063660699], [7335681911802077], [7662941411233782689703567225803128804713126940099316370949524783354272724190112858273949059338016426909764456246144061421682002062140219860233883986835308318875851187611986593369466074150305919925170297467300307108182397980537118925839849063413257372836919], [761646629144121], [590981333592065356403118274434726547041143175595062343989632217964906798416856644], [7799544211359707656487096233362435273656512533746095708381191585636826389374270441585598853564424596767001852683042353810607288453982494720314634672964756659278813337546031057521003444274405373207403707061744094820601081592826956723937560613546808765614571], [870513600], [4588], [282531579216747965402876296033446713389305587546243295355934427959506217052158615], [9176538109553805923352993066610147878142751227974479317801208507599676169134938184901413131474620535], [9539], [4422660286226337277774195705050109912525343052757722996746071518627084202736093474691739134517356235], [5782705962631871271616020358163524489146184083132381561328020065321076901633968541137794476604659811], [572168689679932876831476426200762224304004055483828710235263144681769682849691351526405844169806123979965607625004832425931145000579173296208059620988419101945934793099336526875660837568679967254915690686465217066438476732182], [5583], [1374251034399498071424208919267433761044767101635092414908546370], [925754405511179], [813715457492427389677592604317212299032683468966791305331343382684907471030357890727934766114530174], [2653347929842462677886967493323030622615418773125067043723454257724805210268139511974085207648286420845830225980189580193591685320321288277653360948766576226298139810195], [808188449786278406166344317938816664009624879754003303077119083351361527846701419], [653273454], [8484522060685870038377275490772751189549992663349378998785419400503858614262338473665441116663388220690482311025022437677253868883429645751693242637819018966785189343997097564719242935502424139854133354612934395277770416487723767333416145763105277984581628855924860713968273152749428345666548879903674819453831036143558305201485133494728908046215993322225394599036795650304242022701980500901521072021463604304104891909529895103418440165328004128840299528402413215978420070279047200947692258915068772169293300523022138855648110017108588395616663333316416304989088048325327080166451357430156225059876298342572977137813286745051672716515076196640638480901941648970453588971096688418672191690488751250461303909233403489382942775259681327524569916936440065404696167946610124734111348400433034481871520876696456710839754081073644407954627727045936373422481933544285738495558630845572967108343642935662519747663676466110778899433265184512314049678429992664088218279559066720469875816357095985845325292146814850238020998360428678728180873343463229484592], [846452819141706896124707670263995324274285341890156256105131117361155770534909496041112387091433815569323921632611439738291337923533132818497249838940017129758532482941271233454465912096642751135444385513166122575072354113201569807012771823210874143342464419121323138274909577262922281004364852428351503273070477518780946111971802720116233087918905234432773188696566647191656001908432768159603481167186960432289932666952142712206583801521029], [4652551210379223937031192837459769305941467858507749018192892501593551193439431055902099950341832557401808814933509796392285807027257336333996773718659372843468189694341690038184128170395038219753660017006347183420898926194205328578800527273332235728878192908642774434993133697715304652231076087790492928576910922792458778868330747283737711978694298130376131147838809363566139757750826390595200530966840181882277204219134946922815772328481436367087354858759964904694578342436485441087509795156956296695038542534117009060818972993132848240478716765714972727186233029535653332181188731156215904231223443603171904835832458250928056153895328799206441065034945637866827013302811136355527944847965992159661999375505801660796140932669960737911494625802433608161831166803353169257203350941960115179143294906080353888136807660998208513327301021192765737421373883403893937258904313931950942005685942252893128710169282022575772593653902017151677924548422310069266155945968870855217534191398408221918815553177932], [8315413095770621015334946824952630454884296630325179289490070263090823674794051552609532904721209558352828563148864873279201647010896439504035742320883732025347304854621309608111639293127103994679905467476840849287782935134530529368423259165726833145656286243188064164354625339524738406966753142838559208779576598907057385085794360569804666876870874680540228680204929705622584253316225214911735988569153237641799627515097949512284550793121967872147080384805972828670822584983224105940825712476923161152712970241105481287011795550394228066695967686398443107165539846274421601097272058433394146851259654403822260435203064722443374645953046037213427115315883045616626899944117238026010129378445515368324981976558442998331097920409509111513416260966017222356873236552997213866103992793726607479601884400714380128600423133315477395261216471100134954449299974120913827042305951576834087778171660044400893253571944499479269613620323584954866337112556531330546300921891870485461380694241954420505947505184368697044016993747207829649], [980680964239899151437725050781358823527081668841613553068551998932662381973253844743668850281513480182512015866458832993481300821566465229880981707196405687573512590780119627441982018547684803909520598619098292323756845089057088499877644929478930986616236713723626362589644115273220063577722835384573602075602862248893537307896694792884225194736326188852910507899884328249005393325353450076308462083220235893244465370550357227289931007058495], [253889365289627042839143439513933675734198988465889348480216022825376556593240977286949035988503893116609002792907089067214390926642030924277780949075553877572077060175728972479344342425318335383348006653218790691235170516093491404844072354626877016844423616729756503885351026889614200196845300604724944686855166307237337622366048203897087012012549676319644119051445204452027864234098356922669807743248841389815838539664667755987528981351262672205122], [5542675866182288687521087758134229485338746013073961998456606620723930309018341454365995352643380298979239428933462745345735293305341552953798633656287538793590565470008494350790281463456207829319234767641148005858626482979252327556688637494362616434818804837824445208404204095090812735688495580051617450571536113160140222259766548130789994796082124700267206056522713672569284216541284906616200131887828144441664699438938952248308004361955562900009892900655868889581494679930303159631611246969114465740641987524157032383686253366034352273513633892302074563255134800761154928876713038127418183592337727807461376020750137166136484073472614259892687616937856962579765679310092424406199908458338197222617816268855754846141369293986397068171042953554139824562359496053917724913984755265156567918566824280852941310970588902858780592437256930575531018249645527503435514532626572375630755145909631319216440537605797624307985469297709857175774962412514031124941901214488304116848499326782738320775280687869649], [57627503969971008820712462916937992871277039396582679119483348524101008530255617689272198598878818268886069893369256466058475166618214955578418195122693933288404689847505357440047757875405768869716668807881511441659949550705003122271829308855070783894826112914032537697269048908232509223584145418578653460755872087178799587853128745064574120085669156589705174523806472569012222350297458938214843031648663511015997954381379863619003159632752970022377241973851161004162847114132531293361075182146373927785817404181941233905482776940990354264092947396932763758183715310737438482891578624957028263351586967255739664283112156049155623329193957720189491905334736029021147798740260347259502556797353495191088841187430068548586478422776800457474807058936397452459069047991072606350249358643858004799940771934677838908975389168138191028763044693285944360677601394887368722925493739251973511075168457278846300821674170048241030920154757136889119322944308851813202190585583081560465005171594642654035325259027879560393339101875704552450675076176819935641942], [5640947245574802642066848689585563794837459258029285378773685089147900983508970384355203050343480858965463779938676552539348674818957647127508435450230055133259869413437575997795367912548357285467657733568615826905500812527250043498595375815269136052933969878200928932790260839812522674979909500409106921892889188720886102862318120566619277018898376658942169511189910746175406997591566473813603612228871285330807857523577130935209784816204989719153779039363237873773524868559699881066703316794753896018541468228278633839594494547679265272757592987646035333291340256207215463102130534097296873755455174595549334791980321316039334212863728629983725008212583774869434243374011020392828128833180979874478231082848113968739846945788857070012483928746746257814807149649658219741679917448492669687081003383188305556577635230349038311901451785303656608834016438973553999647532600383061272589037826195883140612630693685142718880161502560302014198166681480490550759011833136641529631962507821049753788631264374529678721547123829912838], [1912941057997185932620202359509530791044400972818671118653506426681230018220138186079733280263764689167332390325017656670518572071293798771207257418329586024283916447856264801005024325154755017298767189918806980177342801720097709960019784078796738256742412105587833209038858054520493441704110152485454035049616235471879409721949929743747375534941443412599038971411506040618089683], [970977739506437414988265536881349892479505154001050826343365690526520498379087741272406813157985463296168848690151113392364813369932843640828621933898988146874340051816253711613260180463137690527908871581369180034725277853833680764207276695965814872661331352437341570057975654611272196700587899985109324992600746129312277805216383626732525649115509127628235012155265759398083946255891599560241725588284733204406836712291935041288743448876516], [973254299747850796795175608466564323955475243308825133080505159392665967630400291836810063313927438139849064646433190559362204695800893999888866033777724012121713093310291068177055914284914869163334473607631757506557206298998900966941196193491908946994605229292582580328102541419025997254239802155796122334503425568394339552790402606739039393741836658811554470045441227720153991829577996943646624484342774658793719213656933836095207784112801], [15585511623968564074548804086756201633038691751081228322415813814811216502336714798717729721752126040765137994618905059143403898430938394157547558687411313081360836155995915837851721526101003046986736924170901356229722525718782731610973186637511678836011254009526394744286492321944231026778210618926346524681485288295172667523523691659205880376876695257005175054128821173890272214499099755877640043485729469798376262207175059070518457889466376061913700904667549607001163336523512702425101091939031182556827163708101279369395296177346779846153377187940003364108325205117700001151120745883441187170538514427771384805329618973829914053434848537024881296685002032802633036356378180506454382712786237276388379046892848025947871178057133448591477433273473058649916978518800886132857675728479482125488614971915393459197415507471697583401867662635342557201951175881726089066924472413703537932110935271320034463671161077162972868657508181846738730419493653026435564277976417922290679169148076301223474283036819841169870679124584078886901419380233801171616], [81742473590645676766380572279706879684088932943198413642489681197826758110921141901585409525179094396722693952735905434371729490388353007450785370299239978641480422749323147679537166542747083351656004278697863363701637735202225080553151566642113746032021356701226831018087118286848609646190048175366638733266452039232496858526395618073728898271869763736891588400162019711517684348069644874651229572216933544489706881518213569473386446573040264240714433289917917589681019583973494517300625404709049736918807440510841747972226988758709424010058731461511216746511480804921874599556565338362973227971794023024315732426306096126074031876750411853919409287538336302374583765115259211921128846220962198655357115938967707431213325088234831937400281050502382652236747494832720601460766597726124666408098633844772214870958951966460744448807158530128194707352886276328110655181045428291808345820606437946496850793867871379262605210307660457408058240949401888670808910796939748301622423841673441579581882005912560174778825021173843551977529457923396528868452], [34440203800970937211308626623612143758984591669616566148199096920786350955422727634266655117032803937565000953587503312158903676676845241659177403071927730310250017626243272611496744515411342901759866639198536513485265157893545039639116436474917753359609791424770041303141783460696170387174838968842901998548739368370114609396449828794625530329353640511718116146381748563214336085707653031057798005035337093630691315260072050147380730236102966950726539100666946154740564963229423551978008239909325668], [27728554969663689923741442264059571090188399722491244882231789251449369000027827997171347904681927817987766456995743107562857898604443643225240440078792483960814688796888929098635169889311768142907268129726925586623471445233955793691418035104697064211375888723224994412779807302271881943373356555977190584329179400484171714268929420088478282369610439421826268852478880285403518225156376559053411094580745386653388727657954866288564177159807799007201965079294234328485668514784174763644203939800787382], [243938325049296573140281168556946380995056805112371968540612839266124731635003597943512714040614561146405420234542600328470215771626389131008833661930529210729996328728893175148960628993606439372779828499026652644534537049696402398001922574856380376644757616018065032019408824951018807107121382965078517866153625673290898834536439041136545963629152279757007697159765145607116891008969029269737266106629273124912676959024811780598413648778709634045914542218055632185042089786765544638801213157557034442874596198450798378958517321307966500587543760444924281278246209716103845874402164437690717141767479187174955870243569991775226533099582310282913418195869848917703275396430889388954848179086371020038965842766971299069864395529711545012461151892219103517326950862632532273590229932074525100018372384800224711328674493903782110372644426862114609773503700450497974411613943492137458621069921862445597800312636176152743458278602707219549873324475225399925729892622629569921458655248536050723982629471636], [5119445810340783549387985202063706676801240968813225484531455097924921414457716808306030404127334292309023921900105752137133964608411280354057034258142176212133358590252736192985796310512582886903379991104494125450895695837696769888808746481090695268332858265916477548482381032689947017731105424303303612367364363814443468049460194382848706038199167106322424933663294111793741261491871285425156635451106338920417716604261916110327879580381727005825539853039586997643502146888964949989583034579068667334277797318323058762072142126671177884303564913702919111225008880212668670591227310783879468915901152129856149896764813339130214748212148383095147076150097949947336353890441488362795759786841692277548466715606440332186796739969496130881790268799515613334282051607582194732012466912948619723021311475792534286014435345985086352600318396792676396713880321118121750313961881875839852491073728501022692560115024285014338847467853847155779299927475571196812570884497285376539951994794864167825213242944141433501678306032594959363], [9267578984395424800493520458239734990394018212400070199766315510452980297564942278027945628934693186975977682922594171621409299719580723550969032807959750436367564240704008986753226644872932653516031350308392641318167031868070939975720774788490975858695833765293151495643796500918792851413293373688828749076086080433375858641484322835364754321803202456845254187433961097320020121051338005573393934232017290974715733281779626218673046774231440476538465443251544387628328485403805266856543892527101422268776413215640132643397984394881064376222852283915584912853236370240439064268839519646680845670061765069541543068476725771101868616078341504611405544336550262952283733232047005181362952110500978154857806884482853243715011148428942447545371244384402549265979206293192634675797247052026282421078408215546882714834617348402907279271713496795221418214858602756328075563714266888843391867763168322003269844372541322545196934157694115599682208300525344533257789234975860954963441058289659496222992783953067], [9245864885939597319106442839413652161578858132062169861483842750547121173648397776267828668245213175060448377832070245445207119019431195654700542046132734715351146181598019750402998101261375970566102228290199128700194380856251651960351749900842004541456137801608040569048529484248124694699238658816725630678236456862999574970069389141135475827234791498517767597623912724857748199596966799483323004558933004417348144748948325500427986216845125147839142677388437829282784792296861597369], [486539687161610852989182730103338462671535048741305545317682483550066070203959103803802331569297136302834981041028700783132309678078962245037304719460440132352764898880916581826832752904778700503292359657819806991061428294536017481900271796611033447218324500043117303346245789360466936685373838362515845620162388316122073115461396754592285532198795294066209836447295353025783147301617234546500474226908149086234602658649642462021547889001560], [6129309567675268507449099614625842210296825330104637421116711631297191637437259336849521290136056472463320128809714479722208041019733347381377709629574267884964719954428631805263497999019062966140349595466358326362939522556153545754529076914276352582555132504332727915501748559669490141110362574654069325593203129270618234909249502546987942099431042060781651772237217784863949262], [36277862609635822704186844932136744979601719215844068286378443370701658856352043099595162411331273483096793874094868540015292720874761638059833631135444755106194634559965780767629295628425104519102942032920356645113013944459107698911678592317472950794924515378747683011368704386099185474186330239248178363271624724584481043661183578892024391961351046756717026505600527817315856204711933725797211062005725536787800656467595096055684596764967713766219132965688438605732277826279961164329310204358518243178127751236014585742522868793495390485445144429683884761310486480838088671212842663702833770997493689827433141670180486106898462813998183212473826040516312091506391931142523417919095574785707191454173486767316941532623514330906149294664829671976766229719413324122957406005038407144067193855931752051273068129662065380262941972972714803907545350183838903938081754024976514870530547607070399438526524220843239381955310025971558014101624305263742993644156793468781187868836562177823225811937510165139134583779219546436609562723448147538612363067449], [702118040022571417089999802896661328294466648071797502649778268272963293523598247224699477049863775633442222726160799755673614931644476216183947019881623723789045522645203357622839295913897212961709996249122293326475340766414388809207934743462157280118624220001007225470330123233778245196413197653742185805657173420427114989006719081413921422480062076577626088992644965086398329471700717653964590947529524785812661155846071585821411134133025949094244], [8148101523870817598633995942198391909737987770292546526897283821979133353935544509766101667259970161591521136906694275553820778411656640312012794586195635816656841573848612443154690279724485307405578918108743393548586426582420028305553425861978681600379706984611718057900617616557517480154912114003121014805100762232180289789422635278262834935766964309542129391411596254356229470], [56172540797442471947380707238872034778245605469762167693052256584653626628485890334592335365378907497251188527664954595189339773095875361508506434082632327186959938622166300855419932617902198432351865224275891143434886902286260810195552416238967770046004259430894162351893136156584931061223815395400014690738375394129940381893434322635207828052894072651542911531109909258150759159643384954423465664938411034728783767635401800353047947282310115255566326052691946158675296681927710396419036175722776535107754187131786932742191889444424188062302098414890228672643436630982252476582310454632928581018310858657248067311406026768642902074588035248961046836769479938184971509636934278765703980005627307661821347239742603328450139917268541354526371102210810970734290669521791169847038310694759547580259077120675071618015573135941457609561350348767694461286892643918241572074032608537854760584089696909718857862148838431347171894712058587316004930065182677192423569886640816436641727565904841618329966508672059974212607021745901238135446500295853807748024], [28829189081535783045667743402721929571711037645646771448543754179628394801057860640114370479883602674770802123934685633468857142919013911958416974484366828696417984556537876245359805819728816419644909193884737048136839750076066202552925789169730407896169030430941943246900525195269477031754191897087914605902707550667204140740523023617913829991671952311846649080731473345927597037940662711191205314758392123469399968777982166329919722276042699157769684182109682284731602431902120076447087458895151137], [9890207027718620010900504817990198676973969090057517097201991478763354072245116921469928604354275590256162164182075273325645616015432200756112733350583575644357443199278605765850342485408287425462982026391320542459759125765256073344771658136929501989813453190142304175433773293631522989804320750774833934940412068675685691411613553904862349657228715316863150023435266608812054822492477731237443664781005301732385797054169804145161579023284394233053021195443456237859877255551438878375089251270639138], [2623266121561550740925559639865072301998943096680633256198336342940925212593200362090985189940663617456450484070769588456924362837160777416508760962845400871723120007044506802208180164171825270466286900811663297324022396350205154592188604550922630857564017085415837469207834015394092657829054350414881516385202972602855886462948497603376960150105798658186012125], [9451624774706780550819578082060680201114526660535601177340482958958802662452234939092117385828368598500735381781163783888754244105507411289488597317844890210424703250822008412636831609241355408323206368674840286702325105894457614094549506400780743086435024322734095849393807106628900634485418178936308462127457997735919246367311750521958532997885205043120826601], [899618133813028455757406535284731271595939771598230174284999777270623059215961831556939547304281901261109698728283591956841338012455795371645739254017564000911447756722020900166937459202884876992990382911094839645618613987985237940399830444882590333979498663353608931033159458722547119030271603302552548726030305321756037491723043500953735091141041801626272196319582570497702498753983217528809619349127742044443419003841165526181538889118097746776758687794118692561453031937354272446965986697121268125949180408138008805632906861434459623366351557139685808833579397478055613339554633142911453469084461032084782505762440382622602082512236634531519313879396635489705938374583863707199809149523890445825712260652223131435873252090428857762719471253037697143704105711617843257407988203952349969489782758780763186238836151232767663546270172562739209258291964155708387781444292972601200490575078734340460061963716517902871822700457024865308936936347239730192617071217246929440574443354564945345815316508718650637179012587241569318435134426355498136830785739518696102575809259646991570245218905991701104553710502687605348071478435416182761984377938872448620716248065468593459695855623107885254896639679873446213567373967280732521929482544799394716967754055856007836639357605422331253267628851820937128054942322429167516864135861393], [1113798041651332675390036661411812759753459533375892426179344091587187375695231975664973723803219152237267312038610070353510475403958840055274067872153523724461184829113856932795859304467561446855700500233054524750716173590775458193761829051311833857343380093450794849164690056350725269893443372600574897484055044160551743378585741898515442579373168655064784954889919800935170546457643685472459351554291339579365362622593068927814350064311701643855323182251519699615672899071873708599904235950138245942673119913208801391213965613989037458830574197091809279346668492734507203822011177532069857661960523548629454029508951267222567299868972459534277881783026203487646298541807938964908713130475482450704629225486694735845535258983511253192670050807379062503198272306551006085790709835243808172656366261058803736873998738353953018168343768379683012226909961221783143862839885079292333639305446879736011245404597987492683148646902511007743494557685183612002247777947898908591485332490148696744147082390379332144604169211694134540942002831282177907468535099565041718805500016678245226638567046564856252040392422630291436182213794837760618322094530174097150333576342221738114652024541774678013835616783934890824327437127585679710381718339747199204655153644095895080548713437833121621223826864187712571367905100613913157526900067755362854618596940502933204265426463348764946774046102987741572838601691937501810122124189795504491454036148454842038870050506659489456531810897605386302422736737471152638396926144067526891729764193580990654272900708952630128668359284657171257567113383562838008211359614322806888], [22578704189865492281383005202974856255837050787360479503960129522750992687494895474827773135894917870472977671179229697898]], "outputs": [["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["52575289\n87193877\n41079136\n97225477\n14817035\n73435309\n75615958\n91431737"], ["47277900\n63789074\n86300702\n02941244\n79321483\n03177543\n07898959\n90572390"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["23\n33"], ["374958079\n619704091\n072830393\n315727559\n146117252\n525583650\n089750936\n302576334\n852392328"], ["1225064667938\n5380399800076\n2484278570346\n1895707490043\n2496642925355\n7901293037631\n6818381382252\n2794188324758\n6238870127262\n7851655529589\n2839494443571\n5271891863922\n4563538257871"], ["54578187936\n96237430090\n81760317626\n50717504894\n57482688668\n03062133130\n41207414411\n47599620243\n73482833532\n18292246871\n45006100226"], ["7203759321\n3461883980\n3716763959\n6162726953\n0535547202\n5340019969\n4904952655\n6422947340\n6290919871\n8036782788"], ["Not a perfect square!"], ["41274223962\n76624357689\n44126463239\n93955700881\n28186938313\n14196459768\n49659125401\n60250140308\n03789566298\n30826689568\n69095789700"], ["4740\n6440\n9713\n9835"], ["499339209175\n413144099419\n201456224451\n154945314387\n015636897782\n832186943172\n849544107393\n286689679798\n642680871086\n706167830491\n679022106108\n122190754340"], ["8719\n6822\n7116\n6274"], ["9568\n7185\n8814\n9096"], ["4709\n7881\n1572\n7583"], ["5265\n2688\n5539\n8235"], ["47245\n60952\n86820\n72132\n59492"], ["264926618\n195551350\n199600875\n526452153\n239997122\n745869676\n068378349\n531211339\n430445707"], ["373664\n477926\n870177\n732500\n079582\n297742"], ["4516746001817642\n8492738090692808\n5557625898121959\n3687949051023904\n8997867052250441\n8014140089454340\n3064675173324255\n1498628047758673\n7645936891676886\n4269184202029865\n1481515093585210\n5646007763680378\n0904537157078379\n1515870685727926\n8753720603717159\n0904547891082418"], ["452\n057\n410"], ["873934\n303051\n807108\n927423\n799958\n085088"], ["3"], ["68862217366\n84041101599\n65582431530\n92343982402\n32410858225\n58563027488\n26452043037\n31507677113\n54083161926\n18521367963\n47721521987"], ["5912571\n3467936\n2101686\n2045821\n6686703\n1357453\n3829620"], ["7433640945031\n7573753082633\n4507114995281\n0257627989380\n8879021908447\n7951231048553\n3028653453759\n2627060513194\n6844329309621\n6851052721374\n9196419909236\n5043825653343\n6213319541577"], ["2350\n5923\n6344\n3115"], ["3252\n8862\n4952\n1676"], ["615448509491487\n349874678326947\n629085528077677\n149034098591541\n405054837073163\n755749843755088\n874356204440981\n840921010848663\n277160446817384\n332990033885636\n674009814167368\n404364245254329\n878595282880941\n735426356074725\n924443464175595"], ["579270341759885\n499284027647654\n076515115300805\n576608109469812\n279208461926303\n902099584648117\n847795661367839\n739404297062763\n001072421589589\n693557423476732\n485136002484348\n950467586291502\n519501711295291\n556261769612041\n000292144115661"], ["481543\n726074\n606294\n796148\n493990\n151718"], ["Not a perfect square!"], ["889793251543710\n916175556705339\n446670144142638\n369169662448570\n373606942167447\n665727536116265\n925946029032900\n421305135017436\n519009395408192\n434851690533712\n599692903124715\n892727178732898\n429048189027757\n318306844485460\n349935995567329"], ["82690233496\n61824251479\n85760374404\n84046201539\n31187575420\n11448065870\n25556754743\n01352675608\n86141341058\n05833465340\n32351804885"], ["80577539438855\n18329011366087\n09405078704537\n01934229280268\n13632000941064\n96686391052641\n18315209179538\n18133169092596\n41881267814502\n07299427771528\n41386514215556\n21445584929563\n60977650105093\n54806359804797"], ["692\n988\n543"], ["7516564999276\n4408603532358\n8488873967367\n8989067282867\n5469207084571\n1014568505670\n4426747985621\n7865008730478\n5248226725647\n3527544245812\n7092897280839\n5511698152339\n3698744974663"], ["17474\n29900\n03280\n39311\n46135"], ["2047\n8659\n5534\n6030"], ["6"], ["9163670990496\n8317891141685\n4576699682611\n2693861063753\n7652421100087\n2096752394642\n1331321735040\n7814370783864\n7894957223140\n3667132078156\n0149565202856\n9158694814918\n9881080273370"], ["255935717371\n697861900972\n135206045670\n053703818156\n857088917526\n464417397344\n956248817605\n548323573205\n171336674093\n262651990158\n126943091366\n802063660699"], ["7335\n6819\n1180\n2077"], ["7662941411233782\n6897035672258031\n2880471312694009\n9316370949524783\n3542727241901128\n5827394905933801\n6426909764456246\n1440614216820020\n6214021986023388\n3986835308318875\n8511876119865933\n6946607415030591\n9925170297467300\n3071081823979805\n3711892583984906\n3413257372836919"], ["Not a perfect square!"], ["590981333\n592065356\n403118274\n434726547\n041143175\n595062343\n989632217\n964906798\n416856644"], ["7799544211359707\n6564870962333624\n3527365651253374\n6095708381191585\n6368263893742704\n4158559885356442\n4596767001852683\n0423538106072884\n5398249472031463\n4672964756659278\n8133375460310575\n2100344427440537\n3207403707061744\n0948206010815928\n2695672393756061\n3546808765614571"], ["870\n513\n600"], ["45\n88"], ["282531579\n216747965\n402876296\n033446713\n389305587\n546243295\n355934427\n959506217\n052158615"], ["9176538109\n5538059233\n5299306661\n0147878142\n7512279744\n7931780120\n8507599676\n1691349381\n8490141313\n1474620535"], ["95\n39"], ["4422660286\n2263372777\n7419570505\n0109912525\n3430527577\n2299674607\n1518627084\n2027360934\n7469173913\n4517356235"], ["5782705962\n6318712716\n1602035816\n3524489146\n1840831323\n8156132802\n0065321076\n9016339685\n4113779447\n6604659811"], ["572168689679932\n876831476426200\n762224304004055\n483828710235263\n144681769682849\n691351526405844\n169806123979965\n607625004832425\n931145000579173\n296208059620988\n419101945934793\n099336526875660\n837568679967254\n915690686465217\n066438476732182"], ["55\n83"], ["13742510\n34399498\n07142420\n89192674\n33761044\n76710163\n50924149\n08546370"], ["Not a perfect square!"], ["Not a perfect square!"], ["2653347929842\n4626778869674\n9332303062261\n5418773125067\n0437234542577\n2480521026813\n9511974085207\n6482864208458\n3022598018958\n0193591685320\n3212882776533\n6094876657622\n6298139810195"], ["808188449\n786278406\n166344317\n938816664\n009624879\n754003303\n077119083\n351361527\n846701419"], ["653\n273\n454"], ["Not a perfect square!"], ["846452819141706896124\n707670263995324274285\n341890156256105131117\n361155770534909496041\n112387091433815569323\n921632611439738291337\n923533132818497249838\n940017129758532482941\n271233454465912096642\n751135444385513166122\n575072354113201569807\n012771823210874143342\n464419121323138274909\n577262922281004364852\n428351503273070477518\n780946111971802720116\n233087918905234432773\n188696566647191656001\n908432768159603481167\n186960432289932666952\n142712206583801521029"], ["Not a perfect square!"], ["83154130957706210153349468249526\n30454884296630325179289490070263\n09082367479405155260953290472120\n95583528285631488648732792016470\n10896439504035742320883732025347\n30485462130960811163929312710399\n46799054674768408492877829351345\n30529368423259165726833145656286\n24318806416435462533952473840696\n67531428385592087795765989070573\n85085794360569804666876870874680\n54022868020492970562258425331622\n52149117359885691532376417996275\n15097949512284550793121967872147\n08038480597282867082258498322410\n59408257124769231611527129702411\n05481287011795550394228066695967\n68639844310716553984627442160109\n72720584333941468512596544038222\n60435203064722443374645953046037\n21342711531588304561662689994411\n72380260101293784455153683249819\n76558442998331097920409509111513\n41626096601722235687323655299721\n38661039927937266074796018844007\n14380128600423133315477395261216\n47110013495444929997412091382704\n23059515768340877781716600444008\n93253571944499479269613620323584\n95486633711255653133054630092189\n18704854613806942419544205059475\n05184368697044016993747207829649"], ["980680964239899151437\n725050781358823527081\n668841613553068551998\n932662381973253844743\n668850281513480182512\n015866458832993481300\n821566465229880981707\n196405687573512590780\n119627441982018547684\n803909520598619098292\n323756845089057088499\n877644929478930986616\n236713723626362589644\n115273220063577722835\n384573602075602862248\n893537307896694792884\n225194736326188852910\n507899884328249005393\n325353450076308462083\n220235893244465370550\n357227289931007058495"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["56409472455748026420668486895855\n63794837459258029285378773685089\n14790098350897038435520305034348\n08589654637799386765525393486748\n18957647127508435450230055133259\n86941343757599779536791254835728\n54676577335686158269055008125272\n50043498595375815269136052933969\n87820092893279026083981252267497\n99095004091069218928891887208861\n02862318120566619277018898376658\n94216951118991074617540699759156\n64738136036122288712853308078575\n23577130935209784816204989719153\n77903936323787377352486855969988\n10667033167947538960185414682282\n78633839594494547679265272757592\n98764603533329134025620721546310\n21305340972968737554551745955493\n34791980321316039334212863728629\n98372500821258377486943424337401\n10203928281288331809798744782310\n82848113968739846945788857070012\n48392874674625781480714964965821\n97416799174484926696870810033831\n88305556577635230349038311901451\n78530365660883401643897355399964\n75326003830612725890378261958831\n40612630693685142718880161502560\n30201419816668148049055075901183\n31366415296319625078210497537886\n31264374529678721547123829912838"], ["Not a perfect square!"], ["970977739506437414988\n265536881349892479505\n154001050826343365690\n526520498379087741272\n406813157985463296168\n848690151113392364813\n369932843640828621933\n898988146874340051816\n253711613260180463137\n690527908871581369180\n034725277853833680764\n207276695965814872661\n331352437341570057975\n654611272196700587899\n985109324992600746129\n312277805216383626732\n525649115509127628235\n012155265759398083946\n255891599560241725588\n284733204406836712291\n935041288743448876516"], ["973254299747850796795\n175608466564323955475\n243308825133080505159\n392665967630400291836\n810063313927438139849\n064646433190559362204\n695800893999888866033\n777724012121713093310\n291068177055914284914\n869163334473607631757\n506557206298998900966\n941196193491908946994\n605229292582580328102\n541419025997254239802\n155796122334503425568\n394339552790402606739\n039393741836658811554\n470045441227720153991\n829577996943646624484\n342774658793719213656\n933836095207784112801"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["51194458103407835493879852020637\n06676801240968813225484531455097\n92492141445771680830603040412733\n42923090239219001057521371339646\n08411280354057034258142176212133\n35859025273619298579631051258288\n69033799911044941254508956958376\n96769888808746481090695268332858\n26591647754848238103268994701773\n11054243033036123673643638144434\n68049460194382848706038199167106\n32242493366329411179374126149187\n12854251566354511063389204177166\n04261916110327879580381727005825\n53985303958699764350214688896494\n99895830345790686673342777973183\n23058762072142126671177884303564\n91370291911122500888021266867059\n12273107838794689159011521298561\n49896764813339130214748212148383\n09514707615009794994733635389044\n14883627957597868416922775484667\n15606440332186796739969496130881\n79026879951561333428205160758219\n47320124669129486197230213114757\n92534286014435345985086352600318\n39679267639671388032111812175031\n39618818758398524910737285010226\n92560115024285014338847467853847\n15577929992747557119681257088449\n72853765399519947948641678252132\n42944141433501678306032594959363"], ["Not a perfect square!"], ["9245864885939597319106\n4428394136521615788581\n3206216986148384275054\n7121173648397776267828\n6682452131750604483778\n3207024544520711901943\n1195654700542046132734\n7153511461815980197504\n0299810126137597056610\n2228290199128700194380\n8562516519603517499008\n4200454145613780160804\n0569048529484248124694\n6992386588167256306782\n3645686299957497006938\n9141135475827234791498\n5177675976239127248577\n4819959696679948332300\n4558933004417348144748\n9483255004279862168451\n2514783914267738843782\n9282784792296861597369"], ["486539687161610852989\n182730103338462671535\n048741305545317682483\n550066070203959103803\n802331569297136302834\n981041028700783132309\n678078962245037304719\n460440132352764898880\n916581826832752904778\n700503292359657819806\n991061428294536017481\n900271796611033447218\n324500043117303346245\n789360466936685373838\n362515845620162388316\n122073115461396754592\n285532198795294066209\n836447295353025783147\n301617234546500474226\n908149086234602658649\n642462021547889001560"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["Not a perfect square!"], ["2623266121561550740\n9255596398650723019\n9894309668063325619\n8336342940925212593\n2003620909851899406\n6361745645048407076\n9588456924362837160\n7774165087609628454\n0087172312000704450\n6802208180164171825\n2704662869008116632\n9732402239635020515\n4592188604550922630\n8575640170854158374\n6920783401539409265\n7829054350414881516\n3852029726028558864\n6294849760337696015\n0105798658186012125"], ["9451624774706780550\n8195780820606802011\n1452666053560117734\n0482958958802662452\n2349390921173858283\n6859850073538178116\n3783888754244105507\n4112894885973178448\n9021042470325082200\n8412636831609241355\n4083232063686748402\n8670232510589445761\n4094549506400780743\n0864350243227340958\n4939380710662890063\n4485418178936308462\n1274579977359192463\n6731175052195853299\n7885205043120826601"], ["Not a perfect square!"], ["1113798041651332675390036661411812759753\n4595333758924261793440915871873756952319\n7566497372380321915223726731203861007035\n3510475403958840055274067872153523724461\n1848291138569327958593044675614468557005\n0023305452475071617359077545819376182905\n1311833857343380093450794849164690056350\n7252698934433726005748974840550441605517\n4337858574189851544257937316865506478495\n4889919800935170546457643685472459351554\n2913395793653626225930689278143500643117\n0164385532318225151969961567289907187370\n8599904235950138245942673119913208801391\n2139656139890374588305741970918092793466\n6849273450720382201117753206985766196052\n3548629454029508951267222567299868972459\n5342778817830262034876462985418079389649\n0871313047548245070462922548669473584553\n5258983511253192670050807379062503198272\n3065510060857907098352438081726563662610\n5880373687399873835395301816834376837968\n3012226909961221783143862839885079292333\n6393054468797360112454045979874926831486\n4690251100774349455768518361200224777794\n7898908591485332490148696744147082390379\n3321446041692116941345409420028312821779\n0746853509956504171880550001667824522663\n8567046564856252040392422630291436182213\n7948377606183220945301740971503335763422\n2173811465202454177467801383561678393489\n0824327437127585679710381718339747199204\n6551536440958950805487134378331216212238\n2686418771257136790510061391315752690006\n7755362854618596940502933204265426463348\n7649467740461029877415728386016919375018\n1012212418979550449145403614845484203887\n0050506659489456531810897605386302422736\n7374711526383969261440675268917297641935\n8099065427290070895263012866835928465717\n1257567113383562838008211359614322806888"], ["Not a perfect square!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,779
def square_it(digits):
4a603d99c6eca2f0f10033bed596fadd
UNKNOWN
# Task Given string `s`, which contains only letters from `a to z` in lowercase. A set of alphabet is given by `abcdefghijklmnopqrstuvwxyz`. 2 sets of alphabets mean 2 or more alphabets. Your task is to find the missing letter(s). You may need to output them by the order a-z. It is possible that there is more than one missing letter from more than one set of alphabet. If the string contains all of the letters in the alphabet, return an empty string `""` # Example For `s='abcdefghijklmnopqrstuvwxy'` The result should be `'z'` For `s='aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyy'` The result should be `'zz'` For `s='abbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxy'` The result should be `'ayzz'` For `s='codewars'` The result should be `'bfghijklmnpqtuvxyz'` # Input/Output - `[input]` string `s` Given string(s) contains one or more set of alphabets in lowercase. - `[output]` a string Find the letters contained in each alphabet but not in the string(s). Output them by the order `a-z`. If missing alphabet is repeated, please repeat them like `"bbccdd"`, not `"bcdbcd"`
["from collections import Counter\nfrom string import ascii_lowercase\n\ndef missing_alphabets(s):\n c = Counter(s)\n m = max(c.values())\n return ''.join(letter * (m - c[letter]) for letter in ascii_lowercase)", "from collections import Counter\nfrom string import ascii_lowercase as alphabet\n\ndef missing_alphabets(s):\n counts = Counter(s)\n max_count = max(counts.values())\n return ''.join(c * (max_count - counts[c]) for c in alphabet)", "def missing_alphabets(s):\n return ''.join(sorted(c * (max(s.count(x) for x in s) - s.count(c)) for c in 'abcdefghijklmnopqrstuvwxyz'))", "from collections import Counter\ndef missing_alphabets(s):\n c, a = Counter(s), Counter(map(chr, range(97, 123)))\n return ''.join(sorted((sum([a] * max(c.values()), Counter()) - c).elements()))", "from collections import Counter\n\ndef missing_alphabets(s):\n a, C = [], []\n count = Counter(s)\n \n for i in range(1,max(count.values()) + 1):\n a.append([k for k,v in list(count.items()) if v >= i ])\n \n\n A = \"abcdefghijklmnopqrstuvwxyz\"\n B = [I for I in A if I not in s]\n \n\n for i in range(0 ,len(a)):\n C.append([I for I in A if I not in a[i]])\n\n return ''.join(sorted([j for i in C for j in i])) \n", "import string\nfrom collections import Counter\ndef missing_alphabets(s):\n my_dict = Counter(s)\n set = max(my_dict.values())\n return \"\".join([letter*(set-my_dict[letter]) for letter in string.ascii_lowercase])", "from string import ascii_lowercase\nfrom collections import Counter\n\ndef missing_alphabets(str_in):\n counts = Counter(str_in)\n most = counts.most_common()[0][1]\n return ''.join(letter * (most - counts[letter]) for letter in ascii_lowercase)", "def missing_alphabets(s):\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n c = []\n for letter in alphabet:\n c.append(s.count(letter))\n sets = max(c)\n result = []\n for letter in alphabet:\n if s.count(letter) != sets:\n result.append(letter*(sets-s.count(letter)))\n return(''.join(result))", "def missing_alphabets(s):\n alphabet = {chr(x):0 for x in range(ord('a'), ord('z')+1)}\n results = []\n for letter in s:\n if letter in alphabet:\n alphabet[letter] += 1\n l_count = max(alphabet.values())\n for key in alphabet:\n if alphabet[key] < l_count:\n results.append(key*(l_count - alphabet[key]))\n\n return ''.join(results)", "from string import ascii_lowercase\nfrom collections import Counter\n\ndef missing_alphabets(s):\n C = Counter(s)\n x = C.most_common(1)[0][1]\n return ''.join(c*(x-C[c]) for c in ascii_lowercase)"]
{"fn_name": "missing_alphabets", "inputs": [["abcdefghijklmnopqrstuvwxy"], ["abcdefghijklmnopqrstuvwxyz"], ["aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyy"], ["abbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxy"], ["codewars"]], "outputs": [["z"], [""], ["zz"], ["ayzz"], ["bfghijklmnpqtuvxyz"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,696
def missing_alphabets(s):
4338d733d5b1ea43da6529da82a90cbc
UNKNOWN
A few years ago, Aaron left his old school and registered at another due to security reasons. Now he wishes to find Jane, one of his schoolmates and good friends. There are `n` schools numbered from 1 to `n`. One can travel between each pair of schools by buying a ticket. The ticket between schools `i` and `j` costs `(i + j) modulo (n + 1)` and can be used multiple times. Help Aaron find the minimum total cost to visit all schools. He can start and finish at any school. Range : 1 ≤ n ≤ 10^(6)
["def find_jane(n):\n return (n - 1) // 2", "import math\ndef find_jane(n):\n return math.ceil((n-2)/2)", "def find_jane(n):\n return (n-1) // 2\n \n\"\"\"\n1,2,3,...,n\ncost = (a+b) % (n+1)\n\nbest association is:\n b = n+1-a -> cost=0\n \n 1 2 3 4 5 -> 1 <-> 5\n 2 <-> 4\n\nto link (\"L\") those two, the best remaining way is:\n b = n+1-a+1 -> cost=1\n\n 1 2 3 4 5 -> 1 <-> 5: 0\n L: 5 <-> 2: 1\n 2 <-> 4: 0\n L: 4 <-> 3: 1\n --------------\n total cost = 2\n\n\n 1 2 3 4 -> 1 <-> 4: 0\n L: 4 <-> 2: 1\n 2 <-> 3: 0\n --------------\n total cost = 1\n\nAnd so on...\n\"\"\"", "find_jane=lambda n:n-1>>1", "def find_jane(n):\n return int(( n - 1 ) / 2) ", "def find_jane(n):\n return n//2-1+n%2\n #5,6\n #4,7\n \n #3,8\n #2,9\n #1,10\n", "find_jane=lambda n:~-n>>1", "def find_jane(n):\n return (n - 1) >> 1", "def find_jane(n):\n return n//2 - 1 if n&1==0 else n//2", "def find_jane(n):\n return sum(divmod(n, 2), -1)"]
{"fn_name": "find_jane", "inputs": [[2], [10]], "outputs": [[0], [4]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,176
def find_jane(n):