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
6926a7d6abd215794c191d7cb003666b
UNKNOWN
We all love the future president (or Führer or duce or sōtō as he could find them more fitting) donald trump, but we might fear that some of his many fans like John Miller or John Barron are not making him justice, sounding too much like their (and our as well, of course!) hero and thus risking to compromise him. For this reason we need to create a function to detect the original and unique rythm of our beloved leader, typically having a lot of extra vowels, all ready to fight the estabilishment. The index is calculated based on how many vowels are repeated more than once in a row and dividing them by the total number of vowels a petty enemy of America would use. For example: ```python trump_detector("I will build a huge wall")==0 #definitely not our trump: 0 on the trump score trump_detector("HUUUUUGEEEE WAAAAAALL")==4 #4 extra "U", 3 extra "E" and 5 extra "A" on 3 different vowel groups: 12/3 make for a trumpy trumping score of 4: not bad at all! trump_detector("listen migrants: IIII KIIIDD YOOOUUU NOOOOOOTTT")==1.56 #14 extra vowels on 9 base ones ``` **Notes:** vowels are only the ones in the patriotic group of "aeiou": "y" should go back to Greece if she thinks she can have the same rights of true American vowels; there is always going to be at least a vowel, as silence is the option of coward Kenyan/terrorist presidents and their friends. Round each result by two decimal digits: there is no place for small fry in Trump's America. *Special thanks for [Izabela](https://www.codewars.com/users/ijelonek) for support and proof-reading.*
["import re\ndef trump_detector(ts):\n x=re.findall(r'([aeiou])(\\1*)',ts,re.I)\n y=[len(i[1]) for i in x]\n return round(sum(y)/len(y),2)", "import re\n\ndef trump_detector(trump_speech):\n lst = [ len(tup[1]) for tup in re.findall(r'([aeiou])(\\1*)', trump_speech, re.I) ]\n return round(sum(lst)/len(lst), 2)", "from itertools import groupby\nfrom statistics import mean\n\ndef trump_detector(trump_speech):\n return round(mean(len(list(l))-1 for k,l in groupby(trump_speech.lower()) if k in \"aeiou\"), 2)", "import re\ndef trump_detector(s):\n r = re.findall(r'a+|e+|i+|o+|u+', s, re.I)\n return round(sum(len(i) - 1 for i in r) / len(r),2)", "import re\n\ndef trump_detector(trump_speech):\n matches = re.findall(r'([aeiou])(\\1*)', trump_speech.lower(), flags=re.I)\n if matches:\n return round(sum(len(m[1]) for m in matches) / len(matches), 2)\n return 0", "import re\nfrom statistics import mean\ntrump_detector = lambda s:round(mean(map(len,re.findall(r'(a+|e+|i+|o+|u+)',s.lower())))-1,2)", "from itertools import groupby\ndef trump_detector(trump_speech):\n return round(sum((len(\"\".join(x)))-1 for i,x in groupby(trump_speech.lower()) if i in \"aeiou\")/len([i for i,_ in groupby(trump_speech.lower()) if i in \"aeiou\"]),2)", "import re;trump_detector=lambda trump_speech:(lambda lst:round(sum(lst)/len(lst),2))([len(t[1])for t in re.findall(r'([aeiou])(\\1*)',trump_speech,re.I)])", "from re import findall;trump_detector=lambda t: round(sum(map(lambda a: len(a[1]), findall(r\"([aeiou])(\\1*)\",t,2)))/len(findall(r\"([aeiou])(\\1*)\",t,2)),2)", "from re import findall, IGNORECASE\n\ndef trump_detector(trump_speech):\n\n final = [len(c[1]) for c in findall(r'([aeiou])(\\1*)',trump_speech,IGNORECASE)]\n \n return round(sum(final)/len(final),2)"]
{"fn_name": "trump_detector", "inputs": [["I will build a huge wall"], ["HUUUUUGEEEE WAAAAAALL"], ["MEXICAAAAAAAANS GOOOO HOOOMEEEE"], ["America NUUUUUKEEEE Oooobaaaamaaaaa"], ["listen migrants: IIII KIIIDD YOOOUUU NOOOOOOTTT"]], "outputs": [[0], [4], [2.5], [1.89], [1.56]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,819
def trump_detector(trump_speech):
50224bb894d1c1ce22f539ee05f6e9a0
UNKNOWN
### The Story: Bob is working as a bus driver. However, he has become extremely popular amongst the city's residents. With so many passengers wanting to get aboard his bus, he sometimes has to face the problem of not enough space left on the bus! He wants you to write a simple program telling him if he will be able to fit all the passengers. ### Task Overview: You have to write a function that accepts three parameters: * `cap` is the amount of people the bus can hold excluding the driver. * `on` is the number of people on the bus. * `wait` is the number of people waiting to get on to the bus. If there is enough space, return 0, and if there isn't, return the number of passengers he can't take. ### Usage Examples: ```python enough(10, 5, 5) 0 # He can fit all 5 passengers enough(100, 60, 50) 10 # He can't fit 10 out of 50 waiting ``` ```if:csharp Documentation: Kata.Enough Method (Int32, Int32, Int32) Returns the number of passengers the bus cannot fit, or 0 if the bus can fit every passenger. Syntax public static int Enough( int cap,   int on, int wait   ) Parameters cap Type: System.Int32 The amount of people that can fit on the bus excluding the driver. on Type: System.Int32 The amount of people on the bus excluding the driver. wait Type: System.Int32 The amount of people waiting to enter the bus. Return Value Type: System.Int32 An integer representing how many passengers cannot fit on the bus, or 0 if every passenger can fit on the bus. ```
["def enough(cap, on, wait):\n return max(0, wait - (cap - on))", "def enough(cap, on, wait):\n return max(0, on + wait - cap)", "def enough(cap, on, wait):\n return wait + on - cap if wait + on > cap else 0", "def enough(cap, on, wait):\n return max(on + wait - cap, 0)", "def enough(cap, on, wait):\n if cap-on>=wait:\n return 0\n else:\n return abs(cap-(on+wait))", "def enough(cap, on, wait):\n rem=cap-on\n if wait<=rem:\n return 0\n else :\n return wait-rem\na=enough(5,3,2)\nif a==0:\n print(\"Yes.Bob can take all passengers with him\")\nelse :\n print((\"Woops.Bob can't able to take \",a,\" passengers into the bus\"))\n \n", "enough = lambda c,o,w: max(0, w-(c-o))", "def enough(cap, on, wait):\n return max(wait + on - cap, 0)", "def enough(cap, on, wait):\n res = cap-(on+wait)\n return [0, abs(res)][res<0]", "def enough(cap, on, wait):\n # Your code here\n if on + wait > cap:\n missed_out = on + wait - cap\n else:\n missed_out = 0\n return missed_out", "def enough(cap, on, wait):\n# See if there is enough room\n if cap - on >= wait:\n return 0 # This means enough room for those waiting\n else:\n return wait - cap + on # This is the number of those who cannot get on", "def enough(cap, on, wait):\n '''\n :param cap: total number of seats\n :param on: number of passengers on the bus\n :param wait: number of passengers waiting for the bus\n :return: number of passengers that can't enter the bus\n '''\n if wait - (cap - on) < 0:\n return 0\n else:\n return wait - (cap - on)", "def enough(cap, on, wait):\n return abs(cap-(on+wait) if cap<(on+wait) else 0)\n", "def enough(cap, on, wait):\n remainingCapacity = cap - on\n if remainingCapacity <= wait:\n return (wait - remainingCapacity)\n else:\n return 0", "def enough(cap, on, wait):\n return abs(min(cap - on - wait, 0))", "def enough(cap, on, wait):\n return 0 if cap - on >= wait else wait - cap + on", "enough = lambda cap, on, wait: 0 if cap - on - wait >= 0 else abs(cap - on - wait)", "def enough(cap, on, wait):\n return -min(0, cap-(on+wait))", "def enough(cap, on, wait):\n # Your code here\n import math\n if cap>=(on+wait):\n return 0\n elif cap<(on+wait):\n return abs((cap-(wait+on)))", "def enough(cap, on, wait):\n a=cap-on\n if a>=wait:\n return 0\n else:\n b=wait-a\n return b", "def enough(cap, on, wait):\n answer = on + wait - cap\n if answer < 0:\n return 0\n else:\n return answer", "def enough(cap, on, wait):\n cap -= on\n if wait-cap <= 0:\n return 0\n else:\n return wait-cap", "def enough(cap, on, wait):\n c=wait-(cap-on)\n if c<0:\n return 0\n return c\n # Your code here\n", "def enough(cap, on, wait):\n num = cap - on\n if num == wait:\n return 0\n if wait > num:\n return (wait-num)\n else:\n return 0", "def enough(cap, on, wait):\n return 0 if cap >= (on+wait) else on+wait-cap", "def enough(cap, on, wait):\n return (cap-on-wait)*-1 if cap-on-wait<=0 else 0", "def enough(cap, on, wait):\n return 0 if cap >= on + wait else (on + wait) % cap", "def enough(cap, on, wait):\n x = on + wait\n if x <= cap:\n return 0\n elif x > cap:\n return x - cap\n else:\n return 'Not Sure'\n", "def enough(cap, on, wait):\n return wait - (cap-on) if wait - (cap-on) >= 0 else 0", "def enough(cap, on, wait):\n cap_lef = cap - on\n still_wait = wait - cap_lef\n if still_wait > 0:\n return still_wait\n else: \n return 0\n", "enough=lambda c,o,w:0 if c-o>=w else w-(c-o)\n", "def enough(cap, on, wait):\n # Your code here\n c=cap-on\n if(wait<=c):\n return 0\n else:\n return wait-c", "def enough(cap, on, wait):\n return 0 if cap-on-wait > 0 else wait-cap+on", "def enough(cap, on, wait):\n empty = cap - on\n return 0 if empty >= wait else wait - empty", "def enough(cap, on, wait):\n if cap < on + wait:\n return wait-(cap-on)\n else:\n return 0", "def enough(cap, on, wait):\n \n remaining = cap - (on+wait)\n return abs(remaining) if remaining < 0 else 0", "def enough(cap, on, wait):\n r = on + wait - cap\n return 0 if r < 0 else r", "def enough(cap, on, wait):\n cap = int(cap)\n on = int(on)\n wait = int(wait)\n \n if cap >= on + wait:\n return 0\n else:\n diff = on + wait - cap\n cap != on + wait\n return diff", "def enough(cap, on, wait):\n if wait <= cap-on:\n return 0\n else:\n return abs(wait-(cap-on))", "def enough(cap, on, wait):\n space = cap - on\n return wait - space if space < wait else 0", "def enough(cap, on, wait):\n return(0 if cap>=on+wait else -cap+on+wait)", "def enough(cap, on, wait):\n enough_space = on + wait - cap\n if enough_space <= 0:\n return 0\n else:\n return enough_space\n", "def enough(cap, on, wait):\n return 0 if wait < cap - on else -(cap-on-wait)", "def enough(cap, on, wait):\n print(cap,on,wait)\n return 0 if on+wait<=cap else on+wait-cap", "def enough(cap, on, wait):\n if cap - on == wait:\n return 0\n elif cap - on < wait:\n return (cap - on - wait)*(-1)\n elif wait < cap - on:\n return 0", "def enough(cap, on, wait):\n \n people_left = wait - (cap - on)\n \n if (people_left <= 0):\n return 0\n \n if people_left > 0:\n return people_left\n \n \n \n \n # Your code here\n", "def enough(cap, on, wait):\n a = cap-on-wait\n if a >= 0:\n return 0\n else:\n return abs(a)\n # Your code here\n", "def enough(cap, on, wait):\n if wait > cap - on:\n return on + wait - cap\n return 0", "def enough(cap, on, wait):\n return -(cap-on-wait) if cap<=on+wait else 0", "def enough(cap, on, wait):\n c = (cap - on) - wait\n if c == 0:\n return 0\n if c > 0:\n return 0 \n else: \n return c * -1", "def enough(cap, on, wait):\n free = cap-on\n return 0 if free >= wait else wait-free\n", "def enough(cap, on, wait):\n x = cap - on - wait\n return x*-1 if x <= 0 else 0", "def enough(cap, on, wait):\n cant=cap-on-wait\n if cant>=0:\n return 0\n else:\n return abs(cant)", "def enough(cap, on, wait):\n if on + wait <= cap:\n return 0\n else:\n rest = cap - (on + wait)\n return abs(rest)", "def enough(cap, on, wait):\n num = wait - (cap - on) \n if num >= 0:\n return num\n else:\n return 0", "def enough(cap, on, wait):\n cant = cap - wait\n if on + wait > cap:\n a = cap - on - wait\n return abs(a) \n else:\n return 0\n", "def enough(cap, on, wait):\n resultado = (on + wait - cap)\n return resultado if resultado > 0 else 0\n # Your code here\n", "def enough(cap, on, wait):\n return -(cap - (on + wait)) if (cap - (on + wait)) < 0 else 0", "def enough(cap, on, wait):\n if on + wait > cap:\n return (cap - (on + wait)) * -1;\n return 0;", "def enough(cap, on, wait):\n if cap-on+1>wait: return 0\n else:return wait-cap+on", "def enough(cap, on, wait):\n # Your code here\n diff = cap-on-wait\n return 0 if diff >=0 else -diff", "def enough(cap, on, wait):\n # Your code here\n c=cap-on\n if c<wait:\n return wait-c\n return 0", "def enough(cap, on, wait):\n if cap - on >= wait: #capacity minus bus occupancy more or equal than of people waiting \n return 0 #If there is enough space, return 0.\n else:\n return abs(cap - (on + wait)) #and if there isn't, return the number of passengers he can't take\n #abs() function: return absolute values of a num.\n", "def enough(cap, on, wait):\n x = cap - on\n if x >= wait:\n return 0\n else:\n return wait - x", "def enough(cap, on, wait):\n if cap - on - wait < 0:\n seats_left = cap - on\n return wait - seats_left\n else:\n return 0", "def enough(cap, on, wait):\n return 0 if wait + on <= cap - 1 else wait + on - (cap)", "def enough(cap, on, wait):\n difference = cap - on\n if difference < wait:\n return wait - difference\n return 0", "def enough(cap, on, wait):\n if wait > cap-on:\n return wait + on - cap\n else:\n return 0", "def enough(cap, on, wait):\n rest = on + wait - cap\n if rest <= 0:\n return 0\n return rest", "def enough(c,n,w):\n x=w-(c-n)\n return x if x>0 else 0", "def enough(cap, on, wait):\n return wait - cap + on if wait - cap + on > 0 else 0", "def enough(cap, on, wait):\n if cap == on + wait or cap > on + wait:\n return 0\n else:\n return abs(cap - (on + wait))", "def enough(cap, on, wait):\n takes = cap - on - wait\n return 0 if takes>=0 else -(takes)\n # Your code here\n", "def enough(cap, on, wait):\n x = wait - cap + on\n return x if x > 0 else 0", "def enough(cap, on, wait):\n available = cap - on\n return max(wait-available, 0)", "def enough(cap, on, wait):\n return 0 if cap - on - wait > 0 else (cap - on - wait) * -1", "def enough(cap, on, wait):\n n=0\n if cap>=on+wait:\n return 0\n else:\n n=cap-on-wait\n return abs(n)\n # Your code here\n", "def enough(cap, on, wait):\n a = cap - on - wait\n if a >= 0: return 0\n else: return a * -1", "def enough(cap, on, wait):\n r = cap - on - wait\n return [0,abs(r)][r<0]", "def enough(cap, on, wait):\n remaining = cap - on\n \n if remaining >= wait:\n return 0\n else:\n return wait - remaining", "def enough(cap, on, wait):\n print(cap,on,wait)\n if on + wait > cap :\n return -cap+(on+wait)\n else:\n return 0", "def enough(cap, on, wait):\n seat = (cap - on) - wait\n\n return 0 if seat >= 0 else abs(seat)", "def enough(cap, on, wait):\n return wait - (cap - on) if on + wait > cap else 0", "def enough(cap, on, wait):\n \"\"\" return wait list if bus is full\"\"\"\n wait_list = on + wait - cap\n return (wait_list > 0) * wait_list", "def enough(cap, on, wait):\n print(cap, on, wait)\n return 0 if wait <= cap-on else wait-(cap- on ) ", "def enough(cap, on, wait):\n if on >= cap:\n return wait\n spots = cap - on\n if spots >= wait:\n return 0\n return wait - spots\n\n", "def enough(maximal, drin, warten):\n pers = drin + warten\n \n if pers <= maximal:\n return 0 \n elif pers > maximal:\n return pers - maximal", "def enough(cap, on, wait):\n # Your code here\n cap -= on\n# if cap>=wait:\n# return 0\n# else:\n# return wait-cap\n return max(wait-cap, 0)", "def enough(cap, on, wait):\n return (on+wait-cap) * (on + wait > cap)", "def enough(cap, on, wait):\n return 0 if cap-on-wait>0 else abs(cap-on-wait) if cap-on-wait<0 else 0", "def enough(cap, on, wait):\n n = (on + wait)\n if cap > n:\n return 0 \n return (on + wait) - cap", "def enough(cap, on, wait):\n total = on + wait\n return 0 if cap >= total else abs(cap - total)", "def enough(cap, on, wait):\n return 0 if cap > on + wait else wait + on - cap", "def enough(cap, on, wait):\n return abs(on + wait - cap) if cap < on + wait else 0", "def enough(cap, on, wait):\n return 0 if cap%(on+wait) == 0 or (on+wait) < cap else (on+wait)-cap\n\n", "def enough(cap, on, wait):\n if on + wait == cap:\n return 0\n elif on + wait > cap:\n return wait - (cap - on)\n else:\n return 0", "def enough(cap, on, wait):\n b = -(cap - on - wait)\n return 0 if cap - (on + wait) >= 0 else b", "exec(\"\"\"\\ndef enough(cap, on, wait):\\n a = on + wait\\n b = cap - a \\n if b >= 0:\\n return 0\\n else:\\n return abs(b)\\n\"\"\")", "def enough(cap, on, wait):\n a = on + wait\n b = cap - a \n if b >= 0:\n return 0\n else:\n return abs(b)", "def enough(cap, on, wait):\n return 0 if cap - on - wait >= 0 else wait + on - cap"]
{"fn_name": "enough", "inputs": [[10, 5, 5], [100, 60, 50], [20, 5, 5]], "outputs": [[0], [10], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,354
def enough(cap, on, wait):
56b3a5dd09ef40cdbf756942ab5b198d
UNKNOWN
The wide mouth frog is particularly interested in the eating habits of other creatures. He just can't stop asking the creatures he encounters what they like to eat. But then he meet the alligator who just LOVES to eat wide-mouthed frogs! When he meets the alligator, it then makes a tiny mouth. Your goal in this kata is to create complete the `mouth_size` method this method take one argument `animal` which corresponds to the animal encountered by frog. If this one is an `alligator` (case insensitive) return `small` otherwise return `wide`.
["def mouth_size(animal): \n return 'small' if animal.lower() == 'alligator' else 'wide'", "def mouth_size(animal): \n return 'wide' if animal.lower() != 'alligator' else 'small'", "def mouth_size(animal): \n mouth = {'alligator':'small'}\n return mouth.get(animal.lower(), 'wide')", "import re\n\ndef mouth_size(animal):\n return 'small' if re.search('alligator', animal, re.IGNORECASE) else 'wide'", "mouth_size = lambda s:\"small\" if (s.lower()==\"alligator\") else \"wide\"", "mouth_size = lambda a: 'small' if a.lower() == 'alligator' else 'wide'", "def mouth_size(s): return \"small\" if s.lower() == \"alligator\" else \"wide\"", "def mouth_size(animal): \n animal1 = animal.lower()\n if animal1 == 'alligator':\n return 'small'\n else:\n return 'wide'", "def mouth_size(animal): \n return \"small\" if \"alligator\" in animal.lower() else \"wide\"\n # code here\n", "def mouth_size(animal): \n if animal.lower() == 'alligator': return 'small'\n return 'wide'", "def mouth_size(animal): \n return 'small' if animal.upper() == 'ALLIGATOR' else 'wide'", "def mouth_size(animal): \n if animal.lower() == \"alligator\":\n return \"small\"\n else:\n return \"wide\"", "mouth_size=lambda animal: [\"wide\",\"small\"][animal.lower()==\"alligator\"]", "def mouth_size(animal: str) -> str:\n \"\"\" The wide mouth frog or the small one? \"\"\"\n return \"small\" if animal.lower() == \"alligator\" else \"wide\"", "mouth_size = lambda animal: 'small' if animal.lower() == 'alligator' else 'wide'", "def mouth_size(animal): \n animal = animal.lower()\n return 'sm' + animal[:3] if animal[3:] == 'igator' else 'wide'", "def mouth_size(animal): \n if animal.casefold() == \"alligator\":\n return \"small\"\n else:\n return \"wide\"\nprint((mouth_size(\"alligator\")))\n\n\n\n # code here\n", "def mouth_size(animal): \n return animal.lower() == 'alligator' and 'small' or 'wide'", "def mouth_size(animal): \n return ('wide', 'small')[animal.lower() == 'alligator']", "def mouth_size(animal): \n if animal.find('l')==1 or animal.find('L')==1:\n return 'small'\n else:\n return 'wide'\n \n", "def mouth_size(animal): \n new_animal = animal.lower()\n return \"small\" if new_animal == \"alligator\" else \"wide\"", "def mouth_size(animal): \n if animal.lower() == \"alligator\" or animal.lower() is \"alligator!\":\n return \"small\"\n return \"wide\"", "small = [\"alligator\"]\n\ndef mouth_size(animal): \n return \"small\" if animal.lower() in small else \"wide\"", "def mouth_size(animal): \n # code \n if(animal.lower() == \"alligator\"):\n return \"small\"\n return \"wide\"", "mouth_size = lambda x: ('wide', 'small')[x.lower() == 'alligator']", "def mouth_size(animal): \n return 'small' if (animal.lower()=='alligator' or animal.lower()=='alligator!') else 'wide'", "def mouth_size(animal):\n animal_lower = animal.lower()\n if animal_lower == 'alligator':\n return 'small'\n else:\n return 'wide'", "def mouth_size(animal): \n if animal.lower() != \"alligator\":\n return \"wide\"\n elif animal.lower() == \"alligator\":\n return \"small\"\n", "def mouth_size(animal):\n return \"small\" if animal.title() == \"Alligator\" else \"wide\"", "def mouth_size(animal):\n animal = animal.title()\n if animal == 'Alligator':\n return 'small'\n else:\n return 'wide'", "def mouth_size(animal): \n state = \"wide\"\n if animal.lower() == \"alligator\":\n state = \"small\"\n return state", "def mouth_size(animal): \n x = 'alligator'\n if animal.casefold() == x.casefold():\n return 'small'\n else:\n return 'wide'", "def mouth_size(animal): \n # code here\n new_animal = animal.lower()\n if new_animal == \"alligator\":\n return \"small\"\n return \"wide\"", "def mouth_size(animal): \n if animal.upper() != 'ALLIGATOR' :\n return 'wide'\n else :\n return 'small'\n # code here\n", "def mouth_size(animal): \n return \"wide\" if animal.upper()!=\"ALLIGATOR\" else \"small\"\n # code here\n", "def mouth_size(animal): \n result = \"\"\n if animal.lower() == \"alligator\":\n result = \"small\"\n else:\n result = \"wide\"\n return result", "def mouth_size(animal): \n return \"small\" if animal.lower() == \"alligator\".lower() else \"wide\"", "def mouth_size(animal):\n \" \u0420\u0432\u0435\u043c \u0430\u043b\u0438\u0433\u0430\u0442\u043e\u0440\u0443 \u043f\u0430\u0441\u0442\u044c\"\n n = animal.lower()\n if n == \"alligator\":\n return \"small\"\n else:\n return \"wide\"", "def mouth_size(animal): \n if \"alligator\" == animal.lower():\n return \"small\"\n return \"wide\"", "def mouth_size(animal): \n animal=animal.lower()\n if animal == 'alligator' or animal == 'alligator!':\n return 'small'\n return 'wide'", "def mouth_size(animal): \n animal=animal.casefold()\n return \"small\" if \"alligator\"in animal else \"wide\"", "def mouth_size(ani):\n animal = ani.lower()\n if animal == \"alligator\":\n return \"small\"\n elif animal == \"toucan\":\n return \"wide\"\n elif animal == \"ant bear\":\n return \"wide\"\n else :\n return \"wide\"", "def mouth_size(animal): \n #casefold makes case insensitive string matching\n if animal.casefold() == \"alligator\":\n return \"small\"\n else:\n return \"wide\"", "def mouth_size(animal:str) -> str:\n if animal.lower() == \"alligator\":\n return \"small\"\n else:\n return \"wide\"\n", "def mouth_size(animal): \n return f'small' if animal.lower()=='alligator' else f'wide'", "def mouth_size(animal): \n if str(animal).lower() == \"alligator\":\n return \"small\"\n return \"wide\"", "def mouth_size(animal): \n new_animal = \"\"\n for letters in animal:\n if 65 <= ord(letters) <= 90:\n new_animal += chr(ord(letters)+32)\n else:\n new_animal += letters\n if new_animal == \"alligator\":\n return \"small\"\n return \"wide\"\n", "import re\n\ndef mouth_size(animal):\n\n pattern = re.match(r'alligator', animal, re.I)\n if pattern:\n return \"small\"\n return \"wide\"\n", "import re\ndef mouth_size(animal): \n if re.search(\"alligator\",animal,re.IGNORECASE):\n return \"small\"\n else:\n return \"wide\"\n # code here\n", "def mouth_size(animal):\n x = animal.casefold()\n if x == 'alligator':\n return 'small'\n print(x)\n return 'wide'", "def mouth_size(animal): \n if animal.rstrip('!').lower() == 'alligator':\n return 'small'\n else:\n return 'wide' ", "def mouth_size(animal):\n animal=animal.lower()\n print (animal)\n if animal==(\"alligator\"):\n return (\"small\")\n else:\n return (\"wide\")\n\n", "def mouth_size(animal): \n return 'wide' if animal.lower().find('alligator') else 'small'\n", "def mouth_size(animal): \n \n animal=animal.lower()\n \n ergebnis=\"wide\"\n \n if animal==\"alligator\":\n ergebnis=\"small\"\n \n return ergebnis ", "def mouth_size(x):\n x = x.lower()\n x = x.replace(\"!\",\"\")\n return \"small\" if x == \"alligator\" else \"wide\"", "def mouth_size(animal):\n animal = str(animal).lower()\n if animal==\"alligator\":\n return \"small\"\n else:\n return \"wide\"\ns = mouth_size(\"alligator\")\nprint(s)", "def mouth_size(animal): \n return \"small\" if (animal.lower()).capitalize() == \"Alligator\" else \"wide\"", "mouth_size = lambda a: ['wide', 'small']['tor' in a.casefold()]", "def mouth_size(animal): \n a = animal.lower()\n print(a)\n if a == \"alligator\": return \"small\"\n else: return \"wide\"", "import re\ndef mouth_size(animal): \n animalnew=animal.lower()\n if animalnew=='alligator':\n return \"small\"\n else:\n return \"wide\"\n # code here\n", "def mouth_size(animal): \n return [\"small\", \"wide\"][animal.lower()!=\"alligator\"]", "def mouth_size(animal): \n anim = animal.lower()\n if anim == \"alligator\":\n return \"small\"\n else:\n return \"wide\"", "def mouth_size(animal):\n if animal.lower() == 'alligator':\n a='small'\n else:\n a='wide'\n return a", "def mouth_size(animal):\n if str(animal).lower() != \"alligator\":\n return (\"wide\")\n else:\n return(\"small\")\n # code here\n", "def mouth_size(animal):\n animaL = animal.lower()\n if animaL == 'alligator':\n return 'small'\n else:\n return 'wide'", "def mouth_size(animal): \n if animal.lower() == \"alligator\" or animal.lower() == \"alligator!\":\n return \"small\"\n else:\n return \"wide\"", "def mouth_size(animal):\n ani=\"alligator\".strip(\"!\")\n return \"small\" if animal.lower() == ani else \"wide\"", "def mouth_size(animal): \n if animal.title() == 'Alligator':\n return \"small\"\n else:\n return \"wide\"", "def mouth_size(animal): \n # code here\n a=len('alligator')\n b=len(animal)\n return 'wide' if b!=a else 'small'", "def mouth_size(animal): \n animal = animal.lower()\n if animal != \"alligator\":\n return \"wide\"\n return \"small\"", "def mouth_size(animal):\n low=animal.lower()\n if low == \"alligator\":\n return \"small\"\n else:\n return \"wide\"", "def mouth_size(animal): \n return \"wide\" if \"alligator\" != animal.lower() else \"small\"", "def mouth_size(animal): \n alligator = \"alligator\"\n if animal.lower() == alligator.lower(): \n return \"small\"\n else: \n return \"wide\"", "def mouth_size(animal): \n return \"wide\" if not animal.lower() in \"alligator\" else \"small\" ", "def mouth_size(animal): \n print(animal.capitalize())\n if animal.capitalize() == 'Alligator':\n return 'small'\n else:\n return 'wide'", "def mouth_size(animal): \n if animal.upper() == \"alligator\".upper():\n return \"small\"\n \n return \"wide\"", "def mouth_size(animal):\n s = animal.lower()\n print(s)\n if s != 'alligator':\n return \"wide\"\n else:\n return \"small\"", "def mouth_size(animal): \n if animal.lower() == \"alligator\":\n mouth = \"small\"\n else:\n mouth = \"wide\"\n return mouth\n", "def mouth_size(animal): \n if animal.lower() != \"alligator\":\n# print (animal.lower())\n return \"wide\"\n else: return \"small\"", "def mouth_size(animal): \n newAnimal = animal.lower()\n if newAnimal == \"alligator\":\n return \"small\"\n else:\n return \"wide\"", "def mouth_size(animal):\n aniLow = animal.lower()\n return \"small\" if aniLow == \"alligator\" else \"wide\"", "'''\ud83d\udc0a\ud83d\udc0a\ud83d\udc0a'''\ndef mouth_size(animal): \n return \"small\" if animal.lower() == \"alligator\" else \"wide\"", "def mouth_size(animal): \n \n ret = 'wide'\n if animal.lower() == 'alligator':\n ret = 'small'\n\n return ret\n", "def mouth_size(animal: str) -> str: \n # code here\n if animal.lower() == 'alligator':\n return 'small'\n return 'wide'", "def mouth_size(animal): \n return \"small\" if ''.join([x.lower() for x in animal]) == \"alligator\" else \"wide\"", "def mouth_size(animal): \n if \"alligator\" in animal.casefold():\n return \"small\"\n else:\n return \"wide\"", "def mouth_size(animal):\n lower_letters = animal.lower()\n if lower_letters == \"alligator\":\n return \"small\"\n else:\n return \"wide\"", "def mouth_size(animal): \n # code here\n if animal.lower()==\"alligator\" or animal==\"wide\":\n return \"small\"\n return \"wide\"", "mouth_size = lambda n: \"small\" if n.casefold()==\"alligator\" else \"wide\"", "def mouth_size(animal): \n x = 'alligator'\n if animal.lower() == x:\n return 'small'\n else:\n return 'wide'\n\n", "def mouth_size(animal):\n if len(animal) < 9: \n return 'wide'\n elif len(animal) > 9: \n return 'wide' \n else: \n return 'small' \n # code here\n", "def mouth_size(animal): \n if animal.upper() == 'alligator'.upper():\n return 'small'\n else:\n return 'wide'", "def mouth_size(animal): \n mouth = \"\"\n if animal.casefold() != \"alligator\":\n mouth = \"wide\"\n else:\n mouth = \"small\"\n return mouth", "def mouth_size(animal):\n a=animal.upper()\n if a=='ALLIGATOR':\n return 'small'\n else:\n return'wide'\n # code here\n", "def mouth_size(animal):\n s = 'alligator'\n return 'small' if animal.lower() == s else 'wide'", "def mouth_size(animal): \n if animal.lower() == 'alligator':\n return 'small'\n else:\n return 'wide'\nmouth_size(\"alligator\")", "def mouth_size(animal):\n new = animal.lower()\n if 'alligator'in new:\n return 'small'\n elif 'alligator!' in new:\n return 'small'\n else:\n return 'wide'", "def mouth_size(animal): \n result = \"\"\n animal_recase = animal.lower() #to make all forms of alligator 'readable'\n if animal_recase == \"alligator\":\n result = \"small\"\n else:\n result = \"wide\"\n return result ", "def mouth_size(animal): \n c = animal.lower()\n a = \"small\"\n b = \"wide\"\n if c == \"alligator\":\n return a\n else:\n return b\n # code here\n", "def mouth_size(x):\n if x.lower() == 'alligator': return 'small'\n else: return 'wide'"]
{"fn_name": "mouth_size", "inputs": [["toucan"], ["ant bear"], ["alligator"]], "outputs": [["wide"], ["wide"], ["small"]]}
INTRODUCTORY
PYTHON3
CODEWARS
13,545
def mouth_size(animal):
38a45307700e366089ae7d9c3a12f0f0
UNKNOWN
In this Kata, you will be given a number in form of a string and an integer `k` and your task is to insert `k` commas into the string and determine which of the partitions is the largest. ``` For example: solve('1234',1) = 234 because ('1','234') or ('12','34') or ('123','4'). solve('1234',2) = 34 because ('1','2','34') or ('1','23','4') or ('12','3','4'). solve('1234',3) = 4 solve('2020',1) = 202 ``` More examples in test cases. Good luck! Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)
["def solve(st, k):\n length = len(st) - k\n return max(int(st[i:i + length]) for i in range(k + 1))", "def solve(st,k):\n c=len(st)-k\n return int(max(st[i:i+c] for i in range(k+1)))", "def solve(st,k):\n return max([int(st[i:i+len(st)-k]) for i in range(len(st))])", "def solve(st, k):\n n = len(st) - k\n return max(int(st[i:i+n]) for i in range(len(st)))", "def solve(st, k):\n window = len(st) - k\n return max(int(st[i:i+window]) for i in range(len(st)))", "def solve(st,k):\n a = len(st) - k\n q = ([st[i:i+a] for i in range(0, len(st))])\n r = [int(item) for item in q]\n return (max(r))", "def solve(st,k):\n x=len(st)-k\n m = 0\n for i in range(len(str(st))):\n y = int(st[i:i+x])\n if y > m:\n m=y\n return m", "def solve(st,k):\n return max(int(st[i:i+len(st)-k]) for i in range(0, len(st) - (len(st)-k) + 1))", "def solve(st,k):\n return max([int(st[i:len(st)-k+i]) for i in range(0, k+1)])", "def solve(s, k):\n n = len(s) - k\n return max(int(s[i:i+n]) for i in range(0, k + 1))"]
{"fn_name": "solve", "inputs": [["1234", 1], ["1234", 2], ["1234", 3], ["2020", 1]], "outputs": [[234], [34], [4], [202]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,083
def solve(st,k):
2a201b7b7170e3b0d189a607a93bb92f
UNKNOWN
Create a function that takes in the sum and age difference of two people, calculates their individual ages, and returns a pair of values (oldest age first) if those exist or `null/None` if: * `sum < 0` * `difference < 0` * Either of the calculated ages come out to be negative
["def get_ages(a,b):\n x = (a+b)/2\n y = (a-b)/2\n return None if a<0 or b<0 or x<0 or y<0 else (x,y)", "def get_ages(s, diff):\n older, younger = (s / 2) + (diff / 2), (s / 2) - (diff / 2) \n if older >= younger >= 0:\n return (older, younger)", "def get_ages(s, diff):\n older = (s / 2) + (diff / 2)\n younger = (s / 2) - (diff / 2)\n \n if older >= younger >= 0:\n return (older, younger)", "def get_ages(sum_, difference):\n a = (sum_ + difference) / 2\n b = sum_ - a\n if 0 <= b <= a:\n return a, b", "def get_ages(a, b):\n x,y = (a+b)/2, (a-b)/2\n if a>=0 and b>=0 and x>=0 and y>=0:\n return x,y", "def get_ages(add, dif):\n return None if any(n < 0 for n in (add, dif, add - dif)) else ((add + dif) / 2, (add - dif) / 2)\n", "def get_ages(sum_, difference):\n x=(sum_+difference)/2\n y=sum_-x\n return None if any(e<0 for e in(x,y,sum_,difference)) else (x,y)", "def get_ages(sum_, difference): \n # Calculating the Ages\n ret = ((sum_ + difference)/2,(sum_ - difference)/2)\n # verifying the assumptions\n if difference < 0 or (ret[1]<0 or ret[0]<0): return None \n else: return ret", "def get_ages(sum, difference):\n age1 = (sum+difference)/2\n age2 = sum - age1\n if sum < 0 or difference < 0 or age1 < 0 or age2 < 0:\n return None \n if age1 > age2:\n return age1, age2 \n else:\n return age2, age1", "get_ages=lambda s,d:(lambda*a:None if any(x<0for x in(*a,s,d))else a)((s+d)/2,(s-d)/2)"]
{"fn_name": "get_ages", "inputs": [[24, 4], [30, 6], [70, 10], [18, 4], [63, 14], [80, 80], [63, -14], [-22, 15]], "outputs": [[[14, 10]], [[18, 12]], [[40, 30]], [[11, 7]], [[38.5, 24.5]], [[80, 0]], [null], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,540
def get_ages(sum_, difference):
3296205cc3e90a8c0e7a7756a9391f0a
UNKNOWN
Generate and return **all** possible increasing arithmetic progressions of six primes `[a, b, c, d, e, f]` between the given limits. Note: the upper and lower limits are inclusive. An arithmetic progression is a sequence where the difference between consecutive numbers is the same, such as: 2, 4, 6, 8. A prime number is a number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11) Your solutions should be returned as lists inside a list in ascending order of the first item (if there are multiple lists with same first item, return in ascending order for the second item etc) are the e.g: `[ [a, b, c, d, e, f], [g, h, i, j, k, l] ]` where `a < g`. If there are no solutions, return an empty list: `[]` ## Examples
["is_prime = lambda n: all(n % d for d in range(3, int(n ** .5) + 1, 2))\n\ndef primes_a_p(lower_limit, upper_limit):\n a_p = []\n for n in range(lower_limit | 1, upper_limit, 2):\n for gap in range(30, (upper_limit - n) // 5 + 1, 30):\n sequence = [n + i * gap for i in range(6)]\n if all(map(is_prime, sequence)):\n a_p.append(sequence)\n return a_p", "limit = 10_000\nsieve = [0]*2 + list(range(2, limit))\nfor i in range(2, limit):\n for j in range(i*i, limit, i):\n sieve[j] = 0\n \nprimes = {i for i in sieve if i}\n\ndef primes_a_p(l, u):\n li, found = sorted([i for i in primes if l<=i<=u]), []\n \n for i, a in enumerate(li):\n for b in li[i+1:]:\n diff, tray = b-a, [a, b]\n\n for _ in range(4):\n c = tray[-1] + diff\n if c in primes and c < u:\n tray.append(c)\n continue\n break\n \n if len(tray)==6:\n found.append(tray)\n \n return found", "from itertools import combinations, compress\nimport numpy as np\n\ns = np.ones(100000)\ns[:2] = s[2::2] = 0\nfor i in range(3, int(len(s)**0.5)+1, 2):\n if s[i]:\n s[i*i::i] = 0\nprimes = list(compress(range(len(s)), s))\n\ndef primes_a_p(lower_limit, upper_limit):\n xs = primes[np.searchsorted(primes, lower_limit):np.searchsorted(primes, upper_limit)]\n return [\n list(range(a, a+6*(b-a), b-a))\n for a, b in combinations(xs, 2)\n if all(x <= upper_limit and s[x] for x in range(b+b-a, a+6*(b-a), b-a))\n ]", "from bisect import *\n\nn=10000\nsieve, PRIMES = [0]*(n+1), []\nfor i in range(2, n+1):\n if not sieve[i]:\n PRIMES.append(i) \n for j in range(i**2, n+1, i): sieve[j] = 1\n \ndef primes_a_p(low, high):\n subPrimes = PRIMES[bisect_left(PRIMES,low):bisect_right(PRIMES,high)]\n ans, sP = [], set(subPrimes)\n \n for i,p in enumerate(subPrimes):\n for q in subPrimes[i+1:]:\n d = q-p\n prog = [p+d*n for n in range(6)]\n if set(prog) <= sP: ans.append(prog)\n return ans\n", "LIMIT = 10**4\nsieve = list(range(LIMIT))\nsieve[1] = 0\nprimes = []\nfor n in sieve:\n if n:\n primes.append(n)\n for i in range(n*n, LIMIT, n):\n sieve[i] = 0\n\ndel sieve\nprimes.remove(2)\n\n\ndef primes_a_p(lower_limit, upper_limit, k=6):\n primes_list = [ p for p in primes if lower_limit <= p <= upper_limit ]\n primes_set = set(primes_list)\n \n max_scope = (upper_limit - lower_limit) // (k-1)\n \n #base_diff = reduce(mul, [ p for p in primes if p <= k ])\n base_diff = 2 * 3 * 5\n \n solutions = []\n \n for n in range(1, max_scope // base_diff + 1):\n diffs = [ n * base_diff * x for x in range(k) ]\n scope = n * base_diff * (k-1)\n \n for p in primes_list:\n if p + scope > upper_limit:\n break\n \n if { p+d for d in diffs } <= primes_set:\n solutions.append([ p + d for d in diffs ])\n \n return sorted(solutions)", "def primes1(n):\n sieve = [True] * n\n for i in range(3,int(n**0.5)+1,2):\n if sieve[i]:\n sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)\n return [2] + [i for i in range(3,n,2) if sieve[i]]\n\nlst = primes1(10000)\n\nimport bisect\ndef primes_a_p(lower_limit, upper_limit):\n lst0 = lst[bisect.bisect_left(lst, lower_limit):bisect.bisect_right(lst,upper_limit)]\n ans = []\n for i in range(len(lst0)-5):\n for j in range(30, upper_limit//5, 30):\n x = lst0[i]+j\n if x not in lst0:\n continue\n if x > lst0[-1]:\n break\n temp = [lst0[i], x]\n flag = True\n while len(temp) < 6:\n x += j\n if x in lst0:\n temp.append(x)\n else:\n flag = False\n break\n if flag == True:\n ans.append(temp)\n return ans", "def primes1(n):\n sieve = [True] * n\n for i in range(3,int(n**0.5)+1,2):\n if sieve[i]:\n sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)\n return [2] + [i for i in range(3,n,2) if sieve[i]]\n\nlst = primes1(10000)\n\nimport bisect\ndef primes_a_p(lower_limit, upper_limit):\n lst0 = lst[bisect.bisect_left(lst, lower_limit):bisect.bisect_right(lst,upper_limit)]\n ans = []\n for i in range(len(lst0)-5):\n for j in range(30, 1500, 30):\n x = lst0[i]+j\n if x not in lst0:\n continue\n if x > lst0[-1]:\n break\n temp = [lst0[i], x]\n flag = True\n while len(temp) < 6:\n x += j\n if x in lst0:\n temp.append(x)\n else:\n flag = False\n break\n if flag == True:\n ans.append(temp)\n return ans\n \n", "def sito(m, n):\n \"\"\"Sito Erastotenesa\"\"\"\n numbers = [x for x in range(0, n+1)]\n numbers[0], numbers[1] = False, False\n primes = {}\n for i,x in enumerate(numbers):\n if x:\n if x >= m:\n primes[x] = x\n index = i**2\n while index < len(numbers):\n numbers[index] = False\n index += x\n return primes\n \n\ndef primes_a_p(lower_limit, upper_limit):\n primes = sito(lower_limit, upper_limit)\n longest_gap = (upper_limit-lower_limit) // 5\n ap_primes = []\n for i in list(primes.keys()):\n for gap in range(2,longest_gap, 2):\n \n if primes[i]+5*gap <= upper_limit:\n check = [primes[i]+n*gap for n in range(0,6)]\n if any(num not in primes for num in check):\n pass\n else:\n ap_primes.append(check)\n return ap_primes\n", "from math import sqrt\n\ndef primes_a_p(lower_limit, upper_limit):\n \n primes = [p for p in prime_sieve(upper_limit + 1) if p >= lower_limit]\n \n res = []\n \n for k in range(30, upper_limit // 5, 30):\n terms = [0, k, 2 * k, 3 * k, 4 * k, 5 * k]\n for p in primes: \n pp = [t + p for t in terms]\n \n if all(t in primes for t in pp): \n res.append(pp)\n \n return sorted(res, key = lambda v: v[0])\n\ndef prime_sieve(n):\n sieve = [True] * n\n for i in range(3, int(sqrt(n)) + 1, 2):\n if sieve[i]:\n sieve[i * i::2 * i]= [False] * ((n - i * i - 1) // (2 * i) + 1)\n return [2] + [i for i in range(3, n, 2) if sieve[i]] "]
{"fn_name": "primes_a_p", "inputs": [[0, 200], [90, 600], [770, 1000], [30, 305], [1000, 4000]], "outputs": [[[[7, 37, 67, 97, 127, 157]]], [[[107, 137, 167, 197, 227, 257], [359, 389, 419, 449, 479, 509]]], [[]], [[[107, 137, 167, 197, 227, 257]]], [[[1013, 1193, 1373, 1553, 1733, 1913], [1039, 1249, 1459, 1669, 1879, 2089], [1039, 1609, 2179, 2749, 3319, 3889], [1091, 1301, 1511, 1721, 1931, 2141], [1201, 1471, 1741, 2011, 2281, 2551], [1289, 1709, 2129, 2549, 2969, 3389], [1301, 1511, 1721, 1931, 2141, 2351], [1307, 1487, 1667, 1847, 2027, 2207], [1321, 1531, 1741, 1951, 2161, 2371], [1381, 1831, 2281, 2731, 3181, 3631], [1451, 1901, 2351, 2801, 3251, 3701], [1453, 1663, 1873, 2083, 2293, 2503], [1511, 1811, 2111, 2411, 2711, 3011], [1619, 2039, 2459, 2879, 3299, 3719], [1663, 1873, 2083, 2293, 2503, 2713], [1669, 2029, 2389, 2749, 3109, 3469], [1973, 2063, 2153, 2243, 2333, 2423], [2129, 2459, 2789, 3119, 3449, 3779], [2207, 2447, 2687, 2927, 3167, 3407], [2221, 2251, 2281, 2311, 2341, 2371], [2339, 2459, 2579, 2699, 2819, 2939], [2351, 2441, 2531, 2621, 2711, 2801], [2377, 2647, 2917, 3187, 3457, 3727], [2437, 2557, 2677, 2797, 2917, 3037], [2467, 2617, 2767, 2917, 3067, 3217]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,895
def primes_a_p(lower_limit, upper_limit):
16d0196257d2c55ec445cbdea89d5890
UNKNOWN
Given a string, turn each letter into its ASCII character code and join them together to create a number - let's call this number `total1`: ``` 'ABC' --> 'A' = 65, 'B' = 66, 'C' = 67 --> 656667 ``` Then replace any incidence of the number `7` with the number `1`, and call this number 'total2': ``` total1 = 656667 ^ total2 = 656661 ^ ``` Then return the difference between the sum of the digits in `total1` and `total2`: ``` (6 + 5 + 6 + 6 + 6 + 7) - (6 + 5 + 6 + 6 + 6 + 1) ------------------------- 6 ```
["def calc(s):\n total1 = ''.join(map(lambda c: str(ord(c)), s))\n total2 = total1.replace('7', '1')\n return sum(map(int, total1)) - sum(map(int, total2))", "def calc(x):\n return ''.join(str(ord(ch)) for ch in x).count('7') * 6", "def calc(x):\n return ''.join([str(ord(x[i])) for i in range(len(x)) ]).count('7') * 6", "def calc(x):\n total1 = \"\".join(str(ord(char)) for char in x)\n total2 = total1.replace(\"7\",\"1\")\n return sum(int(x) for x in total1) - sum(int(x) for x in total2)", "def calc(x):\n return sum(sum(6 for i in str(ord(i)) if i == '7') for i in x)", "def calc(string):\n return \"\".join(str(ord(char)) for char in string).count(\"7\") * 6", "def calc(s):\n return sum(2 if c == 'M' else c in '%/9CFGHIJKLNOWaku' for c in s) * 6", "def calc(x):\n return sum(6 for c in ''.join(map(str, map(ord, x))) if c== '7')", "def calc(x):\n n = ''.join(map(lambda y: str(ord(y)), x))\n return n.count('7') * 6", "def calc(x):\n n1 = \"\".join([str(ord(c)) for c in x])\n n2 = n1.replace('7', '1')\n return sum(map(int, n1))-sum(map(int, n2))"]
{"fn_name": "calc", "inputs": [["abcdef"], ["ifkhchlhfd"], ["aaaaaddddr"], ["jfmgklf8hglbe"], ["jaam"], ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"]], "outputs": [[6], [6], [30], [6], [12], [96]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,109
def calc(x):
86e50c890f825c8f67452def1219a7aa
UNKNOWN
Rule 30 is a one-dimensional binary cellular automaton. You can have some information here: * [https://en.wikipedia.org/wiki/Rule_30](https://en.wikipedia.org/wiki/Rule_30) You have to write a function that takes as input an array of 0 and 1 and a positive integer that represents the number of iterations. This function has to performe the nth iteration of the **Rule 30** with the given input. The rule to derive a cell from itself and its neigbour is: Current cell | 000 | 001 | 010 | 011 | 100 | 101 | 110 | 111 :-------------|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---: **New cell** | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 As you can see the new state of a certain cell depends on his neighborhood. In *Current cells* you have the *nth* cell with his left and right neighbor, for example the first configuration is **000**: * left neighbor = 0 * current cell = 0 * right neighbor = 0 The result for the current cell is **0**, as reported in **New cell** row. You also have to pay attention to the following things: * the borders of the list are always 0 * values different from 0 and 1 must be considered as 0 * a negative number of iteration never changes the initial sequence * you have to return an array of 0 and 1 Here a small example step by step, starting from the list **[1]** and iterating for 5 times: * We have only one element so first of all we have to follow the rules adding the border, so the result will be **[0, 1, 0]** * Now we can apply the rule 30 to all the elements and the result will be **[1, 1, 1]** (first iteration) * Then, after continuing this way for 4 times, the result will be **[1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1]** In Python, you can also use a support function to print the sequence named printRule30. This function takes as parameters the current list of 0 and 1 to print, the max level that you can reach (number of iterations) and the length of initial array. ```python def printRule30(list_, maxLvl, startLen): ... ``` The last two parameters are optional and are useful if you are printing each line of the iteration to center the result like this: ░░▓░░ -> step 1 ░▓▓▓░ -> step 2 ▓▓░░▓ -> step 3 If you pass only the array of 0 and 1 the previous result for each line will be like this: ▓ -> step 1 ▓▓▓ -> step 2 ▓▓░░▓ -> step 3 **Note:** the function can print only the current list that you pass to it, so you have to use it in the proper way during the interactions of the rule 30.
["def rule30(a, n):\n for _ in range(n):\n a = [int(0 < 4*x + 2*y + z < 5) for x, y, z in\n zip([0, 0] + a, [0] + a + [0], a + [0, 0])]\n return a", "def rule30(li, n):\n for i in range(n):\n li = [0] + li + [0]\n li = [(li[k-1] if k else 0)^(l or (li[k+1] if k<len(li)-1 else 0)) for k, l in enumerate(li)]\n return li", "rule = ['0', '1', '1', '1', '1', '0', '0', '0']\n\ndef rule30(list_, n):\n res = ''.join('1' if x == 1 else '0' for x in list_)\n for _ in range(n):\n res = '00' + res + '00'\n res = ''.join(rule[int(res[i:i+3], 2)] for i in range(len(res)-2))\n return list(map(int, res))", "age = lambda cur: int(sum(cur) == 1 or cur == (0,1,1))\ndef rule30(l, n):\n if n <= 0: return l\n l = [0,0] + l + [0,0]\n return rule30([age(cur) for cur in zip(l[:-2],l[1:-1],l[2:])], n-1)\n", "def cell30(l, c, r):\n if l == 1: return 1 if c == 0 and r == 0 else 0\n return 0 if c == 0 and r == 0 else 1\ndef rule30(row, n):\n return pure30([c if c == 1 else 0 for c in row], n)\ndef pure30(row, n):\n for i in range(n):\n row.append(0)\n row.insert(0, 0)\n ref = row[:]\n row = [cell30(0 if i == 0 else ref[i - 1], v, ref[i + 1] if i + 1 < len(ref) else 0) for i, v in enumerate(row)]\n return row", "ONES = set(((0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0)))\n\ndef rule30(array, n):\n if n < 1:\n return array\n array = (0,) + tuple(1 if v == 1 else 0 for v in array) + (0,)\n for _ in range(n):\n array = (array[-1], 0) + array + (0, array[0])\n array = tuple(int(array[i : i + 3] in ONES) for i in range(len(array) - 2))\n return list(array[1:-1])\n", "def rule30(list_, n):\n for _ in range(n):\n list_=[0]+list_+[0]\n list_=[ruler(list_[i-1],list_[i],list_[(i+1)%len(list_)]) for i in range(len(list_))]\n return list_\n\ndef ruler(*args):\n data=[1 if x==1 else 0 for x in args]\n x=int(\"\".join(map(str,data)),2)\n if x==0 or x>4: return 0\n else: return 1", "def rule30(l, n):\n d = {(0, 0, 0): 0, (0, 0, 1): 1, (0, 1, 0): 1,\n (0, 1, 1): 1, (1, 0, 0): 1, (1, 0, 1): 0,\n (1, 1, 0): 0, (1, 1, 1): 0}\n for i in range(0, n):\n l = [0] * 2 + l + [0] * 2\n l = [d[(l[j], l[j + 1], l[j + 2])] for j in range(0, len(l) - 2)]\n return l\n", "def rule30(lst, n):\n dic1 = {'000': 0, '001': 1, '010': 1, '011': 1, '100': 1, '101': 0, \n '110': 0, '111': 0}\n lst = [0]*n + lst + [0]*n\n for _ in range(n):\n temp = lst[:]\n for i in range(0, len(lst)):\n x = [0] + lst[i:i+2] if i == 0 else (lst[i-1:] + [0] if i == len(lst)-1 else lst[i-1:i+2])\n x = ''.join(map(str, x))\n temp[i] = dic1[x]\n lst = temp[:]\n return lst"]
{"fn_name": "rule30", "inputs": [[[1], 1], [[1], 2], [[1], 21], [[0], 5], [[0], 0], [[1, 1, 1], 0], [[0], 3], [[1], -3], [[1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1], 1], [[1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1], 75]], "outputs": [[[1, 1, 1]], [[1, 1, 0, 0, 1]], [[1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [[0]], [[1, 1, 1]], [[0, 0, 0, 0, 0, 0, 0]], [[1]], [[1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1]], [[1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,802
def rule30(list_, n):
6c94816e47ed9587a18eb6da51647ddc
UNKNOWN
Sometimes, I want to quickly be able to convert miles per imperial gallon into kilometers per liter. Create an application that will display the number of kilometers per liter (output) based on the number of miles per imperial gallon (input). Make sure to round off the result to two decimal points. If the answer ends with a 0, it should be rounded off without the 0. So instead of 5.50, we should get 5.5. Some useful associations relevant to this kata: 1 Imperial Gallon = 4.54609188 litres 1 Mile = 1.609344 kilometres
["def converter(mpg):\n '''Converts mpg to kpl. Rounds to two decimal places.'''\n kpl = round(mpg * 1.609344/4.54609188, 2)\n return kpl", "\ndef converter(mpg):\n #your code here\n return round(mpg / 4.54609188 * 1.609344 , 2)\n", "def converter(mpg):\n return round((mpg * 1.609344 / 4.54609188), 2)", "converter = lambda x: round(x * 0.354006043538, 2)", "def converter(mpg):\n gallon_to_liter_rate = 4.54609188\n mile_to_km_rate = 1.609344\n return round( ((mpg * mile_to_km_rate) / gallon_to_liter_rate), 2)", "def converter(mpg):\n return round(mpg/4.54609188*1.609344 ,2) if mpg else 0", "converter = lambda mpg, g=4.54609188, m=1.609344: round(mpg*(m/g), 2)", "KM_PER_MILE = 1.609344\nLITERS_PER_UK_GALLON = 4.54609188\n\ndef converter(mpg):\n return round(mpg * KM_PER_MILE / LITERS_PER_UK_GALLON, 2)\n", "def converter(mpg):\n L_PER_G = 4.54609188 # L\n KM_PER_MI = 1.609344 # km\n return round(mpg * KM_PER_MI / L_PER_G, 2)", "def converter(mpg):\n return round(1.609344/4.54609188*mpg,2)", "def converter(mpg):\n return round(mpg*0.35400604353,2) ", "converter = lambda mpg: round(mpg * 35.400604353) / 100", "def converter(mpg: int) -> float:\n \"\"\" Convert miles per imperial gallon into kilometers per liter. \"\"\"\n return round(mpg / (4.54609188 / 1.609344), 2)", "def converter(mpg):\n x=4.54609188\n y=1.609344\n return round(mpg*y/x,2)", "def converter(mpg):\n c= ( mpg / 4.54609188 * 1.609344)\n return round(c,2)", "def converter(mpg):\n km_new = round ((mpg * 1.609344 ) / 4.54609188, 2)\n return km_new\n", "def converter(mpg):\n lit=4.54609188\n Km=mpg*1.609344\n return round(Km/lit,2)", "def converter(mpg):\n lr, km = 1.609344, 4.54609188\n return round(mpg * (lr / km), 2)", "GALLON_LITRE_RATE = 4.54609188\nMILE_KM_RATE = 1.609344\n\ndef converter(mpg):\n return round(mpg / GALLON_LITRE_RATE * MILE_KM_RATE, 2)\n", "\n\ndef converter(mpg):\n return round(0.3540061*mpg,2)\n", "def converter(mpg):\n GALLON_IN_LITRES = 4.54609188\n MILE_IN_KM = 1.609344\n LITRES_PER_KM_SCALEFACTOR = GALLON_IN_LITRES / MILE_IN_KM\n return round(mpg / LITRES_PER_KM_SCALEFACTOR, 2) ", "def converter(mpg):\n litre = 4.54609188\n mile = 1.609344\n return round(mpg * mile / litre, 2)", "def converter(mpg):\n conversion_factor = 1.609344 / 4.54609188\n kpl = mpg * conversion_factor\n return round(kpl,2)", "def converter(mpg):\n ldReturn = mpg / 4.54609188\n ldReturn *= 1.609344\n return float(\"%.2f\" % ldReturn)", "def converter(mpg):\n mpk=4.54609188/1.609344\n return round(mpg/mpk,2)", "def converter(mpg):\n kpl = 1.609344 / 4.54609188 * mpg\n r = round(kpl, 2)\n if type(r) is int:\n return int(r)\n elif type(r*10) is int:\n return round(r, 1)\n else:\n return r", "def converter(mpg):\n return round(mpg * 0.354006043,2)", "def converter(mpg):\n res = (mpg/4.54609188)* 1.609344\n temp = f'{res:.2f}'\n if temp[-1] == '0':\n temp = f'{res:.1f}'\n erg = float(temp)\n return erg\n", "def converter(mpg):\n km_in_mile = 1.609344\n litres_in_gallon = 4.54609188\n return round(mpg * km_in_mile / litres_in_gallon, 2)", "import numpy as np\ndef converter(mpg):\n return np.round(mpg * 0.354006, 2)", "def converter(mpg):\n \n miles_to_km = 1.609344\n gallon_to_liter = 4.54609188\n \n return round((mpg / gallon_to_liter) * miles_to_km,2)\n", "def converter(mpg):\n k = 1.609344 / 4.54609188\n return round(k * mpg, 2)", "def converter(mpg):\n conver = 1.609344/4.54609188\n return round(mpg*conver,2)", "def converter(mpg):\n ans=mpg*1.609344/4.54609188\n return round(ans,2)", "def converter(mpg):\n Imperial_Gallon = 4.54609188 \n Mile = 1.609344\n \n kml = Mile/Imperial_Gallon\n return round(kml*mpg,2)\n", "def converter(mpg):\n gallon = 4.54609188\n miles = 1.609344\n return round(mpg * miles / gallon, 2)", "def converter(mpg: int):\n return round(mpg * 1.609344 / 4.54609188, 2)", "imperial_gallon = 4.54609188\nmile = 1.609344\ndef converter(mpg):\n return round((mpg / imperial_gallon) * mile, 2)", "converter=lambda n:round(n*1.609344/4.54609188,2)", "def converter(mpg):\n print(4.54609188/1.609344)\n return round(mpg / 2.8248105314960625, 2)", "def converter(mpg):\n mile = 1.609344\n gallon = 4.54609188\n kpl = mpg * mile / gallon\n return round(kpl, 2)", "def converter(mpg):\n gallon = 4.54609188\n mile = 1.609344\n kpl = round(mpg * mile/gallon, 2)\n return kpl\n", "def converter(mpg: int) -> float:\n return round(mpg * (1.609344 / 4.54609188), 2)\n", "def converter(mpg):\n answer = mpg / 2.82481053\n return round(answer,2)\n", "def converter(mpg):\n klm = mpg * 1.609344 / 4.54609188\n return round(klm, 2)", "R = 4.54609188 / 1.609344\n\ndef converter(mpg):\n return round(mpg / R, 2)", "def converter(mpg):\n kml = (mpg * 1.609344) / 4.54609188\n return round(kml, 2)", "def converter(mpg):\n miles_to_km = 1.609344\n gallon_to_litre = 4.54609188\n return round (mpg * miles_to_km / gallon_to_litre, 2)", "def converter(mpg):\n Lpg = 4.54609188\n Kpm = 1.609344\n return round(mpg * Kpm / Lpg, 2)\n \n #Lpg= leterPerGallon\n #Kpm= KilometeresPerMeter\n", "def converter(mpg):\n kmpg = mpg * 1.609344\n \n kmpl = kmpg / 4.54609188\n return float(format(kmpl, '.2f'))", "def converter(mpg):\n l = 4.54609188\n k = 1.609344 \n kpl = k/l*mpg\n return round (kpl,2)\n", "def converter(mpg):\n result = \"{:.2f}\".format(mpg * 1.609344 / 4.54609188)\n return float(result) if result[-1] != '0' else float(result[:-1])", "def converter(mpg):\n \n kpl = mpg * 1.609344 / 4.54609188 \n kpl = round(kpl * 100) / 100\n \n return kpl\n \n \n", "def converter(mpg):\n return float(\"{:.2f}\".format(mpg/(4.54609188/1.609344)))", "def converter(mpg):\n KM_PER_MILE = 1.609344\n LITRE_PER_GALLON = 4.54609188\n tmp = round((mpg * KM_PER_MILE / LITRE_PER_GALLON), 2) * 100\n return (tmp // 10) / 10 if tmp % 10 == 0 else tmp / 100", "#k/l\ndef converter(mpg):\n return round(mpg * (1.609344/ 4.54609188), 2)", "def converter(mpg):\n m = 1.609344 \n g = 4.54609188\n res_round = round(mpg*m/g,2)\n return res_round\n \n \n #your code here\n", "def converter(mpg):\n gln = 4.54609188\n ml = 1.609344\n return round(mpg * ml / gln,2)", "def converter(mpg):\n litres = 4.54609188\n km = 1.609344\n kpl = km/litres*mpg\n return round(kpl,2)\n \n\n \n", "def converter(mpg): return round(mpg / 2.82481, 2)", "def converter(m):\n return round(m*0.354006044,2)\n \n #your code here\n", "converter = lambda mpg: round(mpg * 0.354006043538, 2)\n", "def converter(mpg):\n gallit = 1.609344 / 4.54609188\n lit = round(mpg * gallit,2)\n return lit", "def converter(mpg):\n return round(mpg * 1.609344 / 4.54609188, 2)\n #mpg = m / g\n \n #kpl = k / l\n \n #m to k = m * 1.609344\n #g to l = g * 4.54609188\n", "def converter(mpg):\n m = 1.609344\n g = 4.54609188\n return round(mpg*m/g, 2)", "def converter(mpg):\n x=round(mpg*1.609344/4.54609188,2)\n return x if str(x)[-1]!='0' else float(str(x)[:-1])", "def converter(mpg):\n km = mpg * (1.609344) \n kpl = km / 4.54609188\n return round(kpl, 2)", "def converter(mpg):\n km = mpg * (1.609344) \n kml = km / 4.54609188\n return round(kml, 2)", "def converter(mpg):\n return round(1/4.54609188*1.609344*mpg,2)", "def converter(mpg):\n kmpl = (mpg) * (1.609344) * (1/4.54609188)\n return round(kmpl, 2)", "def converter(mpg):\n liter_per_mile = 1.609344 / 4.54609188\n return round(liter_per_mile * mpg,2)", "def converter(mpg):\n km = 1.609344\n liters = 4.54609188\n return round(mpg / liters * km,2)", "def converter(mpg):\n return round(mpg / 2.8248105, 2)", "def converter(mpg):\n M =1.609344\n g = 4.54609188\n kpg = (mpg *M)/g\n return round(kpg,2)", "def converter(mpg):\n conv = 1.609344/4.54609188\n return round(mpg * conv, 2)", "def converter(mpg):\n t1, t2 = (4.54609188, 1.609344)\n return round(mpg * t2 / t1, 2)", "import math\n\ndef converter(mpg):\n res = mpg * 0.354006\n \n s = str(res)\n dot = s.index('.')\n if [len(s) -1] =='0':\n return float(s[:dot + 1])\n else:\n return round(res,2)\n", "def converter(mpg):\n '''convert miles per imperial gallon into kilometers per liter'''\n kpl = round(mpg * 1.609344/4.54609188, 2)\n return kpl", "def converter(mpg):\n kilo = round(mpg * 1.609344 / 4.54609188, 2)\n return kilo", "def converter(mpg):\n coef = 4.54609188/1.609344\n return round(mpg/coef, 2)", "def converter(mpg):\n '''\n takes miles per gallon as input\n converts it to kilometers per hour\n '''\n ans = (mpg*1.609344)/4.54609188\n return round(ans,2)", "def converter(mpg):\n #your code here\n #mpg is number of miles/1 gallon\n # 1 mpg is 1.609344/4.54609188\n a = mpg * 1.609344/4.54609188\n return(round(a, 2))", "def converter(mpg):\n kpl = mpg * 4.54609188**-1 * 1.609344\n return round(kpl, 2)", "def converter(mpg):\n kml = (mpg*1.609344)/4.54609188\n return float(\"%.2f\" % round(kml,2))", "def converter(mpg):\n return round(mpg/2.824810531,2)\n#Solved on 29th Sept, 2019 at 04:24 PM.\n", "def converter(mpg):\n return round(mpg*(1.609344/4.54609188),2) #I solved this Kata on [27-Sept-2019] ^_^ [04:51 AM]...#Hussam'sCodingDiary", "def converter(x):\n return(round((x/(4.54609188/1.609344)),2))", "def converter(mpg):\n km = round((mpg * 1.609344 / 4.54609188), 2)\n return km\n", "def converter(mpg):return round(mpg*1.609344/4.54609188,2) if str(round(mpg*1.609344/4.54609188,2))[-1]!=0 else round(mpg*1.609344/4.54609188,1)\n", "def converter(mpg):\n conv = 1.609344/4.54609188\n return float(\"{:.2f}\".format(mpg * conv))", "g = 4.54609188; m = 1.609344\nconverter = lambda mpg: round(mpg * m / g, 2)", "def converter(mpg):\n kl = round(((mpg * 1.609344)/4.54609188),2)\n return kl\n\n\n", "def converter(mpg):\n imperial_gallon_in_litres = 4.54609188\n mile_in_km = 1.609344\n lpk = mpg * mile_in_km / imperial_gallon_in_litres\n return float(\"{0:.2f}\".format(lpk))", "def converter(mpg):\n imperial_gallon_in_litres = 4.54609188\n mile_in_km = 1.609344\n kpl = mpg * mile_in_km / imperial_gallon_in_litres\n return float(\"{0:.2f}\".format(kpl))", "def converter(mpg):\n conversionFactor = 1.609344/4.54609188\n return round (mpg * conversionFactor, 2)\n", "converter=lambda mpg:round(0.354006*mpg,2)", "def converter(mpg):\n kpl = mpg/2.8248105314960629921259842519685\n return float(\"{:.2f}\".format(kpl))", "def converter(mpg):\n ans = mpg/2.8248105314960629921259842519685\n return float(\"{:.2f}\".format(ans))", "def converter(mpg):\n kof = 4.54609188 / 1.609344\n a = mpg / kof\n return round(a, 2)\n #your code here\n", "import math\n#Miles per gallon to kilometers per liter\ndef converter(mpg):\n return round(mpg/(4.54609188/1.609344 ),2)", "def converter(mpg):\n g=4.54609188\n m=1.609344\n return (round((mpg*m/g),2))", "MILE = 1.609344\nGALLON = 4.54609188\n\ndef converter(mpg):\n return round(mpg/GALLON * MILE ,2)", "def converter(mpg):\n ig = 4.54609188\n M = 1.609344 \n return round (mpg * M / ig, 2)\n #your code here\n", "IMP_GALLON_IN_LITRES = 4.54609188\nMILE_IN_KMS = 1.609344\n\n\ndef converter(mpg):\n return round((mpg / IMP_GALLON_IN_LITRES) * MILE_IN_KMS, 2)", "def converter(mpg):\n converted_value = mpg * 1.609344 / 4.54609188\n return round(converted_value, 2)", "import decimal\n\ndef converter(mpg):\n mpg = decimal.Decimal(mpg)\n m2km = decimal.Decimal(1.609344)\n g2l = decimal.Decimal(4.54609188)\n r = mpg * m2km / g2l\n return float(r.quantize(decimal.Decimal(\"1.00\")).normalize())\n # Cmon, having to type beck to float because of assert?\n # This is so broken.\n", "def converter(mpg):\n \n \"\"\"Converts mile/gallon to kilometre/litre.\"\"\"\n \n # constants\n mile_to_kilometre = 1.609344\n gallon_to_litre = 4.54609188 \n \n # make some calculations\n formula = mpg * (mile_to_kilometre / gallon_to_litre)\n \n # round the result\n result = round(formula, 2)\n \n return result", "def converter(mpg):\n return round(mpg * (1/4.54609188) * (1.609344/1), 2)", "def converter(mpg):\n lpg = 4.54609188\n kpm = 1.609344\n n = mpg * kpm / lpg\n return float(str('{:.2f}'.format(n)).rstrip('0'))"]
{"fn_name": "converter", "inputs": [[10], [20], [30], [24], [36]], "outputs": [[3.54], [7.08], [10.62], [8.5], [12.74]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,758
def converter(mpg):
e486b8bb1ebfd51b113a520e7d186016
UNKNOWN
The aim of this kata is to split a given string into different strings of equal size (note size of strings is passed to the method) Example: Split the below string into other strings of size #3 'supercalifragilisticexpialidocious' Will return a new string 'sup erc ali fra gil ist ice xpi ali doc iou s' Assumptions: String length is always greater than 0 String has no spaces Size is always positive
["from textwrap import wrap\n\n\ndef split_in_parts(s, part_length): \n return \" \".join(wrap(s,part_length))", "def split_in_parts(s, n): \n return ' '.join([s[i:i+n] for i in range(0, len(s), n)])", "def split_in_parts(s, part_length): \n new = \"\"\n i = 0\n for x in s: # Recorremos s\n if i == part_length: # Si toca meter un espacio...\n new += \" \" # Lo hacemos\n new += x # Y a\u00f1adimos la siguiente letra porque sino el ciclo se salta algunas\n i = 1\n else: # Si no toca meter un espacio...\n new += x # A\u00f1adimos la letra y punto\n i += 1\n return new", "def split_in_parts(s, p): \n return ' '.join(s[i:i+p] for i in range(0,len(s),p))", "def split_in_parts(s, p): \n l=[]\n i=0\n while i < len(s):\n k=s[i:i+p]\n l.append(k)\n i+=p\n res=\" \".join(l)\n return res\n", "def split_in_parts(s, part_length):\n newS = ''\n for i in range(len(s)):\n newS += f' {s[i]}' if i != 0 and i % part_length == 0 else s[i]\n \n return newS\n", "def split_in_parts(stg, size): \n return \" \".join(stg[i:i+size] for i in range(0, len(stg), size))", "def split_in_parts(s, p): \n return ' '.join([s[i:i+p] for i in range(0,len(s),p)])", "def split_in_parts(s, part_length):\n cnt = 0\n answer = \"\"\n for i in s:\n if cnt < part_length:\n answer += i\n cnt += 1\n else:\n answer = answer + \" \" + i\n cnt = 1\n return answer", "def split_in_parts(s, part_length): \n r = []\n for x in range(0,len(s),part_length):\n r += [s[x:x+part_length]]\n\n return \" \".join(r)"]
{"fn_name": "split_in_parts", "inputs": [["supercalifragilisticexpialidocious", 3], ["HelloKata", 1], ["HelloKata", 9]], "outputs": [["sup erc ali fra gil ist ice xpi ali doc iou s"], ["H e l l o K a t a"], ["HelloKata"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,806
def split_in_parts(s, part_length):
b06aca16ec068172628ad5810fa1fcce
UNKNOWN
Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation. ### Examples ``` "1999" --> "20th" "2011" --> "21st" "2154" --> "22nd" "2259" --> "23rd" "1124" --> "12th" "2000" --> "20th" ```
["def what_century(year):\n n = (int(year) - 1) // 100 + 1\n return str(n) + (\"th\" if n < 20 else {1: \"st\", 2: \"nd\", 3: \"rd\"}.get(n % 10, \"th\"))", "def what_century(year):\n year = str(year)\n st = year[:2]\n st = int(st)\n gt = st + 1\n gt = str(gt)\n if year != \"0000\" and year[1:] != \"000\" and year[2:] != \"00\":\n if len(gt) == 2:\n if (gt[0] == \"1\") and (gt[1] == \"0\"):\n return(\"10th\") \n elif (gt[0] == \"1\") and (gt[1] in range(1, 10)):\n return(f\"{gt}th\") \n elif gt[0] != \"1\" and gt[1] == \"0\":\n return(f\"{gt}th\")\n elif gt[0] != \"1\" and gt[1] == \"1\":\n return(f\"{gt}st\")\n elif gt[0] != \"1\" and gt[1] == \"2\":\n return(f\"{gt}nd\")\n elif gt[0] != \"1\" and gt[1] == \"3\":\n return(f\"{gt}rd\") \n else:\n return(f\"{gt}th\")\n else:\n if gt[0] == 1:\n return(\"1st\")\n elif gt[0] == 2:\n return(\"2nd\")\n elif gt[0] == 3:\n return(\"3rd\")\n else:\n return(f\"{gt}th\")\n elif year[1:] == \"000\" and year != \"0000\":\n return(f\"{year[0]}0th\")\n elif year[2:] == \"00\" and year[1:] != \"000\" and year != \"0000\":\n if year[1] == \"1\":\n return(f\"{year[:2]}st\")\n elif year[2] == \"2\":\n return(f\"{year[:2]}nd\")\n elif year[2] == \"3\":\n return(f\"{year[:2]}rd\")\n else:\n return(f\"{year[:2]}th\")\n elif year == \"0000\":\n return(\"0th\")\n", "def what_century(year):\n if 100>=int(year)>0:\n return '1st'\n if 200>=int(year)>100:\n return '2nd'\n if 300>=int(year)>200:\n return '3rd'\n if 400>=int(year)>300:\n return '4th'\n if 500>=int(year)>400:\n return '5th'\n if 600>=int(year)>500:\n return '6th'\n if 700>=int(year)>600:\n return '7th'\n if 800>=int(year)>700:\n return '8th'\n if 900>=int(year)>800:\n return '9th'\n if 1000>=int(year)>900:\n return '10th'\n if 1100>=int(year)>1000:\n return '11th'\n if 1200>=int(year)>1100:\n return '12th'\n if 1300>=int(year)>1200:\n return '13th'\n if 1400>=int(year)>1300:\n return '14th'\n if 1500>=int(year)>1400:\n return '15th'\n if 1600>=int(year)>1500:\n return '16th'\n if 1700>=int(year)>1600:\n return '17th'\n if 1800>=int(year)>1700:\n return '18th'\n if 1900>=int(year)>1800:\n return '19th'\n if 2000>=int(year)>1900:\n return '20th'\n if 2100>=int(year)>2000:\n return '21st'\n if 2200>=int(year)>2100:\n return '22nd'\n if 2300>=int(year)>2200:\n return '23rd'\n if 2400>=int(year)>2300:\n return '24th'\n if 2500>=int(year)>2400:\n return '25th'\n if 2600>=int(year)>2500:\n return '26th'\n if 2700>=int(year)>2600:\n return '27th'\n if 2800>=int(year)>2700:\n return '28th'\n if 2900>=int(year)>2800:\n return '29th'\n if 3000>=int(year)>2900:\n return '30th'\n if 3100>=int(year)>3000:\n return '31st'\n if 3200>=int(year)>3100:\n return '32nd'\n if 3300>=int(year)>3200:\n return '33rd'\n if 3400>=int(year)>3300:\n return '34th'\n if 3500>=int(year)>3400:\n return '35th'\n if 3600>=int(year)>3500:\n return '36th'\n if 3700>=int(year)>3600:\n return '37th'\n if 3800>=int(year)>3700:\n return '38th'\n if 3900>=int(year)>3800:\n return '39th'\n if 4000>=int(year)>3900:\n return '40th'\n if 4100>=int(year)>4000:\n return '41st'\n if 4200>=int(year)>4100:\n return '42nd'\n if 4300>=int(year)>4200:\n return '43rd'\n if 4400>=int(year)>4300:\n return '44th'\n if 4500>=int(year)>4400:\n return '45th'\n if 4600>=int(year)>4500:\n return '46th'\n if 4700>=int(year)>4600:\n return '47th'\n if 4800>=int(year)>4700:\n return '48th'\n if 4900>=int(year)>4800:\n return '49th'\n if 5000>=int(year)>4900:\n return '50th'\n if 5100>=int(year)>5000:\n return '51st'\n if 5200>=int(year)>5100:\n return '52nd'\n if 5300>=int(year)>5200:\n return '53rd'\n if 5400>=int(year)>5300:\n return '54th'\n if 5500>=int(year)>5400:\n return '55th'\n if 5600>=int(year)>5500:\n return '56th'\n if 5700>=int(year)>5600:\n return '57th'\n if 5800>=int(year)>5700:\n return '58th'\n if 5900>=int(year)>5800:\n return '59th'\n if 6000>=int(year)>5900:\n return '60th'\n if 6100>=int(year)>6000:\n return '61st'\n if 6200>=int(year)>6100:\n return '62nd'\n if 6300>=int(year)>6200:\n return '63rd'\n if 6400>=int(year)>6300:\n return '64th'\n if 6500>=int(year)>6400:\n return '65th'\n if 6600>=int(year)>6500:\n return '66th'\n if 6700>=int(year)>6600:\n return '67th'\n if 6800>=int(year)>6700:\n return '68th'\n if 6900>=int(year)>6800:\n return '69th'\n if 7000>=int(year)>6900:\n return '70th'\n if 7100>=int(year)>7000:\n return '71st'\n if 7200>=int(year)>7100:\n return '72nd'\n if 7300>=int(year)>7200:\n return '73rd'\n if 7400>=int(year)>7300:\n return '74th'\n if 7500>=int(year)>7400:\n return '75th'\n if 7600>=int(year)>7500:\n return '76th'\n if 7700>=int(year)>7600:\n return '77th'\n if 7800>=int(year)>7700:\n return '78th'\n if 7900>=int(year)>7800:\n return '79th'\n if 8000>=int(year)>7900:\n return '80th'\n if 8100>=int(year)>8000:\n return '81st'\n if 8200>=int(year)>8100:\n return '82nd'\n if 8300>=int(year)>8200:\n return '83rd'\n if 8400>=int(year)>8300:\n return '84th'\n if 8500>=int(year)>8400:\n return '85th'\n if 8600>=int(year)>8500:\n return '86th'\n if 8700>=int(year)>8600:\n return '87th'\n if 8800>=int(year)>8700:\n return '88th'\n if 8900>=int(year)>8800:\n return '89th'\n if 9000>=int(year)>8900:\n return '90th'\n if 9100>=int(year)>9000:\n return '91st'\n if 9200>=int(year)>9100:\n return '92nd'\n if 9300>=int(year)>9200:\n return '93rd'\n if 9400>=int(year)>9300:\n return '94th'\n if 9500>=int(year)>9400:\n return '95th'\n if 9600>=int(year)>9500:\n return '96th'\n if 9700>=int(year)>9600:\n return '97th'\n if 9800>=int(year)>9700:\n return '98th'\n if 9900>=int(year)>9800:\n return '99th' \n if 10000>=int(year)>9900:\n return '100th'\n \n", "def what_century(year):\n ordinal = lambda n: \"%d%s\" % (n,\"tsnrhtdd\"[(n//10%10!=1)*(n%10<4)*n%10::4])\n return ordinal((int(year) - 1) // 100 + 1)", "def what_century(year):\n # code must go here\n if year[2:]==\"00\":\n century = year[:2]\n else:\n century = str(int(year)//100+1)\n suffix=\"th\"\n if century[0]==\"1\":\n pass\n elif century[1] == \"1\":\n suffix=\"st\"\n elif century[1] == \"2\":\n suffix = \"nd\"\n elif century[1] == \"3\":\n suffix = \"rd\"\n return century+suffix", "def what_century(year):\n y = int(year)\n c, r = divmod(y, 100)\n if r:\n c += 1\n ones = c%10\n tens = (c//10)%10\n if tens == 1:\n suffix = \"th\"\n elif ones == 1:\n suffix = \"st\"\n elif ones == 2:\n suffix = \"nd\"\n elif ones == 3:\n suffix = \"rd\" \n else:\n suffix = \"th\"\n return str(c)+suffix", "SUFFIX_ONE = 'st'\nSUFFIX_TWO = 'nd'\nSUFFIX_THREE = 'rd'\nSUFFIX_OTHER = 'th'\n\ndef what_century(year):\n century = 1 + (int(year) - 1) // 100\n return str(century) + ordinal_suffix(century)\n\ndef ordinal_suffix(number):\n if number // 10 == 1: # ten or teen\n return SUFFIX_OTHER\n elif number % 10 == 1: # ending 1\n return SUFFIX_ONE\n elif number % 10 == 2: # ending 2\n return SUFFIX_TWO\n elif number % 10 == 3: # ending 3\n return SUFFIX_THREE\n else:\n return SUFFIX_OTHER", "def what_century(year):\n year = int(year)\n output_century = year // 100\n ordinal = ''\n\n if year % 100 > 0: output_century += 1\n\n if output_century > 10 and output_century < 14: ordinal = 'th'\n elif output_century % 10 == 1: ordinal = 'st'\n elif output_century % 10 == 2: ordinal = 'nd'\n elif output_century % 10 == 3: ordinal = 'rd'\n else: ordinal = 'th'\n\n return str(output_century) + ordinal"]
{"fn_name": "what_century", "inputs": [["1999"]], "outputs": [["20th"]]}
INTRODUCTORY
PYTHON3
CODEWARS
9,618
def what_century(year):
8b50a65cf2f05fd5dfc8fd9725f76223
UNKNOWN
A stick is balanced horizontally on a support. Will it topple over or stay balanced? (This is a physics problem: imagine a real wooden stick balanced horizontally on someone's finger or on a narrow table, for example). The stick is represented as a list, where each entry shows the mass in that part of the stick. The stick is balanced on a support. The "terrain" is represented by a list of 1s and 0s, where the 1s represent the support and the 0s represent empty space. Each index is a coordinate on the x-axis, so e.g. the physical interpretations of some terrains are as follows: ![](https://i.imgur.com/P4MpHZV.png) The stick will only balance if its centre of mass is directly above some part of its support. Return `True` if the stick will balance and `False` if it will topple. Both lists will be of equal length (that is, the stick and the terrain have equal width so that each index of the stick is directly above the corresponding index of the terrain). Every terrain will contain one, and only one, support. ## Examples: ![](https://i.imgur.com/PyMBsAl.png) ``` [2,3,2] [0,1,0] ---> Perfectly balanced, return True [5,1,1] [0,1,0] ---> will topple to the left, return False [3,3,4] [0,1,0] ---> will topple to the right (but only just) [7,1,1,1,1,1,1,1] [0,1,1,0,0,0,0,0] ---> will balance, perfectly, without a doubt [5, 3, 2, 8, 6] [0, 0, 0, 1, 1] ---> will topple to the left ```
["from math import ceil\n\ndef will_it_balance(stick, gnd):\n gravPt = sum(v*i for i,v in enumerate(stick)) / sum(stick)\n return gnd[int(gravPt)] == gnd[ceil(gravPt)] == 1", "def will_it_balance(stick, terrain):\n com = sum(i*w for i,w in enumerate(stick))/sum(stick)\n return terrain.index(1)<=com<=max(i for i,v in enumerate(terrain) if v==1)", "from scipy.ndimage.measurements import center_of_mass\nfrom math import floor, ceil\nfrom numpy import array\n\ndef will_it_balance(stick, terrain):\n center = center_of_mass(array(stick))[0]\n return terrain[floor(center)] and terrain[ceil(center)]", "from math import ceil, floor\n\ndef will_it_balance(stick, terrain):\n c = sum(i*m for i, m in enumerate(stick, 1)) / sum(stick)\n a, b = floor(c), ceil(c)\n return all(x or not (a <= i <= b) for i, x in enumerate(terrain, 1))", "def will_it_balance(stick, terrain):\n center_of_mass = sum(i * mass for i, mass in enumerate(stick)) / sum(stick)\n terrain_ones = [i for i, x in enumerate(terrain) if x]\n left, right = terrain_ones[0], terrain_ones[-1]\n return left <= center_of_mass <= right", "will_it_balance=lambda a,s:s.index(1)<=sum(i*a[i]for i in range(len(a)))/sum(a)<=len(s)-s[::-1].index(1)-1", "import math\n\ndef will_it_balance(stick, terrain):\n numerator = 0\n denominator = 0\n for index, weight in enumerate(stick):\n numerator += weight * (index+1)\n denominator += weight\n centerOfMass = numerator/denominator\n centerOfMassLowCoord, centerOfMassHighCoord = math.floor(centerOfMass), math.ceil(centerOfMass)\n return terrain[centerOfMassLowCoord-1]==1 and terrain[centerOfMassHighCoord-1]==1", "def will_it_balance(stick, terrain):\n c=0\n T=[]\n for i in range(len(stick)):\n c=c+i*stick[i]\n m=c/sum(stick)\n for i in range(len(terrain)):\n if terrain[i]==1:\n T.append(i)\n \n return (len(T)>=2 and T[0]<=m<=T[-1]) or (len(T)==1 and T[0]==m )\n", "from operator import mul,add\nfrom functools import reduce\ndef will_it_balance(stick, terrain):\n masses = enumerate(stick)\n com = reduce(add,[i*j for i,j in masses])/reduce(add,stick)\n start = terrain.index(1)\n end = [l[0] for l in enumerate(terrain) if l[1] == 1][-1]\n return True if com>= start and com<= end else False", "def will_it_balance(stick, terrain):\n return terrain.index(1) \\\n <= sum(m*x for x, m in enumerate(stick)) / sum(stick) \\\n <= (len(terrain) - 1 - terrain[::-1].index(1))"]
{"fn_name": "will_it_balance", "inputs": [[[2, 3, 2], [0, 1, 0]], [[5, 1, 1], [0, 1, 0]], [[3, 3, 4], [0, 1, 0]], [[9, 7, 1, 1], [1, 1, 0, 0]], [[9, 1, 1, 7], [1, 1, 0, 0]]], "outputs": [[true], [false], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,537
def will_it_balance(stick, terrain):
d11e05d7f81b257720322826afc03ce2
UNKNOWN
# ASC Week 1 Challenge 5 (Medium #2) Create a function that takes a 2D array as an input, and outputs another array that contains the average values for the numbers in the nested arrays at the corresponding indexes. Note: the function should also work with negative numbers and floats. ## Examples ``` [ [1, 2, 3, 4], [5, 6, 7, 8] ] ==> [3, 4, 5, 6] 1st array: [1, 2, 3, 4] 2nd array: [5, 6, 7, 8] | | | | v v v v average: [3, 4, 5, 6] ``` And another one: ``` [ [2, 3, 9, 10, 7], [12, 6, 89, 45, 3], [9, 12, 56, 10, 34], [67, 23, 1, 88, 34] ] ==> [22.5, 11, 38.75, 38.25, 19.5] 1st array: [ 2, 3, 9, 10, 7] 2nd array: [ 12, 6, 89, 45, 3] 3rd array: [ 9, 12, 56, 10, 34] 4th array: [ 67, 23, 1, 88, 34] | | | | | v v v v v average: [22.5, 11, 38.75, 38.25, 19.5] ```
["def avg_array(arrs):\n return [sum(a)/len(a) for a in zip(*arrs)]", "def avg_array(arrs):\n length = len(arrs)\n return [sum(arr)/length for arr in zip(*arrs)]", "from statistics import mean\n\ndef avg_array(arrs):\n return list(map(mean,zip(*arrs)))", "def avg_array(arrs):\n return [(sum(ar[i] for ar in arrs))/len(arrs) for i in range(len(arrs[0]))]", "def avg_array(arr):\n length = len(arr)\n return [sum(numbers) / length for numbers in zip(*arr)]", "def avg_array(arrs):\n\n return [sum(a)/len(a) for a in list(zip(*arrs))]", "def avg_array(arrs):\n return [sum(i)/len(i) for i in zip(*arrs)]", "from statistics import mean\n\ndef avg_array(arrs):\n return [mean(arr) for arr in zip(*arrs)]", "def avg_array(arrs):\n x=[]\n for i in zip(*arrs):\n x.append(sum(i)/len(arrs))\n return x\n", "import numpy as np\ndef avg_array(arrs):\n return (np.sum(arrs, 0) / len(arrs)).tolist()"]
{"fn_name": "avg_array", "inputs": [[[[1, 2, 3, 4], [5, 6, 7, 8]]], [[[2, 3, 9, 10, 7], [12, 6, 89, 45, 3], [9, 12, 56, 10, 34], [67, 23, 1, 88, 34]]], [[[2, 5, 4, 3, 19], [2, 5, 6, 7, 10]]], [[[1.2, 8.521, 0.4, 3.14, 1.9], [2, 4.5, 3.75, 0.987, 1.0]]], [[[2, 5, -4, 3, -19], [-2, -5, 6, 7, 10]]], [[[-2, -18, -45, -10], [0, -45, -20, -34]]]], "outputs": [[[3, 4, 5, 6]], [[22.5, 11, 38.75, 38.25, 19.5]], [[2, 5, 5, 5, 14.5]], [[1.6, 6.5105, 2.075, 2.0635, 1.45]], [[0, 0, 1, 5, -4.5]], [[-1, -31.5, -32.5, -22]]]}
INTRODUCTORY
PYTHON3
CODEWARS
939
def avg_array(arrs):
8bb663d438f0c77954cb2053dcd109ee
UNKNOWN
# Task John won the championship of a TV show. He can get some bonuses. He needs to play a game to determine the amount of his bonus. Here are some cards in a row. A number is written on each card. In each turn, John can take a card, but only from the beginning or the end of the row. Then multiply the number on the card by an coefficient 2^(i)(i means the ith turn). The product is John's bonus of current turn. After all the cards are taken away, the game is over. John's final bonus is the sum of all rounds of bonuses. Obviously, the order in which John takes the cards will affect the amount of John's final bonus. Your task is to help John calculate the maximum amount of bonuses he can get. # Input - `cards`: An integer array. Each element represents the number on the card. - `1 <= cards.length <= 30` - `1 <= cards[i] <= 100` - All inputs are valid. # Output An integer. the maximum amount of bonuses John can get. # Eaxmple For `cards=[1,2,5]`, the output should be `50`. ``` All possible orders are: 1->2->5 bonus:1x2+2*4+5*8=50 1->5->2 bonus:1x2+5*4+2*8=38 5->1->2 bonus:5*2+1*4+2*8=30 5->2->1 bonus:5*2+2*4+1*8=26 The maximum amount of bonus is 50. ```
["def calc(a):\n res = [0] * (len(a) + 1)\n for k in range(len(a)):\n res = [2 * max(a[i] + res[i+1], a[i+k] + res[i]) for i in range(len(a) - k)]\n return res[0]", "from functools import lru_cache\n\ncalc = lambda cards : get(tuple(cards))\nget = lru_cache(None) ( lambda seq, turn=1:max([2**turn*seq[0]+get(seq[1:], turn+1), 2**turn*seq[-1]+get(seq[:-1], turn+1)]) \n if seq else 0 )", "from collections import deque, defaultdict\n\ndef calc(cards):\n memo = defaultdict(int)\n ans = 0\n q = deque([(1, 0, tuple(cards))])\n while q:\n i, score, remains = q.popleft()\n if len(remains) == 1:\n score += remains[0] * 2 ** i\n if score > ans:\n ans = score\n else:\n score_l = score + (remains[0] * 2 ** i)\n if score_l > memo[remains[1:]]:\n memo[remains[1:]] = score_l\n q.append((i + 1, score_l, remains[1:]))\n score_r = score + (remains[-1] * 2 ** i)\n if score_r > memo[remains[:-1]]:\n memo[remains[:-1]] = score_r\n q.append((i + 1, score_r, remains[:-1]))\n return ans", "VISITED = dict()\n\n\ndef calc(cards, idx = 0):\n if idx == 0:\n VISITED.clear()\n \n if len(cards) == 0:\n return 0\n \n tpl = tuple(cards)\n m_value = VISITED.get(tpl, None)\n if m_value:\n return m_value\n \n res = max(cards[0]*(2<<idx) + calc(cards[1:], idx+1), cards[-1]*(2<<idx) + calc(cards[:-1], idx+1))\n VISITED[tpl] = res\n return res\n", "from sys import intern\n\n\ndef calc(cards, i=1, memo={}):\n if len(cards) == 1:\n memo[intern(str((i, cards)))] = cards[0] * 2**i\n return cards[0] * 2**i\n \n if str((i, cards)) in memo:\n return memo[intern(str((i, cards)))]\n \n result = max(cards[0] * 2**i + calc(cards[1:], i+1, memo),\n cards[-1] * 2**i + calc(cards[:-1], i+1, memo))\n memo[intern(str((i, cards)))] = result\n \n return result", "def calc(cards):\n f = 1<<len(cards)\n dp = [f*v for v in cards]\n for d in range(1,len(cards)):\n f>>=1\n dp = [ max( dp[i]+f*cards[i+d], dp[i+1]+f*cards[i] )\n for i in range(len(dp)-1)]\n return dp.pop()", "from functools import lru_cache as memo\n\ndef calc(cards):\n \n @memo(None)\n def get_value(i, j, n):\n if i == j:\n return cards[i]*2**n\n return max(cards[i]*2**n + get_value(i + 1, j, n + 1),\n cards[j]*2**n + get_value(i, j - 1, n + 1)) \n\n return get_value(0, len(cards) - 1, 1)", "\ndef calc(cards):\n \n queue = [(0, (0,len(cards)-1))]\n counter = 1\n multiplier = 1\n global_max = 0\n while True:\n \n hold = {}\n \n for _ in range(counter):\n \n bonus, indices = queue.pop(0)\n if indices[0] > indices[1]: \n return global_max\n \n take_right = (indices[0], indices[1]-1)\n bonus_right = bonus + cards[indices[1]]*(2**multiplier)\n take_left = (indices[0]+1, indices[1])\n bonus_left = bonus + cards[indices[0]]*(2**multiplier)\n \n if take_left in hold:\n hold[take_left] = max(hold[take_left], bonus_left)\n \n else:\n hold[take_left] = bonus_left\n \n if take_right in hold:\n hold[take_right] = max(hold[take_right], bonus_right)\n \n else:\n hold[take_right] = bonus_right\n \n global_max = max(global_max, bonus_left, bonus_right)\n \n queue.extend([(hold[cards], cards) for cards in hold])\n \n counter += 1\n multiplier += 1 \n \n return global_max", "def calc(cards):\n n = len(cards)\n\n table = [[-1 for i in range(n)] for j in range(n)] # stores intermediate highest score\n high = n - 1\n\n def score(low, high, i):\n # base case \n if (i == n):\n return 2**i * cards[low]\n # looks up if we have already calculated highest score\n elif (table[low][high] != -1): \n return table[low][high]\n # recursive case\n else:\n max_score = max( score(low+1, high, i+1) + 2**i * cards[low] , # pick card on the left, LOW\n score(low, high-1, i+1) + 2**i * cards[high] ) # pick card on the right, HIGH\n table[low][high] = max_score\n\n return max_score\n\n return score(0, high, 1)", "def calc(a):\n # k = 0\n res = [0] * (len(a) + 1)\n \n for k in range(1,len(a)+1):\n new_res = []\n new_res_size = len(res)-1\n for i in range(new_res_size):\n j = i+k\n new_res.append(2 * max(a[i]+res[i+1], a[j-1]+res[i]))\n res = new_res\n return res[0]\n"]
{"fn_name": "calc", "inputs": [[[1, 2, 5]], [[1]], [[1, 1]], [[1, 2, 1]], [[4, 10, 2, 3, 1, 3, 1, 6, 9]]], "outputs": [[50], [2], [6], [22], [6722]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,025
def calc(cards):
d2c7bd599710de402de66afeb9bbb5b7
UNKNOWN
In input string ```word```(1 word): * replace the vowel with the nearest left consonant. * replace the consonant with the nearest right vowel. P.S. To complete this task imagine the alphabet is a circle (connect the first and last element of the array in the mind). For example, 'a' replace with 'z', 'y' with 'a', etc.(see below) For example: ``` 'codewars' => 'enedazuu' 'cat' => 'ezu' 'abcdtuvwxyz' => 'zeeeutaaaaa' ``` It is preloaded: ``` const alphabet = ['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'] const consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']; const vowels = ['a','e','i','o','u']; ``` P.S. You work with lowercase letters only.
["def replace_letters(word):\n return word.translate(str.maketrans('abcdefghijklmnopqrstuvwxyz','zeeediiihooooonuuuuutaaaaa')) \n", "table = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'zeeediiihooooonuuuuutaaaaa')\ndef replace_letters(word): return word.translate(table)", "from string import ascii_lowercase as al\n\ntbl = str.maketrans(al, ''.join(\n al[(i-1)%26] if x in 'aeiou' else next(al[j%26]\n for j in range(i+1, 100) if al[j%26] in 'aeiou') for i, x in enumerate(al)\n))\n\ndef replace_letters(word):\n return word.translate(tbl)", "TR = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'zeeediiihooooonuuuuutaaaaa')\n\ndef replace_letters(word):\n return word.translate(TR)", "def replace_letters(word):\n d = {'a':'z','b':'e','c':'e','d':'e','e':'d','f':'i','g':'i','h':'i','i':'h','j':'o','k':'o','l':'o','m':'o','n':'o','o':'n','p':'u','q':'u','r':'u','s':'u','t':'u','u':'t','v':'a','w':'a','x':'a','y':'a','z':'a'}\n return ''.join([d[i] for i in list(word)])", "a={'a':'z','b':'e','c':'e','d':'e','e':'d','f':'i','g':'i','h':'i','i':'h','j':'o','k':'o','j':'o','l':'o','m':'o','n':'o','o':'n','p':'u','q':'u','r':'u','s':'u','t':'u','u':'t','v':'a','w':'a','x':'a','y':'a','z':'a'}\ndef replace_letters(word):\n return ''.join([a[i] for i in word])", "def replace_letters(word):\n t = str.maketrans('abcdefghijklmnopqrstuvwxyz',\n 'zeeediiihooooonuuuuutaaaaa')\n return word.translate(t)", "def replace_letters(word):\n dictionary = {'a': 'z', 'b': 'e', 'c': 'e', 'd': 'e', 'e': 'd', 'f': 'i', 'g': 'i', 'h': 'i', 'i': 'h', 'j': 'o', 'k': 'o', 'l': 'o', 'm': 'o', 'n': 'o', 'o': 'n', 'p': 'u', 'q': 'u', 'r': 'u', 's': 'u', 't': 'u', 'u': 't', 'v': 'a', 'w': 'a', 'x': 'a', 'y': 'a', 'z': 'a'}\n return ''.join(letter.replace(letter, dictionary[letter]) for i, letter in enumerate(word))"]
{"fn_name": "replace_letters", "inputs": [["cat"], ["codewars"], ["abcdtuvwxyz"]], "outputs": [["ezu"], ["enedazuu"], ["zeeeutaaaaa"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,858
def replace_letters(word):
eb082a67f0a881b1ca468b3eb3896b49
UNKNOWN
Give the summation of all even numbers in a Fibonacci sequence up to, but not including, the maximum value. The Fibonacci sequence is a series of numbers where the next value is the addition of the previous two values. The series starts with 0 and 1: 0 1 1 2 3 5 8 13 21... For example: ```python eve_fib(0)==0 eve_fib(33)==10 eve_fib(25997544)==19544084 ```
["def even_fib(m):\n x,y = 0, 1\n counter = 0\n while y < m:\n if y % 2 == 0:\n counter += y\n x,y = y, x+ y\n return counter", "def even_fib(m):\n a, b, total = 1, 1, 0\n \n while a < m:\n if a % 2 == 0:\n total += a\n a, b = b, a + b\n \n return total", "def even_fib(m):\n \"\"\"Returns the sum of all even numbers in a Fibonacci sequence\n up to the maximum value m (non-inclusive of m).\"\"\"\n \n a, b, evens_sum = 0, 1, 0\n\n while (a + b) < m:\n if (a + b) % 2 == 0:\n evens_sum += (a + b)\n\n a, b = b, (a + b)\n\n return evens_sum", "def even_fib(m):\n a,b,c=0,1,0\n while b<m:\n if b%2==0: c+=b\n a,b=b,a+b\n return c", "from itertools import takewhile\n\n\ndef efib():\n a, b = 0, 1\n while True:\n if a % 2 == 0:\n yield a\n a, b = b, a + b\n\n\ndef even_fib(m):\n return sum(takewhile(lambda x: x < m, efib()))", "from bisect import bisect_left\n\ndef gen():\n x, y = 0, 1\n while True:\n yield y\n x, y = y, x+y\nfib, memo, res = gen(), [0], [0]\n\ndef even_fib(m):\n while m > memo[-1]:\n val = next(fib)\n if val % 2 == 0:\n memo.append(val)\n res.append(res[-1] + val)\n return m > 0 and res[bisect_left(memo, m)-1]", "def even_fib(m):\n result = [0,1]\n while result[-1] < m:\n result.append(sum(result[-2:]))\n return sum(num for num in result if num%2 == 0 and num < m)", "def even_fib(m):\n a, b = 0, 1\n sum = 0\n while a < m:\n if a % 2 == 0:\n sum += a\n a, b = b, a + b\n return sum", "def even_fib(m):\n s=0\n a,b=1,1\n while a<m:\n if a%2==0:\n s+=a\n a,b=b,a+b\n return s", "def even_fib(m):\n a, b = 0, 1\n summ = 0\n while b < m:\n if b % 2 == 0:\n summ += b\n a,b = b, a + b\n return summ\n"]
{"fn_name": "even_fib", "inputs": [[0], [10], [5], [100], [1000], [1000000], [100000000], [1000000000], [2147483647], [-1]], "outputs": [[0], [10], [2], [44], [798], [1089154], [82790070], [350704366], [1485607536], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,982
def even_fib(m):
04d217f7a64f7579e849d2d47a1f18f4
UNKNOWN
# Task Define crossover operation over two equal-length strings A and B as follows: the result of that operation is a string of the same length as the input strings result[i] is chosen at random between A[i] and B[i]. Given array of strings `arr` and a string result, find for how many pairs of strings from `arr` the result of the crossover operation over them may be equal to result. Note that (A, B) and (B, A) are the same pair. Also note that the pair cannot include the same element of the array twice (however, if there are two equal elements in the array, they can form a pair). # Example For `arr = ["abc", "aaa", "aba", "bab"]` and `result = "bbb"`, the output should be `2`. ``` "abc" and "bab" can crossover to "bbb" "aba" and "bab" can crossover to "bbb" ``` # Input/Output - `[input]` string array `arr` A non-empty array of equal-length strings. Constraints: `2 ≤ arr.length ≤ 10, 1 ≤ arr[i].length ≤ 10.` - `[input]` string `result` A string of the same length as each of the arr elements. Constraints: `result.length = arr[i].length.` - `[output]` an integer
["from itertools import combinations\ndef strings_crossover(arr, result):\n return sum(1 for s1,s2 in combinations(arr,2) if all(r in (x,y) for x,y,r in zip(s1,s2,result)))", "from collections import Counter\n\ndef strings_crossover(arr, result):\n lstBit = [ int(''.join(['01'[x==y] for x,y in zip(result, w)]), 2) for w in arr ]\n target = 2**len(result) - 1\n c = Counter(lstBit)\n \n v1 = sum( v*w for k,v in list(c.items()) for l,w in list(c.items()) if k|l == target and k!=target and l!=target) // 2\n v2 = 0 if target not in c else (sum(c.values())-c[target]) * c[target]\n v3 = 0 if c[target] < 2 else c[target] * (c[target]-1) // 2\n \n return v1+v2+v3\n", "from itertools import combinations as comb\nstrings_crossover=lambda li,r:sum(all(r[k] in [i[0][k],i[1][k]] for k in range(len(i[0]))) for i in comb(li,2))", "from itertools import combinations\n\ndef strings_crossover(arr, result):\n return sum(\n all(a==b or a==c for a,b,c in zip(result, *xs))\n for xs in combinations(arr, 2)\n )", "from itertools import combinations\n\ndef strings_crossover(arr, result):\n return sum(all(a in b for a, b in zip(result, l)) for l in (zip(*c) for c in combinations(arr, 2)))", "import itertools\ndef strings_crossover(arr, result):\n\n lista = list(itertools.combinations(arr, 2))\n crossovers = 0\n for element in lista:\n flag = True\n for i,e in enumerate(result):\n if element[0][i] != e and element[1][i] != e:\n flag = False\n if flag:\n crossovers += 1\n return crossovers\n", "from itertools import combinations\n\ndef strings_crossover(arr, result):\n return sum(all(x == z or y == z for x, y, z in zip(a, b, result)) for a, b in combinations(arr, 2))", "from itertools import combinations\ndef strings_crossover(arr, result):\n r=0\n for s1,s2 in combinations(arr,2):\n flag=True\n for i in range(len(result)):\n if s1[i]!=result[i] and s2[i]!=result[i]:\n flag=False\n break\n if flag:\n r+=1\n return r", "from itertools import combinations\n\ndef strings_crossover(arr, result):\n combs = [*combinations(arr, 2)]\n t = 0\n for k in range(len(combs)):\n x, y, z = set(enumerate(result)), set(enumerate(combs[k][0])), set(enumerate(combs[k][1]))\n t += not x - (y | z)\n return t", "from itertools import combinations\n\ndef strings_crossover(arr, result):\n return sum(1 for a,b in combinations(arr,2) if all(r in (x,y) for r,x,y in zip(result,a,b)))\n"]
{"fn_name": "strings_crossover", "inputs": [[["abc", "aaa", "aba", "bab"], "bbb"], [["aacccc", "bbcccc"], "abdddd"], [["a", "b", "c", "d", "e"], "c"], [["aa", "ab", "ba"], "bb"], [["a", "b", "c", "d", "e"], "f"], [["aaa", "aaa"], "aaa"]], "outputs": [[2], [0], [4], [1], [0], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,594
def strings_crossover(arr, result):
e036365bf7ba100a115cea34ca73dca5
UNKNOWN
An array is defined to be `inertial`if the following conditions hold: ``` a. it contains at least one odd value b. the maximum value in the array is even c. every odd value is greater than every even value that is not the maximum value. ``` eg:- ``` So [11, 4, 20, 9, 2, 8] is inertial because a. it contains at least one odd value [11,9] b. the maximum value in the array is 20 which is even c. the two odd values (11 and 9) are greater than all the even values that are not equal to 20 (the maximum), i.e., [4, 2, 8] ``` Write a function called `is_inertial` that accepts an integer array and returns `true` if the array is inertial; otherwise it returns `false`.
["def is_inertial(arr):\n mx = max(arr, default=1)\n miO = min((x for x in arr if x%2==1), default=float(\"-inf\"))\n miE2 = max((x for x in arr if x%2==0 and x!=mx), default=float(\"-inf\"))\n return mx%2 == 0 and miE2 < miO", "def is_inertial(lst):\n odds = [n for n in lst if n % 2 == 1]\n evens = sorted(n for n in lst if n % 2 == 0)[-2:]\n return (\n bool(odds)\n and max(lst) in evens\n and (not evens[:-1] or min(odds) > evens[-2])\n )", "def is_inertial(arr):\n even, odd = [], []\n for num in arr:\n if num % 2 == 0:\n even.append(num)\n else:\n odd.append(num)\n if len(odd) == 0 or max(even) != max(arr) or min(odd) < sorted(even)[-2]:\n return False\n else:\n return True", "def is_inertial(arr):\n \"\"\"Try to maximize performance by only looping once over array\"\"\"\n maxnr_odd = minnr_odd = maxnr_even = maxnr2nd_even = None\n\n for nr in arr:\n if nr % 2 == 0:\n if maxnr_even is None:\n maxnr_even = nr\n elif nr > maxnr_even:\n maxnr_even, maxnr2nd_even = nr, maxnr_even\n elif maxnr2nd_even is None or maxnr2nd_even < nr:\n maxnr2nd_even = nr\n else:\n if minnr_odd is None or minnr_odd > nr:\n minnr_odd = nr\n if maxnr_odd is None or maxnr_odd < nr:\n maxnr_odd = nr\n\n return (maxnr_even is not None and maxnr_odd is not None and minnr_odd is not None\n and maxnr_odd < maxnr_even and (maxnr2nd_even is None or minnr_odd > maxnr2nd_even))", "def is_inertial(array) :\n if not array :\n return False\n max_value = max(array)\n if max_value % 2 :\n return False\n try :\n return min(odd for odd in array if odd % 2) > max(even for even in array if even < max_value and even % 2 == 0)\n except ValueError :\n return False", "is_inertial=lambda a:a.sort()or(lambda e,o:e>[]<o and max(e[:-1]+[o[0]-1])<o[0]<=o[-1]<e[-1])(*[[n for n in a if n%2==m]for m in(0,1)])", "def is_inertial(a):\n try:\n return max(a) % 2 == 0 and min(e for e in a if e % 2) > max(e for e in a if e % 2 == 0 and e < max(a))\n except ValueError:\n return False", "def is_inertial(arr):\n try: return sorted([z for z in arr if z%2])[0] > sorted([x for x in arr if x%2==0])[:-1][-1] and max(arr)%2==0 and not not ([z for z in arr if z%2]) if arr else False\n except IndexError: return False \n", "def is_inertial(a):\n odd = {i for i in a if i%2}\n even = set(a) - odd\n if not even: return False\n q = sorted(even)[-2] if len(even)>1 else sorted(even)[0]\n return odd and max(even)>max(odd) and min(odd)>q", "def is_inertial(arr):\n if not arr or len(arr)<2: return False\n m1=max(arr)\n m2,m_odd=max(arr[1:],key=lambda x:(1-(x%2) and x!=m1,x)),min(arr,key=lambda x:(1-x%2,x))\n return bool(m_odd%2) and not bool(m1%2) and bool(m2%2 or m_odd>m2)"]
{"fn_name": "is_inertial", "inputs": [[[]], [[581, -384, 140, -287]], [[11, 4, 20, 9, 2, 8]]], "outputs": [[false], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,013
def is_inertial(arr):
5e83ab1b215abc7b745b3da6489e1f8a
UNKNOWN
## TL;DR Given a number of vertices `N` and a list of weighted directed edges in a directed acyclic graph (each edge is written as `[start, end, weight]` where `from < to`), compute the weight of the shortest path from vertex `0` to vertex `N - 1`. If there is no such path, return `-1`. ## Background A weighted DAG is a directed acyclic graph where each edge has a weight associated with it: 1 5 3 1 5 A B C D In this example, the shortest path from A to D is given by A -> B -> D, which has a total weight of 4. Finding shortest distances in DAGs is made easier by the fact that the nodes can be _linearized:_ they can be given an order `A1, A2, ..., An` such that edges only point forward (that is, there are no edges from `Aj` to `Ai` when `j > i`). In the example above, the two possible linear orderings are `A, B, C, D` and `A, C, B, D.` 1 1 5 5 3 A B C D ## Your Task Given a number `N` (indicating a graph with vertices `0, 1, ..., N-1`) and a list of weighted edges `[start, end, weight]` for a DAG, where `start < end` for each edge, find the weight (a.k.a. length) of the shortest path from node `0` to node `N-1`. For example, if the input is ``` N = 4 edgeList = [ [0, 1, 1], [0, 2, 5], [0, 3, 5], [1, 3, 3], [2, 3, 1] ] ``` then we have the graph depicted above (with `0 = A`, `1 = B`, etc.) and the answer is `4`. If there is no path from node `0` to node `N-1`, return `-1`. ## Notes and Warnings **Precondition:** `N` will always be greater than 1, and edge weights will always be positive integers. There may be multiple edges going between two nodes. **Warning:** You will probably need to use a dynamic programming solution if you want your solution to run fast enough not to time out--that's the whole point of this kata! However, a well-written general shortest-path algorithm such as Dijkstra's Algorithm may also be fast enough to past the soak tests. (The reason is that the dividing line between linear and linearithmic time is hard to define and depends on a variety of external factors, so the kata's tests err on the safe side.)
["import heapq\nfrom collections import defaultdict\n\ndef shortest(N, edge):\n ver, inf = defaultdict(list), 10**10\n for e in edge: ver[e[0]].append(e[1:])\n\n dist = {i:inf for i in range(N)}\n dist[0], pq = 0, []\n heapq.heappush(pq, [dist[0], 0])\n while pq: \n u_dis, u_node = heapq.heappop(pq)\n if u_dis == dist[u_node]:\n for v in ver[u_node]:\n v_node = v[0]\n v_wei = v[1]\n if dist[u_node] + v_wei < dist[v_node]:\n dist[v_node] = dist[u_node] + v_wei\n heapq.heappush(pq, [dist[v_node], v_node])\n return -1 if dist[N-1] == inf else dist[N-1]", "def shortest(n, edges):\n m = [0] + [float('inf')] * (n-1)\n for start, end, weight in sorted(edges):\n if m[start] == float('inf'): continue\n m[end] = min(m[start] + weight, m[end])\n return -1 if m[-1] == float('inf') else m[-1]", "def shortest(N, edgeList):\n \n edgeList.sort(key= lambda x: x[0])\n path_values = [None for _ in range(N)]\n path_values[0] = 0\n \n for edge in edgeList:\n\n if path_values[edge[0]] != None: # If the node value is 0, then we can not use it as a base to go further.\n new_val = edge[2] + path_values[edge[0]]\n \n if path_values[edge[1]] == None:\n path_values[edge[1]] = new_val\n else:\n path_values[edge[1]] = min(path_values[edge[1]], new_val)\n \n if path_values[-1] == None: # no path goes to the end\n return -1\n else:\n return path_values[-1]", "def shortest(N, edges):\n \n path = [0]+[float('inf')]*(N-1)\n for start,end,weight in sorted(edges):\n if path[start]==-1: continue\n path[end] = min(path[start]+weight, path[end] )\n \n \n \n return -1 if path[-1]==float('inf') else path[-1]", "from collections import defaultdict\n\n\nINFINITY = 2 ** 80\n\n\ndef shortest(N, edgeList):\n edges = defaultdict(list)\n for (fro, to, weight) in edgeList:\n edges[fro].append((to, weight))\n \n dist_dp = [INFINITY] * N\n dist_dp[0] = 0\n \n for i in range(N):\n for (to, w) in edges[i]:\n dist_dp[to] = min(dist_dp[to], dist_dp[i] + w)\n \n return -1 if dist_dp[N - 1] >= INFINITY else dist_dp[N - 1]", "from collections import defaultdict\nfrom heapq import heappop, heappush\nfrom typing import List, Tuple\n\n\ndef shortest(N: int, edgeList: List[Tuple[int, int, int]]) -> int:\n graph = defaultdict(list)\n for v, u, e in edgeList:\n graph[v].append((u, e))\n\n pathes = defaultdict(lambda: float('inf'), {0: 0})\n\n queue = [(0, 0)]\n while queue:\n cost, v = heappop(queue)\n\n if v == N - 1:\n return cost\n\n for u, e in graph[v]:\n new_cost = cost + e\n if new_cost < pathes[u]:\n pathes[u] = new_cost\n heappush(queue, (new_cost, u))\n\n return -1", "def shortest(n, edges):\n m = [0] + [-1] * (n-1)\n for start, end, weight in sorted(edges):\n if m[start] == -1: continue\n m[end] = min(m[start] + weight,\n m[end] == -1 and float('inf') or m[end])\n return m[-1]", "def shortest(N, es):\n ee = [[] for _ in range(N)]\n for f, t, w in es:\n ee[f].append((t, w))\n dd = [0x7f7f7f7f for _ in range(N)]\n f = [False for _ in range(N)]\n dd[0] = 0\n q = [0]\n f[0] = True\n while len(q) > 0:\n k = q.pop()\n f[k] = False\n for t, w in ee[k]:\n if dd[t] > dd[k] + w:\n dd[t] = dd[k] + w\n if not f[t]:\n q.append(t)\n f[t] = True\n return -1 if dd[N - 1] == 0x7f7f7f7f else dd[N - 1]", "def shortest(N, edgeList):\n import math\n edgeList.sort(key=lambda x: x[0])\n path_length = [math.inf for _ in range(N)]\n path_length[0] = 0\n \n for start, end, weight in edgeList:\n# each edge is written as [start, end, weight] where from < to wi\u0119c to dzia\u0142a, \n# ale gdyby taki warunek nie by\u0142 prawdziwy to np.\n# shortest(5, [(0,2,0), (0,3,1), (2,1,0), (3,4,1), (1,4,0)]) zwraca\u0142oby 2, zamiast 0\n if path_length[start] == math.inf:\n continue\n path_length[end] = min(path_length[start] + weight, path_length[end])\n \n result = path_length[N-1]\n return result if result is not math.inf else -1\n\n\n\n\n\n# def shortest(N, edgeList):\n# import math, heapq, collections\n# edges = collections.defaultdict(lambda:collections.defaultdict(lambda:math.inf))\n# path_length = [math.inf for _ in range(N)]\n# path_length[0] = 0\n# for start, end, weight in edgeList:\n# edges[start][end] = min(weight, edges[start][end])\n# h = [(0,0)]\n# visited = set()\n# heapq.heapify(h)\n# while h:\n# sum, start = heapq.heappop(h)\n# if start == N-1: return sum\n# if start in visited: continue\n# for end, weight in edges[start].items():\n# if end in visited: continue\n# if sum + weight < path_length[end]:\n# path_length[end] = sum + weight\n# heapq.heappush(h, (sum+weight, end))\n# visited.add(start)\n# return -1\n", "from collections import defaultdict\nfrom heapq import *\n\ndef shortest(N, edges):\n '''Same as def dijkstra(edges, f, t)'''\n f=0;t=N-1\n g = defaultdict(list)\n for l,r,c in edges:\n g[l].append((c,r))\n\n q, seen, mins = [(0,f,())], set(), {f: 0}\n while q:\n (cost,v1,path) = heappop(q)\n if v1 not in seen:\n seen.add(v1)\n path = (v1, path)\n if v1 == t: return cost#,path\n\n for c, v2 in g.get(v1, ()):\n if v2 in seen: continue\n prev = mins.get(v2, None)\n next = cost + c\n if prev is None or next < prev:\n mins[v2] = next\n heappush(q, (next, v2, path))\n\n return -1 #float(\"inf\")"]
{"fn_name": "shortest", "inputs": [[4, [[0, 1, 1], [0, 2, 5], [0, 3, 5], [1, 3, 3], [2, 3, 1]]], [3, [[0, 1, 7], [1, 2, 5], [0, 2, 12]]], [5, [[0, 2, 1], [1, 2, 1], [0, 3, 1], [1, 4, 1]]]], "outputs": [[4], [12], [-1]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,193
def shortest(N, edgeList):
e184aac12ff45976325fde5bff16c37e
UNKNOWN
You will be given two strings `a` and `b` consisting of lower case letters, but `a` will have at most one asterix character. The asterix (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase letters. No other character of string `a` can be replaced. If it is possible to replace the asterix in `a` to obtain string `b`, then string `b` matches the pattern. If the string matches, return `true` else `false`. ``` For example: solve("code*s","codewars") = true, because we can replace the asterix(*) with "war" to match the second string. solve("codewar*s","codewars") = true, because we can replace the asterix(*) with "" to match the second string. solve("codewars","codewars") = true, because the strings already match. solve("a","b") = false ``` More examples in test cases. Good luck!
["from fnmatch import fnmatch\n\ndef solve(a, b):\n return fnmatch(b, a)", "import re\ndef solve(a,b):\n return bool(re.fullmatch(a.replace('*', '.*'), b))", "def solve(a,b):\n if a == b: return True\n if \"*\" not in a: return False\n \n sides = a.split(\"*\")\n missing = b[len(sides[0]):len(b)-len(sides[1])]\n c = a.replace(\"*\", missing)\n return c == b\n", "solve=lambda Q,S:not __import__('re').sub(Q.replace('*','.*'),'',S)", "def solve(a,b):\n s = a.find(\"*\")\n if s == -1:\n return a == b\n else:\n a = list(a)\n b = list(b)\n del b[s:s+1+len(b)-len(a)]\n a.remove(\"*\")\n return a == b", "import re\n\ndef solve(a, b):\n return bool(re.match(f\"^{a.replace('*', '.*')}$\", b))\n\n\n# without re\n#\n#def solve(a, b):\n# if \"*\" in a:\n# s, e = a.split(\"*\")\n# return b.startswith(s) and b.replace(s, \"\").endswith(e)\n# else:\n# return a == b\n", "import re\n\ndef solve(a,b):\n pattern = a.replace(\"*\", \".*\")\n return bool(re.fullmatch(pattern, b))", "import re\n\ndef solve(a,b):\n pattern = f'^{a.replace(\"*\", \".*\")}$'\n return bool(re.match(pattern, b))\n", "import re\ndef solve(a,b):\n rx = '^' + '.*'.join(a.split('*')) + '$'\n return bool(re.search(rx,b))", "solve=lambda a,b:a==b or('*'in a and(lambda l:not(l[0]==l[1]==b)and b.startswith(l[0])and b.endswith(l[1]))(a.split('*')))"]
{"fn_name": "solve", "inputs": [["code*s", "codewars"], ["codewar*s", "codewars"], ["code*warrior", "codewars"], ["c", "c"], ["*s", "codewars"], ["*s", "s"], ["s*", "s"], ["aa", "aaa"], ["aa*", "aaa"], ["aaa", "aa"], ["aaa*", "aa"], ["*", "codewars"], ["aaa*aaa", "aaa"]], "outputs": [[true], [true], [false], [true], [true], [true], [true], [false], [true], [false], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,430
def solve(a,b):
89caf16541b5e8e09e746961cf737c9a
UNKNOWN
Freddy has a really fat left pinky finger, and every time Freddy tries to type an ```A```, he accidentally hits the CapsLock key! Given a string that Freddy wants to type, emulate the keyboard misses where each ```A``` supposedly pressed is replaced with CapsLock, and return the string that Freddy actually types. It doesn't matter if the ```A``` in the string is capitalized or not. When CapsLock is enabled, capitalization is reversed, but punctuation is not affected. Examples: ``` "The quick brown fox jumps over the lazy dog." -> "The quick brown fox jumps over the lZY DOG." "The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness." -> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS." "aAaaaaAaaaAAaAa" -> "" ``` **Note!** If (Caps Lock is Enabled) and then you (HOLD Shift + alpha character) it will always be the reverse Examples: ``` (Caps Lock Enabled) + (HOLD Shift + Press 'b') = b (Caps Lock Disabled) + (HOLD Shift + Press 'b') = B ``` If the given string is `""`, the answer should be evident. Happy coding! ~~~if:fortran *NOTE: In Fortran, your returned string is* **not** *permitted to contain any unnecessary leading/trailing whitespace.* ~~~ (Adapted from https://codegolf.stackexchange.com/questions/158132/no-a-just-caps-lock)
["def fat_fingers(s):\n if not s: return s\n swap = [False]\n return ''.join( c.swapcase() if swap[0] else c for c in s \n if c not in \"aA\" or swap.__setitem__(0, not swap[0]) )", "import re\n\ndef fat_fingers(string):\n return ''.join(w.swapcase() if i%2 else w for i, w in enumerate(re.split('a|A', string)))", "import re;fat_fingers=lambda s:s and re.sub('[aA](.*?)(a|A|$)',lambda m:m[1].swapcase(),s)", "from itertools import cycle\n\ndef fat_fingers(s):\n def characters(s):\n it = cycle([str, str.swapcase])\n f = next(it)\n for c in s:\n if c in 'aA':\n f = next(it)\n else:\n yield f(c)\n return ''.join(characters(s))", "def fat_fingers(string):\n if type(string) != str: return string\n aCnt, chars = 0, []\n for c in string:\n if c in 'aA': aCnt += 1\n else: chars.append(c.swapcase()) if aCnt&1 else chars.append(c) \n return ''.join(chars)\n", "def fat_fingers(string):\n if string is None:\n return None\n tokens = string.replace('a', 'A').split(sep='A')\n for i,token in enumerate(tokens):\n if i % 2 == 0:\n continue # CapsLock presses cancel each other out\n tokens[i] = token.swapcase()\n return ''.join(tokens)", "def fat_fingers(string):\n if string is None:\n return None\n ret = []\n capslock = False\n for c in string:\n if c in 'aA':\n capslock = not capslock\n else:\n ret.append(c.swapcase() if capslock else c)\n return ''.join(ret)", "def fat_fingers(string):\n\n fat_string = \"\"\n count = 0\n \n for i in string:\n \n if (i == \"a\") or (i == \"A\"):\n fat_string += \"\"\n count += 1\n else: \n if count % 2 == 1 and i.upper() == i:\n fat_string += i.lower()\n elif count % 2 ==1 and i.lower() == i:\n fat_string += i.upper()\n else:\n fat_string += i\n \n \n \n return fat_string", "import re;fat_fingers=lambda s:re.sub('[aA](.*?)(a|A|$)',lambda m:m[1].swapcase(),s)", "def fat_fingers(string):\n if string == \"\":\n return string\n \n if string is None:\n return None\n \n new_string = \"\"\n caps_lock = False\n \n for l in string:\n if l.isalpha():\n if l.lower() == 'a':\n caps_lock = not caps_lock\n \n elif caps_lock and l.lower() == l:\n new_string += l.upper()\n \n elif caps_lock and l.upper() == l:\n new_string += l.lower()\n \n else:\n new_string += l\n else:\n new_string += l\n \n \n return new_string"]
{"fn_name": "fat_fingers", "inputs": [["aAaaaaAaaaAAaAa"], ["The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness."], ["a99&a6/<a}"]], "outputs": [[""], ["The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS."], ["99&6/<}"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,891
def fat_fingers(string):
381f33a2d533d745558ffb3867239310
UNKNOWN
In telecomunications we use information coding to detect and prevent errors while sending data. A parity bit is a bit added to a string of binary code that indicates whether the number of 1-bits in the string is even or odd. Parity bits are used as the simplest form of error detecting code, and can detect a 1 bit error. In this case we are using even parity: the parity bit is set to `0` if the number of `1`-bits is even, and is set to `1` if odd. We are using them for the transfer of ASCII characters in binary (7-bit strings): the parity is added to the end of the 7-bit string, forming the 8th bit. In this Kata you are to test for 1-bit errors and return a new string consisting of all of the correct ASCII caracters **in 7 bit format** (removing the parity bit), or `"error"` in place of ASCII characters in which errors were detected. For more information on parity bits: https://en.wikipedia.org/wiki/Parity_bit ## Examples Correct 7 bit string with an even parity bit as the 8th bit: ``` "01011001" <-- The "1" on the right is the parity bit. ``` In this example, there are three 1-bits. Three is an odd number, and the parity bit is set to `1`. No errors are detected, so return `"0101100"` (7 bits). Example of a string of ASCII characters: ``` "01011001 01101110 01100000 01010110 10001111 01100011" ``` This should return: ``` "0101100 error 0110000 0101011 error 0110001" ```
["def parity_bit(binary):\n return ' '.join(byte[:-1] if byte.count('1') % 2 == 0 else 'error' for byte in binary.split())", "def parity_bit(binary):\n return \" \".join(\"error\" if byte.count(\"1\") & 1 else byte[:-1] for byte in binary.split())", "def decode(binary):\n *b, p = binary\n if '01'[b.count('1') % 2] != p:\n return 'error'\n return binary[:-1]\n\ndef parity_bit(binaries):\n return ' '.join(decode(binary) for binary in binaries.split())", "def parity_bit(binary):\n res = ''\n for b in binary.split(' '):\n if b[:-1].count('1') % 2 == int(b[-1]):\n res += b[:-1] + ' '\n else:\n res += 'error '\n return res[:-1]", "def parity_bit(binary):\n \n \n return ' '.join(map(lambda bits : 'error' if bits.count('1')%2 !=0 else bits[:-1] ,binary.split()))", "def parity_bit(binary):\n return \" \".join([\"error\" if signal.count(\"1\")&1 else signal[:-1] for signal in binary.split(\" \")])\n", "def parity_bit(binary):\n return ' '.join('error' if a.count('1') % 2 else a[:-1] for a in binary.split())", "def parity_bit(s):\n return ' '.join('error' if x.count('1') % 2 else x[:-1] for x in s.split())", "def parity_bit(b):\n return \" \".join(s[:-1] if int(s[-1:]) == s[:-1].count('1')%2 else \"error\" for s in b.split())\n", "def parity_bit(binary):\n lst_bin = binary.split()\n final = []\n for i in range(len(lst_bin)):\n n = lst_bin[i][:-1].count(\"1\")\n if lst_bin[i][-1:] == \"0\":\n if n % 2 != 0:\n final.append(\"error\")\n else:\n final.append(lst_bin[i][:-1])\n if lst_bin[i][-1:] == \"1\":\n if n % 2 != 0:\n final.append(lst_bin[i][:-1])\n else:\n final.append(\"error\")\n return \" \".join(final)"]
{"fn_name": "parity_bit", "inputs": [["01011001"], ["00110001"], ["11111111"], ["00000000"], ["11100111"], ["00111100 00111101"], ["00001111 11100001"], ["01011110 00011000"], ["11111111 11011100 11100011"], ["00111110 00110100 00111011"], ["01101110 01100000 01010110 10001111 01100011"], ["10100011 00111001 11001100 01010100 10110110 00111111"]], "outputs": [["0101100"], ["error"], ["1111111"], ["0000000"], ["1110011"], ["0011110 error"], ["0000111 1110000"], ["error 0001100"], ["1111111 error error"], ["error error error"], ["error 0110000 0101011 error 0110001"], ["1010001 0011100 1100110 error error 0011111"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,860
def parity_bit(binary):
0d0d6b4b1c09c28b7393acad6bcc06be
UNKNOWN
## Overview Resistors are electrical components marked with colorful stripes/bands to indicate both their resistance value in ohms and how tight a tolerance that value has. If you did my Resistor Color Codes kata, you wrote a function which took a string containing a resistor's band colors, and returned a string identifying the resistor's ohms and tolerance values. Well, now you need that in reverse: The previous owner of your "Beyond-Ultimate Raspberry Pi Starter Kit" (as featured in my Fizz Buzz Cuckoo Clock kata) had emptied all the tiny labeled zip-lock bags of components into the box, so that for each resistor you need for a project, instead of looking for text on a label, you need to find one with the sequence of band colors that matches the ohms value you need. ## The resistor color codes You can see this Wikipedia page for a colorful chart, but the basic resistor color codes are: 0: black, 1: brown, 2: red, 3: orange, 4: yellow, 5: green, 6: blue, 7: violet, 8: gray, 9: white All resistors have at least three bands, with the first and second bands indicating the first two digits of the ohms value, and the third indicating the power of ten to multiply them by, for example a resistor with a value of 47 ohms, which equals 47 * 10^0 ohms, would have the three bands "yellow violet black". Most resistors also have a fourth band indicating tolerance -- in an electronics kit like yours, the tolerance will always be 5%, which is indicated by a gold band. So in your kit, the 47-ohm resistor in the above paragraph would have the four bands "yellow violet black gold". ## Your mission Your function will receive a string containing the ohms value you need, followed by a space and the word "ohms" (to avoid Codewars unicode headaches I'm just using the word instead of the ohms unicode symbol). The way an ohms value is formatted depends on the magnitude of the value: * For resistors less than 1000 ohms, the ohms value is just formatted as the plain number. For example, with the 47-ohm resistor above, your function would receive the string `"47 ohms"`, and return the string `"yellow violet black gold". * For resistors greater than or equal to 1000 ohms, but less than 1000000 ohms, the ohms value is divided by 1000, and has a lower-case "k" after it. For example, if your function received the string `"4.7k ohms"`, it would need to return the string `"yellow violet red gold"`. * For resistors of 1000000 ohms or greater, the ohms value is divided by 1000000, and has an upper-case "M" after it. For example, if your function received the string `"1M ohms"`, it would need to return the string `"brown black green gold"`. Test case resistor values will all be between 10 ohms and 990M ohms. ## More examples, featuring some common resistor values from your kit ``` "10 ohms" "brown black black gold" "100 ohms" "brown black brown gold" "220 ohms" "red red brown gold" "330 ohms" "orange orange brown gold" "470 ohms" "yellow violet brown gold" "680 ohms" "blue gray brown gold" "1k ohms" "brown black red gold" "10k ohms" "brown black orange gold" "22k ohms" "red red orange gold" "47k ohms" "yellow violet orange gold" "100k ohms" "brown black yellow gold" "330k ohms" "orange orange yellow gold" "2M ohms" "red black green gold" ``` Have fun!
["c='black brown red orange yellow green blue violet gray white'.split()\ndef encode_resistor_colors(ohms_string):\n ohms = str(int(eval(ohms_string.replace('k', '*1000').replace('M', '*1000000').split()[0])))\n return '%s %s %s gold' % (c[int(ohms[0])], c[int(ohms[1])], c[len(ohms[2:])])", "COLORS = {'0': 'black', '1': 'brown', '2': 'red', '3': 'orange', '4': 'yellow', '5': 'green', '6': 'blue', '7': 'violet', '8': 'gray', '9': 'white'}\n\ndef encode_resistor_colors(ohmS):\n ohmS = str(int(eval(ohmS.replace(' ohms','').replace('k','*1000').replace('M','*1000000'))))\n return \"{} {} {} gold\".format(COLORS[ohmS[0]], COLORS[ohmS[1]], COLORS[ str(len(ohmS[2:])) ] )", "def encode_resistor_colors(ohms_string):\n s = str(get_num_ohms(ohms_string))\n ohms = s[:2]\n tolerance = str(len(s[2:]))\n color_bands = [ get_color(ohms[0]), get_color(ohms[1]), get_color(tolerance), 'gold' ]\n return ' '.join(color_bands)\n\n\ndef get_num_ohms(s):\n n = s.split(' ')[0]\n multiplier = 1000 if n[-1] == 'k' else 1000000 if n[-1] == 'M' else 1\n f = float(n[:-1]) * multiplier if multiplier > 1 else float(n)\n return int(f)\n\ndef get_color(n):\n color_map = {\n '0': 'black',\n '1': 'brown',\n '2': 'red',\n '3': 'orange',\n '4': 'yellow',\n '5': 'green',\n '6': 'blue',\n '7': 'violet',\n '8': 'gray',\n '9': 'white'\n }\n return color_map[n]\n", "c='black brown red orange yellow green blue violet gray white'.split()\ndef encode_resistor_colors(ohms_string):\n t, u, *p = str(int(eval(ohms_string.replace('M','*1000k').replace('k','*1000').split()[0])))\n return '%s %s %s gold' % (c[int(t)], c[int(u)], c[len(p)])", "import math\nimport re\n\nCOLORS = {'0': 'black', '1': 'brown', '2': 'red', '3': 'orange', '4': 'yellow',\n '5': 'green', '6': 'blue', '7': 'violet', '8': 'gray', '9': 'white'}\n\ndef encode_resistor_colors(ohms_string):\n ohms = re.sub(r'([0-9\\.]+)([kM])?(.*)', \n lambda x: str(float(x[1]) * (int(x[2].translate(str.maketrans(\n {'k': '1000', 'M': '1000000'}))) if x[2] else 1)), ohms_string) \n return f\"{' '.join(COLORS.get(x) for x in ohms[:2])} {COLORS.get(str(len(ohms[2:]) - 2))} gold\"", "def encode_resistor_colors(ohms_string):\n color_digit = {'0': 'black',\n '1': 'brown',\n '2': 'red',\n '3': 'orange',\n '4': 'yellow',\n '5': 'green',\n '6': 'blue',\n '7': 'violet',\n '8': 'gray',\n '9': 'white'}\n multiplier = {'1': 'black',\n '2': 'black',\n '3': 'brown',\n '4': 'red',\n '5': 'orange',\n '6': 'yellow',\n '7': 'green',\n '8': 'blue',\n '9': 'violet',\n '10': 'grey',\n '11': 'white'}\n\n number = ohms_string.rstrip('ohms')\n snumber = ''\n mult = ''\n answer = ''\n fnum = ''\n check = []\n a, b, c = '', '', ''\n \n #First and Second colors:\n \n for i in number:\n if i.isdigit() == True:\n snumber += i\n if len(snumber) > 1:\n a = snumber[0]\n b = snumber[1]\n answer = str(color_digit.get(a)) + ' ' + str(color_digit.get(b))\n elif len(snumber) == 1:\n a = snumber[0]\n answer = str(color_digit.get(a)) + ' ' + 'black'\n \n # Multiplier color:\n \n for s in number:\n if s.isdigit() == True or s == '.':\n fnum += s\n\n for j in number:\n check.append(j)\n if 'M' in check:\n mult = 1000000\n elif 'k' in check:\n mult = 1000\n else:\n mult = 1\n\n c = str(int(eval(str(fnum) + '*' + str(mult))))\n\n return answer + ' ' + (multiplier.get(str(len(c)))) + ' gold'", "import re\ncolors=['black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'gray', 'white']\ndef encode_resistor_colors(ohms_string):\n split_string=ohms_string.split()\n number=split_string[0]\n if number[-1]=='k':\n number=str(int(float(number[0:-1])*1000))\n elif number[-1]=='M':\n number=str(int(float(number[0:-1])*1000000))\n color1=colors[int(number[0])]\n color2=colors[int(number[1])]\n color3=colors[len(number)-2]\n return color1 + ' ' + color2 + ' ' + color3 + ' gold'\n\n\n \n", "import re\nimport math\n\nREGEX_NUMBERS = r\"\\d+\\.?\\d*\"\nRESISTOR_COLORS = {0: 'black', 1: 'brown', 2: 'red', 3: 'orange', 4: 'yellow', 5: 'green', 6: 'blue', 7: 'violet', 8: 'gray', 9: 'white'}\nMULTIPLIER = {'k': 1000, 'M': 1000000}\n\ndef encode_resistor_colors(ohms_string):\n retrieved_val = re.findall(REGEX_NUMBERS, ohms_string.replace('ohms', ''))[0]\n needs_trailing_zero = len(retrieved_val) == 1\n retrieved_val = retrieved_val + '0' if needs_trailing_zero else retrieved_val\n translation = ' '.join([RESISTOR_COLORS[int(digit)] for digit in retrieved_val if digit.isnumeric()][:2])\n for key in MULTIPLIER:\n retrieved_val = float(retrieved_val) * MULTIPLIER.get(key) if key in ohms_string else float(retrieved_val)\n subtract = 2 if needs_trailing_zero else 1\n return translation + ' '+(RESISTOR_COLORS[math.floor(math.log10(retrieved_val)) - subtract]) + ' gold'", "import re\nfrom math import log10\ndef encode_resistor_colors(ohms_string):\n codes = {'0': 'black', '1': 'brown', '2': 'red', '3': 'orange', '4': 'yellow',\n '5': 'green', '6': 'blue', '7': 'violet','8': 'gray','9': 'white'}\n\n initial_number, group = re.findall(r'([0-9.]+)([k,M])?', ohms_string).pop()\n num = float(initial_number) * int(group=='k' and 1000 or group=='M' and 1000000 or 1)\n processed_number = str(float(initial_number)*10)[:2]\n final = [codes[x] for x in processed_number] + [codes[str(int(log10(num / float(processed_number))))], 'gold']\n return ' '.join(final)", "colors = ['black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'gray', 'white', 'gold']\n\ndef encode_resistor_colors(ohms_string):\n ohms = int(eval(ohms_string.split()[0].replace('k', '*1E3').replace('M', '*1E6')))\n return ' '.join(colors[i] for i in [int(str(ohms)[0]), int(str(ohms)[1]), len(str(ohms)) - 2, 10])"]
{"fn_name": "encode_resistor_colors", "inputs": [["10 ohms"], ["47 ohms"], ["100 ohms"], ["220 ohms"], ["330 ohms"], ["470 ohms"], ["680 ohms"], ["1k ohms"], ["4.7k ohms"], ["10k ohms"], ["22k ohms"], ["47k ohms"], ["100k ohms"], ["330k ohms"], ["1M ohms"], ["2M ohms"]], "outputs": [["brown black black gold"], ["yellow violet black gold"], ["brown black brown gold"], ["red red brown gold"], ["orange orange brown gold"], ["yellow violet brown gold"], ["blue gray brown gold"], ["brown black red gold"], ["yellow violet red gold"], ["brown black orange gold"], ["red red orange gold"], ["yellow violet orange gold"], ["brown black yellow gold"], ["orange orange yellow gold"], ["brown black green gold"], ["red black green gold"]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,457
def encode_resistor_colors(ohms_string):
f1d93d57e6bd92693c685ebfbe2b4efb
UNKNOWN
Your task is to determine the top 3 place finishes in a pole vault competition involving several different competitors. This is isn't always so simple, and it is often a source of confusion for people who don't know the actual rules. Here's what you need to know: As input, you will receive an array of objects. Each object contains the respective competitor's name (as a string) and his/her results at the various bar heights (as an array of strings): [{name: "Sergey", results: ["", "O", "XO", "O", "XXO", "XXX", "", ""]}{name: "Jan", results: ["", "", "", "O", "O", "XO", "XXO", "XXX"]}{name: "Bruce", results: ["", "XO", "XXO", "XXX", "", "", "", ""]}{name: "HerrWert", results: ["XXX", "", "", "", "", "", "", ""]}] In the array of strings described above, each string represents the vaulter's performance at a given height. The possible values are based on commonly used written notations on a pole vault scoresheet: An empty string indicates that the vaulter did not jump at this height for a variety of possible reasons ("passed" at this height, was temporarily called away to a different track and field event, was already eliminated from competition, or withdrew due to injury, for example).An upper-case X in the string represents an unsuccessful attempt at the height. (As you may know, the vaulter is eliminated from the competition after three consecutive failed attempts.)An upper-case O represents a successful attempt. If present at all, this will be the final character in the string, because it indicates that the vaulter has now successfully completed this height and is ready to move on. All vaulters will have a result string (though possibly empty) for every height involved in the competition, making it possible to match up the results of different vaulters with less confusion. Obviously, your first task is to determine who cleared the greatest height successfully. In other words, who has a "O" mark at a higher array element than any other competitor? You might want to work through the arrays from right to left to determine this. In the most straightforward case, you would first determine the winner, then second place, and finally third place by this simple logic. But what if there's a tie for one of these finishing places? Proceed as follows (according to American high school rules, at least): First trace backwards to find the greatest height that both vaulters cleared successfully. Then determine who had the fewest unsuccessful attempts at this height (i.e., the fewest X's in the string for this height). This person wins the tie-break.But what if they're still tied with one another? Do NOT continue to trace backwards through the heights! Instead, compare their total numbers of unsuccessful attempts at all heights in the competition. The vaulter with the fewest total misses wins the tie-break.But what if they're still tied? It depends on the finishing place:If it's for second or third place, the tie stands (i.e., is not broken).But if it's for first place, there must be a jump-off (like overtime or penalty kicks in other sports) to break the tie and determine the winner. (This jump-off occurs - hypothetically - after your code runs and is thus not a part of this kata.) Return a single object as your result. Each place-finish that is included in the results (including at least first place as property "1st" and possibly second and third places as properties "2nd" and "3rd") should have as its value the respective vaulter's name. In the event of a tie, the value of the property is the names of all tied vaulters, in alphabetical order, separated by commas, and followed by the notation "(jump-off)" if the tie is for first place or "(tie)" if it's for second or third place. Here are some possible outcomes to show you what I mean: {1st: "Jan", 2nd: "Sergey"; 3rd: "Bruce"} (These results correspond to the sample input data given above.){1st: "Julia", 2nd: "Madi, Emily (tie)}"{1st: "Caleb, Dustin (jump-off)", 3rd: "Sam"}{1st: "Meredith", 2nd: "Maddy", 3rd: "Cierra, Sara (tie)"}{1st: "Alex, Basti, Max (jump-off)"} If you are familiar with the awarding of place finishes in sporting events or team standings in a league, then you know that there won't necessarily be a 2nd or 3rd place, because ties in higher places "bump" all lower places downward accordingly. One more thing: You really shouldn't change the array of objects that you receive as input. This represents the physical scoresheet. We need this "original document" to be intact, so that we can refer back to it to resolve a disputed result! Have fun with this! - - - - - Notes for the Python version: The rules for the Python version are the same as the original JavaScript version. The input and output will look the same as the JavaScript version. But, the JavaScript objects will be replaced by Python dictionaries. The JavaScript arrays will be replaced by Python lists. The Python function name was changed to include underscores as is customary with Python names. The example below should help clarify all of this. The input for the Python version will be a list containing dictionaries with the competitors' names and results. The names in the dictionaries are strings. The results are lists with a list of strings. And example follows. score_pole_vault([ {"name": "Linda", "results": ["XXO", "O","XXO", "O"]}, {"name": "Vickie", "results": ["O","X", "", ""]}, {"name": "Debbie", "results": ["XXO", "O","XO", "XXX"]}, {"name": "Michelle", "results": ["XO","XO","XXX",""]}, {"name": "Carol", "results": ["XXX", "","",""]} ]) The returned results should be in a dictionary with one to three elements. Examples of possible returned results: {'1st': 'Linda', '2nd': 'Debbie', '3rd': 'Michelle'} {'1st': 'Green, Hayes (jump-off)', '3rd': 'Garcia'} Note: Since first place was tied in this case, there is no 2nd place awarded. {'1st': 'Wilson', '2nd': 'Laurie', '3rd': 'Joyce, Moore (tie)'} I have tried to create test cases that have every concievable tie situation. Have fun with this version, as well!
["def score_pole_vault(vaulter_list):\n popytki = len(vaulter_list[0][\"results\"])\n temp = {}\n res = {}\n for mas in vaulter_list:\n i = popytki - 1\n while i >= 0 and mas[\"results\"][i].find('O') == -1:\n i -= 1\n if i < 0:\n n = 0\n m = ''.join(mas[\"results\"]).count('X')\n else:\n n = mas[\"results\"][i].count('X')\n m = ''.join(mas[\"results\"][:i]).count('X')\n new_key = (popytki - i, n, m)\n temp[new_key] = temp.get(new_key, []) + [mas[\"name\"]]\n k = iter(sorted(temp))\n i = 0\n while i < 3:\n key = next(k)\n if i == 0 and len(temp[key]) == 1:\n res['1st'] = temp[key][0]\n i += 1\n elif i == 0 and len(temp[key]) > 1:\n res['1st'] = ', '.join(sorted(temp[key])) + ' (jump-off)'\n i += len(temp[key])\n elif i == 1 and len(temp[key]) == 1:\n res['2nd'] = temp[key][0]\n i += 1\n elif i == 1 and len(temp[key]) > 1:\n res['2nd'] = ', '.join(sorted(temp[key])) + ' (tie)'\n i += len(temp[key])\n elif i == 2 and len(temp[key]) == 1:\n res['3rd'] = temp[key][0]\n i += 1\n elif i == 2 and len(temp[key]) > 1:\n res['3rd'] = ', '.join(sorted(temp[key])) + ' (tie)'\n i += len(temp[key])\n return res\n", "def score_pole_vault(vaulter_list):\n i = j = 0\n retDict = {}\n vaulter = {}\n updatedVaulterList = []\n \n for vaulter_dict in vaulter_list:\n vaulter = {'name': vaulter_dict['name'], 'results': vaulter_dict['results']}\n highestVaulterJump = 0\n totalUnsuccessfulAttempts = 0\n unsuccessfulAttemptsAtHighestJump = 0\n j = 0\n for resultsList in vaulter_list[i]['results']:\n j -= 1\n if 'O' in resultsList:\n highestVaulterJump = j\n unsuccessfulAttemptsAtHighestJump = resultsList.count('X') \n totalUnsuccessfulAttempts += resultsList.count('X') \n vaulter['highestSuccessfulJump'] = highestVaulterJump\n vaulter['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump'] = unsuccessfulAttemptsAtHighestJump\n vaulter['numOfTotalUnsuccessfulAttempts'] = totalUnsuccessfulAttempts\n updatedVaulterList.append(dict(vaulter))\n i += 1\n\n updatedVaulterList = sorted(updatedVaulterList, key = lambda i: (i['highestSuccessfulJump'], i['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump'], i['numOfTotalUnsuccessfulAttempts'], i['name']))\n jumpOff = 0\n positionsAssigned = 0\n for i in range(len(updatedVaulterList)):\n if i == 0:\n retDict['1st'] = updatedVaulterList[i]['name']\n positionsAssigned += 1\n if i > 0:\n if updatedVaulterList[i]['highestSuccessfulJump'] == updatedVaulterList[0]['highestSuccessfulJump']:\n if updatedVaulterList[i]['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump'] == updatedVaulterList[0]['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump']:\n if updatedVaulterList[i]['numOfTotalUnsuccessfulAttempts'] == updatedVaulterList[0]['numOfTotalUnsuccessfulAttempts']:\n retDict['1st'] = retDict['1st'] + \", \" + updatedVaulterList[i]['name']\n jumpOff = 1\n positionsAssigned += 1\n if jumpOff:\n retDict['1st'] = retDict['1st'] + \" (jump-off)\"\n tie = 0\n if positionsAssigned == 1: #I.e. only first place has been assigned to 1 person\n for i in range(1, len(updatedVaulterList)):\n if i == 1:\n retDict['2nd'] = updatedVaulterList[i]['name']\n positionsAssigned += 1\n if i > 1:\n if updatedVaulterList[i]['highestSuccessfulJump'] == updatedVaulterList[1]['highestSuccessfulJump']:\n if updatedVaulterList[i]['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump'] == updatedVaulterList[1]['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump']:\n if updatedVaulterList[i]['numOfTotalUnsuccessfulAttempts'] == updatedVaulterList[1]['numOfTotalUnsuccessfulAttempts']:\n retDict['2nd'] = retDict['2nd'] + \", \" + updatedVaulterList[i]['name']\n tie = 1\n positionsAssigned += 1\n if tie:\n retDict['2nd'] = retDict['2nd'] + \" (tie)\" \n tie = 0\n if positionsAssigned == 2: #I.e. Either 1st place has a tie, or 1st and 2nd place assigned\n for i in range(2, len(updatedVaulterList)):\n if i == 2:\n retDict['3rd'] = updatedVaulterList[i]['name']\n positionsAssigned += 1\n if i > 2:\n if updatedVaulterList[i]['highestSuccessfulJump'] == updatedVaulterList[2]['highestSuccessfulJump']:\n if updatedVaulterList[i]['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump'] == updatedVaulterList[2]['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump']:\n if updatedVaulterList[i]['numOfTotalUnsuccessfulAttempts'] == updatedVaulterList[2]['numOfTotalUnsuccessfulAttempts']:\n retDict['3rd'] = retDict['3rd'] + \", \" + updatedVaulterList[i]['name']\n tie = 1\n positionsAssigned += 1\n if tie:\n retDict['3rd'] = retDict['3rd'] + \" (tie)\" \n\n return retDict", "def score_pole_vault(vaulters):\n results, k , R = sorted([(v['name'], score(v['results'])) for v in vaulters], key=lambda k: k[1]), 0, {}\n \n for key, tie in [('1st', ' (jump-off)'), ('2nd', ' (tie)'), ('3rd', ' (tie)')]:\n if key == '2nd' and k > 1: continue\n mx, r = results[-1][1], []\n while results and results[-1][1] == mx:\n r += [results.pop()[0]]\n\n k += len(r)\n R[key] = ', '.join(sorted(r)) + tie if len(r) > 1 else r.pop()\n if k >= 3: break\n \n return R \n \ndef score(hh):\n return ([(-1, 0)] + [(i, -len(h)) for i, h in [(i, h) for i, h in enumerate(hh)] if 'O' in h]).pop() +(-sum(j.count('X') for j in hh),)", "from collections import OrderedDict\n\ndef solve_tie_2(_vaulter_list, names, res, c):\n third_criterion = {}\n for player in _vaulter_list:\n if player[\"name\"] in names:\n fails = ''.join(player[\"results\"]).count(\"X\")\n if fails in third_criterion:\n third_criterion[fails].append(player[\"name\"])\n else:\n third_criterion[fails] = [player[\"name\"]]\n third_criterion = OrderedDict(sorted(third_criterion.items()))\n for pair in third_criterion.items():\n if len(pair[1]) == 1:\n res.append(pair[1][0])\n remove_from_dict(_vaulter_list, res[-1])\n c += 1\n if len(res) >= 3 or c >= 3: return c\n else: # unsolvable tie\n res.append(', '.join(sorted(pair[1])))\n for name in pair[1]:\n remove_from_dict(_vaulter_list, name)\n c += len(pair[1])\n if len(res) >= 3 or c >= 3: return c\n return c\n\ndef solve_tie_1(_vaulter_list, names, index, res, c):\n second_criterion = {}\n for player in _vaulter_list:\n if player[\"name\"] in names:\n fails = player[\"results\"][index].count(\"X\")\n if fails in second_criterion:\n second_criterion[fails].append(player[\"name\"])\n else:\n second_criterion[fails] = [player[\"name\"]]\n second_criterion = OrderedDict(sorted(second_criterion.items()))\n for pair in second_criterion.items():\n if len(pair[1]) == 1:\n res.append(pair[1][0])\n remove_from_dict(_vaulter_list, res[-1])\n c += 1\n if len(res) >= 3 or c >= 3: return c\n else: # try to solve according to next criterion\n c = solve_tie_2(_vaulter_list, pair[1], res, c)\n if len(res) >= 3: return c\n return c\n\ndef remove_from_dict(_vaulter_list, name):\n for i in range(len(_vaulter_list)):\n if _vaulter_list[i][\"name\"] == name:\n del _vaulter_list[i]\n break\n\ndef score_pole_vault(vaulter_list):\n if len(vaulter_list) < 1: return {}\n _vaulter_list = vaulter_list.copy()\n res = []\n c = 0\n l = len(_vaulter_list[0][\"results\"])\n best_height_index = l\n while len(res) < 3 and c < 3:\n for i in range(l-1, -1, -1):\n for player in _vaulter_list:\n if \"O\" in player[\"results\"][i]:\n best_height_index = i\n break\n if best_height_index < l: # found\n break\n first_criterion_players = []\n for player in _vaulter_list:\n if \"O\" in player[\"results\"][best_height_index]:\n first_criterion_players.append(player[\"name\"])\n if len(first_criterion_players) == 1:\n res.append(first_criterion_players[0])\n remove_from_dict(_vaulter_list, res[-1])\n c += 1\n else:\n c = solve_tie_1(_vaulter_list, first_criterion_players, best_height_index, res, c)\n l = best_height_index\n \n res_dict = {\"1st\": res[0] + (\" (jump-off)\" if \",\" in res[0] else \"\")}\n n = len(res_dict[\"1st\"].split(\",\"))\n if n == 3: return res_dict\n if n == 2:\n res_dict[\"3rd\"] = res[1] + (\" (tie)\" if \",\" in res[1] else \"\")\n return res_dict\n else:\n res_dict[\"2nd\"] = res[1] + (\" (tie)\" if \",\" in res[1] else \"\")\n if \",\" in res_dict[\"2nd\"]: return res_dict\n else:\n res_dict[\"3rd\"] = res[2] + (\" (tie)\" if \",\" in res[2] else \"\")\n return res_dict", "def score_pole_vault(vaulter_list):\n r={}\n for v in vaulter_list:\n x=[len(v['results']),0,0]\n f=0\n for i,t in enumerate(v['results'][::-1]):\n if 'O' in t and x[0]==len(v['results']):\n x=[i,t.count('X'),0]\n f+=t.count('X')\n x[2]=f\n r[v['name']]=tuple(x)\n rank=sorted(list(r.keys()),key=lambda x:r[x])\n first=[rank[0]]\n second=[]\n third=[]\n for name in rank[1:]:\n if r[first[0]]==r[name]:\n first.append(name)\n elif not second or r[second[0]]==r[name]:\n second.append(name)\n elif not third or r[third[0]]==r[name]:\n third.append(name)\n if len(first)>=2:\n d={'1st': ', '.join(sorted(first))+' (jump-off)'}\n if len(first)==2:\n if len(second)==1:\n d['3rd']=second[0]\n else:\n d['3rd']=', '.join(sorted(second))+' (tie)'\n else:\n d={'1st': first[0]}\n if len(second)>=2:\n d['2nd']=', '.join(sorted(second))+' (tie)'\n else:\n d['2nd']=second[0]\n if len(third)==1:\n d['3rd']=third[0]\n else:\n d['3rd']=', '.join(sorted(third))+' (tie)'\n return d\n", "def score_pole_vault(vaulter_list):\n summary=[]\n for i in vaulter_list:\n total_X=0\n highest_cleared=-1\n X_at_highest = 0\n for j in range(len(i[\"results\"])):\n if \"O\" in i[\"results\"][j]:\n highest_cleared=j\n X_at_highest=i[\"results\"][j].count(\"X\")\n total_X += i[\"results\"][j].count(\"X\")\n summary.append((-highest_cleared, X_at_highest, total_X, i[\"name\"]))\n final_standing= sorted(summary)\n \n result = {}\n winners_stat= final_standing[0][:3]\n winners=[]\n for i in final_standing:\n if i[:3]==winners_stat[:3]: winners.append(i[3])\n result[\"1st\"] = \", \".join(winners) + \" (jump-off)\"*(len(winners)>1)\n \n if len(winners)>2: return result\n \n if len(winners)==1:\n second_stat= final_standing[1][:3]\n seconds=[]\n for i in final_standing:\n if i[:3]==second_stat[:3]: seconds.append(i[3])\n result[\"2nd\"] = \", \".join(seconds) + \" (tie)\"*(len(seconds)>1)\n if len(seconds)>1: return result\n \n thirds=[]\n third_stat = final_standing[2][:3]\n for i in final_standing:\n if i[:3]==third_stat[:3]: thirds.append(i[3])\n result[\"3rd\"] = \", \".join(thirds) + \" (tie)\"*(len(thirds)>1)\n return result\n", "def score_pole_vault(vaulters):\n results = sorted([(v['name'], score(v['results'])) for v in vaulters], key=lambda k: k[1])\n k, R = 0, {}\n \n for key, tie in [('1st', ' (jump-off)'), ('2nd', ' (tie)'), ('3rd', ' (tie)')]:\n if key == '2nd' and k > 1: continue\n mx, r = results[-1][1], []\n while results and results[-1][1] == mx:\n r += [results.pop()[0]]\n\n k += len(r)\n R[key] = ', '.join(sorted(r)) + tie if len(r) > 1 else r.pop()\n if k >= 3: break\n \n return R \n \ndef score(heights):\n highest, highest_jumps, fails = -1, 0, 0\n for i, h in enumerate(heights):\n fails += h.count('X')\n if 'O' in h:\n highest,highest_jumps = i, len(h)\n return (highest, -highest_jumps, -fails) ", "from collections import defaultdict\n\ndef score_pole_vault(vaulter_list):\n scoreboard = defaultdict(list)\n for v in vaulter_list:\n score = 0\n fails = 0\n for i, result in enumerate(v[\"results\"], 1):\n fails += result.count(\"X\")\n if \"O\" in result:\n score = i * 10 - result.count(\"X\")\n scoreboard[(-score, fails)].append(v[\"name\"])\n nWinners = 0\n places = [\"3rd\", \"2nd\", \"1st\"]\n answer = {}\n for performance in sorted(scoreboard):\n place = places.pop()\n winnerList = sorted(scoreboard[performance])\n l = len(winnerList)\n winners = \", \".join(winnerList)\n if l > 1:\n winners += \" (jump-off)\" if place == \"1st\" else \" (tie)\"\n answer[place] = winners\n nWinners += l\n if nWinners >= 3:\n break\n if nWinners == len(places) == 2:\n places.pop()\n return answer"]
{"fn_name": "score_pole_vault", "inputs": [[[{"name": "Linda", "results": ["XXO", "O", "XXO", "O"]}, {"name": "Vickie", "results": ["O", "X", "", ""]}, {"name": "Debbie", "results": ["XXO", "O", "XO", "XXX"]}, {"name": "Michelle", "results": ["XO", "XO", "XXX", ""]}, {"name": "Carol", "results": ["XXX", "", "", ""]}]], [[{"name": "Linda", "results": ["XXO", "O", "XXO", "XXX"]}, {"name": "Vickie", "results": ["O", "X", "", ""]}, {"name": "Debbie", "results": ["XXO", "O", "XO", "XXX"]}, {"name": "Michelle", "results": ["XO", "XO", "XXX", ""]}, {"name": "Carol", "results": ["XXX", "", "", ""]}]], [[{"name": "Kimberly", "results": ["O", "O", "XO", "XXX"]}, {"name": "Constance", "results": ["O", "X", "", ""]}, {"name": "Phoebe", "results": ["XXO", "O", "XO", "XXX"]}, {"name": "Carol", "results": ["XXX", "", "", ""]}]], [[{"name": "Lana", "results": ["XO", "O", "O", "XXO", "XXX"]}, {"name": "Onyx", "results": ["XXO", "XXO", "XO", "O", "XXX"]}, {"name": "Molly", "results": ["XO", "XO", "O", "XXX", ""]}, {"name": "Alexandria", "results": ["XO", "XO", "O", "XXX", ""]}, {"name": "Rebecca", "results": ["XXO", "O", "O", "XXX", ""]}]], [[{"name": "Lana", "results": ["XO", "O", "O", "XXO", "XXX"]}, {"name": "Onyx", "results": ["XXO", "XXO", "XO", "O", "XXX"]}, {"name": "Molly", "results": ["XO", "XO", "O", "XXX", ""]}, {"name": "Rebecca", "results": ["XXO", "O", "O", "XXX", ""]}]], [[{"name": "Sarah", "results": ["O", "X", "", ""]}, {"name": "Brett", "results": ["XO", "O", "XO", "XXO"]}, {"name": "Sharon", "results": ["O", "X", "", ""]}, {"name": "Kelli", "results": ["XXX", "", "", ""]}, {"name": "Laura", "results": ["O", "XO", "XO", "XXO"]}]], [[{"name": "Elle", "results": ["O", "O", "XXO", "XXO"]}, {"name": "Sarah", "results": ["O", "X", "", ""]}, {"name": "Brett", "results": ["XO", "O", "XO", "XXO"]}, {"name": "Kelli", "results": ["XXX", "", "", ""]}, {"name": "Laura", "results": ["O", "XO", "XO", "XXO"]}]], [[{"name": "Allison", "results": ["XO", "O", "XXO", "XXX"]}, {"name": "Olivia", "results": ["O", "XO", "XXO", "XXX"]}, {"name": "Rhyana", "results": ["XO", "O", "XO", "XO"]}, {"name": "Zola", "results": ["XO", "O", "XXX", ""]}, {"name": "Megan", "results": ["XO", "O", "XXX", ""]}]], [[{"name": "Allison", "results": ["XO", "O", "XXO", "XXX"]}, {"name": "Olivia", "results": ["O", "XO", "XXO", "XXX"]}, {"name": "Rhyana", "results": ["XO", "O", "XO", "XO"]}, {"name": "Zola", "results": ["XO", "O", "XXX", ""]}, {"name": "Megan", "results": ["XO", "O", "XXO", "XXX"]}]], [[{"name": "Anna", "results": ["XO", "O", "XO", "XO"]}, {"name": "Allison", "results": ["XO", "O", "XXO", "XXX"]}, {"name": "Olivia", "results": ["O", "XO", "XXO", "XXX"]}, {"name": "Rhiana", "results": ["XO", "O", "XO", "XO"]}, {"name": "Zola", "results": ["XO", "O", "XXX", ""]}, {"name": "Megan", "results": ["XO", "O", "XXO", "XXX"]}]]], "outputs": [[{"1st": "Linda", "2nd": "Debbie", "3rd": "Michelle"}], [{"1st": "Debbie", "2nd": "Linda", "3rd": "Michelle"}], [{"1st": "Kimberly", "2nd": "Phoebe", "3rd": "Constance"}], [{"1st": "Onyx", "2nd": "Lana", "3rd": "Alexandria, Molly, Rebecca (tie)"}], [{"1st": "Onyx", "2nd": "Lana", "3rd": "Molly, Rebecca (tie)"}], [{"1st": "Brett, Laura (jump-off)", "3rd": "Sarah, Sharon (tie)"}], [{"1st": "Brett, Elle, Laura (jump-off)"}], [{"1st": "Rhyana", "2nd": "Allison, Olivia (tie)"}], [{"1st": "Rhyana", "2nd": "Allison, Megan, Olivia (tie)"}], [{"1st": "Anna, Rhiana (jump-off)", "3rd": "Allison, Megan, Olivia (tie)"}]]}
INTRODUCTORY
PYTHON3
CODEWARS
14,451
def score_pole_vault(vaulter_list):
0e312a53bbcfdf05fd83869ccd3eaeba
UNKNOWN
An anagram is a word, a phrase, or a sentence formed from another by rearranging its letters. An example of this is "angel", which is an anagram of "glean". Write a function that receives an array of words, and returns the total number of distinct pairs of anagramic words inside it. Some examples: - There are 2 anagrams in the array `["dell", "ledl", "abc", "cba"]` - There are 7 anagrams in the array `["dell", "ledl", "abc", "cba", "bca", "bac"]`
["from collections import Counter\n\ndef anagram_counter(words):\n return sum(n*(n-1)// 2 for n in Counter(''.join(sorted(x)) for x in words).values())", "def anagram_counter(words):\n def is_anagrams(s1, s2): return sorted(s1) == sorted(s2)\n return 0 if not words else sum([1 for x in range(len(words)-1) for y in range(x+1, len(words)) if is_anagrams(words[x], words[y])])", "from collections import Counter\n\ndef anagram_counter(words):\n return sum(n*(n-1)>>1 for n in Counter(''.join(sorted(word)) for word in words).values())", "from collections import Counter\n\ndef anagram_counter(words):\n return sum(n * (n - 1) / 2 for n in Counter(frozenset(word) for word in words).values())", "from collections import Counter\nfrom itertools import combinations\ndef anagram_counter(words):\n return sum(1 for a, b in combinations((frozenset(Counter(w)) for w in words), 2) if a == b)", "from collections import Counter\n\ndef anagram_counter(words):\n anag = Counter( tuple(sorted(Counter(w).items())) for w in words )\n return sum(n*(n-1)//2 for n in anag.values())", "def anagram_counter(words):\n anagrams = 0\n for i, word in enumerate(words):\n for wrd in [w for w in words if w != word and set(word) == set(w)]:\n anagrams += 1\n return anagrams / 2", "from collections import Counter\n\ndef anagram_counter(words):\n return sum(n * (n - 1) // 2 for n in Counter(''.join(sorted(w)) for w in words).values())", "from collections import Counter\n\ndef anagram_counter(a):\n return sum(n * (n - 1) / 2 for n in Counter(\"\".join(sorted(x)) for x in a).values())", "# METHOD ONE ~ list comprehension\n\"100 seconds per 1000 runs of Lorem Ipsum\"\n# def anagram_counter(s):\n# return sum([1for i,c in enumerate(s)for w in s[i+1:]if sorted(c)==sorted(w)])\n\n# METHOD TWO ~ standard iteration\n\"50 seconds per 1000 runs of Lorem Ipsum\"\n#def anagram_counter(words):\n# anagram_count = 0\n# for i, current in enumerate(words):# FUN FACT:\n# cenrrtu = sorted(current)\n# for word in words[i+1:]:\n# if cenrrtu == sorted(word):# Lorum Ipsum contains 6,862 anagram matches\n# anagram_count += 1\n# return anagram_count\n\n# METHOD THREE ~ comparing sets to counts\n\"0.5 seconds per 1000 runs of Lorem Ipsum\"\ndef run_down(number):\n count = 0\n while number:\n count += number - 1\n number -= 1\n return count\n\ndef anagram_counter(words):\n sorts = list(''.join(sorted(word)) for word in words)\n unique = set(sorts)\n return sum(run_down(sorts.count(word)) for word in unique)\n \n\"\"\"\niterations _comp_ _iter_ _sets_\n1 0.0990 0.0541 0.0008\n10 1.0113 0.4954 0.0054\n100 9.9280 4.8606 0.0535\n1000 101.2153 50.2576 0.5660\n\"\"\""]
{"fn_name": "anagram_counter", "inputs": [[[]], [["dell", "ledl", "abc", "cba"]], [["dell", "ledl", "lled", "cba"]], [["dell", "ledl", "abc", "cba", "bca", "bac", "cab"]]], "outputs": [[0], [2], [3], [11]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,884
def anagram_counter(words):
75368dc016aca49d26409533c065e839
UNKNOWN
# RoboScript #1 - Implement Syntax Highlighting ## Disclaimer The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental. ## About this Kata Series This Kata Series is based on a fictional story about a computer scientist and engineer who owns a firm that sells a toy robot called MyRobot which can interpret its own (esoteric) programming language called RoboScript. Naturally, this Kata Series deals with the software side of things (I'm afraid Codewars cannot test your ability to build a physical robot!). ## Story You are a computer scientist and engineer who has recently founded a firm which sells a toy product called MyRobot which can move by receiving a set of instructions by reading a file containing a script. Initially you have planned the robot to be able to interpret JavaScript files for its movement instructions but you later decided that it would make MyRobot too hard to operate for most customers out there who aren't even computer programmers in the first place. For this reason, you have decided to invent a new (esoteric) scripting language called RoboScript which has a much simpler syntax so non-computer programmers can easily learn how to write scripts in this language which would enable them to properly operate MyRobot. However, you are currently at the initial stage of inventing this new Esolang. The first step to popularize this (esoteric) scripting language is naturally to invent a new editor for it which provides syntax highlighting for this language so your customers feel like they are writing a proper program when they are writing scripts for MyRobot. ## Task Your MyRobot-specific (esoteric) scripting language called RoboScript only ever contains the following characters: `F`, `L`, `R`, the digits `0-9` and brackets (`(` and `)`). Your goal is to write a function `highlight` which accepts 1 required argument `code` which is the RoboScript program passed in as a string and returns the script with syntax highlighting. The following commands/characters should have the following colors: - `F` - Wrap this command around `` and `` tags so that it is highlighted pink in our editor - `L` - Wrap this command around `` and `` tags so that it is highlighted red in our editor - `R` - Wrap this command around `` and `` tags so that it is highlighted green in our editor - Digits from `0` through `9` - Wrap these around `` and `` tags so that they are highlighted orange in our editor - Round Brackets - Do not apply any syntax highlighting to these characters For example: And for multiple characters with the same color, simply wrap them with a **single** `` tag of the correct color: Note that the use of `` tags must be **exactly** the same format as demonstrated above. Even if your solution produces the same visual result as the expected answers, if you miss a space betwen `"color:"` and `"green"`, for example, you will fail the tests. ## Kata in this Series 1. **RoboScript #1 - Implement Syntax Highlighting** 2. [RoboScript #2 - Implement the RS1 Specification](https://www.codewars.com/kata/5870fa11aa0428da750000da) 3. [RoboScript #3 - Implement the RS2 Specification](https://www.codewars.com/kata/58738d518ec3b4bf95000192) 4. [RoboScript #4 - RS3 Patterns to the Rescue](https://www.codewars.com/kata/594b898169c1d644f900002e) 5. [RoboScript #5 - The Final Obstacle (Implement RSU)](https://www.codewars.com/kata/5a12755832b8b956a9000133)
["import re\ndef highlight(code):\n code = re.sub(r\"(F+)\", '<span style=\"color: pink\">\\g<1></span>', code)\n code = re.sub(r\"(L+)\", '<span style=\"color: red\">\\g<1></span>', code)\n code = re.sub(r\"(R+)\", '<span style=\"color: green\">\\g<1></span>', code)\n code = re.sub(r\"(\\d+)\", '<span style=\"color: orange\">\\g<1></span>', code)\n return code", "import re\n\nHL = {'R+': 'green',\n 'F+': 'pink',\n 'L+': 'red',\n '\\d+': 'orange'}\n \nPATTERN_HL = re.compile(r'|'.join(HL))\nHL_FORMAT = '<span style=\"color: {}\">{}</span>'\n\ndef replacment(m):\n s,k = m.group(), m.group()[0] + '+'\n return (HL_FORMAT.format(HL[k], s) if k in HL else\n HL_FORMAT.format(HL['\\d+'], s) if s.isdigit() else\n s)\n\ndef highlight(code):\n return PATTERN_HL.sub(replacment, code)", "wrap = lambda s: s if s[0] in '()' else '<span style=\"color: ' + {'F':'pink', 'L':'red', 'R':'green'}.get(s[0], 'orange') + '\">' + s + '</span>' \n\ndef highlight(code):\n r, last = '', ''\n \n for c in code:\n if last and c != last[-1] and not (c.isdigit() and last.isdigit()):\n r += wrap(last)\n last = ''\n last += c\n \n return r + wrap(last) ", "from re import sub\n\ndef repl(match):\n COLORS = {\"F\": \"pink\", \"L\": \"red\", \"R\": \"green\"}\n match = match.group()\n color = COLORS.get(match[0], \"orange\")\n return f'<span style=\"color: {color}\">{match}</span>'\n\n\ndef highlight(code):\n return sub(\"F+|L+|R+|\\d+\", repl, code)", "import re\n\ndef highlight(code):\n code = re.sub(r'(\\d+)', r'<span style=\"color: orange\">\\1</span>',\n re.sub(r'(R+)', r'<span style=\"color: green\">\\1</span>',\n re.sub(r'(L+)', r'<span style=\"color: red\">\\1</span>',\n re.sub(r'(F+)', r'<span style=\"color: pink\">\\1</span>',\n code))))\n return code", "import re\n\ncolors = dict.fromkeys('0123456789', 'orange')\ncolors.update(F='pink', L='red', R='green')\n\ndef repl(m):\n c = m.group()\n return '<span style=\"color: {}\">{}</span>'.format(colors[c[:1]], c)\n \ndef highlight(code):\n return re.sub('F+|L+|R+|[0-9]+', repl, code)", "import re\n\ndef highlight(code):\n colors = dict(zip(\"FLR0123456789\", [\"pink\", \"red\", \"green\"] + [\"orange\"]*10))\n span = '<span style=\"color: {}\">{}</span>'\n regex = r\"(F+|L+|R+|[0-9]+|\\(|\\))\"\n highlight_command = lambda g: g if g in \"()\" else span.format(colors[g[:1]], g)\n return \"\".join(highlight_command(m.group(0)) for m in re.finditer(regex, code))", "import re\nspan = \"<span style=\\\"color: {0}\\\">{1}</span>\"\nsubs = {\n \"F\": \"pink\", \n \"L\": \"red\",\n \"R\": \"green\",\n \"digit\": \"orange\"\n}\n\n\ndef sub(match):\n char = match.group(0)[0]\n if char.isdigit():\n return span.format(subs[\"digit\"], match.group(0))\n else:\n return span.format(subs[char], match.group(0))\n\ndef highlight(code):\n return re.sub(\"(F+|L+|R+|[0-9]+)\", sub, code) ", "import re\n\n\ndef highlight(code):\n patterns = {\n 'F': 'pink',\n 'L': 'red',\n 'R': 'green',\n '0-9': 'orange',\n }\n new_string = code\n for pattern, color in patterns.items():\n _pattern = re.compile(r'([{}]+)'.format(pattern))\n new_string = _pattern.sub(r'<span style=\"color: {}\">\\1</span>'.format(color), new_string)\n return new_string", "highlight=lambda s:__import__('re').sub(r'([FLR])\\1*|\\d+',lambda m:'<span style=\"color: %s\">%s</span>'%({'F':'pink','L':'red','R':'green'}.get(m.group()[0],'orange'),m.group()),s)"]
{"fn_name": "highlight", "inputs": [["F3RF5LF7"], ["FFFR345F2LL"], ["RRRRRF45L3F2"], ["RRRRR(F45L3)F2"], ["FF(LF6(RF3)2)3"]], "outputs": [["<span style=\"color: pink\">F</span><span style=\"color: orange\">3</span><span style=\"color: green\">R</span><span style=\"color: pink\">F</span><span style=\"color: orange\">5</span><span style=\"color: red\">L</span><span style=\"color: pink\">F</span><span style=\"color: orange\">7</span>"], ["<span style=\"color: pink\">FFF</span><span style=\"color: green\">R</span><span style=\"color: orange\">345</span><span style=\"color: pink\">F</span><span style=\"color: orange\">2</span><span style=\"color: red\">LL</span>"], ["<span style=\"color: green\">RRRRR</span><span style=\"color: pink\">F</span><span style=\"color: orange\">45</span><span style=\"color: red\">L</span><span style=\"color: orange\">3</span><span style=\"color: pink\">F</span><span style=\"color: orange\">2</span>"], ["<span style=\"color: green\">RRRRR</span>(<span style=\"color: pink\">F</span><span style=\"color: orange\">45</span><span style=\"color: red\">L</span><span style=\"color: orange\">3</span>)<span style=\"color: pink\">F</span><span style=\"color: orange\">2</span>"], ["<span style=\"color: pink\">FF</span>(<span style=\"color: red\">L</span><span style=\"color: pink\">F</span><span style=\"color: orange\">6</span>(<span style=\"color: green\">R</span><span style=\"color: pink\">F</span><span style=\"color: orange\">3</span>)<span style=\"color: orange\">2</span>)<span style=\"color: orange\">3</span>"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,691
def highlight(code):
32b2832a6e623c1d55af0e0fa6e33bea
UNKNOWN
In this Kata, you will be given two numbers, `a` and `b`, and your task is to determine if the first number `a` is divisible by `all` the prime factors of the second number `b`. For example: `solve(15,12) = False` because `15` is not divisible by all the prime factors of `12` (which include`2`). See test cases for more examples. Good luck! If you like this Kata, please try: [Sub-array division](https://www.codewars.com/kata/59eb64cba954273cd4000099) [Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)
["import fractions\n\ndef solve(a, b):\n c = fractions.gcd(a, b)\n while c > 1:\n b //= c\n c = fractions.gcd(a, b)\n return b == 1", "from math import gcd\n\n\ndef solve(a, b):\n while 1 < gcd(a, b):\n b = b // gcd(a, b)\n return b == 1\n", "from math import gcd\n\ndef solve(a, b):\n x = gcd(a, b)\n if x == 1: return False\n if x == b: return True\n return solve(a, b//x)", "from fractions import gcd\ndef solve(a,b):\n if b == 1:\n return True \n if gcd(a,b) == 1:\n return False \n return solve(a,b/(gcd(a,b)))", "def solve(a,b):\n li,j = [],2\n while b>1:\n if b%j : j+=1 ; continue\n li.append(j) ; b//=j\n if a%j:return 0\n return 1", "def solve(a,b):\n k = 2\n while k <= int(b**0.5):\n while b%k == 0:\n b //= k\n if a%k != 0: return False\n k += 1\n return a%b == 0\n", "def solve(a,b):\n b1 = b\n answer = True\n i = 2\n primfac = []\n \n while i * i <= b:\n while b1 % i == 0:\n primfac.append(i)\n b1 = b1 // i\n i = i + 1\n if b1 > 1:\n primfac.append(b1)\n\n for i in range(0, len(primfac)):\n if (a % primfac[i] != 0):\n answer = False\n\n return answer", "N = 10_000\na = [1] * N\na[0] = a[1] = 0\nfor i in range(2, N):\n if a[i]:\n for j in range(i**2, N, i):\n a[j] = 0\na = [i for i, x in enumerate(a) if x]\n\ndef solve(n, m):\n return all(not n % x for x in f(m))\n\ndef f(n):\n s = set()\n for x in a:\n if x > n:\n break\n while not n % x:\n n //= x\n s.add(x)\n if n > 1:\n s.add(n)\n return s", "def solve(a,b):\n p = 2\n while True:\n if b == 1: return True\n if a%p > 0 and b%p == 0: return False\n while b%p == 0: b /= p\n p += 1", "from math import ceil, sqrt\n\ndef factorize(x):\n factors = []\n for i in range(2, ceil(sqrt(x))+1):\n while x % i == 0:\n factors.append(i)\n x /= i\n if x != 1:\n factors.append(x)\n return factors\n\ndef solve(a,b):\n factors = factorize(b)\n ok = True\n for factor in factors:\n if a % factor != 0:\n ok = False\n return ok\n\n"]
{"fn_name": "solve", "inputs": [[2, 256], [2, 253], [9, 243], [15, 12], [21, 2893401], [21, 2893406], [54, 2834352], [54, 2834359], [1000013, 7187761], [1000013, 7187762]], "outputs": [[true], [false], [true], [false], [true], [false], [true], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,321
def solve(a,b):
78d1c9ce2871c18ccd800511b4ec36f2
UNKNOWN
A strongness of an even number is the number of times we can successively divide by 2 until we reach an odd number starting with an even number n. For example, if n = 12, then * 12 / 2 = 6 * 6 / 2 = 3 So we divided successively 2 times and we reached 3, so the strongness of 12 is `2`. If n = 16 then * 16 / 2 = 8 * 8 / 2 = 4 * 4 / 2 = 2 * 2 / 2 = 1 we divided successively 4 times and we reached 1, so the strongness of 16 is `4` # Task Given a closed interval `[n, m]`, return the even number that is the strongest in the interval. If multiple solutions exist return the smallest strongest even number. Note that programs must run within the allotted server time; a naive solution will probably time out. # Constraints ```if-not:ruby 1 <= n < m <= INT_MAX ``` ```if:ruby 1 <= n < m <= 2^64 ``` # Examples ``` [1, 2] --> 2 # 1 has strongness 0, 2 has strongness 1 [5, 10] --> 8 # 5, 7, 9 have strongness 0; 6, 10 have strongness 1; 8 has strongness 3 [48, 56] --> 48
["\"\"\"Strongest even number in an interval kata\n\nDefines strongest_even(n, m) which returns the strongest even number in the set\nof integers on the interval [n, m].\n\nConstraints:\n 1. 1 <= n < m < MAX_INT\n\nNote:\n 1. The evenness of zero is need not be defined given the constraints.\n 2. In Python 3, the int type is unbounded. In Python 2, MAX_INT is\n determined by the platform.\n\nDefinition:\n A number is said to be more strongly even than another number if the\n multiplicity of 2 in its prime factorization is higher than in the prime\n factorization of the other number.\n\"\"\"\nfrom math import log2\n\n\ndef strongest_even(n, m):\n \"\"\"Returns the strongest even number in the set of integers on interval\n [n, m].\n \"\"\"\n\n #It can be shown that the largest power of 2 on an interval [n, m] will\n #necessarily be the strongest even number. Check first if the interval\n #contains a power of 2, by comparing the log2 of the endpoints.\n if int(log2(m)) > int(log2(n)):\n return 2**int(log2(m))\n\n #Modify the endpoints exclude any odd numbers. If the two endpoints are\n #equal, the original interval contains only a single even number. Return it.\n n += n % 2\n m -= m % 2\n if n == m:\n return n\n\n #All optimizations and edge cases are exhausted. Recurse with the\n #modified endpoints halved, and multiply the result by 2.\n return 2*strongest_even(n // 2, m // 2)\n", "def strongest_even(n, m):\n while m & m - 1 >= n:\n m &= m - 1\n return m", "def strongest_even(n, m):\n while True:\n if m & m - 1 < n: return m\n m &= m - 1", "from math import log2\n\ndef strongest_even(n, m):\n b = x = 2**int(log2(m))\n \n while not n <= x <= m:\n b //= 2\n x = (m // b) * b\n \n return x", "def strongest_even(n, m):\n while n <= m:\n prev = n\n n += 1 << strongness(n)\n return prev\n\ndef strongness(n):\n return n.bit_length() - len(format(n, 'b').rstrip('0'))", "def strongest_even(n, m):\n x, y = bin(n)[2:], bin(m)[2:]\n if len(x) < len(y): return 1 << len(y)-1\n i = next(i for i in range(len(x)) if x[i] != y[i])\n res = x[:i] + ('1' if '1' in x[i:] else '0') + '0'*(len(x)-i-1)\n return int(res, 2)", "def strongest_even(n, m):\n n = n if n % 2 == 0 else n + 1\n m = m if m % 2 == 0 else m - 1\n \n x = 2\n \n while not x * 2 > m:\n x *= 2\n \n if x < n:\n i, s, a = m, n, x\n \n while i >= n:\n if i % a/2 == 0:\n s = i\n i -= a\n a = x\n \n a = a/2 if a/2 > 1 else 2\n \n return s\n else:\n return x\n \n", "def strongest_even(n, m):\n exponent = 1\n while (m > 2**exponent):\n exponent += 1\n \n if (n <= 2**exponent <= m):\n return 2**exponent\n\n while(exponent > 0):\n exponent -= 1\n factor = 1\n while((2**exponent)*factor <= m):\n if (n <= (2**exponent)*factor <= m):\n return (2**exponent)*factor\n factor += 2", "def strongest_even(n, m):\n pow = 1\n while pow <= m:\n pow *= 2\n if pow/2 <= m and pow/2 >= n:\n return pow/2\n else:\n pow /= 4\n multiplier = 3\n while True:\n multiple = pow * multiplier\n while multiple <= m:\n if n <= multiple:\n return multiple\n else:\n multiplier += 1\n multiple = pow * multiplier\n pow /= 2\n multiple = 3\n", "from math import log\nfrom math import floor\n\ndef strongest_even(n,m):\n a=2**floor(log(m)/log(2));b=1; \n while a*b<n or a*b>m:\n a /= 2;\n b += 2;\n while a*b<=m:\n if a*b>=n:\n return a*b\n b +=2\n \n return a*b \n#strongest_even(33,47)\n"]
{"fn_name": "strongest_even", "inputs": [[1, 2], [5, 10], [48, 56], [129, 193], [2, 3], [4, 6], [3, 310], [33, 40], [456445, 678860], [324243, 897653214], [1151592177, 2129680158], [2085422641, 2128923730], [1082012216, 1876572332], [1806570867, 2067832928], [206346325, 1289058842]], "outputs": [[2], [8], [48], [192], [2], [4], [256], [40], [524288], [536870912], [1610612736], [2113929216], [1610612736], [1879048192], [1073741824]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,038
def strongest_even(n, m):
c549e62f397f9b32588884ae2508b3bf
UNKNOWN
Inspired by the development team at Vooza, write the function `howManyLightsabersDoYouOwn`/`how_many_light_sabers_do_you_own` that * accepts the name of a programmer, and * returns the number of lightsabers owned by that person. The only person who owns lightsabers is Zach, by the way. He owns 18, which is an awesome number of lightsabers. Anyone else owns 0. ```if:coffeescript,javascript,php,python,ruby,typescript **Note**: your function should have a default parameter. ``` ```c# Kata.HowManyLightsabersDoYouOwn("Adam") == 0 Kata.HowManyLightsabersDoYouOwn("Zach") == 18 ``` ```python how_many_light_sabers_do_you_own('Zach') == 18 how_many_light_sabers_do_you_own('Adam') == 0 how_many_light_sabers_do_you_own() == 0 ```
["def how_many_light_sabers_do_you_own(name=\"\"):\n return (18 if name==\"Zach\" else 0)", "how_many_light_sabers_do_you_own=lambda n='': 18 if n=='Zach' else 0", "def how_many_light_sabers_do_you_own(name='haha'):\n return 18 if name=='Zach' else 0", "def how_many_light_sabers_do_you_own(name=''):\n switch = { \n 'Zach': 18,\n }\n return switch.get(name, 0)", "def how_many_light_sabers_do_you_own(name=\"\"):\n if name == \"Zach\":\n return 18\n else:\n return 0", "def how_many_light_sabers_do_you_own(name=False):\n return name == \"Zach\" and 18", "how_many_light_sabers_do_you_own=lambda n=str():0x12.__mul__(sum(map(ord,n)).__eq__(0x186))", "def how_many_light_sabers_do_you_own(name=\"\"):\n \n return {'Zach': 18}.get(name,0)\n \n \n", "def how_many_light_sabers_do_you_own(name='tigerk00'):\n return 18 if name == 'Zach' else 0", "# Do your stuff here!\ndef how_many_light_sabers_do_you_own(name=''):\n if name == \"Zach\":\n return 18\n else: return 0", "def how_many_light_sabers_do_you_own(name = \"Brad\"):\n if name == \"Zach\":\n lightsabers = 18\n else:\n lightsabers = 0 \n return lightsabers", "def how_many_light_sabers_do_you_own(*name):\n if name != ():\n print(name)\n if name[0] == 'Zach':\n return 18\n return 0\n return 0", "def how_many_light_sabers_do_you_own(*name):\n if len(name) == 0: return 0\n return 18 if name[0] == 'Zach' else 0", "def how_many_light_sabers_do_you_own(name = \"Someone\"):\n return 18 if name == \"Zach\" else 0", "def how_many_light_sabers_do_you_own(name = \"x\"):\n if name == 'Zach': return 18\n elif name == 'x': return 0\n else: return 0", "def how_many_light_sabers_do_you_own(name=None):\n return name == \"Zach\" and 18", "def how_many_light_sabers_do_you_own(name=\"john\"):\n if name == \"Zach\":\n return 18\n else:\n return 0", "def how_many_light_sabers_do_you_own(name=\"No one\"):\n if name == \"Zach\":\n return 18\n else:\n return 0", "def how_many_light_sabers_do_you_own(a=\"\"):\n return 18 if a == \"Zach\" else 0", "how_many_light_sabers_do_you_own = lambda *name: 18 if 'Zach' in name else 0", "def how_many_light_sabers_do_you_own(that_person_is='someone else'): return 18 if that_person_is==\"Zach\" else 0", "def how_many_light_sabers_do_you_own(name='Abc'):\n return 18 if name=='Zach' else 0", "def how_many_light_sabers_do_you_own(name=\"l\"):\n return 0 if name != \"Zach\" else 18", "def how_many_light_sabers_do_you_own(name = 'ehhh'):\n return 18 if name =='Zach' else 0", "def how_many_light_sabers_do_you_own(name=0):\n a = ['Zach']\n if name == a[0]:\n return 18\n else: return 0", "def how_many_light_sabers_do_you_own(*name):\n try:\n return 18 if name[0]=='Zach' else 0\n except:\n return 0", "def how_many_light_sabers_do_you_own(name=None):\n try:\n return 18 if name=='Zach'else 0\n except AttributeError:\n return 0", "def how_many_light_sabers_do_you_own(name='James'):\n return 18 if name == 'Zach' else 0", "import re\n\n# Assigning default empty value if no name is entered.\n# When not done, Exit code is non-zero with a TypeError - missing 1 required positional argument: 'name'\n# if the function is called without argument.\ndef how_many_light_sabers_do_you_own(name=''):\n # Return 18 if you match Zach, in all other cases, return 0\n return 18 if re.match('^Zach$', name) else 0", "def how_many_light_sabers_do_you_own(name=None):\n return 0 if not name else 18 if name == \"Zach\" else 0\n", "def how_many_light_sabers_do_you_own(name=\"Levi\"):\n\n if name == \"Zach\":\n return 18\n return 0\n", "def how_many_light_sabers_do_you_own(name='null'):\n return 18 if name == 'Zach' else 0", "def how_many_light_sabers_do_you_own(name=\"null\"):\n try:\n if name==\"Zach\":\n return 18\n else:\n return 0\n except TypeError:\n return 0", "def how_many_light_sabers_do_you_own(name = 'pete'):\n return 18 if name == 'Zach' else 0", "def how_many_light_sabers_do_you_own(x = \"\"):\n return 0 if x != \"Zach\" else 18", "def how_many_light_sabers_do_you_own(name = \"Adam\",lightsabers = 0):\n if name == \"Zach\":\n return 18\n else:\n return lightsabers\n", "def how_many_light_sabers_do_you_own(name = \"rex\"):\n if name == \"Zach\":\n return 18\n else:\n return 0", "def how_many_light_sabers_do_you_own(name = 'Jack'):\n return 18 if name == 'Zach' else 0", "def how_many_light_sabers_do_you_own(name = 'notZach'):\n return 18 if name == 'Zach' else 0\n", "def how_many_light_sabers_do_you_own(*name):\n res=list(name)\n try:\n return 18 if res[0]==\"Zach\" else 0\n except:\n return 0", "def how_many_light_sabers_do_you_own(*args):\n \n if len(args) == 0:\n return 0\n \n return 18 if args[0] == 'Zach' else 0", "def how_many_light_sabers_do_you_own(name=''):\n '''\n Inspired by the development team at Vooza, write the function\n \n howManyLightsabersDoYouOwn / how_many_light_sabers_do_you_own that\n \n - accepts the name of a programmer, nad\n - returns the number of lightsabers owned by that person.\n \n The only person who owns lightsavers is Zach, by the way.\n He owns 18, which is an awesome number of lightsabers.\n Anyone elese owns 0.\n '''\n if name == 'Zach':\n return 18\n return 0", "def how_many_light_sabers_do_you_own(name = 'Joe'):\n return 18 if name == 'Zach' else 0", "def how_many_light_sabers_do_you_own(name='no_name'):\n return 18 if name == 'Zach' else 0", "def how_many_light_sabers_do_you_own(name=\"Jack\"):\n if name == 'Zach':\n return 18\n else:\n return 0", "def how_many_light_sabers_do_you_own(*name):\n try:\n name = list(name)\n if name is []:\n name.append(\"\")\n \n return 18 if str(name[0]) == \"Zach\" else 0\n except:\n return 0", "def how_many_light_sabers_do_you_own(*name):\n if len(name)>0:\n return 18 if name == ('Zach',) else 0\n else:\n return 0", "def how_many_light_sabers_do_you_own(name = None):\n if not name:\n return 0\n return 18 if name == \"Zach\" else 0", "def how_many_light_sabers_do_you_own(name = \"George\"):\n return 18 if name == \"Zach\" else 0", "def how_many_light_sabers_do_you_own(name='Hugo'):\n return 18 if name=='Zach' else 0", "def how_many_light_sabers_do_you_own(name='p'):\n return 18 if name=='Zach' else 0", "def how_many_light_sabers_do_you_own(*name):\n return sum([18 if i == 'Zach' else 0 for i in name])", "def how_many_light_sabers_do_you_own(name =\"stam\"):\n return 18 if name == \"Zach\" else 0", "def how_many_light_sabers_do_you_own(name=''):\n if name == \"Zach\".capitalize():\n return 18\n else:\n return 0", "def how_many_light_sabers_do_you_own(*name):\n return 0 if len(name) == 0 else 18 if name[0]==\"Zach\" else 0", "def how_many_light_sabers_do_you_own(name = 0):\n d = {'Zach':18}\n return d.get(name,0)", "def how_many_light_sabers_do_you_own(name='aring'):\n try:\n return 18 if name == 'Zach' else 0\n \n except:\n return 0\n", "def how_many_light_sabers_do_you_own(name='kendall jenner'):\n if name == 'Zach':\n return 18\n else:\n return 0 ", "def how_many_light_sabers_do_you_own(name='s'):\n if name == \"Zach\":\n return 18\n else:\n return 0", "# end goal - the function should return 18 lightsabers for Zach and 0 for anyone else\n# use a ternary operator or simple if/else\n\n# input - string, name\n# output - integer\n# edge cases - lower case names, invalid unittests \n\n# function that takes name argument\ndef how_many_light_sabers_do_you_own(name=''):\n# if name is Zach\n if name == \"Zach\":\n# return 18\n return 18\n# else\n else:\n# return 0\n return 0", "def how_many_light_sabers_do_you_own(name=\"!\"):\n return 18 if name==\"Zach\" else 0", "def how_many_light_sabers_do_you_own(s=''):\n# if name == 'Zach':\n# return 18\n# return 0\n return s.count('Zach') * 18", "def how_many_light_sabers_do_you_own(name=\"None\"):\n return 18*int(name == \"Zach\")", "def how_many_light_sabers_do_you_own(*args):\n if len(args) == 0:\n return 0\n if args[0] == 'Zach':\n return 18\n return 0", "def how_many_light_sabers_do_you_own(*args, zach=18):\n return zach if \"Zach\" in args else 0", "def how_many_light_sabers_do_you_own(name='a'):\n return {'Zach' : 18}.get(name, 0)", "def how_many_light_sabers_do_you_own(name=\"Carlos\"):\n if name == \"Zach\":\n return 18\n else:\n return 0", "how_many_light_sabers_do_you_own = lambda name = 'zach': 18 if name == 'Zach' else 0", "def how_many_light_sabers_do_you_own(*name):\n try: name\n except NameError:\n return 0\n else:\n if 'Zach' in name:\n return 18\n return 0", "def how_many_light_sabers_do_you_own(name= 'abc'):\n return 18 if name == 'Zach' else 0", "def how_many_light_sabers_do_you_own(name = 'xxx'):\n return 18 if name in'Zach' else 0", "def how_many_light_sabers_do_you_own(name = 'Boob'):\n return [0, 18][name == 'Zach']", "def how_many_light_sabers_do_you_own(n=0): \n return 0 if n!='Zach' else 18", "def how_many_light_sabers_do_you_own(name=\"\"):\n if name == \"Zach\":\n return 18\n elif name == \"\":\n return 0\n else:\n return 0"]
{"fn_name": "how_many_light_sabers_do_you_own", "inputs": [["Zach"], ["zach"]], "outputs": [[18], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
9,745
def how_many_light_sabers_do_you_own(*name):
0bd7da6d86fd671133e54b43375dceac
UNKNOWN
**Getting Familiar:** LEET: (sometimes written as "1337" or "l33t"), also known as eleet or leetspeak, is another alphabet for the English language that is used mostly on the internet. It uses various combinations of ASCII characters to replace Latinate letters. For example, leet spellings of the word leet include 1337 and l33t; eleet may be spelled 31337 or 3l33t. GREEK: The Greek alphabet has been used to write the Greek language since the 8th century BC. It was derived from the earlier Phoenician alphabet, and was the first alphabetic script to have distinct letters for vowels as well as consonants. It is the ancestor of the Latin and Cyrillic scripts.Apart from its use in writing the Greek language, both in its ancient and its modern forms, the Greek alphabet today also serves as a source of technical symbols and labels in many domains of mathematics, science and other fields. **Your Task :** You have to create a function **GrεεκL33t** which takes a string as input and returns it in the form of (L33T+Grεεκ)Case. Note: The letters which are not being converted in (L33T+Grεεκ)Case should be returned in the lowercase. **(L33T+Grεεκ)Case:** A=α (Alpha) B=β (Beta) D=δ (Delta) E=ε (Epsilon) I=ι (Iota) K=κ (Kappa) N=η (Eta) O=θ (Theta) P=ρ (Rho) R=π (Pi) T=τ (Tau) U=μ (Mu) V=υ (Upsilon) W=ω (Omega) X=χ (Chi) Y=γ (Gamma) **Examples:** GrεεκL33t("CodeWars") = "cθδεωαπs" GrεεκL33t("Kata") = "κατα"
["def gr33k_l33t(string):\n gl = { \"a\":\"\u03b1\", \"b\":\"\u03b2\", \"d\":\"\u03b4\", \"e\":\"\u03b5\", \"i\":\"\u03b9\", \"k\":\"\u03ba\", \"n\":\"\u03b7\", \"o\":\"\u03b8\", \n \"p\":\"\u03c1\", \"r\":\"\u03c0\", \"t\":\"\u03c4\", \"u\":\"\u03bc\", \"v\":\"\u03c5\", \"w\":\"\u03c9\", \"x\":\"\u03c7\", \"y\":\"\u03b3\" }\n return \"\".join([gl.get(letter, letter) for letter in string.lower()])", "lib = {'a':'\u03b1', 'b':'\u03b2', 'd':'\u03b4', 'e':'\u03b5', 'i':'\u03b9', 'k':'\u03ba', 'n':'\u03b7', 'o':'\u03b8', 'p':'\u03c1', 'r':'\u03c0', 't':'\u03c4', 'u':'\u03bc', 'v':'\u03c5', 'w':'\u03c9', 'x':'\u03c7', 'y':'\u03b3'}\ngr33k_l33t = lambda s: \"\".join([lib[c] if c in lib else c for c in s.lower()])", "def gr33k_l33t(string):\n doc = { e[0].lower():e[-1] for e in 'A=\u03b1 B=\u03b2 D=\u03b4 E=\u03b5 I=\u03b9 K=\u03ba N=\u03b7 O=\u03b8 P=\u03c1 R=\u03c0 T=\u03c4 U=\u03bc V=\u03c5 W=\u03c9 X=\u03c7 Y=\u03b3'.split() }\n return ''.join( doc.get(e,e) for e in string.lower() )", "def gr33k_l33t(s):\n doc = {\n 'a':'\u03b1', 'b':'\u03b2', 'd':'\u03b4', 'e':'\u03b5', 'i':'\u03b9', 'k':'\u03ba', 'n':'\u03b7', 'o':'\u03b8', \n 'p':'\u03c1', 'r':'\u03c0', 't':'\u03c4', 'u':'\u03bc', 'v':'\u03c5', 'w':'\u03c9', 'x':'\u03c7', 'y':'\u03b3'\n }\n return ''.join(doc.get(e ,e) for e in s.lower())", "trans = str.maketrans(\"abdeiknoprtuvwxy\", \"\u03b1\u03b2\u03b4\u03b5\u03b9\u03ba\u03b7\u03b8\u03c1\u03c0\u03c4\u03bc\u03c5\u03c9\u03c7\u03b3\")\n\ndef gr33k_l33t(string):\n return string.lower().translate(trans)", "def gr33k_l33t(string):\n return string.lower().translate(str.maketrans('abdeiknoprtuvwxy', '\u03b1\u03b2\u03b4\u03b5\u03b9\u03ba\u03b7\u03b8\u03c1\u03c0\u03c4\u03bc\u03c5\u03c9\u03c7\u03b3'))", "def gr33k_l33t(string):\n greek = {'A':'\u03b1','B':'\u03b2','D':'\u03b4','E':'\u03b5','I':'\u03b9','K':'\u03ba','N':'\u03b7','O':'\u03b8','P':'\u03c1','R':'\u03c0','T':'\u03c4','U':'\u03bc','V':'\u03c5','W':'\u03c9','X':'\u03c7','Y':'\u03b3'}\n return ''.join(greek.get(c.upper(), c.lower()) for c in string)", "table = {'A': '\u03b1', 'B': '\u03b2', 'D': '\u03b4', 'E': '\u03b5', 'I': '\u03b9', 'K': '\u03ba',\n 'N': '\u03b7', 'O': '\u03b8', 'P': '\u03c1', 'R': '\u03c0', 'T': '\u03c4', 'U': '\u03bc',\n 'V': '\u03c5', 'W': '\u03c9', 'X': '\u03c7', 'Y': '\u03b3'}\n\ndef gr33k_l33t(string):\n result = []\n for a in string.upper():\n try:\n result.append(table[a])\n except KeyError:\n result.append(a.lower())\n return ''.join(result)\n", "# -*- coding: utf-8 -*-\na = {'A': '\u03b1', 'B': '\u03b2', 'D': '\u03b4', 'E': '\u03b5', 'I': '\u03b9', 'K': '\u03ba', 'N': '\u03b7', 'O': '\u03b8', 'P': '\u03c1', 'R': '\u03c0', 'T': '\u03c4',\n 'U': '\u03bc', 'V': '\u03c5', 'W': '\u03c9', 'X': '\u03c7', 'Y': '\u03b3'}\n\n\ndef gr33k_l33t(string):\n b = list(string.upper())\n return ''.join([a[x] if x in a else x.lower() for x in b])"]
{"fn_name": "gr33k_l33t", "inputs": [["codewars"], ["kata"], ["kumite"], ["greekleet"], ["This Kata's Sensei is Divyansh"], ["Any reviews about CS50"], ["Man is still the most extraordinary computer of all."], ["I do not fear computers. I fear the lack of them."], ["Do you also think these quotes are conflicting each other?"]], "outputs": [["c\u03b8\u03b4\u03b5\u03c9\u03b1\u03c0s"], ["\u03ba\u03b1\u03c4\u03b1"], ["\u03ba\u03bcm\u03b9\u03c4\u03b5"], ["g\u03c0\u03b5\u03b5\u03bal\u03b5\u03b5\u03c4"], ["\u03c4h\u03b9s \u03ba\u03b1\u03c4\u03b1's s\u03b5\u03b7s\u03b5\u03b9 \u03b9s \u03b4\u03b9\u03c5\u03b3\u03b1\u03b7sh"], ["\u03b1\u03b7\u03b3 \u03c0\u03b5\u03c5\u03b9\u03b5\u03c9s \u03b1\u03b2\u03b8\u03bc\u03c4 cs50"], ["m\u03b1\u03b7 \u03b9s s\u03c4\u03b9ll \u03c4h\u03b5 m\u03b8s\u03c4 \u03b5\u03c7\u03c4\u03c0\u03b1\u03b8\u03c0\u03b4\u03b9\u03b7\u03b1\u03c0\u03b3 c\u03b8m\u03c1\u03bc\u03c4\u03b5\u03c0 \u03b8f \u03b1ll."], ["\u03b9 \u03b4\u03b8 \u03b7\u03b8\u03c4 f\u03b5\u03b1\u03c0 c\u03b8m\u03c1\u03bc\u03c4\u03b5\u03c0s. \u03b9 f\u03b5\u03b1\u03c0 \u03c4h\u03b5 l\u03b1c\u03ba \u03b8f \u03c4h\u03b5m."], ["\u03b4\u03b8 \u03b3\u03b8\u03bc \u03b1ls\u03b8 \u03c4h\u03b9\u03b7\u03ba \u03c4h\u03b5s\u03b5 q\u03bc\u03b8\u03c4\u03b5s \u03b1\u03c0\u03b5 c\u03b8\u03b7fl\u03b9c\u03c4\u03b9\u03b7g \u03b5\u03b1ch \u03b8\u03c4h\u03b5\u03c0?"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,990
def gr33k_l33t(string):
b832095f384c4fc6316716e3dc5234f5
UNKNOWN
# Task Two integer numbers are added using the column addition method. When using this method, some additions of digits produce non-zero carries to the next positions. Your task is to calculate the number of non-zero carries that will occur while adding the given numbers. The numbers are added in base 10. # Example For `a = 543 and b = 3456,` the output should be `0` For `a = 1927 and b = 6426`, the output should be `2` For `a = 9999 and b = 1`, the output should be `4` # Input/Output - `[input]` integer `a` A positive integer. Constraints: `1 ≤ a ≤ 10^7` - `[input]` integer `b` A positive integer. Constraints: `1 ≤ b ≤ 10^7` - `[output]` an integer
["def number_of_carries(a, b):\n ans, carrie = 0, 0\n while a > 0 or b > 0:\n carrie = (a%10 + b%10 + carrie) // 10 \n ans += [0,1][carrie > 0]\n a //= 10\n b //= 10\n return ans", "def number_of_carries(a, b):\n i=1\n carry_over=0\n counter=0\n length1=len(str(a))\n length2=len(str(b))\n if length1>length2:\n while length2-i>=0:\n if int(str(a)[length1-i])+int(str(b)[length2-i])+carry_over>=10:\n counter+=1\n carry_over=1\n i+=1\n else:\n carry_over=0\n i+=1\n while length1-i>=0:\n if int(str(a)[length1-i])+carry_over>=10:\n counter+=1\n carry_over=1\n i+=1\n else:\n carry_over=0\n i+=1\n elif length2>length1:\n while length1-i>=0:\n if int(str(a)[length1-i])+int(str(b)[length2-i])+carry_over>=10:\n counter+=1\n carry_over=1\n i+=1\n else:\n carry_over=0\n i+=1\n while length2-i>=0:\n if int(str(b)[length2-i])+carry_over>=10:\n counter+=1\n carry_over=1\n i+=1\n else:\n carry_over=0\n i+=1\n elif length2==length1:\n while length1-i>=0:\n if int(str(a)[length1-i])+int(str(b)[length2-i])+carry_over>=10:\n counter+=1\n carry_over=1\n i+=1\n else:\n carry_over=0\n i+=1\n return counter\n \n", "def number_of_carries(a, b):\n a, b, c, r = [int(x) for x in f\"000000{a}\"], [int(x) for x in f\"000000{b}\"], 0, 0\n for x, y in zip(reversed(a), reversed(b)):\n c = x + y + c > 9\n r += c\n return r", "from itertools import zip_longest\nhelp = lambda n: map(int, reversed(str(n)))\n\ndef number_of_carries(a, b):\n carry = res = 0\n for x,y in zip_longest(help(a), help(b), fillvalue=0):\n tmp = x + y + carry\n res += tmp > 9\n carry = tmp // 10\n return res", "from itertools import zip_longest\ndef number_of_carries(a, b):\n carry,li = [0],[]\n for i, j in zip_longest(str(a)[::-1], str(b)[::-1], fillvalue='0'):\n s = int(i) + int(j) + carry[-1]\n li.append(s % 10)\n if s > 9 : carry.append(int(str(s)[0])) ; continue\n carry.append(0)\n return carry.count(1)", "from itertools import zip_longest\n\ndef number_of_carries(a, b):\n x, y = str(a)[::-1], str(b)[::-1]\n result = c = 0\n for a, b in zip_longest(map(int, x), map(int, y), fillvalue=0):\n c = (a + b + c) > 9\n result += c\n return result", "def number_of_carries(a, b):\n a, b = str(a)[::-1], str(b)[::-1]\n l = max(len(a), len(b))\n carry, carries = 0, 0\n for col in [int(m)+int(n) for m, n in zip(f\"{a:<0{l}s}\", f\"{b:<0{l}s}\")]:\n carry = (col + carry) > 9\n carries += carry\n return carries", "def number_of_carries(a, b):\n # Reverse and align\n a, b = str(a)[::-1], str(b)[::-1]\n while len(a) < len(b):\n a += '0'\n while len(a) > len(b):\n b += '0'\n # Perform base 10 addition\n carry, carries = 0, 0\n for ad, bd in zip(a, b):\n ad, bd = int(ad), int(bd)\n nd = ad + bd + carry\n if nd > 9:\n carry = (nd - (nd % 10)) // 10\n carries += 1\n else:\n carry = 0\n return carries\n", "def number_of_carries(a, b):\n c = [0]\n while a or b:\n c, a, b = c + [(c[-1] + a % 10 + b % 10) // 10], a // 10, b // 10\n return sum(c)", "number_of_carries=r=lambda a,b,c=0:a+b+c and c+r(a//10,b//10,a%10+b%10+c>9)"]
{"fn_name": "number_of_carries", "inputs": [[543, 3456], [1927, 6426], [9999, 1], [1234, 5678]], "outputs": [[0], [2], [4], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,841
def number_of_carries(a, b):
301e6d672e7462b9ffa1d53e1d2302ab
UNKNOWN
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized **only** if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). ## Examples ```python to_camel_case("the-stealth-warrior") # returns "theStealthWarrior" to_camel_case("The_Stealth_Warrior") # returns "TheStealthWarrior" ```
["def to_camel_case(text):\n removed = text.replace('-', ' ').replace('_', ' ').split()\n if len(removed) == 0:\n return ''\n return removed[0]+ ''.join([x.capitalize() for x in removed[1:]])", "import re\ndef to_camel_case(text):\n return re.sub('[_-](.)', lambda x: x.group(1).upper(), text)", "def to_camel_case(text):\n return text[:1] + text.title()[1:].replace('_', '').replace('-', '')", "from re import compile as reCompile\n\nPATTERN = reCompile(r'(?i)[-_]([a-z])')\n\ndef to_camel_case(text):\n return PATTERN.sub(lambda m: m.group(1).upper(), text)\n", "def to_camel_case(text):\n return text[0] + ''.join([w[0].upper() + w[1:] for w in text.replace(\"_\", \"-\").split(\"-\")])[1:] if text else ''\n", "def to_camel_case(text):\n words = text.replace('_', '-').split('-')\n return words[0] + ''.join([x.title() for x in words[1:]])", "def to_camel_case(text):\n cap = False\n newText = ''\n for t in text:\n if t == '_' or t == '-':\n cap = True\n continue\n else:\n if cap == True:\n t = t.upper()\n newText = newText + t\n cap = False\n return newText", "def to_camel_case(text):\n return \"\".join([i if n==0 else i.capitalize() for n,i in enumerate(text.replace(\"-\",\"_\").split(\"_\"))])"]
{"fn_name": "to_camel_case", "inputs": [[""], ["the_stealth_warrior"], ["The-Stealth-Warrior"], ["A-B-C"]], "outputs": [[""], ["theStealthWarrior"], ["TheStealthWarrior"], ["ABC"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,341
def to_camel_case(text):
7120875140b74e1f3f688480aaea89b6
UNKNOWN
The number n is Evil if it has an even number of 1's in its binary representation. The first few Evil numbers: 3, 5, 6, 9, 10, 12, 15, 17, 18, 20 The number n is Odious if it has an odd number of 1's in its binary representation. The first few Odious numbers: 1, 2, 4, 7, 8, 11, 13, 14, 16, 19 You have to write a function that determine if a number is Evil of Odious, function should return "It's Evil!" in case of evil number and "It's Odious!" in case of odious number. good luck :)
["def evil(n):\n return \"It's %s!\" % [\"Evil\",\"Odious\"][bin(n).count(\"1\")%2]", "def evil(n):\n return \"It's Evil!\" if bin(n).count('1')%2 == 0 else \"It's Odious!\"", "def evil(n):\n return 'It\\'s {}!'.format(('Evil', 'Odious')[bin(n).count('1') % 2])\n", "def evil(n):\n count = 0\n while n:\n n &= n - 1\n count += 1\n return \"It's Odious!\" if count & 1 else \"It's Evil!\"", "def evil(n):\n return f\"It's {('Evil', 'Odious')[bin(n).count('1')&1]}!\"", "def evil(n):\n return f\"It's {['Odious', 'Evil'][bin(n).count('1') % 2 == 0]}!\"", "def evil(n):\n return [\"It's Odious!\", \"It's Evil!\"][not str(bin(n)[2:]).count('1') % 2]", "def evil(n):\n return 'It\\'s Odious!' if bin(n)[2:].count('1')%2 else 'It\\'s Evil!'", "evil = lambda n: \"It's %s!\" % (\"Evil\" if len(list(filter(lambda d: d == '1', list(bin(n))))) % 2 == 0 else \"Odious\")", "def evil(n):\n evil = bin(n)[2:].count('1') % 2 == 0\n return \"It's Evil!\" if evil else \"It's Odious!\"", "def evil(n):\n count_one = str(bin(n)).count('1')\n if count_one % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"", "def evil(n):\n bin_number = bin(n)\n count = 0\n for i in bin_number:\n if i == '1':\n count += 1\n if count%2==0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"", "def evil(n):\n n=int(n)\n b =[2**i for i in range(100)]\n d = b[::-1]\n c=0\n for i in d:\n if int(n-i)>=0:\n c+=1\n n-=i\n if c%2==0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"\n pass", "def evil(n):\n return \"It's Odious!\" if bin(n).count('1') % 2 else \"It's Evil!\"", "def evil(n):\n n = (n & 0x5555555555555555) + ((n >> 1) & 0x5555555555555555)\n n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333)\n n = (n & 0x0F0F0F0F0F0F0F0F) + ((n >> 4) & 0x0F0F0F0F0F0F0F0F)\n n = (n & 0x00FF00FF00FF00FF) + ((n >> 8) & 0x00FF00FF00FF00FF)\n n = (n & 0x0000FFFF0000FFFF) + ((n >> 16) & 0x0000FFFF0000FFFF)\n n = (n & 0x00000000FFFFFFFF) + ((n >> 32) & 0x00000000FFFFFFFF)\n \n return \"It's Odious!\" if n % 2 == 1 else \"It's Evil!\"", "evil = lambda n: [\"It's Evil!\",\"It's Odious!\"][bin(n).count('1')%2]", "def evil(n):\n n_bin = bin(n)[2:]\n ones = n_bin.count('1')\n if (ones % 2 != 0):\n return 'It\\'s Odious!'\n else:\n return 'It\\'s Evil!'", "def evil(n): return \"It's Odious!\" if bin(n).count('1')&1 else \"It's Evil!\"", "def evil(a):\n return \"It's Odious!\" if str(bin(a)).count('1') % 2 == 1 else \"It's Evil!\"\n", "def evil(n):\n return \"It's {}!\".format(('Evil', 'Odious')[f'{n:b}'.count('1') % 2])", "def evil(n):\n return bin(n).count(\"1\") % 2 and \"It's Odious!\" or \"It's Evil!\"", "import re\n\ndef evil(n):\n binary = \"{0:b}\".format(n)\n \n return f\"It's {'Evil' if len(re.findall('1', binary)) % 2 == 0 else 'Odious'}!\"", "def evil(n):\n x = bin(n)\n counts = x.count(\"1\")\n if counts % 2==0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"", "def evil(n: int) -> str:\n \"\"\"\n Check if the given number is:\n - evil: it has an even number of 1's in its binary representation\n - odious: it has an odd number of 1's in its binary representation\n \"\"\"\n return f\"It's {'Odious' if str(bin(n)).count('1') % 2 else 'Evil'}!\"", "evil = lambda n: [\"It's Evil!\", \"It's Odious!\"][bin(n).count(\"1\") & 1]", "evil=lambda n: \"It's Odious!\" if bin(n).count(\"1\")%2 else \"It's Evil!\"", "def evil(n):\n c = 0\n while(n):\n c += n & 1\n n >>= 1\n \n if c & 1:\n return(\"It's Odious!\")\n else:\n return(\"It's Evil!\")", "def evil(n):\n return \"It's Odious!\" if sum(map(int, bin(n)[2:])) % 2 else \"It's Evil!\"", "def evil(n):\n return \"It's Odious!\" if sum(map(int, bin(n)[2:])) & 1 else \"It's Evil!\"", "def evil(n):\n return [\"It's Evil!\",\"It's Odious!\"][format(n, \"b\").count('1') % 2]", "def evil(n):\n count = 0\n while n > 0:\n if (n >> 1) << 1 != n:\n count += 1\n n >>= 1\n if count % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"", "def evil(n):\n e = 0\n while n:\n n = n & (n-1)\n e += 1\n return \"It's Evil!\" if e & 1 == 0 else \"It's Odious!\"", "def evil(n):\n return 'It\\'s Evil!' if bin(n)[2:].count('1') % 2 == 0 else 'It\\'s Odious!'", "def evil(n):\n _odious = \"It's Odious!\"\n _evil = \"It's Evil!\"\n \n is_evil = True\n for degree in evilometer(n):\n is_evil = not is_evil\n \n return is_evil and _evil or _odious\n \ndef evilometer(n):\n while n != 0:\n if n % 2 == 1:\n yield\n n = n // 2\n \ndef expand_to_string(n):\n binary = \"\"\n while n != 0:\n binary += str(n % 2)\n n = n // 2\n return binary", "def evil(n):\n return \"It's Evil!\" if not bin(n)[2:].count(\"1\")%2 else \"It's Odious!\"", "evil = lambda n: \"It's %s!\" % ['Evil', 'Odious'][bin(n).count('1') % 2]", "def evil(n):\n bin_rep = str(bin(n))\n state = \"Evil\" if bin_rep.count(\"1\") % 2 == 0 else \"Odious\"\n return f\"It's {state}!\"", "def evil(n):\n x=bin(n).count('1')\n test= 'Odious' if x%2 else 'Evil'\n return \"It's {}!\".format(test)\n#test = x.count(1)\n", "def evil(n):\n evil_odious_count = str(bin(n).replace(\"0b\", \"\")).count(\"1\")\n return \"It's Evil!\" if evil_odious_count % 2 == 0 else \"It's Odious!\"", "def evil(n):\n binary = bin(n)[2:]\n binary_string = str(binary)\n num_of_1s = binary_string.count('1')\n if num_of_1s % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"", "def evil(n):\n n=bin(n)\n count=0\n for x in n:\n if x==\"1\":\n count+=1\n return \"It's Evil!\" if count%2==0 else \"It's Odious!\"", "def evil(n):\n n = bin(n)[2:]\n\n return \"It's Evil!\" if n.count('1') % 2 == 0 else \"It's Odious!\"", "def evil(n):\n str = bin(n)\n total = sum(a == '1' for a in str)\n return \"It's Odious!\" if total%2 != 0 else \"It's Evil!\"", "def evil(n):\n return \"It's Odious!\" if int(str(bin(n))[2:].count('1'))&1 else \"It's Evil!\"", "evil = lambda n: \"It's \" + ('Odious!' if str(bin(n)).count('1')&1 else 'Evil!')", "def evil(n):\n num = bin(n)\n ones = 0 \n for i in num:\n if i == '1':\n ones += 1\n return \"It's Evil!\" if ones % 2 == 0 else \"It's Odious!\"", "def evil(n):\n return \"It's \" + (\"Evil!\" if bin(n).count(\"1\")%2==0 else \"Odious!\")", "def evil(n):\n binary = bin(n).replace(\"0b\", \"\") \n \n return \"It's Evil!\" if binary.count('1') % 2 == 0 else \"It's Odious!\"", "def evil(n):\n return \"It's Evil!\" if sum([1 for i in bin(n) if i=='1']) % 2 == 0 else \"It's Odious!\"", "def evil(n):\n binary = bin(n)\n \n ones = 0\n \n for i in binary:\n if i == '1':\n ones = ones + 1\n \n if ones % 2 == 0:\n return \"It's Evil!\"\n \n return \"It's Odious!\"", "def evil(n):\n return 'It\\'s Odious!' if sum(map(int,list(bin(n)[2:])))%2 else 'It\\'s Evil!'", "def evil(n):\n return 'It\\'s Evil!' if sum([int(i) for i in list(bin(n))[2:]]) % 2 == 0 else 'It\\'s Odious!'", "def evil(n):\n return \"It's {}!\".format('Odious' if sum(map(int, bin(n)[2:])) % 2 else 'Evil')", "def evil(n):\n a = bin(n)\n b = str(a)\n c = b.count(\"1\")\n if int(c) % 2 == 0: \n return \"It's Evil!\"\n if int(c) % 2 != 0:\n return \"It's Odious!\"\n", "def evil(n):\n binary = bin(n)[2:]\n\n count = 0\n for i in str(binary):\n if i == '1':\n count += 1\n \n if count % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"\n", "def evil(n):\n n=bin(n)\n s=str(n)\n c1=0\n for i in s:\n if(i=='1'):\n c1+=1\n if(c1%2==0):\n return(\"It's Evil!\")\n else:\n return(\"It's Odious!\")\n", "def evil(n):\n return [\"It's Evil!\", \"It's Odious!\"][f'{n:b}'.count('1')%2]", "def evil(n):\n b = format(n, 'b')\n if b.count('1') % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"", "def evil(n):\n return \"It's Evil!\" if (sum([i == '1' for i in str(bin(n))]) % 2 == 0) else \"It's Odious!\"", "def evil(n):\n n = str(bin(n))\n b = n.replace('0b', '')\n b = int(b)\n d = [int(i) for i in str(b)]\n if d.count(1) % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"\n", "def evil(n):\n return f\"It's {'Evil' if bin(n)[2:].count('1') %2==0 else 'Odious'}!\"\n", "def evil(n):\n n = bin(n) [2:]\n ans = n.count('1')\n if ans % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"\n", "def evil(n):\n c=bin(n)\n if str(c).count(\"1\")%2==0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"", "def evil(n):\n n_as_bin_string = \"{0:b}\".format(n)\n nof_ones = n_as_bin_string.count('1')\n return \"It's Odious!\" if nof_ones % 2 else \"It's Evil!\"", "def evil(n):\n count = 0\n while n:\n n &= n - 1\n count += 1\n if count & 1:\n return \"It's Odious!\"\n else:\n return\"It's Evil!\"", "def evil(n):\n return \"It's Odious!\" if int(bin(n).count(\"1\")) % 2 == 1 else \"It's Evil!\"", "def evil(n):\n if not bin(n)[2:].count('1')%2:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"", "def evil(n):\n print(bin(n))\n return \"It's Evil!\" if bin(n).count(\"1\") % 2 == 0 else \"It's Odious!\"", "def dec_to_binary(n, n_bits=8):\n bin_list=[]\n x=n\n while x>0:\n bit=x%2\n print(x, bit)\n bin_list.append(bit)\n print(bit)\n x//=2\n return bin_list\n\n\ndef evil(n):\n if dec_to_binary(n).count(1)%2==1:\n return \"It's Odious!\"\n else:\n return \"It's Evil!\"", "def binary_places(num):\n current_num = num\n values_list = []\n\n if current_num % 2 == 1:\n values_list.append(1)\n current_num -= 1\n else:\n values_list.append(0)\n\n if current_num > 0:\n cumulative_values = 2\n\n while cumulative_values <= current_num:\n values_list.insert(0, \"?\")\n cumulative_values *= 2\n\n this_place_value = 2 ** (len(values_list) - 1)\n current_place = 0\n\n while current_num > 1:\n\n if current_num >= this_place_value:\n values_list[current_place] = 1\n\n current_num -= this_place_value\n current_place += 1\n this_place_value /= 2\n else:\n values_list[current_place] = 0\n current_place += 1\n this_place_value /= 2\n\n for index, char in enumerate(values_list):\n if char == '?':\n values_list[index] = 0\n\n return values_list\n\n\ndef evil(n):\n num_list = binary_places(n)\n\n if 1 in num_list and num_list.count(1) % 2 == 0:\n return \"It's Evil!\"\n elif 1 in num_list and num_list.count(1) % 2 == 1:\n return \"It's Odious!\"\n", "def int_to_bin(n):\n \n bin_lst=[]\n x = n \n while x > 0: \n bit= x % 2\n bin_lst.append(bit)\n x//=2\n \n return bin_lst[::-1]\n\n \ndef evil(n):\n if int_to_bin(n).count(1)%2==1:\n return \"It's Odious!\"\n else: \n return \"It's Evil!\"\n\n", "def dec_to_binary(n):\n bin_list = []\n x = n\n \n while x > 0:\n bit = x % 2\n bin_list.append(bit)\n x //= 2\n \n return bin_list[::-1]\n\ndef evil(n):\n if dec_to_binary(n).count(1) % 2 == 1:\n return \"It's Odious!\"\n else:\n return \"It's Evil!\"\n pass", "def dec_to_bin(n):\n bin_list = []\n x = n\n\n while x > 0:\n bit = x % 2\n bin_list.append(bit)\n x //= 2\n \n return bin_list\n \ndef evil(n):\n binary = dec_to_bin(n)\n if binary.count(1) % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"\n", "def evil(n):\n bit = bin(n)\n if bit.count('1') % 2 == 0:\n return \"It's Evil!\"\n return \"It's Odious!\"", "def evil(n):\n count=0\n for x in str(bin(n)[2:]):\n if x==\"1\":\n count+=1\n return \"It's Odious!\" if count%2 else \"It's Evil!\"\n \n \n", "def evil(n):\n return \"It's Odious!\" if bin(n)[1:].count('1')%2==1 else \"It's Evil!\"", "def evil(n):\n s = [] # List reminder\n length = (n+2) // 2\n for i in range(length):\n r = n % 2\n s.append(r)\n if n // 2 == 0:\n break\n n = n//2\n \n s_reverse = s[::-1] # reverse list\n binary = \"\" # conversion to string\n for n in s_reverse:\n binary += str(n)\n \n count = 0 # Ones count\n for s in binary:\n if s == \"1\":\n count += 1\n \n if count % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"", "def evil(n):\n return \"It's {}!\".format([\"Evil\", \"Odious\"][bin(n)[2:].count(\"1\")%2])", "def evil(anum):\n thecount = bin(anum).count('1')\n if thecount % 2 == 0:\n return 'It\\'s Evil!'\n elif thecount % 2 != 0:\n return 'It\\'s Odious!'", "def evil(n):\n verdict = \"Odious\" if bin(n).count('1') % 2 else \"Evil\"\n return f\"It's {verdict}!\"", "def evil(n):\n return 'It\\'s Odious!' if n<=2 or bin(n)[2:].count('1')%2 else \"It's Evil!\"", "def evil(n):\n x = str(bin(n))[2:]\n t = 0\n for i in x:\n if i == \"1\":\n t+=1\n \n if t % 2 == 0 and t >= 1:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"", "def evil(n):\n binary=bin(n).replace(\"0b\", \"\")\n count=0\n for i in str(binary):\n if i=='1':\n count=count+1\n if count%2==0:\n return \"It's Evil!\"\n return \"It's Odious!\"", "def evil(n):\n count = 0\n for x in bin(n):\n if x=='1':\n count+= 1\n \n return \"It's Evil!\" if count%2==0 else \"It's Odious!\"\n", "def evil(n):\n n=str(bin(n)).count('1')\n return 'It\\'s {}!'.format(['Odious', 'Evil'][n%2==0])", "def evil(n):\n r = 0\n while n > 0:\n r += n%2\n n //= 2\n \n return \"It's Odious!\" if r%2 else \"It's Evil!\"", "def evil(n):\n count_1 = bin(n).count('1')\n msg = \"It's Evil!\"\n if count_1 % 2:\n msg = \"It's Odious!\"\n return msg", "def evil(n):\n bin_str = str(bin(n))\n sum = bin_str[2:].count('1')\n msg = \"It's Evil!\"\n if sum % 2:\n msg = \"It's Odious!\"\n return msg", "def evil(n):\n b=bin(n)\n l=list(b)\n return \"It's Evil!\" if l[2:].count(\"1\")%2==0 else \"It's Odious!\"", "def evil(n):\n n=bin(n)\n count_one=n.count('1')\n if count_one%2==0:\n return (\"It's Evil!\")\n else:\n return (\"It's Odious!\")", "def evil(n):\n if int(list(bin(n)).count('1')) % 2 != 0:\n print((list(bin(n)), list(bin(n)).count('1')))\n return \"It's Odious!\"\n else: \n print((list(bin(n))))\n return \"It's Evil!\"\n", "def evil(n):\n\n one_sum = 0\n while n:\n one_sum += n & 1\n n>>=1\n\n if one_sum % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"\n", "def evil(n):\n\n a = bin(n)\n b = list(\"\".join(a[2:]))\n c = sum([int(i) for i in b])\n\n if c % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\"", "def countSetBits(n):\n count = 0\n\n while (n):\n n = n & (n-1)\n count = count + 1\n\n return count\n\n\ndef evil(n):\n return \"It's Odious!\" if (countSetBits(n) % 2 == 1) else \"It's Evil!\"\n", "def evil(n):\n if f\"{n:b}\".count(\"1\") % 2:\n ret = \"Odious\"\n else:\n ret = \"Evil\"\n return f\"It's {ret}!\"", "def evil(n):\n return [\"It\\'s Odious!\", \"It\\'s Evil!\"][str(bin(n)).count('1')%2==0]", "def evil(n):\n return [\"It's Odious!\",\"It's Evil!\"][str(bin(n)).count('1')%2==0]", "def evil(n):\n return f\"It's {'Odious' if '{0:b}'.format(n).count('1')%2 else 'Evil'}!\"", "def evil(n):\n binario = bin(n)[2::]\n unos = binario.count(\"1\")\n return \"It's Odious!\" if unos%2!=0 else \"It's Evil!\"", "def evil(n):\n one_count = bin(n).count(\"1\")\n if one_count % 2 == 0:\n return \"It's Evil!\"\n else:\n return \"It's Odious!\""]
{"fn_name": "evil", "inputs": [[1], [2], [3]], "outputs": [["It's Odious!"], ["It's Odious!"], ["It's Evil!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
16,920
def evil(n):
a780511a5fbd6c228cf42d5d3867028a
UNKNOWN
# Task You are given a car odometer which displays the miles traveled as an integer. The odometer has a defect, however: it proceeds from digit `3` to digit `5` always skipping the digit `4`. This defect shows up in all positions (ones, tens, hundreds, etc). For example, if the odometer displays `15339` and the car travels another mile, the odometer changes to `15350` (instead of `15340`). Your task is to calculate the real distance, according The number the odometer shows. # Example For `n = 13` the output should be `12`(4 skiped). For `n = 15` the output should be `13`(4 and 14 skiped). For `n = 2003` the output should be `1461`. # Input/Output - `[input]` integer `n` The number the odometer shows. `1 <= n <= 999999999` - `[output]` an integer The real distance.
["tr=str.maketrans('56789','45678')\n\ndef faulty_odometer(n):\n return int(str(n).translate(tr),9)", "def faulty_odometer(n):\n result = 0\n digits = len(str(n))\n nonaryTranslation = \"\".join([str(int(x)-1) if int(x) >= 5 else x for x in list(str(n))])\n for i in nonaryTranslation:\n digits -= 1\n result += int(i) * (9**digits)\n return result\n \n", "def faulty_odometer(n):\n return int(str(n).translate(str.maketrans('56789','45678')),9)", "def faulty_odometer(n, acc=0):\n rang = len(str(n)) - 1\n amt = int('1' + '0' * rang)\n q = n//amt\n if q >= 4:\n n -= amt\n q -= 1\n res = n - (amt - 9 ** rang) * q\n left = n - amt*q\n acc += res - left\n return faulty_odometer(left, acc) if left >= 4 else acc + left", "faulty_odometer=lambda n:int(str(n).translate(''.maketrans('56789','45678')),9)", "faulty_odometer = lambda n: int(str(n).translate(str.maketrans('56789', '45678')), 9)", "faulty_odometer = lambda n: int(str(n).translate(''.maketrans('56789', '45678')), base = 9)", "def faulty_odometer(n): \n return sum('012356789'.index(c)*9**i for i, c in enumerate(str(n)[::-1]))", "def faulty_odometer(n):\n digits = []\n while n > 0:\n digits.append(n%10)\n n //= 10\n \n result = 0\n count = len(digits)\n for i in range(len(digits)-1, -1, -1):\n if digits[i] >= 5:\n digits[i] -= 1\n result += digits[i] * 9**(count-1)\n count -= 1\n return result"]
{"fn_name": "faulty_odometer", "inputs": [[13], [15], [55], [2005], [1500], [999999], [165826622]], "outputs": [[12], [13], [40], [1462], [1053], [531440], [69517865]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,516
def faulty_odometer(n):
23f0ca5cbcacfb2760d1fb6fb25b8767
UNKNOWN
Given a string, s, return a new string that orders the characters in order of frequency. The returned string should have the same number of characters as the original string. Make your transformation stable, meaning characters that compare equal should stay in their original order in the string s. ```python most_common("Hello world") => "lllooHe wrd" most_common("Hello He worldwrd") => "lllHeo He wordwrd" ``` Explanation: In the `hello world` example, there are 3 `'l'`characters, 2 `'o'`characters, and one each of `'H'`, `'e'`, `' '`, `'w'`, `'r'`, and `'d'`characters. Since `'He wrd'`are all tied, they occur in the same relative order that they do in the original string, `'Hello world'`. Note that ties don't just happen in the case of characters occuring once in a string. See the second example, `most_common("Hello He worldwrd")`should return `'lllHeo He wordwrd'`, not `'lllHHeeoo wwrrdd'`. **This is a key behavior if this method were to be used to transform a string on multiple passes.**
["from collections import Counter\n\ndef most_common(s):\n count = Counter(s)\n return ''.join(sorted(s, key=lambda c: -count[c]))", "def most_common(s):\n return ''.join(sorted(s, key = s.count, reverse = True))", "def most_common(stg):\n return \"\".join(sorted(stg, key=stg.count, reverse=True))", "def most_common(s):\n return \"\".join(sorted(s, key=lambda i: -s.count(i)))", "from collections import Counter\n\ndef most_common(s):\n count = Counter(s)\n return ''.join(t[2] for t in sorted( (-count[c], i, c) for i,c in enumerate(s) ))", "from collections import Counter\ndef most_common(s):\n c=Counter(s)\n return \"\".join(sorted(s,key=lambda x:-c[x]))", "def most_common(s):\n T = sorted(s,key = lambda x: -s.count(x))\n return ''.join(T)", "def most_common(s: str) -> str:\n return \"\".join(sorted(s, key = s.count, reverse = True))", "def most_common(a):\n return ''.join(sorted(a, key = a.count, reverse = True))", "most_common = lambda s: \"\".join(\"\".join(x[2] for x in y) for _, y in __import__(\"itertools\").groupby(sorted((-s.count(x), i, x) for i, x in enumerate(s)), lambda x: x[0])) "]
{"fn_name": "most_common", "inputs": [["Hello world"], [""], ["wubz dermatoglyphics"], ["Four score and seven years ago"], ["Hello He worldwrd"]], "outputs": [["lllooHe wrd"], [""], ["wubz dermatoglyphics"], [" eeeeorsorasarsaonnFucdvyg"], ["lllHeo He wordwrd"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,152
def most_common(s):
ce6a1fa2fc9893290c2a851866b2f67d
UNKNOWN
In this kata, you will be given a string of text and valid parentheses, such as `"h(el)lo"`. You must return the string, with only the text inside parentheses reversed, so `"h(el)lo"` becomes `"h(le)lo"`. However, if said parenthesized text contains parenthesized text itself, then that too must reversed back, so it faces the original direction. When parentheses are reversed, they should switch directions, so they remain syntactically correct (i.e. `"h((el)l)o"` becomes `"h(l(el))o"`). This pattern should repeat for however many layers of parentheses. There may be multiple groups of parentheses at any level (i.e. `"(1) (2 (3) (4))"`), so be sure to account for these. For example: ```python reverse_in_parentheses("h(el)lo") == "h(le)lo" reverse_in_parentheses("a ((d e) c b)") == "a (b c (d e))" reverse_in_parentheses("one (two (three) four)") == "one (ruof (three) owt)" reverse_in_parentheses("one (ruof ((rht)ee) owt)") == "one (two ((thr)ee) four)" ``` Input parentheses will always be valid (i.e. you will never get "(()").
["def reverse_in_parentheses(s):\n stack = []\n for i in s:\n stack.append(i)\n \n if i == ')':\n opening = len(stack) - stack[::-1].index('(') - 1\n stack.append(''.join([i[::-1].translate(str.maketrans('()',')(')) for i in stack[opening:][::-1]])) \n del stack[opening:-1]\n \n return ''.join(stack) ", "def reverse_in_parentheses(string):\n a = 0\n for n in range(string.count(\"(\")):\n a, b = string.find(\"(\", a), 0\n for i in range(a, len(string)):\n if string[i] == \"(\": b += 1\n elif string[i] == \")\": b -= 1\n \n if b == 0: break\n a += 1\n string = string[:a] + string[a:i][::-1].translate(str.maketrans(\")(\", \"()\")) + string[i:]\n return string", "def reverse_in_parentheses(s):\n\n def find_pairs(s):\n stack, pairs = [], {}\n for i, c in enumerate(s):\n if c == '(': stack.append(i)\n if c == ')':\n opening = stack.pop()\n pairs[opening] = i\n pairs[i] = opening\n return pairs\n\n def walk(start, end, direction):\n while start != end:\n if s[start] not in '()':\n yield s[start]\n else:\n yield '('\n yield from walk(pairs[start]-direction, start, -direction)\n yield ')'\n start = pairs[start]\n start += direction\n \n pairs = find_pairs(s)\n return ''.join(walk(0, len(s), 1))", "import itertools\n\ndef reverse_in_parentheses(string):\n stream = iter(string)\n return _recurse(stream)\n\ndef safe_rev(s):\n return s[::-1].translate(str.maketrans('()', ')('))\n\ndef _recurse(stream):\n ret = ''\n for c in stream:\n if c == '(':\n ret += c\n ret += safe_rev(_recurse(stream)) + ')'\n elif c == ')':\n break\n else:\n ret += c\n return ret\n", "def reverse_in_parentheses(string):\n counter = 0\n res = [\"\"]\n \n for i in string:\n \n if i == \"(\":\n res.append(\"\")\n counter += 1\n \n elif i == \")\":\n counter -= 1\n \n if counter % 2 == 0:\n res[counter] += \"(\" + res.pop() + \")\"\n else:\n res[counter] = \"(\" + res.pop() + \")\" + res[counter] \n \n elif counter % 2 == 0:\n res[counter] += i\n \n else:\n res[counter] = i + res[counter]\n \n return res[0]", "def reverse_in_parentheses(string):\n for i in range(len(string)):\n if string[i]==\"(\":\n finder,depth=i,1\n while depth>int():depth,finder=depth+\")(\".index(string[finder+1])-1+\")(\".index(string[finder+1]) if string[finder+1] in \"()\" else depth,finder+1\n string=string[:i+1]+\"\".join([\"()\"[\")(\".index(y)] if y in \"()\" else y for y in list(reversed(string[i+1:finder]))])+string[finder:]\n return string", "def reverse_in_parentheses(string):\n for i in range(len(string)):\n if string[i]==\"(\":\n walker,depth=i,1\n while depth>int():depth,walker=depth+\")(\".index(string[walker+1])-1+\")(\".index(string[walker+1]) if string[walker+1] in \"()\" else depth,walker+1\n string=string[:i+1]+\"\".join([\"()\"[\")(\".index(y)] if y in \"()\" else y for y in list(reversed(string[i+1:walker]))])+string[walker:]\n return string", "def reverse_in_parentheses(string):\n for i in range(len(string)):\n if string[i]==\"(\":\n counter,k=i,1\n while k>int():k,counter=k+\")(\".index(string[counter+1])-1+\")(\".index(string[counter+1]) if string[counter+1] in \"()\" else k,counter+1\n string=string[:i+1]+\"\".join([\"()\"[\")(\".index(y)] if y in \"()\" else y for y in list(reversed(string[i+1:counter]))])+string[counter:]\n return string", "swap_parentheses = str.maketrans('()', ')(')\n\ndef reverse_in_parentheses(s):\n stack, res = [], list(s)\n for i, c in enumerate(s):\n if c == '(': stack.append(i)\n elif c == ')':\n j = stack.pop()\n res[j + 1:i] = ''.join(res[i - 1:j:-1]).translate(swap_parentheses)\n return ''.join(res)", "def pairs(s):\n stack, pairs = [], {}\n for i, c in enumerate(s):\n if c == '(': stack.append(i)\n elif c == ')': pairs[stack.pop()] = i\n return pairs\n\nswap_parentheses = str.maketrans('()', ')(')\n\ndef reverse_in_parentheses(s):\n res = list(s)\n for i, j in pairs(s).items():\n res[i + 1:j] = ''.join(res[j - 1:i:-1]).translate(swap_parentheses)\n return ''.join(res)"]
{"fn_name": "reverse_in_parentheses", "inputs": [["h(el)lo"], ["a ((d e) c b)"], ["one (two (three) four)"], ["one (ruof ((rht)ee) owt)"], [""], ["many (parens) on (top)"], ["( ( ) (()) )"]], "outputs": [["h(le)lo"], ["a (b c (d e))"], ["one (ruof (three) owt)"], ["one (two ((thr)ee) four)"], [""], ["many (snerap) on (pot)"], ["( (()) ( ) )"]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,817
def reverse_in_parentheses(string):
93a3e87100c5ace16506a9baf707eb5c
UNKNOWN
You're writing an excruciatingly detailed alternate history novel set in a world where [Daniel Gabriel Fahrenheit](https://en.wikipedia.org/wiki/Daniel_Gabriel_Fahrenheit) was never born. Since Fahrenheit never lived the world kept on using the [Rømer scale](https://en.wikipedia.org/wiki/R%C3%B8mer_scale), invented by fellow Dane [Ole Rømer](https://en.wikipedia.org/wiki/Ole_R%C3%B8mer) to this very day, skipping over the Fahrenheit and Celsius scales entirely. Your magnum opus contains several thousand references to temperature, but those temperatures are all currently in degrees Celsius. You don't want to convert everything by hand, so you've decided to write a function, `celsius_to_romer()` that takes a temperature in degrees Celsius and returns the equivalent temperature in degrees Rømer. For example: `celsius_to_romer(24)` should return `20.1`.
["def celsius_to_romer(temp):\n # Converts temperature in degrees Celsius to degrees Romer\n return (temp * 21 / 40) + 7.5\n", "def celsius_to_romer(temp):\n return temp * 21 / 40 + 7.5\n", "def celsius_to_romer(c):\n return c * 21 / 40 + 7.5 ", "def celsius_to_romer(x):\n return x * 21 / 40 + 7.5", "def celsius_to_romer(temp):\n # Your code here.\n # equation for Celcius to Romer is [\u00b0C] \u00d7 \u200a21\u204440 + 7.5\n return (((float(temp) * 21)/40) + 7.5)", "celsius_to_romer=lambda x:(x*21.0/40)+7.5", "def celsius_to_romer(temp):\n temp *= 21\n temp /=40\n temp += 7.5\n return(temp)\n", "celsius_to_romer=lambda t: t * 21 / 40.0 + 7.5 ", "def celsius_to_romer(temp):\n # Your code here.\n #temp*(21/40)+7.5\n \n return (temp*(21/40)+7.5)", "def celsius_to_romer(temp):\n # Your code here.\n #temp*(21/40)+7.5\n \n return (temp*(21/40)+7.5)\n#this turns Celsius to Romer. Need the conversion factor (equation of conversion). temp is in the input temperature. you use the conversion equation. follor PEMDAS.\n"]
{"fn_name": "celsius_to_romer", "inputs": [[24], [8], [29]], "outputs": [[20.1], [11.7], [22.725]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,081
def celsius_to_romer(temp):
b576bb7d414ebf950e5cec3f71438288
UNKNOWN
You have invented a time-machine which has taken you back to ancient Rome. Caeser is impressed with your programming skills and has appointed you to be the new information security officer. Caeser has ordered you to write a Caeser cipher to prevent Asterix and Obelix from reading his emails. A Caeser cipher shifts the letters in a message by the value dictated by the encryption key. Since Caeser's emails are very important, he wants all encryptions to have upper-case output, for example: If key = 3 "hello" -> KHOOR If key = 7 "hello" -> OLSSV Input will consist of the message to be encrypted and the encryption key.
["def caeser(message, key):\n return ''.join(chr(65 + (ord(c.upper()) + key - 65) % 26) if c.isalpha() else c for c in message)", "def caeser(message, key):\n return ''.join(chr(ord(x)+key if ord(x)+key <= 122 else ord(x)+key-122 + 96).upper() if x.isalpha() else x for x in message)", "import string\n\ndef caeser(message, key):\n return ''.join([chr((ord(s.upper()) + key - 65) % 26 + 65) if s in string.ascii_lowercase else s for s in message])", "def caeser(m, k):\n r=\"\"; M=m.upper()\n for c in M:\n if c>='A' and c<='Z': r+=chr(65+(ord(c)-65+k)%26)\n else: r+=c\n return r", "def caeser(message, key): return''.join('ABCDEFGHIJKLMNOPQRSTUVWXYZ'[('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.index(el)+key)%len('ABCDEFGHIJKLMNOPQRSTUVWXYZ')] if el in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' else el for el in message.upper())", "def caeser(message, key):\n return \"\".join( char_if(c,key) for c in message.upper() )\n\ndef char_if(char, key):\n alpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n return alpha[(alpha.index(char)+key)%26] if char in alpha else char\n", "def caeser(m, k):\n m = m.lower()\n return ''.join([chr((ord(i)-ord('a')+k)%26+ord('a')).upper() if i.isalpha() else i for i in m])", "import string\n\ndef caeser(message, key=1):\n letters = string.ascii_lowercase\n mask = letters[key:] + letters[:key]\n trantab = str.maketrans(letters, mask)\n return message.translate(trantab).upper()"]
{"fn_name": "caeser", "inputs": [["This is a message", 0], ["who are you?", 18], ["..5tyu..", 25], ["..#$%^..", 0], ["..#$%^..", 26], ["final one", 9]], "outputs": [["THIS IS A MESSAGE"], ["OZG SJW QGM?"], ["..5SXT.."], ["..#$%^.."], ["..#$%^.."], ["ORWJU XWN"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,437
def caeser(message, key):
6c639b06057f18f50b57048c5fd94b8d
UNKNOWN
### Longest Palindrome Find the length of the longest substring in the given string `s` that is the same in reverse. As an example, if the input was “I like racecars that go fast”, the substring (`racecar`) length would be `7`. If the length of the input string is `0`, the return value must be `0`. ### Example: ``` "a" -> 1 "aab" -> 2 "abcde" -> 1 "zzbaabcd" -> 4 "" -> 0 ```
["\"\"\"\n***************************************\n* O(n) time complexity solution ! *\n***************************************\n\"\"\"\n\ndef longest_palindrome (s):\n\n maxPal, tmpPal = 0, 1\n count_dct = {}\n inPal = False\n \n for i,l in enumerate(s):\n \n count_dct[l] = count_dct.get(l,0) + 1\n \n if not inPal and count_dct[l] >= 2: # might encounter a palindrome, there...\n if l == s[i-1]: # ... palindrome with double character in the middle\n inPal = True\n tmpPal = 2\n \n elif l == s[i-2]: # ... palindrome with one \"peak\" character in the middle\n inPal = True\n tmpPal = 3\n \n elif inPal and l == s[max(0, i-tmpPal-1)]: # still in a palindrome...\n tmpPal += 2\n \n else: # goes out of this palindrome\n inPal = False\n tmpPal = 1\n \n maxPal = max(maxPal, tmpPal)\n \n return maxPal", "def longest_palindrome (s):\n if not s: return 0\n substrings = [s[i:j] for i in range(0,len(s)) for j in range(i,len(s)+1)]\n return max(len(s) for s in substrings if s == s[::-1])", "def longest_palindrome (s):\n return max((n for n in range(len(s), 0, -1) for i in range(len(s)-n+1) if s[i:i+n] == s[i:i+n][::-1]), default=0)", "def longest_palindrome (s):\n if s: return max(map(len, filter(palindrome, substrings(s))))\n else: return 0\n \ndef palindrome (s):\n return s[::-1] == s\n \ndef substrings (s):\n return [s[i:j+1] for i in range(0, len(s)) for j in range(i, len(s))]", "def longest_palindrome (s):\n\n longest = 0\n\n for j in range(1, len(s)+1):\n for i in range(j):\n t = s[i:j]\n if t == t[::-1]:\n longest = max(longest, len(t))\n \n return longest"]
{"fn_name": "longest_palindrome", "inputs": [["a"], ["aa"], ["baa"], ["aab"], ["baabcd"], ["baablkj12345432133d"], ["I like racecars that go fast"], ["abcdefghba"], [""], ["FourscoreandsevenyearsagoourfaathersbroughtforthonthiscontainentanewnationconceivedinzLibertyanddedicatedtothepropositionthatallmenarecreatedequalNowweareengagedinagreahtcivilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth"]], "outputs": [[1], [2], [2], [2], [4], [9], [7], [1], [0], [7]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,962
def longest_palindrome (s):
ed2b3c72e6d3e111621c61487a4c45fa
UNKNOWN
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: Give you two number `m` and `n`(two positive integer, m < n), make a triangle pattern with number sequence `m to n`. The order is clockwise, starting from the top corner, like this: ``` When m=1 n=10 triangle is: 1 9 2 8 0 3 7 6 5 4 ``` Note: The pattern only uses the last digit of each number; Each row separated by "\n"; Each digit separated by a space; Left side may need pad some spaces, but don't pad the right side; If `m to n` can not make the triangle, return `""`. # Some examples: ``` makeTriangle(1,3) should return: 1 3 2 makeTriangle(6,20) should return: 6 7 7 6 8 8 5 0 9 9 4 3 2 1 0 makeTriangle(1,12) should return "" ```
["def make_triangle(m,n):\n lns, sm = 0, 0\n while sm < n - m + 1:\n lns += 1\n sm += lns\n if sm > n - m + 1: return \"\"\n matrix = [[0] * (i + 1) for i in range(lns)]\n y, x, s = 0, 0, 0\n ds = ((1, 1), (0, -1), (-1, 0))\n dy, dx = ds[s]\n for i in range(m, n + 1):\n matrix[y][x] = str(i % 10)\n if not 0 <= y + dy < len(matrix) or not 0 <= x + dx < len(matrix[y + dy]) or matrix[y + dy][x + dx]:\n s += 1\n dy, dx = ds[s % 3]\n y, x = y + dy, x + dx\n return \"\\n\".join(\" \".join(ln).center(len(matrix[-1]) * 2 - 1).rstrip() for ln in matrix)", "from itertools import cycle\nfrom math import sqrt\n\n\ndef make_triangle(start, end):\n rows = sqrt(8 * (end - start) + 9) / 2 - .5\n\n if not rows.is_integer():\n return ''\n\n rows = int(rows)\n row, col, value = -1, -1, start\n\n directions = cycle([(1, 0), (0, -1), (-1, 1)])\n triangle = [[''] * n for n in range(1, rows + 1)]\n\n for times in range(rows, 0, -1):\n cur_dir = next(directions)\n\n for _ in range(times):\n row += cur_dir[0]\n col += cur_dir[1]\n\n triangle[row][col] = str(value % 10)\n value += 1\n\n return \"\\n\".join(' ' * (rows - i - 1) + ' '.join(r) for i, r in enumerate(triangle))\n", "from itertools import cycle\n\nMOVES = ((1,1),(0,-1),(-1,0))\n\ndef make_triangle(m,n):\n X = ((1+8*(n-m+1))**.5-1) / 2\n if X%1: return ''\n \n X = int(X)\n tri = [[-1]*(i+1) for i in range(int(X))]\n x,y,v,moves = 0, 0, m%10, cycle(MOVES)\n dx,dy = next(moves)\n for _ in range(n-m+1):\n tri[x][y] = str(v)\n v = (v+1)%10\n if not (0<=x+dx<X and 0<=y+dy<X) or tri[x+dx][y+dy]!=-1:\n dx,dy = next(moves)\n x+=dx ; y+=dy\n return '\\n'.join(' '*(X-i-1)+' '.join(row) for i,row in enumerate(tri))", "def make_triangle(m,n):\n size = ((8*(n-m+1)+1)**.5-1)/2\n if size % 1 : return ''\n \n grid = [[' ' for _ in range(int(size)*2-1)] for _ in range(int(size))]\n i,j = 0,int(size-1)\n grid[i][j] = str(m%10)\n \n while m<n:\n for inc,dec in [(1,1),(0,-2),(-1,1)]:\n while 0<=i+inc<size and 0<=j+dec<size*2-1 and grid[i+inc][j+dec].isspace():\n i, j, m = i+inc, j+dec, m+1\n grid[i][j] = str(m%10)\n \n return '\\n'.join([''.join(i).rstrip() for i in grid])", "def make_triangle(m, n):\n \"\"\"\n makeTriangle produces a \u2206 in a special sequence of numbers.\n m is the starting point and n is the finishibg one.\n The final digit of each number is taken as a character in making the \u2206.\n This functions returns a \u2206 as a string if possible with the given input else, returns an empty string.\n \"\"\"\n\n #Type check for arguments\n if (type(m)!=type(0)) or (type(n)!=type(0)):\n raise TypeError(\"m and n should be int\")\n #Value check for arguments\n if m >= n:\n raise ValueError(\"m not < n\")\n\n chars = [str(i)[-1] for i in range(m, n+1)]\n #chars contains all the characters that will make up the \u2206.\n \n #Can this set of chars make a \u2206.\n row, charc = 0, 0 #ncpr is the no. of rows in a \u2206. And charc is the no. of characters a \u2206 of specific side length contains. Both initially set to 0.\n\n while True:\n #The loop will break if the \u2206 is possible else, will cause the function to return an empty string.\n row += 1; charc = 0\n for j in range(1, row): charc += j\n if len(chars) == charc: row -= 1; break\n if len(chars) < charc: return ''\n \n #\u2206 generation\n lor = [[' ' for j in range(i)] for i in range(1, row+1)] #lor contains all the rows of the \u2206 as white strings.\n #For Step-1 to work\n i1,sp, b = 0, 0, -1\n #For Step-2 to work\n c = 2\n i2, l = row-c, 0\n #For Step-3 to work\n i3, j= row-2, 0\n while True: \n if len(chars)==0: break\n #Step-1\n while i1 <= row-1:\n lor[i1][b] = chars[0]\n chars.pop(0)\n i1 += 1\n i1 = sp+2; b -= 1\n if len(chars)==0: break\n #Step-2\n while i2 >= l:\n lor[row-1][i2] = chars[0]\n chars.pop(0)\n i2 -= 1\n row -= 1; c += 1; i2 = row-c; l += 1\n if len(chars)==0: break\n #Step-3\n while i3 > sp:\n lor[i3][j] = chars[0]\n chars.pop(0)\n i3 -= 1\n i3 = row-2; j += 1; sp += 2\n l = ''\n for i in lor:\n if i==lor[0]:\n l += ' '*(len(lor)-len(i))+i[0]+'\\n'\n continue\n for j in range(len(i)):\n if j==0:\n l += ' '*(len(lor)-len(i))+i[j]+' '\n elif j==len(i)-1:\n l += i[j]\n else:\n l += i[j]+' '\n if i!=lor[-1]:\n l += '\\n'\n return l", "def make_triangle(m,n):\n count=0\n rec=n-m+1\n for i in range(1,99999999):\n count+=i\n if count>rec:\n return \"\"\n elif count==rec:\n limit=i\n break\n right=limit\n left=0\n triangle=[[\" \"]*i for i in range(1,limit+1)] \n while m<=n:\n for i in range(left,right):\n triangle[i+left][i]=str(m%10)\n m+=1\n right-=1\n for i in range(right-1,left-1,-1):\n triangle[right+left][i]=str(m%10)\n m+=1\n right-=1\n for i in range(right,left,-1):\n triangle[i+left][left]=str(m%10)\n m+=1\n left+=1\n res=[]\n for j,i in enumerate(triangle):\n res.append(\" \"*(limit-(j)-1)+\" \".join(i))\n return \"\\n\".join(res)", "def make_triangle(n,m):\n layers = layer(m-n+1)\n if layers == False:\n return \"\"\n board = []\n for i in range(layers):\n board.append([\"\"]*(i+1))\n triangle = make(n%10,board,0,0,len(board))\n return tri_print(triangle)\n \ndef layer(n):\n a = 0\n layer = 0\n for i in range(1,n):\n a+= i\n layer += 1\n if a == n:\n return layer\n elif a > n:\n return False\n else:\n continue\ndef tri_print(board):\n sentence = \"\"\n for i in range(len(board)):\n sentence += \" \"*(len(board)-1-i)\n for j in range(len(board[i])):\n sentence+= str(board[i][j]) + \" \"\n sentence = sentence[:-1] + \"\\n\"\n return sentence[:-1]\n \n \ndef make(n,board,row,col,x):\n for i in range(row,x):\n if board[i][col] == \"\":\n board[i][col] = n\n if n == 9:\n n = 0\n else:\n n+=1\n col +=1\n for j in range(x-1,-1,-1):\n if board[x-1][j] == \"\" :\n board[x-1][j] = n\n n_col = j\n if n == 9:\n n = 0\n else:\n n+=1\n if check(board):\n return board\n for z in range(x-1,row,-1):\n if board[z][n_col] == \"\":\n board[z][n_col] = n\n rw,cl = z,n_col\n if n == 9:\n n = 0\n else:\n n+=1\n \n if not check(board):\n return make(n,board,rw,cl,x-1)\n return board\n\ndef check(board):\n for i in board:\n for j in i:\n if j == \"\" :\n return False\n return True", "def make_triangle(start, end):\n from itertools import cycle\n from math import sqrt\n\n rows = sqrt(8 * (end - start) + 9) / 2 - .5\n if not rows.is_integer():\n return ''\n\n rows = int(rows)\n row, col, fill = -1, -1, start\n ls = [[''] * n for n in range(1, rows+1)]\n directions = cycle([(1, 1), (0, -1), (-1, 0)])\n\n for i in range(rows):\n dir = next(directions)\n\n for j in range(rows-i):\n row += dir[0]\n col += dir[1]\n ls[row][col] = str(fill%10)\n fill += 1\n\n return '\\n'.join(' ' * (rows-i-1) + ' '.join(r) for i, r in enumerate(ls))\n", "import numpy as np\ndef make_triangle(m,n):\n num=n-m+1\n level=int((num*2)**(1.0/2))\n if level*(level+1)/2!=num:\n return \"\"\n else:\n level_max=level*2-1\n npres=np.full((level,level_max),' ')\n l,p,f=0,level_max//2,int(str(m)[-1])\n for i in range(num):\n npres[l][p]=f\n f=(f+1)%10\n if p>=level_max//2 and l!=level-1:\n if npres[l+1][p+1]==' ':\n l+=1\n p+=1\n else:\n p-=2\n level-=1\n elif l==level-1 and p>0:\n if npres[l][p-2]==' ':\n p-=2\n else:\n p+=1\n l-=1\n elif (p<level_max//2 and l!=level-1) or( l==level-1 and p==0):\n if npres[l - 1][p + 1] == ' ':\n p+=1\n l-=1\n else:\n l+=1\n p+=1\n res='\\n'.join(''.join(str(x) for x in n).rstrip() for n in npres.tolist() )\n return res", "def make_triangle(m,n):\n if n == m:\n return m\n\n else:\n Num = len(range(m,n+1))\n\n elNum = 0\n k = 1\n while elNum < Num:\n k += 1\n elNum = int(k*(k+1)/2)\n \n if elNum != Num:\n return \"\"\n \n Lyr = (k-1)//3 + 1\n\n\n L1 = []\n for i in range(k):\n L1.append([])\n for j in range(k+i):\n L1[-1].append(\" \")\n L1[-1].append(\"\\n\")\n\n el = m-1\n\n for CLyr in range(Lyr):\n topR = 2*CLyr\n topC = -2*(CLyr+1)\n \n CSize = k - 3*CLyr\n\n for i in range(CSize):\n el += 1\n L1[topR+i][-2*(1+CLyr)] = str(el % 10)\n\n for i in range(CSize-1):\n el += 1\n L1[topR+CSize-1][-4-2*(i+CLyr)] = str(el % 10)\n\n for i in range(CSize-2):\n el += 1\n L1[topR+CSize-1-1-i][i+1+CLyr*3] = str(el % 10)\n\n L2 = [e for inner_list in L1 for e in inner_list][:-1]\n return \"\".join(L2)"]
{"fn_name": "make_triangle", "inputs": [[1, 12], [1, 100]], "outputs": [[""], [""]]}
INTRODUCTORY
PYTHON3
CODEWARS
10,366
def make_triangle(m,n):
d48cf185f76a9d37581ad934b73c537b
UNKNOWN
Consider an array containing cats and dogs. Each dog can catch only one cat, but cannot catch a cat that is more than `n` elements away. Your task will be to return the maximum number of cats that can be caught. For example: ```Haskell solve(['D','C','C','D','C'], 2) = 2, because the dog at index 0 (D0) catches C1 and D3 catches C4. solve(['C','C','D','D','C','D'], 2) = 3, because D2 catches C0, D3 catches C1 and D5 catches C4. solve(['C','C','D','D','C','D'], 1) = 2, because D2 catches C1, D3 catches C4. C0 cannot be caught because n == 1. solve(['D','C','D','D','C'], 1) = 2, too many dogs, so all cats get caught! ``` Do not modify the input array. More examples in the test cases. Good luck!
["def solve(arr, reach):\n dogs, nCats = {i for i,x in enumerate(arr) if x=='D'}, 0\n for i,c in enumerate(arr):\n if c == 'C':\n catchingDog = next((i+id for id in range(-reach,reach+1) if i+id in dogs), None)\n if catchingDog is not None:\n nCats += 1\n dogs.remove(catchingDog)\n return nCats", "def solve(lst, n):\n lst, caught = lst[:], 0\n while {\"C\", \"D\"} <= set(lst):\n d, c = lst.index(\"D\"), lst.index(\"C\")\n if abs(d - c) <= n:\n caught, lst[d], lst[c] = caught + 1, \"\", \"\"\n else:\n lst[min(d, c)] = \"\"\n return caught", "def solve(arr, n):\n dogs = [i for i, x in enumerate(arr) if x == 'D']\n cats = {i for i, x in enumerate(arr) if x == 'C'}\n catch = 0\n while dogs and cats:\n dog = dogs.pop()\n cat = max((cat for cat in cats if abs(dog - cat) <= n), default=-1)\n if cat >= 0:\n catch += 1\n cats.remove(cat)\n return catch", "def solve(arr,n):\n c,l = 0,len(arr)\n for i in range(l):\n if arr[i] == 'C':\n a = max(0,i-n)\n b = min(l-1,i+n)\n for j in range(a,b+1):\n if arr[j] == 'D':\n arr[j] = 'd'\n c += 1\n break\n return c", "def solve(arr, n):\n caught = 0\n for i in range(0, len(arr)):\n if arr[i] == 'C':\n for j in range(0, len(arr)):\n if abs(i - j) <= n and arr[j] == 'D' and arr[i] != 'X':\n arr[i], arr[j] = 'X', 'X'\n caught += 1\n return caught", "def solve(d,pos):\n for i, j in enumerate(d):\n if j == 'D':\n left = next((k for k in range((i - pos) if i - pos > -1 else 0, i) if d[k] == 'C'), -1)\n right = next((k for k in range(i, (i + pos + 1) if i + pos < len(d) else len(d)) if d[k] == 'C'), -1)\n if left != -1 : d[left] = '.'\n elif right != -1 : d[right] = '.'\n return d.count('.')", "def solve(arr, n):\n caught = []\n for d in [idx for idx in range(len(arr)) if arr[idx] == 'D']:\n for c in [idx for idx in range(len(arr)) if arr[idx] == 'C']:\n if c in range(d - n, d + n + 1) and c not in caught:\n caught += [c]\n break\n return len(caught)", "def solve(arr,n):\n dc=n*['x']+arr[:]+n*['x']\n p=0\n ct=0\n while p<len(dc):\n if dc[p]=='D':\n for i in range(p-n,p+n+1):\n if dc[i]=='C':\n dc[i]='X'\n ct+=1\n break\n p+=1\n return ct", "def solve(arr,n):\n eaten = []\n dog = []\n for i in range(len(arr)):\n if arr[i] == \"D\":\n for j in range(max(0, i-n), min(1+i+n, len(arr))):\n if arr[j] == \"C\" and j not in eaten and i not in dog:\n dog.append(i)\n eaten.append(j)\n return len(eaten)", "def solve(arr,n):\n a=['']*n+arr[:]+['']*n\n r=0\n for i,e in enumerate(a):\n if e=='D':\n for j in range(i-n,i+n+1):\n if a[j]=='C':\n r+=1\n a[j]=''\n break\n return r"]
{"fn_name": "solve", "inputs": [[["D", "C", "C", "D", "C"], 1], [["C", "C", "D", "D", "C", "D"], 2], [["C", "C", "D", "D", "C", "D"], 1], [["D", "C", "D", "C", "C", "D"], 3], [["C", "C", "C", "D", "D"], 3], [["C", "C", "C", "D", "D"], 2], [["C", "C", "C", "D", "D"], 1], [["C", "C", "C", "D", "D", "D", "C", "D", "D", "D", "C", "D", "C", "C"], 2]], "outputs": [[2], [3], [2], [3], [2], [2], [1], [5]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,321
def solve(arr,n):
dddc44d246a450b28cb7274e3b81e88c
UNKNOWN
Your friend won't stop texting his girlfriend. It's all he does. All day. Seriously. The texts are so mushy too! The whole situation just makes you feel ill. Being the wonderful friend that you are, you hatch an evil plot. While he's sleeping, you take his phone and change the autocorrect options so that every time he types "you" or "u" it gets changed to "your sister." Write a function called autocorrect that takes a string and replaces all instances of "you" or "u" (not case sensitive) with "your sister" (always lower case). Return the resulting string. Here's the slightly tricky part: These are text messages, so there are different forms of "you" and "u". For the purposes of this kata, here's what you need to support: "youuuuu" with any number of u characters tacked onto the end "u" at the beginning, middle, or end of a string, but NOT part of a word "you" but NOT as part of another word like youtube or bayou
["import re\n\ndef autocorrect(input):\n return re.sub(r'(?i)\\b(u|you+)\\b', \"your sister\", input)", "from re import sub, I\n\ndef autocorrect(input):\n return sub(r'\\b(you+|u)\\b', 'your sister', input, flags=I)", "import re\ndef autocorrect(input):\n return re.sub(r'(?i)\\b(you+|u)\\b', 'your sister', input)", "import re\ndef autocorrect(input):\n return re.sub(r\"\\b(yo[u]+|[u])(?!'\\w)\\b\",'your sister',input,flags=re.IGNORECASE)\n \n \n \n", "def autocorrect(s):\n s,n = s.split(),[]\n for i in s:\n if i == 'you' or i == 'u':\n n.append('your sister')\n elif len(i) == 4 and i[:-1]=='you':\n n.append('your sister'+i[-1]) \n elif i.count('Y')+i.count('y')+i.count('o')+i.count('u')==len(i) and i.count('u')==len(i)-2:\n n.append('your sister')\n else:\n n.append(i)\n return ' '.join(n)", "import re\ndef autocorrect(i): \n return \" \".join(re.sub(r\"^(y+o+u+|u)([,.!])?$\",r\"your sister\\2\", word, flags=re.IGNORECASE) for word in i.split())", "import re\ndef autocorrect(input):\n rgx = r'\\b([Yy]ou+|u)\\b'\n return re.sub(rgx, 'your sister', input)", "import re\ndef autocorrect(input):\n auto_re = r\"\\b(u|you+)\\b\"\n return re.sub(auto_re, \"your sister\", input, flags=re.IGNORECASE)", "import re\ndef autocorrect(input):\n return re.sub(r'(\\bu\\b|\\byo[u]+\\b)', \"your sister\", input, flags=re.IGNORECASE)\n", "import re\nautocorrect=lambda s: re.sub(r'(?i)\\b(u|you+)\\b', 'your sister', s)"]
{"fn_name": "autocorrect", "inputs": [["I miss you!"], ["u want to go to the movies?"], ["Can't wait to see youuuuu"], ["I want to film the bayou with you and put it on youtube"], ["You should come over Friday night"], ["You u youville utube you youyouyou uuu raiyou united youuuu u you"]], "outputs": [["I miss your sister!"], ["your sister want to go to the movies?"], ["Can't wait to see your sister"], ["I want to film the bayou with your sister and put it on youtube"], ["your sister should come over Friday night"], ["your sister your sister youville utube your sister youyouyou uuu raiyou united your sister your sister your sister"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,571
def autocorrect(input):
27c3c26fb7478cd9b3b8de4c5794fdb5
UNKNOWN
## Task You need to implement two functions, `xor` and `or`, that replicate the behaviour of their respective operators: - `xor` = Takes 2 values and returns `true` if, and only if, one of them is truthy. - `or` = Takes 2 values and returns `true` if either one of them is truthy. When doing so, **you cannot use the or operator: `||`**. # Input - Not all input will be booleans - there will be truthy and falsey values [the latter including also empty strings and empty arrays] - There will always be 2 values provided ## Examples - `xor(true, true)` should return `false` - `xor(false, true)` should return `true` - `or(true, false)` should return `true` - `or(false, false)` should return `false`
["def func_or(a, b):\n return not (bool(a) == bool(b) == False)\n\ndef func_xor(a, b):\n return not (bool(a) == bool(b))", "def func_or(a,b):\n return bool(a) | bool(b)\n\ndef func_xor(a,b):\n return bool(a) ^ bool(b)", "def func_or(a, b):\n return bool(a) + bool(b) > 0\n\ndef func_xor(a, b):\n return bool(a) + bool(b) == 1", "def func_or(*a):\n return any(a)\n\ndef func_xor(*a):\n return any(a) and not all(a)", "def func_or(a, b):\n return bool(a if a else b)\n\ndef func_xor(a, b):\n return bool(not b if a else b)", "def func_or(a,b):\n return False if not a and not b else True\n\ndef func_xor(a,b):\n return True if (not a and b) or (a and not b) else False", "def func_or(a,b):return bool(a)or bool(b)\ndef func_xor(a,b):return bool(a) is not bool(b)", "func_or, func_xor = lambda a,b: bool(bool(a)+bool(b)), lambda a,b: bool(a)+bool(b)==1", "def func_or(a,b):\n return bool(a) or bool(b)\n\ndef func_xor(a,b):\n return bool(a) != bool(b)", "def func_or(a,b):\n if a:\n return True\n else:\n return not(not b)\n\ndef func_xor(a,b):\n if a:\n return not b\n else:\n return not(not b)"]
{"fn_name": "func_or", "inputs": [[true, true], [true, false], [false, false], [0, 11], [null, []]], "outputs": [[true], [true], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,176
def func_or(a,b):
8a3d3353020504d4b9dbad33666a5dca
UNKNOWN
Write a function which reduces fractions to their simplest form! Fractions will be presented as an array/tuple (depending on the language), and the reduced fraction must be returned as an array/tuple: ``` input: [numerator, denominator] output: [newNumerator, newDenominator] example: [45, 120] --> [3, 8] ``` All numerators and denominators will be positive integers. Note: This is an introductory Kata for a series... coming soon!
["from fractions import Fraction\ndef reduce_fraction(fraction):\n t = Fraction(*fraction)\n return (t.numerator, t.denominator)", "def gcd(a, b):\n return a if b == 0 else gcd(b, a % b)\n \ndef reduce_fraction(fraction):\n num, denom = fraction\n gcd_num_denom = gcd(num, denom)\n return (num // gcd_num_denom, denom // gcd_num_denom)", "from math import gcd \n\ndef reduce_fraction(fraction):\n g = gcd(*fraction)\n return tuple(n // g for n in fraction)", "def gcd(a, b):\n if not a%b:\n return b\n else:\n return gcd(b, a%b)\n\ndef reduce_fraction(fraction):\n return tuple(int(x/gcd(*fraction)) for x in fraction)", "from math import gcd\n\ndef reduce_fraction(fraction):\n numerator, denominator = fraction\n d = gcd(numerator, denominator)\n return (numerator // d, denominator // d)", "def reduce_fraction(fraction):\n num, denom = fraction\n for x in range(2, min(num, denom) + 1):\n while num % x == denom % x == 0:\n num //= x\n denom //= x\n if x > min(num, denom):\n break\n return (num, denom)", "def mcd(fraccion):\n if fraccion[0]%fraccion[1]==0:\n return fraccion[1]\n else:\n return mcd((fraccion[1], fraccion[0]%fraccion[1]))\n\ndef reduce_fraction(fraccion):\n return (fraccion[0]//mcd(fraccion), fraccion[1]//mcd(fraccion))", "from math import gcd\n\ndef reduce_fraction(fraction):\n a, b = fraction\n g = gcd(a, b)\n return (a//g, b//g)", "def reduce_fraction(fraction):\n n1, n2 = fraction[0], fraction[1]\n for i in range(2, 999):\n if n1 % i == 0 and n2 % i == 0:\n n1, n2 = n1 // i, n2 // i\n fraction = reduce_fraction([n1, n2]) \n return tuple(fraction)", "def reduce_fraction(fraction):\n # your code here\n def get_gcd(x, y):\n a = min(x,y)\n b = max(x,y)\n if a == 0:\n return b\n return get_gcd(a, b % a)\n gcd = get_gcd(fraction[0], fraction[1])\n \n return tuple([int(x / gcd) for x in fraction])\n"]
{"fn_name": "reduce_fraction", "inputs": [[[60, 20]], [[80, 120]], [[4, 2]], [[45, 120]], [[1000, 1]], [[1, 1]], [[10956590, 13611876]], [[35884747, 5576447]], [[24622321, 24473455]], [[4255316, 11425973]]], "outputs": [[[3, 1]], [[2, 3]], [[2, 1]], [[3, 8]], [[1000, 1]], [[1, 1]], [[30605, 38022]], [[76841, 11941]], [[42673, 42415]], [[17228, 46259]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,077
def reduce_fraction(fraction):
c80da313e544cb90e295e8344befbfff
UNKNOWN
ASC Week 1 Challenge 4 (Medium #1) Write a function that converts any sentence into a V A P O R W A V E sentence. a V A P O R W A V E sentence converts all the letters into uppercase, and adds 2 spaces between each letter (or special character) to create this V A P O R W A V E effect. Examples: ```javascript vaporcode("Lets go to the movies") // output => "L E T S G O T O T H E M O V I E S" vaporcode("Why isn't my code working?") // output => "W H Y I S N ' T M Y C O D E W O R K I N G ?" ``` ```ruby vaporcode("Lets go to the movies") # output => "L E T S G O T O T H E M O V I E S" vaporcode("Why isn't my code working?") # output => "W H Y I S N ' T M Y C O D E W O R K I N G ?" ``` ```python vaporcode("Lets go to the movies") # output => "L E T S G O T O T H E M O V I E S" vaporcode("Why isn't my code working?") # output => "W H Y I S N ' T M Y C O D E W O R K I N G ?" ``` ```crystal vaporcode("Lets go to the movies") # output => "L E T S G O T O T H E M O V I E S" vaporcode("Why isn't my code working?") # output => "W H Y I S N ' T M Y C O D E W O R K I N G ?" ``` ```cpp vaporcode("Lets go to the movies") // output => "L E T S G O T O T H E M O V I E S" vaporcode("Why isn't my code working?") // output => "W H Y I S N ' T M Y C O D E W O R K I N G ?" ``` ```haskell vaporcode "Lets go to the movies" -- output => "L E T S G O T O T H E M O V I E S" vaporcode "Why isn't my code working?" -- output => "W H Y I S N ' T M Y C O D E W O R K I N G ?" ```
["def vaporcode(s):\n return \" \".join(s.replace(\" \", \"\").upper())", "def vaporcode(s):\n string = ''\n s = ''.join(s.split()).upper()\n for c in s:\n string += c + ' '\n return string[:-2]", "vaporcode = lambda s: \" \".join(list(s.replace(\" \", \"\").upper()))", "def vaporcode(s):\n return ' '.join([letter for word in s.upper().split(' ') for letter in word])", "from string import ascii_lowercase, ascii_uppercase\ntrans = str.maketrans(ascii_lowercase, ascii_uppercase, ' ')\n\ndef vaporcode(s):\n return \" \".join(s.translate(trans))", "def vaporcode(s):\n return((\" \".join((\" \".join((s.upper()))).split())))", "def vaporcode(s):\n vapor_s = ''.join(['{} '.format(i) for i in s.upper().replace(' ','')])\n return vapor_s.rstrip()", "vaporcode=lambda s:\" \".join(list(s.upper().replace(\" \", \"\")))", "def vaporcode(s):\n result = ''\n for x in s:\n if x == ' ':\n continue\n result = result + x.upper() + ' '\n return result[:len(result)-2]\n", "def vaporcode(s):\n return ' '.join(i.upper() for i in s if i!=' ')"]
{"fn_name": "vaporcode", "inputs": [["Lets go to the movies"], ["Why isn't my code working?"]], "outputs": [["L E T S G O T O T H E M O V I E S"], ["W H Y I S N ' T M Y C O D E W O R K I N G ?"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,121
def vaporcode(s):
e0aa27a7a8cce4a9c43c0aab85bfeb31
UNKNOWN
It's March and you just can't seem to get your mind off brackets. However, it is not due to basketball. You need to extract statements within strings that are contained within brackets. You have to write a function that returns a list of statements that are contained within brackets given a string. If the value entered in the function is not a string, well, you know where that variable should be sitting. Good luck!
["import re\n\nREGEX = re.compile(r'\\[(.*?)\\]')\n\n\ndef bracket_buster(strng):\n try:\n return REGEX.findall(strng)\n except TypeError:\n return 'Take a seat on the bench.'\n", "from re import findall\n\ndef bracket_buster(s):\n return \"Take a seat on the bench.\" if type(s) is not str else findall(r'\\[(.*?)\\]', s)", "brackets = __import__(\"re\").compile(r\"\\[(.*?)\\]\").findall\n\ndef bracket_buster(string):\n return brackets(string) if type(string) == str else \"Take a seat on the bench.\"", "import re\n\ndef bracket_buster(string):\n if not isinstance(string, str):\n return \"Take a seat on the bench.\"\n return re.findall(r'\\[(.*?)\\]', string)\n", "import re\n\ndef bracket_buster(string):\n return re.findall(\"\\[(.*?)\\]\", string) if type(string) == str else \"Take a seat on the bench.\"", "import re\n\ndef bracket_buster(s):\n return re.findall(r'\\[(.*?)\\]', s) if isinstance(s, str) else 'Take a seat on the bench.'", "import re\n\ndef bracket_buster(string):\n if type(string) is not str:\n return \"Take a seat on the bench.\"\n return re.findall(r'\\[(.*?)\\]', string)", "from re import findall as f\nbracket_buster=lambda s:f(r\"\\[(.*?)\\]\",s) if isinstance(s,str) else \"Take a seat on the bench.\"", "import re\ndef bracket_buster(x):\n if type(x) != str:\n return 'Take a seat on the bench.'\n pat = r'\\[.*?\\]'\n\n results = [match[1:-1] for match in re.findall(pat,str(x))]\n\n if len(results) == 0:\n return 'Take a seat on the bench.'\n else:\n return results", "def bracket_buster(string):\n # Get after it!\n if string == None or not isinstance(string,str) : return \"Take a seat on the bench.\"\n import re\n pattern = re.compile(r'\\[([\\w\\s\\'?!\\d\\-]+|\\[{1,}|'')\\]', re.I)\n mo = pattern.findall(string)\n return mo"]
{"fn_name": "bracket_buster", "inputs": [[[1, 2, 3]], [{"3": 4}], [false], [23.45], ["arc.tic.[circle]?[?]"], ["Big [L][e][B][r][o][n]!][["], ["[][]]]][[[[[[][]"], ["logger?]?system...12.12.133333 at [12-32-1432-16]"]], "outputs": [["Take a seat on the bench."], ["Take a seat on the bench."], ["Take a seat on the bench."], ["Take a seat on the bench."], [["circle", "?"]], [["L", "e", "B", "r", "o", "n"]], [["", "", "[[[[[", ""]], [["12-32-1432-16"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,887
def bracket_buster(string):
326f5b61a822a76d9c25bb756ac79468
UNKNOWN
The [Sharkovsky's Theorem](https://en.wikipedia.org/wiki/Sharkovskii%27s_theorem) involves the following ordering of the natural numbers: ```math 3≺5≺7≺9≺ ...\\ ≺2·3≺2·5≺2·7≺2·9≺...\\ ≺2^n·3≺2^n·5≺2^n·7≺2^n·9≺...\\ ≺2^{(n+1)}·3≺2^{(n+1)}·5≺2^{(n+1)}·7≺2^{(n+1)}·9≺...\\ ≺2^n≺2^{(n-1)}≺...\\ ≺4≺2≺1\\ ``` Your task is to complete the function which returns `true` if `$a≺b$` according to this ordering, and `false` otherwise. You may assume both `$a$` and `$b$` are non-zero positive integers.
["def sharkovsky(a, b): return f(a)<f(b)\n\ndef f(n,p=0):\n while n%2==0:\n n>>=1\n p+=1\n return n==1, p*(-1)**(n==1), n", "def analyse(x):\n n = (b := bin(x)).rstrip(\"0\")\n p = len(b) - len(n)\n return (n := int(n, 2)) == 1, p * (-1)**(n == 1), n\n\n\ndef sharkovsky(a, b):\n return analyse(a) < analyse(b)", "key=lambda n:[(0,e:=n&-n,n//e),(1,-n)][e==n]\nsharkovsky=lambda a,b:key(a)<key(b)", "from math import log\n\ndef decompose(n):\n \"\"\"\n Given integer n, finds the coefficient and exponent of 2 decomposition\n (c, p) such that c * 2^p == n when c, p are both integers\n \"\"\"\n for p in range(int(log(n, 2)), -1, -1):\n c = n / (2 ** p)\n if c == int(c):\n c = int(c)\n return c, p\n \n\ndef sharkovsky(a, b):\n \"\"\"\n Given a, b determine if a precedes b in a Sharkovsky sequence.\n \n Any natural number can be decomposed into a position in the table (k \\in \\mathbb{N}):\n \n 3.2^0 5.2^0 7.2^0 ... (2(k-1)+1).2^0 (2k+1).2^0 ...\n 3.2^1 5.2^1 7.2^1 ... (2(k-1)+1).2^1 (2k+1).2^1 ...\n 3.2^2 5.2^2 7.2^2 ... (2(k-1)+1).2^2 (2k+1).2^2 ...\n 3.2^3 5.2^3 7.2^3 ... (2(k-1)+1).2^3 (2k+1).2^3 ...\n ... ... ... ... ... ... ...\n 1.2^(2k+1) 1.2^(2(k-1)+1) 1.2^(2(k-2)+1) ... 2.2^2 1.2^1 1.2^0\n \n Reading the table left to right, top to bottom gives the Sharkovsky sequence\n \"\"\"\n coef_a, exp_a = decompose(a)\n coef_b, exp_b = decompose(b)\n if coef_a == 1 and coef_b == 1:\n # Both on the final row\n return exp_b < exp_a\n if coef_a == 1 or coef_b == 1:\n # One on the final row\n return coef_b == 1\n if exp_a != exp_b:\n # On differing rows\n return exp_a < exp_b\n if exp_a == exp_b:\n # On same row\n return coef_a < coef_b\n return False\n", "def div2(n):\n i = 0\n while n%2 == 0:\n n = n/2\n i += 1\n return n, i\n\ndef sharkovsky(a, b):\n n1, rem1 = div2(a)\n n2, rem2 = div2(b)\n if n1 == 1 and n2 == 1:\n return not (rem1 < rem2)\n elif n1 == 1 and n2 != 1:\n return False\n elif n1 != 1 and n2 == 1:\n return True\n else:\n if rem1 == rem2:\n return n1 < n2\n else:\n return rem1 < rem2\n", "def sharkovsky(a, b):\n if b == a:\n return False\n elif b == 1:\n return True\n elif a == 1:\n return False\n elif a%2 == 1:\n if b%2 == 0:\n return True\n elif a<b:\n return True\n else:\n return False\n else:\n if b%2 == 1:\n return False\n else:\n result = sharkovsky(a/2, b/2)\n return result", "def sharkovsky(a, b):\n def key(n): even = n & -n; return [(even, n // even), (float('inf'), -n)][n == even]\n return key(a) < key(b)", "def sharkovsky(a, b):\n if a == b:\n return False\n if a == 1:\n return False\n if b == 1:\n return a > 1\n c = get_highest_power_of_two_divisible_by_number(a)\n d = get_highest_power_of_two_divisible_by_number(b)\n if c == d:\n a //= c\n b //= d\n if a != 1 and b == 1:\n return True\n elif a == 1:\n return False\n else:\n return a < b\n elif c < d:\n a //= c\n b //= d\n if a == 1 and b != 1:\n return False\n elif a == 1 and b == 1:\n return False\n else:\n return True\n else:\n a //= c\n b //= d\n if a != 1 and b == 1:\n return True\n elif a == 1 and b == 1:\n return True\n else:\n return False\n\ndef get_highest_power_of_two_divisible_by_number(number):\n twos = []\n while number % 2 == 0:\n twos.append(2)\n number //= 2\n result = 2 ** len(twos)\n return result\n\ndef is_power_of_two(number):\n twos = []\n while number % 2 == 0:\n twos.append(2)\n number //= 2\n twos = remove_duplicates(twos)\n return twos == [2]\n\ndef remove_duplicates(lst):\n result = []\n for i in lst:\n if i not in result:\n result.append(i)\n return result", "import numpy as np\ndef sharkovsky(a, b):\n l = []\n for i in range(0, int(np.log2(max(a, b))) + 3):\n for j in range(3, max(a, b) + 1, 2):\n if a == (2 ** i) * j:\n l.append(a)\n a = b\n if len(l) >= 2:\n return True\n for n in range(int(np.log2(max(a, b))) + 3, -1, -1):\n if a == 2 ** n:\n l.append(a)\n a = b\n if len(l) >= 2:\n return True\n return False", "def sharkovsky(a, b):\n i = 0\n while a % 2 == 0:\n a //= 2\n i += 1\n j = 0\n while b % 2 == 0:\n b //= 2\n j += 1;\n if a == 1 and b == 1:\n return i > j\n elif a == 1:\n return False\n elif b == 1:\n return True\n elif i == j:\n return a < b\n else:\n return i < j\n", "def sharkovsky(a,b):\n \n def Answer(n):\n con = True\n p = 0\n while con == True:\n if n %2!=0:\n ans = (p,n)\n con = False\n else:\n n= n /2\n p +=1\n return ans\n ans_a = Answer(a) \n ans_b = Answer(b) \n \n if ans_a[1]==1 and ans_b[1]!=1:\n return False\n elif ans_a[1]!=1 and ans_b[1]==1:\n return True\n elif ans_a[1]==1 and ans_b[1]==1:\n return ans_a[0]>ans_b[0]\n else:\n if ans_a[0]>ans_b[0]:\n return False\n elif ans_a[0]<ans_b[0]:\n return True\n else:\n return ans_a[1]<ans_b[1]\n", "def sharkovsky(a, b): \n if a%2==0 and b%2==0:\n while a%2==0 and b%2==0:\n a=a/2\n b=b/2 \n \n if b%2==0:\n if a ==1 :\n return 1==2 \n else:\n return 1==1\n elif a%2==0:\n if b== 1:\n return 1==1\n else:\n return 1==2 \n else:\n if b==1:\n return 1==1\n elif a==1:\n return 1==2\n else:\n return a<b ", "def sharkovsky(a, b):\n while True:\n if a==1 or b==1: return a!=1\n if a%2 or b%2: return a%2==1 and not ( b%2==1 and a>=b )\n a/=2\n b/=2", "def sharkovsky(a, b):\n power_a, odd_number_a = solve(a)\n power_b, odd_number_b = solve(b)\n print((\"a info power then oddnum\", power_a, odd_number_a))\n if(odd_number_a == 1 and odd_number_b == 1):\n return True if power_a > power_b else False\n elif(odd_number_a == 1 and odd_number_b > 1):\n return False\n elif(odd_number_a > 1 and odd_number_b == 1):\n return True\n elif(power_a > power_b):\n return False\n elif(power_a < power_b):\n return True\n elif(power_a == power_b):\n return True if odd_number_a < odd_number_b else False\n \ndef solve(a):\n power_of_two = 0\n num = a\n while num % 2 == 0:\n power_of_two += 1\n num = num / 2 # This is an int because of while loop\n return power_of_two, a / (2 ** power_of_two)\n", "import math\n\n\ndef splitnumber(x):\n counter =0\n while x%2 ==0:\n counter +=1\n x = x/2\n return [counter ,x]\n \n \n\ndef sharkovsky(a, b):\n x = splitnumber(a)\n y = splitnumber(b)\n \n if (x[1] ==1) and (y[1]==1):\n return a>b\n elif (x[1]!= 1) and (y[1]==1):\n return True\n elif (x[1]==1) and (y[1]!=1):\n return False\n else:\n if x[0] ==y[0]:\n return a<b\n else:\n return x[0] < y[0]\n\n return False\n", "def sharkovsky(a, b):\n if a == b:\n return False\n if a <3:\n return False\n if b<3:\n return True\n print(a,b)\n higher = max(a,b)\n lower = min(a,b)\n number = 3\n while number <= higher:\n if number == a:\n return True\n if number == b:\n return False\n number = number + 2\n counter = 3\n number = 2 * counter\n while number <= higher:\n if number == a:\n return True\n if number == b:\n return False\n counter = counter + 2\n number = 2 * counter\n counter = 3\n exponential = 1\n number = (2**exponential) * counter\n while number <= higher:\n if number == a:\n return True\n if number == b:\n return False\n counter = counter + 2\n exponential = exponential + 1\n number = (2**exponential) * counter\n counter = 3\n exponential = 2\n number = (2**exponential) * counter\n while number <= higher:\n if number == a:\n return True\n if number == b:\n return False\n counter = counter + 2\n exponential = exponential + 1\n number = (2**exponential) * counter\n exponential = 1\n number = (2**exponential) \n while number >= lower:\n if number == a:\n return True\n if number == b:\n return False\n exponential = exponential - 1\n number = (2**exponential) \n number = higher \n while number >= lower:\n if number == a:\n return True\n if number == b:\n return False\n number = (number - 2)\n return False", "import math\ndef max2pow(n):\n even = 1\n while n % 2 == 0:\n even *= 2\n n /= 2\n return even, n\n\ndef sharkovsky(a, b):\n if a == b:\n return False\n even_a, odd_a = max2pow(a)\n even_b, odd_b = max2pow(b)\n if odd_a == 1 and odd_b == 1:\n return even_a > even_b\n if odd_a == 1 or odd_b == 1:\n return odd_b == 1 \n if even_a == even_b:\n return odd_a < odd_b\n return even_a < even_b\n \n", "import math\ndef sharkovsky(a, b):\n if a%2 != b%2: # a and b has one odd and one even\n if (b==1):\n return True\n elif (a%2 == 1) & (a !=1): \n return True\n else:\n return False\n elif a%2 == 1: # both are odd\n if b==1:\n return True\n elif (a < b) & (a !=1):\n return True\n else: \n return False\n else: # both are even\n if (math.pow(2,int(math.log2(a))) == a) & (math.pow(2,int(math.log2(b))) == b) & (a > b):\n return True\n elif (math.pow(2,int(math.log2(a))) != a):\n if (math.pow(2,int(math.log2(b))) == b):\n return True\n else:\n i = 0\n while((a%2==0)and(b%2==0)):\n i += 1\n a = a/2\n b = b/2\n if b%2 == 0:\n return True\n elif a%2 == 0:\n return False\n else:\n if a<b:\n return True\n else:\n return False\n else:\n return False", "def sharkovsky(a, b):\n a_red = a \n a_rem = a % 2 \n a_count = 0\n while a_rem == 0 :\n a_count = a_count + 1 \n a_red = int(a_red/2) \n a_rem = a_red % 2 \n \n \n b_red = b \n b_rem = b % 2 \n b_count = 0\n while b_rem == 0 :\n b_count = b_count + 1 \n b_red = int(b_red/2) \n b_rem = b_red % 2\n \n if (a_red > 1) and (b_red > 1) :\n if(a_count != b_count) :\n return a_count < b_count \n else :\n return a_red < b_red \n elif (a_red == 1) and (b_red > 1) :\n return False\n elif (a_red > 1) and (b_red == 1) :\n return True \n else :\n return a_count > b_count \n", "def factorTwos(n):\n twos = 0\n while not n % 2:\n n //= 2\n twos += 1\n \n return (twos, n)\n \n#not the prettiest, but it works\ndef sharkovsky(a, b):\n twosA, remA = factorTwos(a)\n twosB, remB = factorTwos(b)\n \n if remA == 1:\n return remB == 1 and twosA > twosB\n elif remB == 1:\n return remA != 1 or twosA > twosB\n elif twosA == twosB:\n return remA < remB\n else:\n return twosA < twosB"]
{"fn_name": "sharkovsky", "inputs": [[18, 12], [3, 9], [10, 16], [1, 22], [32, 1024], [17, 17]], "outputs": [[true], [true], [true], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,641
def sharkovsky(a, b):
fb0ea44822a4a4f2c6e3233cd8401084
UNKNOWN
You will be given a string. You need to return an array of three strings by gradually pulling apart the string. You should repeat the following steps until the string length is 1: a) remove the final character from the original string, add to solution string 1. b) remove the first character from the original string, add to solution string 2. The final solution string value is made up of the remaining character from the original string, once originalstring.length == 1. Example: "exampletesthere" becomes: ["erehtse","example","t"] The Kata title gives a hint of one technique to solve.
["def pop_shift(s):\n l1 = list(s); l2 = []; l3 = []\n while len(l1) > 1:\n l2.append(l1.pop())\n l3.append(l1.pop(0))\n return [\"\".join(l2),\"\".join(l3),\"\".join(l1)]", "def pop_shift(s):\n il, ir = len(s) // 2, (len(s) + 1) // 2\n return [s[:ir-1:-1], s[:il], s[il:ir]]", "def pop_shift(s):\n half, odd_len = divmod(len(s), 2)\n return [s[half + odd_len:][::-1], s[:half], s[half] if odd_len else '']", "def pop_shift(string):\n mid = len(string) // 2\n return [string[::-1][:mid], string[:mid], string[mid : len(string)-mid]]", "def pop_shift(s):\n i = len(s)//2\n return [s[-1:-i-1:-1], s[:i], s[i:i+len(s)%2]]", "def pop_shift(s):\n i, j = divmod(len(s), 2)\n return [s[i+j:][::-1], s[:i], s[i:i+j]]", "def pop_shift(stg):\n d, m = divmod(len(stg), 2)\n return [stg[:d+m-1:-1], stg[:d], stg[d] if m else \"\"]", "def pop_shift(strn):\n s2=''.join(strn[-i-1] for i in range(len(strn)//2))\n s1=''.join(strn[i] for i in range(len(strn)//2))\n s0=''.join(strn[len(s1):-len(s1)])\n if len(strn)==1:\n s0=strn\n return [s2,s1,s0]", "def pop_shift(input):\n input = list(input)\n x, y = list(), list()\n while len(input) > 1: \n x.append(input.pop())\n y.append(input.pop(0))\n return [''.join(x), ''.join(y), ''.join(input)]\n", "def pop_shift(str):\n l = len(str)\n return [str[::-1][:l//2], str[:l//2], str[l//2]*(l%2)]"]
{"fn_name": "pop_shift", "inputs": [["reusetestcasesbitcointakeovertheworldmaybewhoknowsperhaps"], ["turnsoutrandomtestcasesareeasierthanwritingoutbasicones"], ["exampletesthere"], ["letstalkaboutjavascriptthebestlanguage"], ["iwanttotraveltheworldwritingcodeoneday"], ["letsallgoonholidaysomewhereverycold"]], "outputs": [[["spahrepswonkohwebyamdlroweht", "reusetestcasesbitcointakeove", "r"]], [["senocisabtuognitirwnahtreis", "turnsoutrandomtestcasesaree", "a"]], [["erehtse", "example", "t"]], [["egaugnaltsebehttpir", "letstalkaboutjavasc", ""]], [["yadenoedocgnitirwdl", "iwanttotravelthewor", ""]], [["dlocyreverehwemos", "letsallgoonholida", "y"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,443
def pop_shift(s):
ad5c2060327d322dc9f675db2103f721
UNKNOWN
**Background** You most probably know, that the *kilo* used by IT-People differs from the *kilo* used by the rest of the world. Whereas *kilo* in kB is (mostly) intrepreted as 1024 Bytes (especially by operating systems) the non-IT *kilo* denotes the factor 1000 (as in "1 kg is 1000g"). The same goes for the prefixes mega, giga, tera, peta and so on. To avoid misunderstandings (like your hardware shop selling you a 1E+12 Byte harddisk as 1 TB, whereas your Windows states that it has only 932 GB, because the shop uses factor 1000 whereas operating systems use factor 1024 by default) the International Electrotechnical Commission has proposed to use **kibibyte** for 1024 Byte.The according unit symbol would be **KiB**. Other Prefixes would be respectivly: ``` 1 MiB = 1024 KiB 1 GiB = 1024 MiB 1 TiB = 1024 GiB ``` **Task** Your task is to write a conversion function between the kB and the KiB-Units. The function receives as parameter a memory size including a unit and converts into the corresponding unit of the other system: ``` memorysizeConversion ( "10 KiB") -> "10.24 kB" memorysizeConversion ( "1 kB") -> "0.977 KiB" memorysizeConversion ( "10 TB") -> "9.095 TiB" memorysizeConversion ( "4.1 GiB") -> "4.402 GB" ``` **Hints** - the parameter always contains a (fractioned) number, a whitespace and a valid unit - units are case sensitive, valid units are **kB MB GB TB KiB MiB GiB TiB** - result must be rounded to 3 decimals (round half up,no trailing zeros) see examples above **Resources** If you want to read more on ...ibi-Units: https://en.wikipedia.org/wiki/Kibibyte
["def memorysize_conversion(memorysize):\n [value, unit] = memorysize.split(\" \")\n kibis = [\"KiB\", \"MiB\", \"GiB\", \"TiB\"]\n kilos = [\"kB\", \"MB\", \"GB\", \"TB\"]\n if unit in kibis:\n return (str(round(float(value)*pow(1.024, kibis.index(unit)+1), 3))+\" \"+kilos[kibis.index(unit)])\n else:\n return (str(round(float(value)/pow(1.024, kilos.index(unit)+1), 3))+\" \"+kibis[kilos.index(unit)])", "CONV = {'KiB': 'kB', 'MiB': 'MB', 'GiB': 'GB', 'TiB': 'TB',\n 'kB': 'KiB', 'MB': 'MiB', 'GB': 'GiB', 'TB': 'TiB'}\n\ndef memorysize_conversion(size):\n val, unit = size.split()\n val = float(val)\n p = 'KMGT'.index(unit[0].upper()) + 1\n \n r = 1.024 if 'i' in unit else 1 / 1.024\n \n return '%s %s' % (round(val * r ** p, 3), CONV[unit])", "def memorysize_conversion(size):\n x, unit = size.upper().split()\n x, (u, *i, _) = float(x), unit\n op = float.__mul__ if i else float.__truediv__\n p, conv = \"_KMGT\".index(u), f\"{u}{'' if i else 'i'}B\"\n return f\"{round(op(x, 1.024**p), 3)} {conv}\".replace(\"KB\", \"kB\")", "v1, v2 = 1000/1024, 1024/1000\n\nD1 = {\"kB\":v1, \"MB\":v1**2, \"GB\":v1**3, \"TB\":v1**4,\n \"KiB\":v2, \"MiB\":v2**2, \"GiB\":v2**3, \"TiB\":v2**4}\n \nD2 = {\"kB\":\"KiB\", \"MB\":\"MiB\", \"GB\":\"GiB\", \"TB\":\"TiB\",\n \"KiB\":\"kB\", \"MiB\":\"MB\", \"GiB\":\"GB\", \"TiB\":\"TB\"}\n\ndef memorysize_conversion(memorysize):\n x, y = memorysize.split()\n return f\"{round(float(x) * D1[y], 3)} {D2[y]}\"", "from decimal import Decimal, ROUND_HALF_UP\n\nunits = 'KMGT'\nq = Decimal('0.001')\n\ndef memorysize_conversion(memorysize):\n n, unit = memorysize.split()\n n = Decimal(n)\n i = units.find(unit[0].upper()) + 1\n if unit[1] == 'i':\n n *= 1024 ** i\n n /= 1000 ** i\n new_unit = ['kB', 'MB', 'GB', 'TB'][i-1]\n else:\n n *= 1000 ** i\n n /= 1024 ** i\n new_unit = ['KiB', 'MiB', 'GiB', 'TiB'][i-1]\n new_value = format(n.quantize(n, rounding=ROUND_HALF_UP), '.3f').rstrip('0.')\n return f'{new_value} {new_unit}'", "kibi = ['KiB', 'MiB', 'GiB', 'TiB']\nsi = ['kB', 'MB', 'GB', 'TB']\n\ndef memorysize_conversion(size):\n val, unit = size.split()\n n = 'KMGT'.index(unit[0].upper())\n \n if unit in kibi:\n return '%s %s' % (round(float(val) * 1.024 ** (n+1), 3), si[n])\n else:\n return '%s %s' % (round(float(val) / 1.024 ** (n+1), 3), kibi[n])", "d = {'KiB':1.024,'kB':0.9765625,'GiB':1.073741824,'GB':0.93132257461548,'MiB':1.048576,'MB':0.95367431640625,'TiB':1.099511627776,'TB':0.90949470177293}\nto = {'KiB':' kB','GiB':' GB','MiB':' MB','TiB':' TB','TB':' TiB','GB':' GiB','MB':' MiB','kB':' KiB'}\nmemorysize_conversion=lambda m:str(round(float(m.split()[0]) * d[m.split()[1]],3)) + to[m.split()[1]]", "d={'k':1,'m':2,'g':3,'t':4}\ndef memorysize_conversion(memorysize):\n n,u=memorysize.split(' ')\n n=float(n)\n x=d[u[0].lower()]\n if u[1]=='i':\n n=round(n*(1.024**x),3)\n return '{} {}{}'.format(n,u[0],u[2]).replace('K','k')\n else:\n n=round(n/(1.024**x),3)\n return '{} {}i{}'.format(n,u[0].upper(),u[1])", "DCT_TO_IB = { unit: 1.024**p for unit,p in zip('KMGT',range(1,5)) }\n\ndef memorysize_conversion(s):\n toB = s[-2]=='i'\n v,u = s.split()\n unit = (u[0]!='K' and u[0] or 'k')+u[-1] if toB else u[0].upper()+\"i\"+u[-1]\n out = float(v) * DCT_TO_IB[u[0].upper()]**(toB or -1)\n out = f'{ out :.3f}'.rstrip('0')\n return f'{out} {unit}'", "def memorysize_conversion(s):\n a, b = s.split()\n n, m, i = (1024, 1000, \"\") if \"i\" in b else (1000, 1024, \"i\")\n p = \" KMGT\".index(b[0].upper())\n return f\"{round(float(a) * n**p / m**p, 3)} {'k' if b[0] == 'K' else b[0].upper()}{i}B\""]
{"fn_name": "memorysize_conversion", "inputs": [["1 KiB"]], "outputs": [["1.024 kB"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,821
def memorysize_conversion(memorysize):
33e75d0a85ace734b7d831219eafd6de
UNKNOWN
Create a function which checks a number for three different properties. - is the number prime? - is the number even? - is the number a multiple of 10? Each should return either true or false, which should be given as an array. Remark: The Haskell variant uses `data Property`. ### Examples ```python number_property(7) # ==> [true, false, false] number_property(10) # ==> [false, true, true] ``` The number will always be an integer, either positive or negative. Note that negative numbers cannot be primes, but they can be multiples of 10: ```python number_property(-7) # ==> [false, false, false] number_property(-10) # ==> [false, true, true] ```
["import math\n\ndef number_property(n):\n return [isPrime(n), isEven(n), isMultipleOf10(n)]\n # Return isPrime? isEven? isMultipleOf10?\n #your code here\n\ndef isPrime(n):\n if n <= 3:\n return n >= 2\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(n ** 0.5) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n \ndef isEven(n):\n return n % 2 == 0\n\ndef isMultipleOf10(n):\n return n % 10 == 0", "def number_property(n):\n return [n == 2 or n > 2 and pow(2, n-1, n) == 1,\n not n % 2,\n not n % 10]", "import random\n\nCERTAINTY = 10 # False positive rate: 4 ** -CERTAINTY\n\n\ndef number_property(n):\n return [is_prime(n), n % 2 == 0, n % 10 == 0]\n\n\ndef is_prime(n, k=CERTAINTY):\n if n == 2 or n == 3:\n return True\n if n < 2 or n % 2 == 0:\n return False\n\n s, d = _factorize(n - 1)\n\n for _ in range(k):\n a = random.randint(2, n - 2)\n x = pow(a, d, n)\n if _is_witness(x, n, s):\n return False\n\n return True # Probably\n\n\ndef _factorize(n):\n i = 0\n while n % 2 == 0:\n n >>= 1\n i += 1\n return i, n\n\n\ndef _is_witness(x, n, s):\n if x == 1 or x == n - 1:\n return False\n\n for _ in range(s - 1):\n x = pow(x, 2, n)\n if x == 1:\n return True\n if x == n - 1:\n return False\n\n return True", "def number_property(n):\n ans=[False,False,False]\n j=[]\n k=[]\n if n>1:\n for x in range(2,int(n ** 0.5)+ 1):\n j.append(x)\n if n%x:\n k.append(x)\n if k==j:\n ans[0]=True\n if n%2==0:\n ans[1]=True\n if n%10==0:\n ans[2]=True\n return ans", "import math\n\ndef number_property(n):\n return [isprime(n), n % 2 == 0, n % 10 == 0]\n\ndef isprime(fltx):\n if fltx == 2: return True\n if fltx <= 1 or fltx % 2 == 0: return False\n return all(fltx % i != 0 for i in range(3,int(math.sqrt(fltx))+1,2))"]
{"fn_name": "number_property", "inputs": [[0], [2], [5], [25], [131], [1], [100], [179424691], [179424693]], "outputs": [[[false, true, true]], [[true, true, false]], [[true, false, false]], [[false, false, false]], [[true, false, false]], [[false, false, false]], [[false, true, true]], [[true, false, false]], [[false, false, false]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,074
def number_property(n):
ca771be734043144f951e73b3bf080a0
UNKNOWN
There is an array of strings. All strings contains similar _letters_ except one. Try to find it! ```python find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) # => 'BbBb' find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) # => 'foo' ``` Strings may contain spaces. Spaces is not significant, only non-spaces symbols matters. E.g. string that contains only spaces is like empty string. It’s guaranteed that array contains more than 3 strings. This is the second kata in series: 1. [Find the unique number](https://www.codewars.com/kata/585d7d5adb20cf33cb000235) 2. Find the unique string (this kata) 3. [Find The Unique](https://www.codewars.com/kata/5862e0db4f7ab47bed0000e5)
["from collections import defaultdict\n\ndef find_uniq(a):\n d = {}\n c = defaultdict(int)\n for e in a:\n t = frozenset(e.strip().lower())\n d[t] = e\n c[t] += 1\n \n return d[next(filter(lambda k: c[k] == 1, c))]", "def find_uniq(arr):\n if set(arr[0].lower()) == set(arr[1].lower()):\n majority_set = set(arr[0].lower())\n elif set(arr[0].lower()) == set(arr[2].lower()):\n majority_set = set(arr[0].lower())\n else:\n majority_set = set(arr[1].lower())\n \n for string in arr:\n if set(string.lower()) != majority_set:\n return string", "\ndef find_uniq(arr):\n arr.sort(key=lambda x: x.lower())\n arr1 = [set(i.lower()) for i in arr]\n return arr[0] if arr1.count(arr1[0]) == 1 and str(arr1[0]) != 'set()' else arr[-1]", "import numpy as np\ndef find_uniq(arr):\n arr1 = [''.join(sorted(set(i.lower().replace(' ','')))) for i in arr]\n lst = np.unique(arr1)\n for i in lst:\n if arr1.count(i) == 1:\n return arr[arr1.index(i)] \n", "from collections import Counter\n\n\ndef find_uniq(arr):\n c = Counter(\"\".join(arr).lower())\n match = [string_ for string_ in arr if min(c, key=c.get) in string_.lower()]\n return match[0]\n", "def find_uniq(arr):\n counts = {}\n result = {}\n \n for s in arr:\n hash = frozenset(s.strip().lower())\n counts[hash] = counts.get(hash, 0) + 1\n result[hash] = s\n \n if len(counts) > 1 and counts[max(counts, key=counts.get)] > 1:\n return result[min(counts, key=counts.get)]", "from collections import Counter\n\ndef find_uniq(arr):\n res = Counter(''.join(arr)).most_common()\n return ''.join([x for x in arr if res[-1][0] in x])\n", "def find_uniq(arr):\n S = ''. join (arr) \n D = {}\n for i in S:\n D[i]=D.get(i,0)+1\n L = sorted([(v, k) for k, v in list(D.items())], reverse=True)\n Minv = L[-1][0] \n Min = L[-1][1] \n for word in arr:\n if word.count(Min) >= Minv:\n return word \n \n\n\n\n\n\n\n\n \n \n\n"]
{"fn_name": "find_uniq", "inputs": [[["Aa", "aaa", "aaaaa", "BbBb", "Aaaa", "AaAaAa", "a"]], [["abc", "acb", "bac", "foo", "bca", "cab", "cba"]], [["silvia", "vasili", "victor"]], [["Tom Marvolo Riddle", "I am Lord Voldemort", "Harry Potter"]], [["", "", "", "a", "", ""]], [[" ", " ", " ", "a", " ", ""]], [["foobar", "barfo", "fobara", " ", "fobra", "oooofrab"]]], "outputs": [["BbBb"], ["foo"], ["victor"], ["Harry Potter"], ["a"], ["a"], [" "]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,075
def find_uniq(arr):
209c8983fbfa6ea1062ee82cf6a4c713
UNKNOWN
Given two integers `a` and `x`, return the minimum non-negative number to **add to** / **subtract from** `a` to make it a multiple of `x`. ```python minimum(10, 6) #= 2 10+2 = 12 which is a multiple of 6 ``` ## Note - 0 is always a multiple of `x` ## Constraints **1 <= a <= 10^(6)** **1 <= x <= 10^(5)**
["def minimum(a, x):\n return min(a % x, -a % x)", "def minimum(a, x):\n return min(x-a%x, a%x)\n", "def minimum(a, x):\n return abs(a - x*round(a/x))\n", "def minimum(a, x):\n return min(a%x, abs(x - a%x))\n", "def minimum(a, x):\n r = a % x\n return r and min(r, x - r)", "def minimum(a, x):\n return abs(a-round(a/x)*x)\n", "def minimum(a, x):\n near=x\n while near<a:\n near += x\n plus = near-a\n minus = a-(near-x)\n return plus if plus < minus else minus", "def minimum(a, b):\n return min(a % b, b - a % b)", "def minimum(a, x):\n return min(a%x, x-a%x)", "def minimum(a, x):\n n = a % x\n m = (a // x + 1) * x - a\n return min(n, m)"]
{"fn_name": "minimum", "inputs": [[9, 4], [10, 6]], "outputs": [[1], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
701
def minimum(a, x):
865839a26e6217d41923f3a7f59e7f08
UNKNOWN
Your colleagues have been looking over you shoulder. When you should have been doing your boring real job, you've been using the work computers to smash in endless hours of codewars. In a team meeting, a terrible, awful person declares to the group that you aren't working. You're in trouble. You quickly have to gauge the feeling in the room to decide whether or not you should gather your things and leave. ```if-not:java Given an object (meet) containing team member names as keys, and their happiness rating out of 10 as the value, you need to assess the overall happiness rating of the group. If <= 5, return 'Get Out Now!'. Else return 'Nice Work Champ!'. ``` ```if:java Given a `Person` array (meet) containing team members, you need to assess the overall happiness rating of the group. If <= 5, return "Get Out Now!". Else return "Nice Work Champ!". The `Person` class looks like: ~~~java class Person { final String name; // team memnber's name final int happiness; // happiness rating out of 10 } ~~~ ``` Happiness rating will be total score / number of people in the room. Note that your boss is in the room (boss), their score is worth double it's face value (but they are still just one person!). The Office II - Boredom Score The Office III - Broken Photocopier The Office IV - Find a Meeting Room The Office V - Find a Chair
["def outed(meet, boss):\n return 'Get Out Now!' if (sum(meet.values()) + meet[boss] ) / len(meet) <= 5 else 'Nice Work Champ!'", "def outed(meet, boss):\n # sum of all people plus boss value, boss counts twice\n total_score = sum(meet.values()) + meet[boss]\n happiness_rating = total_score / len(meet)\n if happiness_rating > 5:\n return 'Nice Work Champ!'\n else:\n return 'Get Out Now!'\n", "def outed(meet, boss):\n return 'Get Out Now!' if sum(meet[person] if not person == boss else meet[person] * 2 for person in meet) / len(meet) <= 5 else 'Nice Work Champ!'", "def outed(meet, boss):\n total = sum(v if k != boss else v*2 for k, v in meet.items())\n return 'Nice Work Champ!' if total / len(meet) > 5 else 'Get Out Now!'", "def outed(meet, boss):\n return 'Get Out Now!' if sum([ i[1] for i in list(meet.items())] + [meet[boss]])/len(meet) <= 5 else 'Nice Work Champ!'\n", "def outed(meet, boss):\n return 'Nice Work Champ!' if (sum(meet.values()) + meet[boss]) > 5 * len(meet) else 'Get Out Now!'", "def outed(meet, boss):\n return 'Nice Work Champ!' if (sum(meet.values()) + meet[boss]) / len(meet) > 5 else 'Get Out Now!'", "def outed(d, boss):\n return ['Get Out Now!','Nice Work Champ!'][(sum(d.values()) + d[boss])/len(d)>5]\n", "outed=lambda meet, boss: \"Get Out Now!\" if sum([meet[i]*(1 if i!=boss else 2) for i in meet])/len(meet)<=5 else \"Nice Work Champ!\"", "def outed(meet, boss):\n total = sum(v for v in meet.values()) + meet[boss]\n if total / len(meet) <= 5:\n return 'Get Out Now!'\n return 'Nice Work Champ!'"]
{"fn_name": "outed", "inputs": [[{"tim": 0, "jim": 2, "randy": 0, "sandy": 7, "andy": 0, "katie": 5, "laura": 1, "saajid": 2, "alex": 3, "john": 2, "mr": 0}, "laura"], [{"tim": 1, "jim": 3, "randy": 9, "sandy": 6, "andy": 7, "katie": 6, "laura": 9, "saajid": 9, "alex": 9, "john": 9, "mr": 8}, "katie"], [{"tim": 2, "jim": 4, "randy": 0, "sandy": 5, "andy": 8, "katie": 6, "laura": 2, "saajid": 2, "alex": 3, "john": 2, "mr": 8}, "john"]], "outputs": [["Get Out Now!"], ["Nice Work Champ!"], ["Get Out Now!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,611
def outed(meet, boss):
b7816e85276cbee75a92b335fb29cc16
UNKNOWN
You receive some random elements as a space-delimited string. Check if the elements are part of an ascending sequence of integers starting with 1, with an increment of 1 (e.g. 1, 2, 3, 4). Return: * `0` if the elements can form such a sequence, and no number is missing ("not broken", e.g. `"1 2 4 3"`) * `1` if there are any non-numeric elements in the input ("invalid", e.g. `"1 2 a"`) * `n` if the elements are part of such a sequence, but some numbers are missing, and `n` is the lowest of them ("broken", e.g. `"1 2 4"` or `"1 5"`) ## Examples ``` "1 2 3 4" ==> return 0, because the sequence is complete "1 2 4 3" ==> return 0, because the sequence is complete (order doesn't matter) "2 1 3 a" ==> return 1, because it contains a non numerical character "1 3 2 5" ==> return 4, because 4 is missing from the sequence "1 5" ==> return 2, because the sequence is missing 2, 3, 4 and 2 is the lowest ```
["def find_missing_number(sequence):\n if not sequence:\n return 0\n try:\n sequence = set(int(a) for a in sequence.split())\n except ValueError:\n return 1\n for b in range(1, max(sequence) + 1):\n if b not in sequence:\n return b\n return 0\n", "def find_missing_number(sequence):\n try:\n numbers = sorted([int(x) for x in sequence.split()])\n for i in range(1, len(numbers)+1):\n if i not in numbers:\n return i\n except ValueError:\n return 1\n \n return 0", "def find_missing_number(sequence):\n try:\n sequence = [int(n) for n in sequence.split()]\n except ValueError:\n return 1\n for i, n in enumerate(sorted(sequence)):\n if n != i + 1:\n return i + 1\n return 0\n", "def find_missing_number(sequence):\n try:\n seq = set(map(int, sequence.split()))\n return (set(range(1, 1 + max(seq, default = 0))) - seq or {0}).pop()\n except:\n return 1", "def find_missing_number(sequence: str) -> int:\n try:\n elements = set(map(int, sequence.split()))\n except ValueError:\n return 1\n\n return min(set(range(1, len(elements) + 1)) - elements or [0])\n", "def find_missing_number(sequence):\n if not sequence:\n return 0\n if not sequence.replace(\" \", \"\").isnumeric():\n return 1\n seq = list(map(int, sequence.split(\" \")))\n result = [number for number in [x for x in range(1, max(seq))] if number not in seq]\n return 0 if not result else result[0]", "def find_missing_number(sequence):\n try:\n numbers = sorted(int(word) for word in sequence.split(\" \") if word)\n except ValueError:\n return 1\n return next((i + 1 for i, n in enumerate(numbers) if i + 1 != n), 0)", "def find_missing_number(sequence):\n ns = sequence.split()\n numbers = {int(x) for x in ns if x.isdigit()}\n if len(numbers) != len(ns):\n return 1\n for i in range(1, max(numbers, default=0)+1):\n if i not in numbers:\n return i\n return 0", "def find_missing_number(sequence):\n s = sequence.split()\n if all(el.isdigit() for el in s):\n for i in range(1, len(s) + 1):\n if str(i) not in s:\n return i\n return 0\n return 1", "def find_missing_number(sequence):\n \n sequence = sequence.strip().split()\n \n data = []\n \n for ch in sequence:\n if not ch.isdigit(): return 1\n else:\n data.append(int(ch))\n \n if data == [] : return 0\n else :\n data = sorted(data)\n \n pattern = list(range(1, len(data) + 1))\n \n if pattern == data:\n return 0 # all is good\n else:\n for pair in zip(pattern, data):\n if pair[0] != pair[1]:\n return pair[0] # here's the missing number\n\n", "def find_missing_number(sequence):\n try:\n seq = sorted(int(i) for i in sequence.split())\n except ValueError:\n return 1\n if seq and seq[0] != 1:\n return 1\n for idx, nr in enumerate(seq[:-1]): #slice sequence to prevent IndexError\n if nr+1 != seq[idx+1]:\n return nr+1\n return 0", "def find_missing_number(s):\n if not s:\n return 0\n elif s.replace(' ', '').isdigit():\n try:\n return [p[0]+1==p[1] for p in enumerate(sorted(map(int, s.split())))].index(False) + 1\n except ValueError:\n return 0\n else:\n return 1", "def find_missing_number(sequence):\n try:\n numbers = list(map(int, sequence.split()))\n except ValueError:\n return 1\n if not numbers: return 0\n all_nums = list(range(1, max(numbers)))\n r = sorted(set(all_nums) - set(numbers))\n return r[0] if len(r) > 0 else 0\n", "find_missing_number=lambda w:(lambda s:min(set(range(max(s)))-s or[0]))((set(w)<=set('0123456789 ')and set(map(int,w.split()))or{2})|{w==''})", "from itertools import count\n\ndef find_missing_number(sequence):\n try:\n seq = sorted(map(int, sequence.split()))\n return next(a for a, b in zip(count(1), seq) if a != b)\n except ValueError:\n return 1\n except StopIteration:\n return 0", "import re\n\ndef find_missing_number(sequence):\n if len(sequence) == 0:\n return 0\n elif not sequence.replace(\" \", \"\").isnumeric():\n return 1\n list1 = [int(i) for i in sequence.split(\" \")]\n maxNum = max(list1)\n if maxNum >= 10:\n for i in range(1, maxNum):\n s = str(i)\n if re.search('(:?(:?[^0-9]|^)'+s+' | '+s+'(:?[^0-9]|$))', sequence) == None:\n return i\n else:\n for i in range(1, maxNum):\n if str(i) not in sequence:\n return i\n return 0", "def find_missing_number(s):\n try:\n nums = set(map(int, s.split()))\n except:\n return 1\n \n missing = [ n for n in range(1, max(nums, default=0) +1) if n not in nums ]\n \n return min(missing, default=0)\n", "def find_missing_number(seq):\n try:\n seq = [int(a) for a in seq.split()]\n except ValueError:\n return 1\n for num in range(1, len(seq) + 1):\n if num not in seq: return num\n return 0", "def find_missing_number(sequence):\n s = sequence.split()\n try:\n s= [int(x) for x in s]\n except ValueError:\n return 1\n s.sort()\n for i in range(len(s)):\n if s[i] != i+1:\n return i+1\n return 0", "def find_missing_number(sequence):\n if not sequence.replace(\" \", \"\").isdigit(): return 1 * bool(sequence)\n sequence = set(int(a) for a in sequence.split(\" \"))\n missing = list(set(range(1, max(sequence))) - sequence)\n return 0 if not missing else missing[0]", "def find_missing_number(sequence):\n items = sequence.split(' ')\n try:\n items = sorted(int(x) for x in items) if sequence else []\n except ValueError:\n return 1\n for i, x in enumerate(items, 1):\n if i != x: return i\n return 0 ", "def find_missing_number(sequence):\n v = 1\n try:\n for n in sorted(map(int, sequence.split())):\n if n != v:\n return v\n v += 1\n except:\n return 1\n return 0", "def find_missing_number(sequence):\n arr = sequence.split(' ')\n if arr == ['']:\n return 0\n for i in range(0, len(arr)):\n try:\n arr[i] = int(arr[i]) \n except ValueError:\n return 1\n c = 1\n while c in arr:\n c += 1\n if c > max(arr):\n return 0\n return c", "def find_missing_number(s):\n if not s : return 0\n try : s = sorted(int(i) for i in s.split())\n except : return 1\n return next((i+1 for i in range(s[-1]) if i+1 not in s), 0)", "def find_missing_number(sequence):\n if not sequence:\n return 0\n sequenceList = list(sequence.split(' '))\n \n try:\n sequenceInt = [int(i) for i in sequenceList]\n except:\n return 1\n \n sequenceInt.sort()\n for i, number in enumerate(sequenceInt):\n if i+1 != number:\n return i+1\n return 0", "def find_missing_number(sequence):\n try: l = sorted([int(x) for x in sequence.split()])\n except: return 1\n for x, y in zip(l, range(1, len(l) + 1)):\n if y != x:\n return y\n return 0", "def find_missing_number(sequence):\n if len(sequence) == 0:\n return 0\n else:\n try:\n x = [int(i) for i in sequence.split()]\n except:\n return 1\n missing = set(range(1,max(x)+1)) - set(x)\n if len(missing) == 0:\n return 0\n else:\n return list(missing)[0]", "def find_missing_number(s):\n if s ==\"\":\n return 0\n try: s=set(map(int,s.split(\" \")))\n except ValueError: return 1\n try: return min(set(range(1,max(s))).difference(s))\n except ValueError: return 0", "def find_missing_number(seq):\n try:seq=sorted(map(int,seq.split()))\n except ValueError:return 1\n if not seq:return 0\n if seq[0]!=1:return 1\n for i,v in enumerate(seq[:-1]):\n if v+1!=seq[i+1]:\n return v+1\n return 0", "def find_missing_number(sequence):\n if len(sequence) == 0:\n return 0\n \n num = sequence.split()\n if not all(n.isdigit() for n in num):\n return 1\n \n num = [0] + sorted(map(int, num))\n return next((i for i in range(1, len(num)) if num[i] - num[i - 1] != 1), 0)", "def find_missing_number(sequence):\n if not sequence : return 0\n try : s=set(map(int,sequence.split(\" \")))\n except ValueError : return 1\n for i in range(len(s)):\n if not i+1 in s : return i+1\n return 0 ", "def find_missing_number(sequence):\n #if string is empty return 0\n if sequence == \"\":\n return 0\n \n #if string contains any letters or non numbers return 1\n if not sequence.isdigit or any(c.isalpha() for c in sequence) or \"_\" in sequence:\n return 1\n\n #create list of acsending numbers from string\n s = sorted(int(num) for num in sequence.split(' '))\n \n #if the elements in list form a perfect sequence from 1 return 0\n if s[-1] == len(s) and s[0] ==1:\n return 0\n\n #compare the list s to a newly created list starting from 1\n #if number is not in s, return number\n for i in range(len(s)):\n if s[i] != i+1:\n return i+1\n \n", "def find_missing_number(sequence):\n if sequence=='':\n return 0\n else:\n se=sequence.split()\n for j in se:\n if j.isdigit():\n continue\n else:\n return 1\n \n for i in range(1,len(se)+1):\n if str(i) not in se:\n return i\n return 0 \n \n", "def find_missing_number(s):\n if any(x.isalpha() or x=='_' for x in s):\n return 1\n s = sorted(map(int, s.split()))\n return 0 if not s or all(x in s for x in range(1, s[-1]+1)) else min(set(range(1, s[-1]+1))-set(s))\n", "def find_missing_number(sequence):\n if not sequence: return 0\n try: sequence = [int(el) for el in sequence.split(\" \")]\n except: return 1\n sequence.sort()\n if sequence[0] != 1: return 1\n for i in range(1, len(sequence)):\n if sequence[i] != sequence[i-1] + 1: return sequence[i-1] + 1\n return 0\n", "def find_missing_number(sequence):\n if not sequence:\n return 0\n try:\n numbers = sorted([int(x) for x in sequence.split()])\n except ValueError:\n return 1\n \n for i in range(1, len(numbers)+1):\n if i not in numbers:\n return i\n \n return 0\n", "def find_missing_number(sequence):\n lst = sequence.split(\" \")\n\n if sequence == \"\":\n return 0\n\n try:\n numbers = sorted([int(x) for x in lst])\n except ValueError:\n return 1\n\n if numbers == list(range(1, len(numbers)+1)):\n return 0\n \n if numbers[0] == 2 and numbers == list(range(2, len(numbers) + 2)):\n return 1\n\n #\"It must return 1 for a sequence missing the first element\"\n\n else:\n for i in range(len(numbers)-1):\n if numbers[i] + 1 != numbers[i+1]:\n return numbers[i] + 1", "def find_missing_number(sequence):\n a = []\n for i in sequence.split():\n if i.isdigit():\n a.append(int(i))\n else:\n return 1\n if a == []: return 0\n for i in range(1,max(a)+1):\n if not i in a:\n return i\n return 0", "def find_missing_number(sequence):\n try:\n t=[int(i) for i in sequence.split()]\n st=set(range(1,len(t)+1))-set(t)\n return min(st) if st else 0\n except:\n return 1", "def find_missing_number(sequence):\n \n if sequence == \"\":\n \n return 0\n \n try:\n \n sequence = set(int(x) for x in sequence.split())\n \n except ValueError:\n \n return 1\n \n for w in range(1,max(sequence)+1):\n \n if w not in sequence:\n \n return w\n \n return 0\n", "def find_missing_number(sequence):\n if not sequence:\n return 0\n if not is_valid(sequence):\n return 1\n numbers = sorted([int(x) for x in sequence.split(' ')])\n n = 1\n for i in range(0, len(numbers)):\n if numbers[i] != n:\n return n\n n += 1\n return 0\n\ndef is_valid(sequence):\n numbers = sequence.split(' ')\n for a in numbers:\n if not a.isdigit():\n return False\n return True\n", "def find_missing_number(sequence):\n if sequence =='': return 0\n if any(not x.isdigit() for x in sequence.split(' ')): return 1\n s = sorted(list(map(int,sequence.split(' '))))\n if s == list(range(1, max(s)+1)): return 0\n else: return min(i for i in range(1, max(s)+1) if i not in s) ", "def find_missing_number(sequence):\n try:\n l=[int(i) for i in sequence.split()]\n l.sort()\n for i in range(1,l[-1]):\n if i not in l:\n return i\n else:\n return 0\n except:\n return 1 if sequence !='' else 0", "def find_missing_number(sequence):\n a = list(map(int,list(filter(str.isdigit,sequence.split()))))\n if len(sequence.split()) != len(a): return 1\n if a:\n for n in range(1,max(a)+1):\n if n not in a:\n return n\n return 0\n", "def find_missing_number(sequence):\n if not sequence:\n return 0\n \n arr = sequence.split(' ')\n \n if any(not ch.isdigit() for ch in arr):\n return 1\n \n for n in range(1, len(arr)+1):\n if str(n) not in arr:\n return n\n \n return 0", "def find_missing_number(sequence):\n #your code here\n if sequence == \"\" : return 0\n try :\n seq = sorted([int(s) for s in sequence.split(' ')])\n except : return 1\n \n a = list(range(1, seq[-1]+1))\n return 0 if seq == a else (list(set(a)-set(seq)))[0]", "def find_missing_number(s):\n if s == '': return 0\n a = s.split(' ')\n if not all([x.isdigit() for x in a]): \n return 1\n b = sorted([int(x) for x in a])\n c = list(range(1, b[-1]+1))\n if b == c: \n return 0\n else: \n for x in c:\n if x not in b:\n return x\n return \"I've missed something\"", "def find_missing_number(sequence: str):\n if not sequence:\n return 0\n try:\n sequence = [int(i) for i in sequence.split(' ')]\n except:\n return 1\n for i in range(1, max(sequence) + 1):\n if i not in sequence:\n return i\n return 0", "def find_missing_number(s):\n if not s: \n return 0\n elif not all(x.isdigit() for x in s.split()):\n return 1\n \n s = sorted([int(i) for i in s.split()])\n if s[0] != 1:\n return 1\n \n a = [i for i in range(1,max(s)+1) if i not in s]\n return a[0] if len(a) > 0 else 0", "def find_missing_number(seq):\n if not seq:\n return 0\n elif not seq.replace(' ','').isdecimal(): \n return 1\n else:\n seq = set(map(int, seq.split()))\n full = set(range(1, max(seq) + 1))\n return 0 if seq == full else min(full - seq)\n", "def find_missing_number(sequence):\n if sequence == \"\":\n return 0\n seq = sequence.split()\n if not ''.join(seq).isdigit():\n return 1\n seq = list(map(int, seq))\n qwe = [i for i in range(1, max(seq) + 1)]\n if len(seq) == len(qwe):\n return 0\n for i in range(1, max(seq) + 1):\n if i not in seq:\n return i\n break", "def find_missing_number(sequence):\n if len(sequence) == 0:\n return 0\n sequence = sequence.split()\n int_sequence = sorted(int(d) for d in sequence if d.isdigit())\n if len(sequence) != len(int_sequence):\n return 1\n control = [n for n in range(1, int_sequence[-1]+1)]\n for n, j in zip(control, int_sequence):\n if n != j:\n return n\n return 0", "def find_missing_number(sequence):\n try:\n a = set(map(int, sequence.split()))\n try:\n return min(set(range(1, max(a) + 1)) - set(a))\n except:\n return 0\n except:\n return 1", "def find_missing_number(s):\n try:\n lst = sorted(map(int, s.split()))\n return next((x for x, y in zip(range(1, lst[-1] + 1), lst) if x != y), 0)\n except IndexError: return 0\n except ValueError: return 1", "def find_missing_number(sequence): \n if sequence == \"\": return(0) \n sequence = sequence.split(' ')\n for i in range(len(sequence)):\n if not sequence[i].isdigit(): return(1)\n else: sequence[i] = int(sequence[i])\n for i in range(1, max(sequence)):\n if i not in sequence: return(i)\n return(0)", "def find_missing_number(sequence):\n sequence=sequence.rsplit(sep=' ')\n if sequence==['']:\n return 0\n for a in sequence:\n try: int(a)\n except ValueError: \n return 1\n sequence=[int(b) for b in sequence]\n for c in range(1,max(sequence)+1):\n if c not in sequence:\n return c\n else:\n return 0", "def find_missing_number(sequence):\n if sequence=='': return 0\n if [x for x in sequence.split(' ') if x.isnumeric()==False]: return 1\n m = max(int(x) for x in sequence.split(' '))\n for x in range(1,m+1):\n if str(x) not in sequence.split(' '): return x\n return 0\n \n", "def find_missing_number(s):\n if s == \"\": return 0\n l = s.split(\" \")\n for i in l:\n if not i.isdigit():\n return 1\n l = sorted([int(i) for i in l])\n for i in range(len(l)):\n if i + 1 != l[i]:\n return i + 1\n return 0", "def find_missing_number(sequence):\n try:\n sequence = [int(num) for num in sequence.split()]\n nums = set(sequence)\n for i in range(1, len(sequence) + 1):\n if i not in nums:\n return i\n return 0\n except ValueError:\n return 1", "def find_missing_number(s):\n l = s.split(' ')\n if s == '':\n return 0\n st = []\n for x in l:\n for c in l:\n if c.isalpha():\n st.append(c)\n if len(st) > 0:\n return 1\n elif sorted([x for x in l]) == [str(y) for y in range(1,len(l)+1)]:\n return 0\n elif sorted([x for x in l]) != [str(y) for y in range(1,len(l)+1)]:\n missing = []\n for a in range(1,len(l)+1):\n if str(a) not in [x for x in l]:\n missing.append(int(a))\n return min(missing)", "def find_missing_number(sequence):\n if not sequence:\n return 0\n try:\n l = [int(elem) for elem in sequence.split(' ')]\n except ValueError:\n return 1\n for i in range(1, len(l)+1):\n if i not in l:\n return i\n return 0", "def find_missing_number(sequence):\n if not sequence:\n return 0\n sequence = sequence.split()\n for item in sequence:\n if not item.isdigit():\n return 1\n sequence = sorted(list(map(int, sequence)))\n proper_seq = range(1, len(sequence) + 1)\n for x, y in zip(sequence, proper_seq):\n if x != y:\n return y\n return 0", "def find_missing_number(sequence):\n\n # \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043d\u0430 \u043d\u0435 \u043f\u0443\u0441\u0442\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443\n if not sequence:\n return 0\n\n # \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043d\u0430 int \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430\n try:\n sequence = [int(elem) for elem in sequence.split()]\n except ValueError:\n return 1\n\n # \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043d\u0430 \u0441\u043e\u0432\u043f\u0430\u0434\u0435\u043d\u0438\u0435\n for elem in range(1, len(sequence) + 1):\n if elem not in sequence:\n return elem\n\n return 0", "def find_missing_number(sequence):\n\n # \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043d\u0430 \u043d\u0435 \u043f\u0443\u0441\u0442\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443\n if not sequence:\n return 0\n\n # \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043d\u0430 int \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u0430\n try:\n sequence = [int(elem) for elem in sequence.split()]\n except ValueError:\n return 1\n\n pattern = list(range(1, len(sequence) + 1))\n sequence.sort()\n\n for idx, elem in enumerate(sequence):\n if elem != pattern[idx]:\n return pattern[idx]\n\n return 0", "def find_missing_number(sq):\n if sq == '':\n return 0\n try:\n arr = [int(e) for e in sq.split(' ')]\n except ValueError:\n return 1\n else:\n arr.sort()\n for i in range(0, len(arr)):\n if arr[i] != i + 1:\n return i + 1 \n return 0\n \n \n", "def find_missing_number(sequence):\n try:\n nums=list(map(int,sequence.split()))\n nums.sort()\n for i in range(len(nums)):\n if nums[i]!=i+1:\n return i+1\n \n return 0\n \n except:\n return 1\n", "def find_missing_number(sequence):\n if not sequence:\n return 0\n try:\n sequence = set(sorted(int(s) for s in sequence.split()))\n diff = set(range(1, max(sequence)+1)) - sequence\n if not diff:\n return 0\n return min(diff)\n except:\n return 1\n", "def find_missing_number(sequence):\n try:\n nums = list(map(int, sequence.split()))\n except:\n return 1\n\n max_num = max(nums) if nums else 0\n return (\n min(set(range(1, max_num + 1)) - set(nums))\n if set(range(1, max_num + 1)) != set(nums)\n else 0\n )\n", "def find_missing_number(sequence):\n if sequence==\"\":\n return 0\n sequence=sequence.split(\" \")\n try:\n sequence=list(map( int ,sequence))\n sequence.sort()\n maxi = max(sequence)\n for i in range(1,maxi+1):\n if i not in sequence:\n return i\n except ValueError:\n return 1\n return 0", "def find_missing_number(s):\n try:s = sorted(map(int, s.split()))\n except: return 1\n for i,j in enumerate(s[:-1]):\n if j+1!= s[i+1]:\n return j+1\n return 0 if not s or s[0]==1 else 1", "def find_missing_number(sequence):\n sequence = sequence.split()\n if any(not n.isdigit() for n in sequence):\n return 1\n sequence = sorted(int(n) for n in sequence)\n for i, n in enumerate(sequence, 1):\n if int(n) != i:\n return i\n return 0", "def find_missing_number(sequence):\n if len(sequence) == 0:\n return 0\n l = sequence.split()\n try:\n l = list(map(int, l))\n s1 = set(l)\n s2 = list(range(1, max(l)+1))\n s2 = set(s2)\n dif = s2.difference(s1)\n if len(dif) != 0:\n return next(iter(dif))\n else:\n return 0\n except ValueError:\n return 1", "def find_missing_number(sequence):\n if len(sequence) == 0:\n return 0\n myNumbers = sequence.split(\" \")\n try:\n myNumbers = list(map(int,myNumbers))\n myNumbers.sort()\n except:\n return 1\n for i in range(0,len(myNumbers)):\n if (myNumbers[i] != (i+1)):\n return i +1\n return 0", "def find_missing_number(sequence):\n try:\n if not sequence:\n return 0\n elements = list(map(int, sequence.split(' ')))\n start = 1\n for element in sorted(elements):\n if element != start:\n return start\n start += 1\n return 0\n except:\n return 1", "def find_missing_number(sequence):\n try:\n return next((i for i,x in enumerate(sorted(map(int, sequence.split())), 1) if i != x), 0)\n except:\n return 1", "def find_missing_number(sq):\n num = 0\n sq = sq.split()\n try:\n sq = list(map(int, sq))\n sq = sorted(sq)\n for i in sq:\n num += 1\n if i != num:\n return num\n return 0\n except ValueError:\n return 1", "def find_missing_number(sequence):\n if sequence == \"\":\n return 0\n\n x = sequence.split()\n result = []\n for i in x:\n if i.isdigit() == False:\n return 1\n elif i.isdigit() == True:\n result.append(int(i))\n\n result.sort()\n start = 0\n for i in range(len(result)):\n if result[i] == start+1:\n start = start + 1\n else:\n prev = start\n break\n else:\n return 0\n\n return prev+1", "def find_missing_number(sequence):\n try:\n for idx, x in enumerate(sorted(map(int,sequence.split()))):\n if int(x) != idx+1:\n return idx +1\n except:\n return 1\n \n return 0", "def find_missing_number(s):\n if not s:\n return 0\n try:\n arr = list(map(int, s.split()))\n mi, mx = min(arr), max(arr)\n for i in range(1,mx+1):\n if i not in arr:\n return i\n return 0\n except:\n return 1", "def find_missing_number(sequence):\n #your code here\n if not sequence:\n return 0\n try:\n list = [int(a) for a in sequence.split()]\n for i in range(1, len(list)+1):\n if i not in list:\n return i\n except ValueError:\n return 1\n return 0", "def find_missing_number(sequence):\n try:\n nums = set(map(int, sequence.split()))\n try:\n return min(c for c in range(1, max(nums)) if c not in nums)\n except:\n return 0\n except:\n return 1", "def find_missing_number(sequence):\n if not sequence:\n return 0\n if sequence.replace(\" \", \"\").isnumeric():\n sequence = sorted(int(i) for i in sequence.split(\" \"))\n for i in range(1, sequence[len(sequence) - 1]):\n if i not in sequence:\n return i \n return 0\n return 1", "def find_missing_number(s):\n try:\n l = sorted([int(i) for i in s.split()])\n except:\n return 1\n if l == []: return 0\n a = [i for i, x in enumerate(l, min(l))]\n b = [x for i, x in enumerate(l, min(l))]\n if a == b and a[0] == 1:\n return 0\n c = [i for i, x in enumerate(l, 1)]\n d = [x for i, x in enumerate(l)]\n return min([i for i in c if i not in d])\n \n \n", "def find_missing_number(sequence):\n if not sequence:\n return 0\n elif not sequence.replace(\" \", \"\").isdigit():\n return 1\n \n new_seq = list( map( int, sequence.split()))\n try :\n ans = min( set( range( 1, max( new_seq) + 1)).difference( set( new_seq)))\n return ans\n except :\n return 0", "def find_missing_number(sequence):\n if not sequence: return 0\n lst = sequence.split(\" \")\n if not all([el.isdigit() for el in lst]): #present not number\n return 1\n lst = list([int(el) for el in lst])\n max_seq = max(lst)\n for el in range(1, max_seq + 1):\n if el not in lst:\n return el\n return 0\n", "def find_missing_number(sequence):\n if not sequence:\n return 0\n items = sequence.split(' ')\n numbers = []\n for item in items:\n try:\n numbers.append(int(item))\n except ValueError:\n return 1\n numbers.sort()\n if numbers[0] != 1:\n return 1\n for i, x in enumerate(numbers[:-1]):\n if numbers[i + 1] != x + 1:\n return x + 1\n return 0", "def find_missing_number(sequence):\n s = sequence.split()\n if s == []:\n return 0\n try:\n s = list(map(int,s))\n except:\n return 1\n for i in range(1,max(s)+1):\n if i not in s:\n return i\n return 0\n", "def find_missing_number( sequence ):\n if not sequence:\n return 0\n l = sequence.split()\n sd = \"\".join( l )\n if sd.isdigit():\n l = [ int( i ) for i in l ]\n for idx, el in enumerate( sorted( l ), 1 ):\n if el != idx:\n return idx\n return 0\n return 1\n", "def find_missing_number(sequence):\n #your code here\n if len(sequence) < 1:\n return 0\n try:\n sequence = [int(item) for item in sequence.split(sep=' ')]\n except ValueError:\n return 1\n else:\n for item in range(1, len(sequence) + 1):\n if item not in sequence:\n return item\n return 0\n", "def find_missing_number(seq):\n if not seq:\n return 0\n try:\n numbers = sorted(map(int, seq.split(' ')))\n for i in range(len(numbers)):\n if numbers[i] != i + 1:\n return i + 1\n return 0\n except:\n return 1", "def find_missing_number(sequence):\n if sequence=='':\n return 0\n tmp = []\n for i in sequence.split(' '):\n try:\n tmp.append(int(i))\n except:\n return 1\n t = 0\n print(tmp)\n for i in sorted(tmp):\n if t+1 == i:\n t+=1\n continue\n else:\n return t+1\n return 0", "def find_missing_number(sequence):\n missing = []\n l = sequence.split()\n for i in range(1, len(l)+1):\n if not l[i-1].isdigit():\n return 1\n if str(i) not in l:\n missing.append(i)\n return min(missing) if missing else 0\n", "def find_missing_number(sequence):\n if sequence:\n for i in sequence:\n if i not in '0123456789 ':\n return 1\n break\n strArr=sequence.split()\n Arr=[int(i) for i in strArr]\n Arr.sort()\n check=[i for i in range(1, max(Arr)+1)]\n for i in check:\n if i not in Arr:\n return i\n break\n return 0\n else:\n return 0", "def find_missing_number(s):\n if len(s) < 1: return 0\n try:\n s = sorted(int(x) for x in s.split())\n except:\n return 1\n for c, x in enumerate(s, 1):\n if c != int(x):\n return c\n return 0", "def find_missing_number(x):\n try:\n x=sorted(list(map(lambda i:int(i),(x.split()))))\n for i in range(1,len(x)+1):\n if x[i-1]!=i:\n return(i)\n return(0)\n except:\n return(1)", "def find_missing_number(sequence):\n if sequence=='':\n return 0\n elif not all([x.isdigit() for x in sequence.split()]):\n return 1\n else:\n s = sorted(sequence.split(), key=lambda x: int(x))\n print((int(s[0])))\n for x in range(len(s)-1):\n if int(s[x+1])-int(s[x])!=1:\n return int(s[x])+1\n elif int(s[0])!=1:\n return 1\n elif len(s)==int(s[-1]):\n return 0\n \n \n", "def find_missing_number(s):\n s = s.split()\n if not all(x.isdigit() for x in s): return 1\n r = range(1, len(s) + 1)\n for x in r:\n if str(x) not in s: return x\n return 0", "def find_missing_number(sequence):\n if sequence == \"\":\n return 0\n sequence = sequence.split()\n if any(not x.isdigit() for x in sequence):\n return 1\n sequence = set(int(x) for x in sequence)\n if sequence == set(range(1, max(sequence)+1)):\n return 0\n else:\n return min(set(range(1, max(sequence)+1)).difference(sequence))", "def find_missing_number(sequence):\n if sequence == \"\": \n return 0\n try: \n sq = [int(x) for x in sequence.split()]\n except: \n return 1\n mini, maxi = min(sq), max(sq)\n for x in range(mini, maxi+1): \n if x not in sq: \n return x\n return mini - 1", "def find_missing_number(sequence):\n try:\n seq = [int(e) for e in sequence.split()]\n except ValueError:\n return 1\n for i in range(1, len(seq) + 1):\n if i not in seq:\n return i\n return 0"]
{"fn_name": "find_missing_number", "inputs": [["1 2 3 5"], ["1 5"], [""], ["1 2 3 4 5"], ["2 3 4 5"], ["2 6 4 5 3"], ["_______"], ["2 1 4 3 a"], ["1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 91 92 93 94 95 96 97 98 99 100 101 102"]], "outputs": [[4], [2], [0], [0], [1], [1], [1], [1], [90]]}
INTRODUCTORY
PYTHON3
CODEWARS
32,935
def find_missing_number(sequence):
68e8313c239c5029c7d51ba6b5a8de30
UNKNOWN
When working with color values it can sometimes be useful to extract the individual red, green, and blue (RGB) component values for a color. Implement a function that meets these requirements: + Accepts a case-insensitive hexadecimal color string as its parameter (ex. `"#FF9933"` or `"#ff9933"`) + Returns an object with the structure `{r: 255, g: 153, b: 51}` where *r*, *g*, and *b* range from 0 through 255 **Note:** your implementation does not need to support the shorthand form of hexadecimal notation (ie `"#FFF"`) ## Example ``` "#FF9933" --> {r: 255, g: 153, b: 51} ```
["def hex_string_to_RGB(s): \n return {i:int(s[j:j+2],16) for i,j in zip('rgb',[1,3,5])}", "def hex_string_to_RGB(hex): \n return {'r': int(hex[1:3],16),'g': int(hex[3:5],16), 'b': int(hex[5:7],16)}", "def hex_string_to_RGB(s): \n return {c: int(s[1+2*i:3+2*i], 16) for i,c in enumerate('rgb')}", "def hex_string_to_RGB(hex_string): \n return {\n 'r': int(f'0x{hex_string[1:3]}', 16),\n 'g': int(f'0x{hex_string[3:5]}', 16),\n 'b': int(f'0x{hex_string[5:]}', 16)\n }\n", "def hex_string_to_RGB(h): \n def hex(_h): return int(_h, 16)\n return {'r': hex(h[1:3]), 'g':hex(h[3:5]), 'b':hex(h[5:7])}", "def hex_string_to_RGB(hex_string): \n # your code here\n r = int(hex_string[1:3], 16)\n g = int(hex_string[3:5], 16)\n b = int(hex_string[5:7], 16)\n \n return {'r': r, 'g': g, 'b': b}", "def hex_string_to_RGB(hex_string):\n r, g, b = [ int(hex_string[i:i+2], 16) for i in (1, 3, 5) ]\n return {'r': r, 'g': g, 'b': b}", "def hex_string_to_RGB(hex_string):\n color = int(hex_string[1:], 16)\n return {'r': color >> 16 & 255, 'g': color >> 8 & 255, 'b': color & 255}", "def hex_string_to_RGB(hex_string):\n n = int(hex_string[1:],16)\n return {'r' : n>>16, 'g': (n>>8)&0xff, 'b':n&0xff}", "def hex_string_to_RGB(hex_string): \n integer = eval(f'0x{hex_string.lstrip(\"#\").lower()}')\n return {'r': (integer >> 16) & 255, 'g': (integer >> 8) & 255, 'b': integer & 255}"]
{"fn_name": "hex_string_to_RGB", "inputs": [["#FF9933"], ["#beaded"], ["#000000"], ["#111111"], ["#Fa3456"]], "outputs": [[{"r": 255, "g": 153, "b": 51}], [{"r": 190, "g": 173, "b": 237}], [{"r": 0, "g": 0, "b": 0}], [{"r": 17, "g": 17, "b": 17}], [{"r": 250, "g": 52, "b": 86}]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,451
def hex_string_to_RGB(hex_string):
b785a2b1bb2a6872e9428c07d851e7c3
UNKNOWN
# Task `EvilCode` is a game similar to `Codewars`. You have to solve programming tasks as quickly as possible. However, unlike `Codewars`, `EvilCode` awards you with a medal, depending on the time you took to solve the task. To get a medal, your time must be (strictly) inferior to the time corresponding to the medal. You can be awarded `"Gold", "Silver" or "Bronze"` medal, or `"None"` medal at all. Only one medal (the best achieved) is awarded. You are given the time achieved for the task and the time corresponding to each medal. Your task is to return the awarded medal. Each time is given in the format `HH:MM:SS`. # Input/Output `[input]` string `userTime` The time the user achieved. `[input]` string `gold` The time corresponding to the gold medal. `[input]` string `silver` The time corresponding to the silver medal. `[input]` string `bronze` The time corresponding to the bronze medal. It is guaranteed that `gold < silver < bronze`. `[output]` a string The medal awarded, one of for options: `"Gold", "Silver", "Bronze" or "None"`. # Example For ``` userTime = "00:30:00", gold = "00:15:00", silver = "00:45:00" and bronze = "01:15:00"``` the output should be `"Silver"` For ``` userTime = "01:15:00", gold = "00:15:00", silver = "00:45:00" and bronze = "01:15:00"``` the output should be `"None"` # For Haskell version ``` In Haskell, the result is a Maybe, returning Just String indicating the medal if they won or Nothing if they don't. ```
["def evil_code_medal(user_time, gold, silver, bronze):\n for medal, time in [[\"Gold\", gold], [\"Silver\", silver], [\"Bronze\", bronze]]:\n if user_time < time:\n return medal\n \n return \"None\"\n", "from bisect import bisect_right as bisect\n\nMEDALS = [\"Gold\", \"Silver\", \"Bronze\", \"None\"]\n\ndef evil_code_medal(user_time, *times):\n return MEDALS[bisect(times, user_time)]", "def evil_code_medal(t,g,s,b):\n return \"Gold\"if t<g else\"Silver\"if t<s else\"Bronze\"if t<b else'None'", "def evil_code_medal(user_time, gold, silver, bronze):\n user_seconds = time_to_seconds(user_time)\n if user_seconds < time_to_seconds(gold):\n return \"Gold\"\n elif user_seconds < time_to_seconds(silver):\n return \"Silver\"\n elif user_seconds < time_to_seconds(bronze):\n return \"Bronze\"\n else:\n return \"None\"\n \ndef time_to_seconds(time):\n hours, minutes, seconds = time.split(':')\n return 3600 * int(hours) + 60 * int(minutes) + int(seconds) ", "def evil_code_medal(user_time, *medals):\n return next(\n (name for name, time in zip(\"Gold Silver Bronze\".split(), medals) if user_time < time),\n \"None\")", "evil_code_medal=lambda *args: [\"None\",\"Bronze\",\"Silver\",\"Gold\"][sum(arg>args[0] for arg in args[1:])]", "def evil_code_medal(user_time, gold, silver, bronze):\n return ['None', 'Bronze', 'Silver', 'Gold'][\n (user_time < bronze) + (user_time < silver) + (user_time < gold)\n ]", "evil_code_medal=lambda t,*m:next((s for s,n in zip((\"Gold\",\"Silver\",\"Bronze\"),m)if t<n),\"None\")", "def evil_code_medal(t, g, s, b):\n return t<g and 'Gold' or t<s and 'Silver' or t<b and 'Bronze' or 'None'", "def evil_code_medal(*t):\n return ('None', 'Bronze', 'Silver', 'Gold')[sorted(t, reverse=True).index(t[0])]"]
{"fn_name": "evil_code_medal", "inputs": [["00:30:00", "00:15:00", "00:45:00", "01:15:00"], ["01:15:00", "00:15:00", "00:45:00", "01:15:00"], ["00:00:01", "00:00:10", "00:01:40", "01:00:00"], ["00:10:01", "00:00:10", "00:01:40", "01:00:00"], ["00:00:01", "00:00:02", "00:00:03", "00:00:04"], ["90:00:01", "60:00:02", "70:00:03", "80:00:04"], ["03:15:00", "03:15:00", "03:15:01", "03:15:02"], ["99:59:58", "99:59:57", "99:59:58", "99:59:59"], ["14:49:03", "77:39:08", "92:11:36", "94:07:41"], ["61:01:40", "64:19:53", "79:30:02", "95:24:48"]], "outputs": [["Silver"], ["None"], ["Gold"], ["Bronze"], ["Gold"], ["None"], ["Silver"], ["Bronze"], ["Gold"], ["Gold"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,879
def evil_code_medal(user_time, gold, silver, bronze):
02d6a2b9453f7a7d295e17da1bd1bd19
UNKNOWN
In this Kata, you will be given a number and your task will be to rearrange the number so that it is divisible by `25`, but without leading zeros. Return the minimum number of digit moves that are needed to make this possible. If impossible, return `-1` ( `Nothing` in Haskell ). For example: More examples in test cases. Good luck!
["def solve(n):\n moves = []\n for a, b in [\"25\", \"75\", \"50\", \"00\"]:\n s = str(n)[::-1]\n x = s.find(a)\n y = s.find(b, x+1 if a == \"0\" else 0)\n if x == -1 or y == -1:\n continue\n moves.append(x + y - (x > y) - (a == b))\n s = s.replace(a, \"\", 1).replace(b, \"\", 1)\n l = len(s.rstrip(\"0\"))\n if l:\n moves[-1] = moves[-1] + (len(s) - l)\n elif s:\n moves.pop()\n return min(moves, default=-1)", "def moves(st, ending):\n s = list(st)\n \n steps = 0\n for i in range(-1, -len(ending) - 1, -1):\n char = ending[i]\n while s[i] != char:\n # Find latest example of the missing char in the string prior to our position\n actual = [j for j, c in enumerate(s[:i]) if c == char][-1]\n # Transpose it with the character to its right\n s[actual], s[actual + 1] = s[actual + 1], s[actual]\n steps += 1\n\n while s[0] == '0':\n # Transpose first non-zero character with character to its left \n actual = [j for j, c in enumerate(s) if c != '0'][0]\n s[actual - 1], s[actual] = s[actual], s[actual - 1]\n steps += 1\n \n return steps\n\n\n\ndef solve(n):\n print(f'n: {n}')\n s = str(n)\n _0, _2, _5, _7 = s.count('0'), s.count('2'), s.count('5'), s.count('7')\n \n best = not_possible = len(s) * 2 + 1\n if _0 > 1:\n # Enough 0s to end in ..00\n best = min(best, moves(s, '00'))\n if _2 and _5:\n # 2 & 5 present so we can end in ..25\n best = min(best, moves(s, '25'))\n if _5 and _0: \n # 5 & 0 present so we can end in ..50\n best = min(best, moves(s, '50'))\n if _7 and _5: \n # 7 & 5 present so we can end in ..75\n best = min(best, moves(s, '75'))\n\n if best == not_possible:\n best = -1\n return best\n", "def solve(n):\n def inversion(s, a, b):\n x, y = s.rfind(a), s.rfind(b)\n if a == b: x = s.rfind(a, 0, y)\n # Suffix not found\n if not x > -1 < y: return float('inf')\n inv = len(s) - 2 - x + len(s) - 1 - y + (x > y)\n # Leading zeros\n if not x > 0 < y:\n t = s[1 + ({x, y} == {0, 1}):]\n if t: inv += len(s) - len(str(int(t))) - 1 - ({x, y} == {0, 1})\n return inv\n\n inv = min(inversion(str(n), a, b) for a, b in '00 25 50 75'.split())\n return -1 if inv == float('inf') else inv\n", "from functools import partial\n\ndef check(s, tail):\n i = s.find(tail[1])\n if i == -1: return float('inf')\n s = s[:i] + s[i+1:]\n \n j = s.find(tail[0])\n if j == -1: return float('inf')\n s = s[:j] + s[j+1:]\n \n if not s: return i+j\n if s == '0'*len(s): return float('inf')\n return i + j + next(i for i,c in enumerate(reversed(s)) if c != '0')\n\ndef solve(n):\n result = min(map(partial(check, str(n)[::-1]), ('00', '25', '50', '75')))\n return -1 if result == float('inf') else result", "from collections import Counter as C\ndef solve(n):\n c, l, li = C(str(n)), len(str(n))-1, []\n for i in '75 50 00 25'.split():\n if not C(i) - c:\n a, b, cn, t = i[0], i[1], 0, list(str(n))\n bi = l - t[::-1].index(b)\n t.insert(l, t.pop(bi))\n ai = l - t[:-1][::-1].index(a) - 1\n t.insert(l-1, t.pop(ai))\n li.append((l-bi)+(l-ai-1)+[0,next(k for k,l in enumerate(t) if l!='0')][t[0]=='0'])\n return min(li,default=-1) #headache", "def solve(n):\n sn = str(n)\n ret = 0\n if n % 25 == 0:\n return ret\n \n if not (sn.count('0') >= 2 or ('5' in sn and ('0' in sn or '2' in sn or '7' in sn))):\n return -1\n\n zeroes = []\n two = -1\n five = -1\n seven = -1\n for c in range(len(sn)):\n if sn[c] == '0':\n zeroes.append(c)\n elif sn[c] == '2':\n two = c\n elif sn[c] == '5':\n five = c\n elif sn[c] == '7':\n seven = c\n \n minlen = 2 * len(sn)\n if len(zeroes) > 1:\n # '00' possible\n # move last 0 to last place\n steps = len(sn) - zeroes[-1] - 1\n # move second to last 0 to last place but 1\n steps += len(sn) - zeroes[-2] - 2\n minlen = min(minlen, steps)\n \n if five != -1:\n # 25\n if two != -1:\n steps = 2*len(sn) - five - two - 3\n if five < two:\n steps += 1\n # check for leading zeroes\n min25 = min(two,five)\n max25 = max(two,five)\n popsn = sn[:min25] + sn[min25+1:max25] + sn[max25+1:]\n update = False\n while len(popsn) > 0 and popsn[0] == '0':\n steps += 1\n update = True\n popsn = popsn[1:]\n minlen = min(minlen, steps)\n # 50\n if zeroes != []:\n steps = 2*len(sn) - five - zeroes[-1] - 3\n if zeroes[-1] < five:\n steps += 1\n # check for leading zeroes\n min50 = min(zeroes[-1],five)\n max50 = max(zeroes[-1],five)\n popsn = sn[:min50] + sn[min50+1:max50] + sn[max50+1:]\n update = False\n while len(popsn) > 0 and popsn[0] == '0':\n steps += 1\n update = True\n popsn = popsn[1:]\n minlen = min(minlen, steps)\n # 75\n if seven != -1:\n steps = 2*len(sn) - five - seven - 3\n if five < seven:\n steps += 1\n # check for leading zeroes\n min75 = min(five,seven)\n max75 = max(five,seven)\n popsn = sn[:min75] + sn[min75+1:max75] + sn[max75+1:]\n update = False\n while len(popsn) > 0 and popsn[0] == '0':\n steps += 1\n update = True\n popsn = popsn[1:]\n minlen = min(minlen, steps)\n return minlen\n", "def spoc(sn, cyfry):\n if sn.endswith(cyfry): return 0\n cp, co = cyfry\n res = 0\n ico = sn.rfind(co)\n res += len(sn) - ico - 1\n sn = sn[:ico] + sn[ico+1:]\n icp = sn.rfind(cp)\n res += len(sn) - icp - 1\n sn = sn[:icp] + sn[icp+1:]\n lpz,i = 0, 0\n if len(sn) > 0 and len(sn) == sn.count('0'): return None\n while sn and sn[i] == '0':\n i += 1\n lpz += 1\n return res + lpz\n \ndef solve(n):\n print(n)\n sn, t = str(n), []\n if sn.count('0') > 1:\n t.append(spoc(sn, '00'))\n for p, d in ('25', '50', '75'):\n if p in sn and d in sn:\n x = spoc(sn, p + d)\n if x is not None: t.append(x)\n return min(t) if t else -1\n", "import re\ndef difference(n,s) :\n n = str(n)[::-1]\n try :\n right_index = n.index(s[1])\n left_index = n.index(s[0],[0,1 + right_index][s[0] == s[1]])\n except : return float('inf')\n upper_index = 1 + max(left_index,right_index) == len(n) and '0' == n[-2] and len(re.search('0*.$',n)[0])\n return right_index + left_index - 1 + (left_index < right_index) + (upper_index and upper_index - 1 - (len(n) <= min(left_index,right_index) + upper_index))\ndef solve(n) :\n removes = min([difference(n,'00'),difference(n,'25'),difference(n,'50'),difference(n,'75')])\n return [-1,removes][int == type(removes)]\n", "def solve(n):\n min_cost = -1\n # Change the number to a string and reverse it.\n # This makes it possible to use .index to find the lowest place a digit appears.\n s = str(n)[::-1]\n # Calculate cost of each possible ending digit pair and keep the lowest cost at each point.\n for pair in ('00', '25', '50', '75'):\n cost = calculate_ending_pair_cost(s, pair)\n if min_cost == -1 or (cost != -1 and cost < min_cost):\n min_cost = cost\n\n return min_cost\n\ndef calculate_ending_pair_cost(s, pair):\n # First find the lowest place indices of each desired digit.\n indices = find_lowest_places(s, pair)\n # If we can't find one of the digits, then this ending pair is not possible.\n if indices is None:\n return -1\n # Start with an indicator of whether the desired digits are in the wrong order.\n cost = 1 if indices[1] > indices[0] else 0\n # Then swap the digits so the rest of our calculations are easier.\n # It's important to have these index numbers in descending order.\n if cost == 1:\n indices = (indices[1], indices[0])\n # Our number now looks something like this: aaa2bbbb5ccccc\n # The cost should be the number of digits (b's) we have to displace to move the 2 next to the 5,\n # and then twice the number of digits to displace to move the 2 and 5 to the \"front\".\n # This is because each c must move past both the 5 and the 2.\n cost += indices[0] - indices[1] - 1\n cost += 2 * indices[1]\n # We have one last special case to consider: What about leaving leading 0's in the high places?\n # We only bother with this if the number is more than 2 digits.\n if len(s) > 2:\n non_zero_index = first_non_zero_digit_after_indices(s, indices)\n if non_zero_index is None:\n return -1\n cost += len(s) - 1 - non_zero_index\n # Make sure not to double-count any digits we already moved as part of the desired digits.\n cost -= 1 if indices[0] > non_zero_index else 0\n cost -= 1 if indices[1] > non_zero_index else 0\n \n return cost\n\ndef find_lowest_places(s, pair):\n # Split the two-char string into the 1s place digit and 10s place digit.\n d10, d1 = pair\n try:\n i1 = s.index(d1)\n except:\n # Index raises an exception if it can't find the digit,\n # so just use that as an indicator of when to return a failure state.\n return None\n \n # If the pair we're looking for is a repeated digit ('00'), then we need to start\n # searching the string at the index just beyond that point.\n start = 0\n if d1 == d10:\n start = i1 + 1\n try:\n i10 = s.index(d10, start)\n except:\n return None\n \n return (i10, i1)\n\ndef first_non_zero_digit_after_indices(s, indices):\n # We need to reverse the string and indices because we're actually searching\n # from the highest place in the number now.\n s = s[::-1]\n indices = [len(s) - 1 - indices[i] for i in range(len(indices))]\n # Now search through linearly for the first non-zero digit which is not an index.\n non_zero_index = None\n for i in range(len(s)):\n if i not in indices and s[i] != '0':\n non_zero_index = i\n break\n # If we didn't find a non-zero index, that means we're dealing with something like\n # trying to use '25' as the final digits of 250. In other words, impossible.\n if non_zero_index is None:\n return None\n # Otherwise, translate the index back into place number.\n return len(s) - 1 - non_zero_index", "import re\ndef solve(n):\n print(n)\n min_moves=[]\n n=str(n)\n l=len(n)-1\n extra=0\n \n if '2' in n and '5' in n:\n print('25')\n temp=list(n)\n if n.rindex('2') > n.rindex('5'):\n extra=1\n temp[n.rindex('2')]=''\n temp[n.rindex('5')]=''\n #temp=re.sub(' ','',temp)\n temp=''.join(temp)\n if temp and temp[0]=='0':\n x = re.search(\"[1-9]\", temp)\n if x:\n extra+=x.start()\n min_moves.append(l-1-n.rindex('2')+l-n.rindex('5')+extra)\n extra=0\n \n if '7' in n and '5' in n:\n print('75')\n temp=list(n)\n if n.rindex('7') > n.rindex('5'):\n extra=1\n temp[n.rindex('7')]=''\n temp[n.rindex('5')]=''\n #temp=re.sub(' ','',temp)\n temp=''.join(temp)\n print('temp',temp)\n if temp and temp[0]=='0':\n x = re.search(\"[1-9]\", temp)\n if x:\n extra+=x.start()\n print('extra',extra)\n min_moves.append(l-1-n.rindex('7')+l-n.rindex('5')+extra)\n extra=0\n if '5' in n and '0' in n:\n print('50')\n if n.rindex('5') > n.rindex('0'):\n extra=1\n \n min_moves.append(l-1-n.rindex('5')+l-n.rindex('0')+extra)\n extra=0\n if n.count('0')>1:\n print('00')\n min_moves.append(l-1-n.rindex('0')+l-n.rindex('0',0,n.rindex('0')))\n print(min_moves)\n if not min_moves:\n return -1\n return min(min_moves)"]
{"fn_name": "solve", "inputs": [[50], [25], [52], [57], [75], [100], [521], [1], [5071], [705], [1241367], [50011117], [1002], [50011111112], [2057], [50001111312], [500111117], [64954713879], [71255535569], [72046951686], [68151901446], [3848363615], [75733989998], [87364011400], [2992127830], [98262144757], [81737102196], [50892869177], [5000033333337], [7000033333335], [500033332], [50303332], [5003033332], [20], [5], [7], [2], [60], [100000], [500000], [507], [502], [205]], "outputs": [[0], [0], [1], [1], [0], [0], [3], [-1], [4], [1], [-1], [9], [2], [12], [1], [13], [10], [8], [9], [12], [10], [-1], [17], [0], [-1], [1], [-1], [11], [16], [8], [10], [8], [11], [-1], [-1], [-1], [-1], [-1], [0], [0], [2], [2], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,700
def solve(n):
61bfb382c1729a8868f96755e1832f91
UNKNOWN
# Kata Task Given a list of random integers, return the Three Amigos. These are 3 numbers that live next to each other in the list, and who have the **most** in common with each other by these rules: * lowest statistical range * same parity # Notes * The list will contain at least 3 numbers * If there is more than one answer then return the first one found (reading the list left to right) * If there is no answer (e.g. no 3 adjacent numbers with same parity) then return an empty list. # Examples * ex1 * Input = ```[1, 2, 34, 2, 1, 5, 3, 5, 7, 234, 2, 1]``` * Result = ```[5,3,5]``` * ex2 * Input = ```[2, 4, 6, 8, 10, 2, 2, 2, 1, 1, 1, 5, 3]``` * Result = ```[2,2,2]``` * ex3 * Input = ```[2, 4, 5, 3, 6, 3, 1, 56, 7, 6, 3, 12]``` * Result = ```[]```
["def three_amigos(numbers):\n return min(\n ([a, b, c] for a, b, c in zip(numbers, numbers[1:], numbers[2:]) if a & 1 == b & 1 == c & 1), \n key=lambda triple: max(triple) - min(triple),\n default=[])", "three_amigos = lambda a: (sorted(((max(a[i:i+3])-min(a[i:i+3]), a[i:i+3]) for i in range(len(a)-2) if a[i]%2==a[i+1]%2==a[i+2]%2), key=lambda x: x[0])+[(None, [])])[0][1]\n", "from collections import defaultdict\n\n\ndef three_amigos(numbers):\n candidates = defaultdict(list)\n for i in range(len(numbers) - 2):\n triplet = numbers[i:i+3]\n if len({n % 2 for n in triplet}) == 1:\n candidates[max(triplet) - min(triplet)].append(triplet)\n return candidates[min(candidates)][0] if candidates else []\n", "from collections import defaultdict\n\ndef three_amigos(numbers):\n amigos = defaultdict(list)\n \n for i in range(len(numbers)-3 +1):\n a, b, c = numbers[i:i+3]\n \n if a%2 == b%2 == c%2:\n rnge = max(a, b, c) - min(a, b, c)\n amigos[rnge].append([a, b, c])\n \n return amigos[min(amigos.keys())][0] if amigos else []", "import sys\ndef three_amigos(numbers):\n\n p1 = 0\n min_range = sys.maxsize\n output = None\n \n for idx in range(3, len(numbers)+1):\n slice = numbers[p1:idx]\n p1 += 1\n if sameParity(slice):\n minmax = max(slice) - min(slice)\n if minmax < min_range:\n min_range = minmax\n output = slice\n \n return output if output else []\n \n \n \n \ndef sameParity(arr):\n even = True if arr[0] % 2 == 0 else False\n \n for idx in range(1, len(arr)):\n if even and arr[idx] % 2 != 0:\n return False\n if not even and arr[idx] % 2 == 0:\n return False\n \n return True", "def three_amigos(a):\n li = []\n for i in range(len(a) - 2):\n s = a[i] & 1\n t = a[i:i + 3]\n if all(j & 1 == s for j in t): \n m = max(t)\n m_ = min(t)\n li.append([m - m_, t])\n return min(li,key=lambda x:x[0],default=[[],[]])[1]", "def three_amigos(numbers):\n it = (xs for xs in zip(numbers, numbers[1:], numbers[2:]) if len({x % 2 for x in xs}) == 1)\n return list(min(it, key=lambda xs: max(xs)-min(xs), default=()))", "def three_amigos(numbers):\n return list(min((a for a in zip(numbers, numbers[1:], numbers[2:]) if sum(b % 2 for b in a) in [0, 3]), key = lambda x : max(x) - min(x), default = []))", "three_amigos=lambda l:min(([a,b,c]for a,b,c in zip(l,l[1:],l[2:])if a%2==b%2==c%2),key=lambda t:max(t)-min(t),default=[])", "three_amigos=lambda a:min([[max(a[i:i+3])-min(a[i:i+3]),a[i:i+3]]for i in range(len(a)-2)if all(j&1==a[i]&1for j in a[i:i+3])],key=lambda x:x[0],default=[[],[]])[1]"]
{"fn_name": "three_amigos", "inputs": [[[1, 2, 34, 2, 1, 5, 3, 5, 7, 234, 2, 1]], [[2, 4, 6, 8, 10, 2, 2, 2, 1, 1, 1, 5, 3]], [[2, 4, 5, 3, 6, 3, 1, 56, 7, 6, 3, 12]], [[1, 3, 5]], [[1, 3, 2]], [[1, 3, 5, 7, 9, 11, 13, 15]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 5]], [[-5, -4, -2, 0, 1, 2, 3, 4, 5]], [[-8, -25, 21, -7, -5]], [[8, 5, 20, 17, -18, -11, 19, 5]], [[6, 9, -18, -19, -14, -10, -24]], [[0, -1, -1, 1, -1, -1, -3]], [[-8, -2, 0, 2, 4, 6, 8]]], "outputs": [[[5, 3, 5]], [[2, 2, 2]], [[]], [[1, 3, 5]], [[]], [[1, 3, 5]], [[1, 3, 5]], [[-4, -2, 0]], [[21, -7, -5]], [[-11, 19, 5]], [[-14, -10, -24]], [[-1, -1, 1]], [[-2, 0, 2]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,874
def three_amigos(numbers):
c5b905bd2d31fc73d96b34e345369c9e
UNKNOWN
You are given an array of `n+1` integers `1` through `n`. In addition there is a single duplicate integer. The array is unsorted. An example valid array would be `[3, 2, 5, 1, 3, 4]`. It has the integers `1` through `5` and `3` is duplicated. `[1, 2, 4, 5, 5]` would not be valid as it is missing `3`. You should return the duplicate value as a single integer.
["def find_dup(arr):\n return sum(arr) - len(arr)*(len(arr)-1)/2\n #your code here\n", "def find_dup(arr):\n return max([i for i in arr if arr.count(i) > 1])", "from collections import Counter\nfind_dup = lambda xs: Counter(xs).most_common(1)[0][0]", "def find_dup(arr):\n return sum(arr) - len(arr) * (len(arr) - 1) // 2", "def find_dup(arr):\n return sum(arr) - sum(range(len(arr)))", "find_dup = lambda l: [v for i, v in enumerate(l) if l.index(v) != i][0]\n", "def find_dup(arr):\n for i in range(1, len(arr)):\n for j in range(i):\n if arr[i] == arr[j]:\n return arr[i] \n return None", "def find_dup(arr):\n return sum(arr) - (len(arr) - 1) * len(arr) // 2", "def find_dup(arr):\n return next(n for n in arr if arr.count(n) == 2)\n"]
{"fn_name": "find_dup", "inputs": [[[1, 1, 2, 3]], [[1, 2, 2, 3]], [[5, 4, 3, 2, 1, 1]], [[1, 3, 2, 5, 4, 5, 7, 6]], [[8, 2, 6, 3, 7, 2, 5, 1, 4]]], "outputs": [[1], [2], [1], [5], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
802
def find_dup(arr):
37593ae874208c88e106693e763f6c90
UNKNOWN
Character recognition software is widely used to digitise printed texts. Thus the texts can be edited, searched and stored on a computer. When documents (especially pretty old ones written with a typewriter), are digitised character recognition softwares often make mistakes. Your task is correct the errors in the digitised text. You only have to handle the following mistakes: * `S` is misinterpreted as `5` * `O` is misinterpreted as `0` * `I` is misinterpreted as `1` The test cases contain numbers only by mistake.
["def correct(string):\n return string.translate(str.maketrans(\"501\", \"SOI\"))", "def correct(string):\n return string.replace('1','I').replace('0','O').replace('5','S')", "tr=str.maketrans('015','OIS')\n\ndef correct(string):\n return string.translate(tr)", "def correct(string):\n return string.replace('5','S').replace('0','O').replace('1','I')", "def correct(s):\n return s.translate(str.maketrans(\"015\", \"OIS\"))", "def correct(strng):\n return strng.translate(strng.maketrans(\"501\",\"SOI\"))", "def correct(s):\n mapping = str.maketrans({'0': 'O', '1': 'I', '5': 'S'})\n return s.translate(mapping)", "def correct(string):\n return ''.join({'0':'O', '5':'S', '1':'I'}.get(c, c) for c in string)", "\ndef correct(string):\n cor=''\n for leter in string:\n if leter =='1':\n cor+='I'\n elif leter=='5':\n cor+='S'\n elif leter=='0':\n cor+='O'\n else:\n cor+=leter\n return cor", "def correct(string):\n tr = {'0': 'O', '1' : 'I', '5':'S'}\n return ''.join([tr[i] if i.isdigit() else i for i in string])", "def correct(string):\n return string.translate(bytes.maketrans(b\"501\",b\"SOI\"))", "correct = lambda s: s.replace('5','S').replace('1','I').replace('0','O')", "def correct(string):\n return string.translate(string.maketrans(\"501\", \"SOI\"))", "def correct(string):\n fixes = {'0': 'O', '5': 'S', '1': 'I'}\n issue = '015'\n result = ''\n for s in string:\n if s in issue:\n result += fixes[s]\n else:\n result += s\n return result\n", "def correct(string):\n output = \"\"\n for letter in string:\n if letter == '5':\n output += 'S'\n elif letter == '0':\n output += 'O'\n elif letter == '1':\n output += 'I'\n else:\n output += letter\n return output", "correct=lambda s: s.replace(\"5\",\"S\").replace(\"0\",\"O\").replace(\"1\",\"I\")", "def correct(string):\n a = ''\n for x in string:\n if x == '5':\n a += 'S'\n elif x == '0':\n a += 'O'\n elif x == '1':\n a += 'I'\n else:\n a += x\n return a", "def correct(string):\n for e, c in {'5':'S','0':'O','1':'I'}.items():\n string = string.replace(e,c)\n return string", "def correct(s):\n return ''.join('S' if x == '5' else 'O' if x == '0' else 'I' if x == '1' else x for x in s)", "def correct(string):\n d = dict(zip('015', 'OIS'))\n return ''.join(d.get(c, c) for c in string)", "import re\ndef correct(string):\n return re.sub('(\\d)', lambda x: {'5': 'S', '0': 'O', '1': 'I'}[x.group()], string)", "def correct(string):\n corrected = {\"0\":\"O\", \"1\":\"I\", \"3\":\"E\", \"5\":\"S\", \"7\":\"T\"}\n\n for char in string:\n for num, alpha in corrected.items():\n if char == num:\n string = string.replace(char, alpha) \n\n return string", "def correct(string):\n for letter in ((\"5\",\"S\"),(\"0\",\"O\"),(\"1\",\"I\")):\n string = string.replace(*letter)\n return string", "def correct(string):\n return ''.join([({'0':'O','5':'S','1':'I'}[ch] if ch in ['5','0','1'] else ch) for ch in string])", "def correct(string):\n newList = []\n for i in list(string):\n if i == \"0\":\n newList.append(\"O\")\n elif i == \"5\":\n newList.append(\"S\")\n elif i == \"1\":\n newList.append(\"I\")\n else:\n newList.append(i)\n return \"\".join(newList)", "def correct(string):\n remap = {'5':'S','0':'O','1':'I'}\n return ''.join(x.replace(x,remap[x]) if x in remap else x for x in list(string))", "def correct(string):\n string = string.replace('5','S',-1)\n string = string.replace('0','O',-1)\n string = string.replace('1','I',-1)\n return string", "def correct(string):\n replace = {'5':'S', '0':'O', '1':'I'}\n for key, value in list(replace.items()):\n string = string.replace(key, value)\n return string\n", "def correct(string):\n for strings in string:\n if strings.isdigit():\n string = string.replace(\"5\",\"S\")\n string = string.replace(\"0\",\"O\")\n string = string.replace(\"1\",\"I\")\n return string\n", "def correct(string):\n dict = {'0': 'O', '1': 'I', '5': 'S'}\n output = ''\n for x in string:\n if x.isdigit():\n output += dict[x]\n else:\n output += x\n return output", "def correct(string):\n matches = \"501\"\n for char in string:\n if char in matches:\n if char == \"5\":\n string = string.replace(char, \"S\")\n if char == \"0\":\n string = string.replace(char, \"O\")\n if char == \"1\":\n string = string.replace(char, \"I\")\n return string", "def correct(string):\n# return string.replace(\"0\", \"O\").replace(\"1\", \"I\").replace(\"5\", \"S\")\n trans = string.maketrans({\"0\":\"O\", \"1\":\"I\", \"5\":\"S\"})\n return string.translate(trans)", "def correct(string):\n string=list(string)\n for i in range(len(string)):\n if (isinstance(string[i],int))==True:\n pass\n else:\n if (string[i])=='0':\n string[i]='O'\n if (string[i])=='5':\n string[i]='S'\n if (string[i])=='1':\n string[i]='I'\n string=''.join(string)\n return string\n", "def correct(string):\n inpstr = string\n oplst = []\n for c in inpstr:\n if c.isnumeric():\n if int(c) == 0:\n oplst.append('O')\n elif int(c) == 5:\n oplst.append('S')\n elif int(c) == 1:\n oplst.append('I')\n else:\n oplst.append(c)\n \n return ''.join(oplst)", "def correct(string):\n output=\"\"\n for i in range(len(string)):\n if string[i]==\"5\":\n output=output+\"S\"\n elif string[i]==\"0\":\n output=output+\"O\"\n elif string[i]==\"1\":\n output=output+\"I\"\n else:\n output=output+string[i]\n return output", "def correct(string):\n answer = \"\"\n for i in string:\n if i == \"0\":\n answer += \"O\"\n elif i == \"5\":\n answer += \"S\"\n elif i == \"1\":\n answer += \"I\"\n else:\n answer += i\n return answer", "def correct(string):\n var1 = string.replace(\"0\", \"O\")\n var2 = var1.replace(\"5\", \"S\")\n var3 = var2.replace(\"1\", \"I\")\n return var3", "def correct(string):\n string2 = ''\n for char in string:\n if char == '0':\n string2 = string2 + 'O'\n elif char == '1':\n string2 = string2 + 'I'\n elif char == '5':\n string2 = string2 + 'S'\n else:\n string2 = string2 + char\n return string2\n \n", "def correct(string):\n for i in string:\n if i == \"0\":\n string = string.replace(\"0\", \"O\")\n print(string)\n elif i == \"1\":\n string = string.replace(\"1\", \"I\")\n elif i == \"5\":\n string = string.replace(\"5\", \"S\")\n return string\n", "def correct(string):\n \n li = []\n\n\n\n for i in string:\n li.append(i)\n print(li)\n\n for i in range(len(li)):\n if li[i] == '0':\n li[i] = 'O'\n elif li[i] == '1':\n li[i] = 'I'\n elif li[i] == '5':\n li[i] = 'S'\n\n\n return \"\".join(li)\n \n", "def correct(string):\n letters = [i for i in string]\n for i in letters:\n if i == \"5\":\n letters[letters.index(i)] = \"S\"\n elif i == \"0\":\n letters[letters.index(i)] = \"O\"\n elif i == \"1\":\n letters[letters.index(i)] = \"I\"\n return \"\".join(letters)", "def correct(string):\n string = string.replace('1', 'I')\n string = string.replace('0', 'O')\n return string.replace('5', 'S')", "def correct(string):\n d = []\n for i in string:\n if i == \"5\":\n d.append(\"S\")\n elif i == \"0\":\n d.append(\"O\") \n elif i == \"1\":\n d.append(\"I\") \n else:\n d.append(i)\n return \"\".join(d) ", "def correct(string):\n dict = {\"5\":\"S\", \"0\":\"O\", \"1\":\"I\"}\n new = \"\"\n for i in string:\n if i in dict.keys():\n new += dict[i]\n else:\n new += i\n return new", "def correct(string):\n wrong = ['5','0','1']\n right = ['S','O','I']\n for x in wrong:\n string = string.replace(x,right[wrong.index(x)])\n return string", "def correct(string):\n return \"\".join(\"I\" if k == \"1\" else k for k in (\"O\" if j == \"0\" else j for j in (\"S\" if i == \"5\" else i for i in string)))\n", "def correct(string):\n \n ans1 = string.replace(\"5\",\"S\")\n ans2 = ans1.replace(\"0\",\"O\")\n ans3 = ans2.replace(\"1\",\"I\")\n \n return ans3", "def correct(string):\n \n answer1 = string.replace(\"5\",\"S\")\n \n \n answer2 = answer1.replace(\"0\",\"O\")\n \n answer3 = answer2.replace(\"1\",\"I\")\n\n return answer3", "def correct(string):\n newstring = \"\"\n for item in string:\n if item in ['5','0','1']:\n if item == \"5\":\n newstring = newstring + \"S\"\n if item == \"0\":\n newstring = newstring + \"O\"\n if item == \"1\":\n newstring = newstring + \"I\"\n else:\n newstring = newstring + item\n \n return newstring\n", "def correct(string):\n new = ''\n for i in string:\n if i == \"0\":\n new = new + 'O'\n elif i == '1':\n new = new + 'I'\n elif i == '5':\n new = new + 'S'\n else:\n new = new + i\n return new\n", "import re\ndef correct(string):\n string = re.sub('0', 'O', string)\n string = re.sub('5', 'S', string)\n string = re.sub('1', 'I', string)\n \n return string\n \n", "def correct(string):\n answer = ''\n for c in string:\n if c == '5':\n answer += 'S'\n elif c == '0':\n answer += 'O'\n elif c == '1':\n answer += 'I'\n else:\n answer += c\n \n return answer", "def correct(string):\n errors = {'5' : 'S',\n '0' : 'O',\n '1' : 'I'}\n n_str = \"\"\n for letter in string:\n if letter in errors:\n letter = errors[letter]\n n_str = n_str + letter \n return n_str", "def correct(string):\n ans = []\n for i in string:\n if i == '5':\n c = i.replace('5','S')\n ans.append(c)\n elif i == \"0\":\n c = i.replace('0','O')\n ans.append(c)\n elif i == \"1\":\n c = i.replace('1','I')\n ans.append(c)\n else:\n ans.append(i)\n return ''.join(ans)", "def correct(string):\n# pass\n string=string.replace(\"5\",\"S\")\n string=string.replace(\"0\",\"O\")\n string=string.replace(\"1\",\"I\")\n return string", "def correct(string):\n y=((string.replace(\"5\",\"S\")).replace(\"0\",\"O\")).replace(\"1\",\"I\")\n# y=string.replace(\"0\",\"O\")\n# y=string.replace(\"1\",\"I\")\n return y\n", "def correct(string):\n a =[(\"0\",\"O\"),(\"5\",\"S\"),(\"1\",\"I\")]\n for x,y in a:\n \n string = string.replace(x,y)\n return string", "def correct(string):\n errors = ((\"5\", \"S\"), (\"0\", \"O\"), (\"1\", \"I\"))\n \n for error in errors:\n string = string.replace(*error)\n \n return string", "def correct(string):\n print(string)\n a =\"\"\n bad = {\"0\": \"O\", \"1\": \"I\", \"5\": \"S\"}\n for i in string:\n #print(i)\n if i in bad:\n a = a + bad.get(i)\n else:\n a = a + i\n return a", "def correct(string):\n inttab = '501'\n outtab = 'SOI'\n x = string.maketrans(inttab, outtab)\n return string.translate(x)", "def correct(string):\n l = list(string)\n for idx, char in enumerate(l):\n if char == '5':\n l[idx] = 'S'\n if char == '0':\n l[idx] = 'O'\n if char == '1':\n l[idx] = 'I'\n return ''.join(l)\n\nprint(correct(\"5INGAPORE\"))", "dict = {\"5\":\"S\", \"0\":\"O\", \"1\":\"I\"}\ndef correct(string):\n for i in string:\n if i in dict.keys():\n string = string.replace(i, dict[i])\n return string", "def correct(string):\n d = {\"5\":\"S\",\"1\":\"I\",\"0\":\"O\"}\n new = \"\"\n for i in string:\n if i.isalpha():\n new+=i\n elif i==\"5\" or i==\"0\" or i==\"1\":\n new+= d[i]\n else:\n new+=i\n return new", "def correct(string):\n r = \"\"\n for c in string:\n if c == '0':\n r += 'O'\n elif c == '1':\n r += 'I'\n elif c == '5':\n r += 'S'\n else:\n r += c\n return r", "def correct(string):\n neu = string.replace(\"1\", \"I\").replace(\"0\", \"O\").replace(\"5\", \"S\")\n return neu", "def correct(string):\n d ={'5':'S', '0':'O', '1':'I'}\n return ''.join([d.get(i,i) for i in string])", "def correct(string: str) -> str:\n return string.translate(str.maketrans(\"501\", \"SOI\"))\n", "def correct(string):\n chars = ['5','0', '1']\n for ch in chars:\n return string.replace(chars[0],\"S\").replace(chars[1],\"O\").replace(chars[2], \"I\")\n\n \n \n", "def correct(s):\n return s.translate({48:'O',49:'I',53:'S'})", "def correct(string):\n letters = {\n '5': 'S',\n '0': 'O',\n '1': 'I'\n }\n \n return ''.join(letters[x] if x.isdigit() else x for x in string)", "def correct(string):\n return \"\".join({\"5\": \"S\", \"0\": \"O\", \"1\": \"I\"}.get(l, l) for l in string)", "def correct(string):\n new_string = string.replace('0', 'O')\n newer_string = new_string.replace('1', 'I')\n newest_string = newer_string.replace('5', 'S')\n \n return newest_string\n \n", "def correct(string):\n crtd = []\n for x in string:\n if x == \"5\":\n x = \"S\"\n elif x == \"0\":\n x = \"O\"\n elif x == \"1\":\n x = \"I\"\n crtd.append(x)\n return ''.join(crtd)", "def correct(string):\n new_s = ''\n for i in string:\n if not i.isdigit():\n new_s += i\n elif i == '0':\n new_s += 'O'\n elif i == '5':\n new_s += 'S'\n else:\n new_s += 'I'\n return new_s", "def correct(string):\n dic1={'5':'S','0':'O','1':'I'}\n return ''.join(dic1.get(char,char) for char in string)", "def correct(string):\n return string.translate({53: 'S', 48: 'O', 49: 'I'})", "def correct(string):\n x = {'5' : 'S', '0' : 'O', '1' : 'I'}\n return \"\".join(s if s not in x.keys() else x.get(s) for s in string )", "def correct(string: str) -> str:\n \"\"\"It corrects the errors in the digitised text.\"\"\"\n return string.replace(\"5\", \"S\").replace(\"0\", \"O\").replace(\"1\", \"I\")", "def correct(string):\n for element in string:\n string = string.replace(\"1\", \"I\")\n string = string.replace(\"5\", \"S\")\n string = string.replace(\"0\", \"O\")\n return string", "def correct(string):\n return ''.join([{'5':'S','0':'O','1':'I'}.get(i, i) for i in string])\n", "def correct(string):\n if '5' or '0' or '1' in string: \n string = string.replace('0','O')\n string = string.replace('1','I')\n string = string.replace('5','S')\n return string", "def correct(string):\n c=''\n for char in string:\n if char == '0':\n c+='O'\n elif char == '1':\n c+='I'\n elif char == '5':\n c+='S'\n else:\n c+=char\n return c", "def correct(string):\n return \"\".join([\"OSI\"[\"051\".index(c)] if c in \"051\" else c for c in string ])", "def correct(string):\n new_string = ''\n for letter in string:\n if letter == '5':\n new_string = new_string + 'S'\n elif letter == '1':\n new_string = new_string + 'I'\n elif letter == '0':\n new_string = new_string + 'O'\n else:\n new_string = new_string + letter\n return new_string", "import string\ndef correct(string):\n return string.translate(string.maketrans(\"051\",\"OSI\"))", "def correct(string):\n s = ''\n for i in string:\n s = string.replace('5','S').replace('1','I').replace('0','O')\n return s", "def correct(string):\n value = {\"0\":\"O\",\"5\":\"S\",\"1\":\"I\"}\n result = \"\"\n \n for letter in string :\n if value.get(letter) :\n result = result + value[letter] \n else :\n result = result + letter\n \n return result", "def correct(string):\n x = \"501\"\n y = \"SOI\"\n other = string.maketrans(x,y)\n return(string.translate(other))", "def correct(string):\n dict = {\"5\" : \"S\", \"0\" : \"O\", \"1\" : \"I\" }\n str = \"\"\n for x in string:\n if x in dict:\n str += dict[x]\n else:\n str += x\n return(str)\n", "def correct(string):\n dic = {'5':'S', \"1\": \"I\", \"0\": \"O\"}\n return \"\".join([dic[x] if x in dic else x for x in list(string) ])\n", "def correct(s):\n x = s.maketrans('501','SOI')\n return s.translate(x)", "def correct(string):\n temp = string.replace('5','S')\n temp = temp.replace('0',\"O\")\n temp = temp.replace('1','I')\n return temp\n pass", "def correct(string):\n correct={'5':'S','0':'O','1':'I'}\n for i in correct:\n string=string.replace(i,correct[i])\n return string", "def correct(string):\n correct = ''\n for i in string:\n if i == '5':\n correct += 'S'\n elif i == '0':\n correct += 'O'\n elif i == '1':\n correct +='I'\n else:\n correct += i\n \n return correct", "def correct(s):\n st=\"\"\n for c in s:\n if c=='5':\n st+='S'\n elif c=='0':\n st+='O'\n elif c=='1':\n st+='I'\n else:\n st+=c\n return st\n", "\nCORRECTIONS = {\n '0': 'O',\n '5': 'S',\n '1': 'I',\n}\n\nCORRECTION_TRANSLATION = str.maketrans(CORRECTIONS)\n\ndef correct(string):\n return string.translate(CORRECTION_TRANSLATION)", "def correct(string):\n end =''\n for x in string:\n if x =='0':\n end+='O'\n elif x=='5':\n end +='S'\n elif x=='1':\n end += 'I'\n else:\n end +=x\n return end", "def correct(string):\n# for i in string:\n # if i == \"5\":\n# string = string.replace(\"5\",\"S\")\n # if i == \"0\":\n # string = string.replace(\"0\",\"O\")\n # if i == \"1\":\n # string = string.replace(\"1\",\"I\")\n #return string\n\n\n\n new_word = []\n for letter in string:\n if letter == \"5\":\n new_word.append(\"S\")\n elif letter == \"0\":\n new_word.append(\"O\")\n elif letter == \"1\":\n new_word.append(\"I\")\n else:\n new_word.append(letter)\n return \"\".join(new_word)\n", "def correct(string):\n str1 = string.replace(\"0\", \"O\")\n str2 = str1.replace(\"5\", \"S\")\n str3 = str2.replace(\"1\", \"I\")\n return str3 \n \n \n \n \n", "def correct(string):\n arr=[]\n for i in string:\n arr.append(i)\n res=\"\"\n for i in range(0,len(arr)):\n if arr[i]==\"0\":\n arr[i]=\"O\"\n if arr[i]==\"5\":\n arr[i]=\"S\"\n if arr[i]==\"1\":\n arr[i]=\"I\"\n res+=arr[i]\n return res"]
{"fn_name": "correct", "inputs": [["1F-RUDYARD K1PL1NG"], ["R0BERT MERLE - THE DAY 0F THE D0LPH1N"], ["R1CHARD P. FEYNMAN - THE FEYNMAN LECTURE5 0N PHY51C5"], ["R1CHARD P. FEYNMAN - 5TAT15T1CAL MECHAN1C5"], ["5TEPHEN HAWK1NG - A BR1EF H15T0RY 0F T1ME"], ["5TEPHEN HAWK1NG - THE UN1VER5E 1N A NUT5HELL"], ["ERNE5T HEM1NGWAY - A FARWELL T0 ARM5"], ["ERNE5T HEM1NGWAY - F0R WH0M THE BELL T0LL5"], ["ERNE5T HEM1NGWAY - THE 0LD MAN AND THE 5EA"], ["J. R. R. T0LK1EN - THE L0RD 0F THE R1NG5"], ["J. D. 5AL1NGER - THE CATCHER 1N THE RYE"], ["J. K. R0WL1NG - HARRY P0TTER AND THE PH1L050PHER'5 5T0NE"], ["J. K. R0WL1NG - HARRY P0TTER AND THE CHAMBER 0F 5ECRET5"], ["J. K. R0WL1NG - HARRY P0TTER AND THE PR150NER 0F Azkaban"], ["J. K. R0WL1NG - HARRY P0TTER AND THE G0BLET 0F F1RE"], ["J. K. R0WL1NG - HARRY P0TTER AND THE 0RDER 0F PH0EN1X"], ["J. K. R0WL1NG - HARRY P0TTER AND THE HALF-BL00D PR1NCE"], ["J. K. R0WL1NG - HARRY P0TTER AND THE DEATHLY HALL0W5"], ["UR5ULA K. LE GU1N - A W1ZARD 0F EARTH5EA"], ["UR5ULA K. LE GU1N - THE T0MB5 0F ATUAN"], ["UR5ULA K. LE GU1N - THE FARTHE5T 5H0RE"], ["UR5ULA K. LE GU1N - TALE5 FR0M EARTH5EA"]], "outputs": [["IF-RUDYARD KIPLING"], ["ROBERT MERLE - THE DAY OF THE DOLPHIN"], ["RICHARD P. FEYNMAN - THE FEYNMAN LECTURES ON PHYSICS"], ["RICHARD P. FEYNMAN - STATISTICAL MECHANICS"], ["STEPHEN HAWKING - A BRIEF HISTORY OF TIME"], ["STEPHEN HAWKING - THE UNIVERSE IN A NUTSHELL"], ["ERNEST HEMINGWAY - A FARWELL TO ARMS"], ["ERNEST HEMINGWAY - FOR WHOM THE BELL TOLLS"], ["ERNEST HEMINGWAY - THE OLD MAN AND THE SEA"], ["J. R. R. TOLKIEN - THE LORD OF THE RINGS"], ["J. D. SALINGER - THE CATCHER IN THE RYE"], ["J. K. ROWLING - HARRY POTTER AND THE PHILOSOPHER'S STONE"], ["J. K. ROWLING - HARRY POTTER AND THE CHAMBER OF SECRETS"], ["J. K. ROWLING - HARRY POTTER AND THE PRISONER OF Azkaban"], ["J. K. ROWLING - HARRY POTTER AND THE GOBLET OF FIRE"], ["J. K. ROWLING - HARRY POTTER AND THE ORDER OF PHOENIX"], ["J. K. ROWLING - HARRY POTTER AND THE HALF-BLOOD PRINCE"], ["J. K. ROWLING - HARRY POTTER AND THE DEATHLY HALLOWS"], ["URSULA K. LE GUIN - A WIZARD OF EARTHSEA"], ["URSULA K. LE GUIN - THE TOMBS OF ATUAN"], ["URSULA K. LE GUIN - THE FARTHEST SHORE"], ["URSULA K. LE GUIN - TALES FROM EARTHSEA"]]}
INTRODUCTORY
PYTHON3
CODEWARS
20,357
def correct(string):
cf8980c3cd164e4308d44fbaaabe8642
UNKNOWN
Write a function `titleToNumber(title) or title_to_number(title) or titleToNb title ...` (depending on the language) that given a column title as it appears in an Excel sheet, returns its corresponding column number. All column titles will be uppercase. Examples: ``` titleTonumber('A') === 1 titleTonumber('Z') === 26 titleTonumber('AA') === 27 ```
["def title_to_number(title):\n ret = 0\n for i in title:\n ret = ret*26 + ord(i) - 64\n return ret", "def title_to_number(title):\n return sum((ord(c) - 64) * 26**i for i, c in enumerate(title[::-1]))", "def title_to_number(title):\n return sum((ord(char) - 64) * 26 ** i for i, char in enumerate(title[::-1]))", "def title_to_number(title):\n #your code here\n offset = ord('A') - 1\n radix = 26\n \n val = 0\n for i in title:\n val = radix * val + (ord(i) - offset)\n \n return val", "from string import ascii_uppercase\ndef title_to_number(t):\n return 0 if len(t) == 0 else (ascii_uppercase.index(t[0]) + 1) * 26 ** (len(t) - 1) + title_to_number(t[1:])", "from string import ascii_uppercase\nfrom functools import reduce\n\nval = {c:i+1 for i,c in enumerate(ascii_uppercase)}\nadd = lambda x,y: 26*x + y\n\ndef title_to_number(title):\n return reduce(add, map(val.get, title))", "from string import ascii_uppercase as letters\n\n\ndef title_to_number(title):\n transfer = list(title)[::-1]\n result = 0\n for i, char in enumerate(transfer):\n result += (letters.find(char)+1) * 26**i\n return result", "title_to_number = lambda a: 0 if a == '' else 1 + ord(a[-1]) - ord('A') + 26 * title_to_number(a[:-1])", "from string import ascii_uppercase as a\n\ndef title_to_number(title):\n return sum(\n (a.index(x) + 1) * 26 ** i\n for i, x in enumerate(title[::-1])\n )"]
{"fn_name": "title_to_number", "inputs": [["A"], ["Z"], ["AA"], ["AZ"], ["BA"], ["CODEWARS"], ["ZZZTOP"], ["OYAJI"], ["LONELINESS"], ["UNFORGIVABLE"]], "outputs": [[1], [26], [27], [52], [53], [28779382963], [321268054], [7294985], [68400586976949], [79089429845931757]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,471
def title_to_number(title):
e5290cc12a630eabee9abdfcbd0cffeb
UNKNOWN
## Description Peter enjoys taking risks, and this time he has decided to take it up a notch! Peter asks his local barman to pour him **n** shots, after which Peter then puts laxatives in **x** of them. He then turns around and lets the barman shuffle the shots. Peter approaches the shots and drinks **a** of them one at a time. Just one shot is enough to give Peter a runny tummy. What is the probability that Peter doesn't need to run to the loo? ## Task You are given: **n** - The total number of shots. **x** - The number of laxative laden shots. **a** - The number of shots that peter drinks. return the probability that Peter won't have the trots after drinking. **n** will always be greater than **x**, and **a** will always be less than **n**. **You must return the probability rounded to two decimal places i.e. 0.05 or 0.81**
["from functools import reduce\ndef get_chance(n, x, a):\n return round(reduce(lambda m, b: m * (1 - x / (n - b)), range(a), 1), 2)", "def get_chance(n, x, a):\n r = 1\n z = n-x\n while a>0:\n r *= z/n\n n-=1\n z-=1\n a-=1\n return round(r,2)", "def get_chance(shots, laxatives, drinks):\n proba = 1\n for i in range(drinks):\n proba *= 1 - (laxatives / shots)\n shots -= 1\n return round(proba, 2)", "from operator import mul\nfrom functools import reduce\n\n\ndef get_chance(n, x, a):\n return round(reduce(mul,((n-i-x)/(n-i) for i in range(a))), 2)", "import numpy as np\n\ndef get_chance(n, x, a):\n ns = np.arange(n, n-a, -1)\n return np.multiply.reduce((ns - x) / ns).round(2)", "def get_chance(n, x, a):\n p = 1\n for i in range(a):\n p = p * (n-x-i) / (n-i)\n return float(\"{:.2f}\".format(p) if p < 1 else 0.0)", "from functools import reduce\ndef get_chance(n,x,a):\n return round(reduce(lambda x,y:x*y,((n-x-i)/(n-i) for i in range(a))),2)", "def get_chance(n, x, a):\n # Calculate the probabilty that Peter drink just safe drinks\n # First time the prob equals with (n-x) / n\n # After first shot, the prob equal with ((n-1) - x )/ ( n - 1)\n prob = 1\n while a :\n prob *= (n - x) / n\n n -=1 \n a -=1\n return round(prob, 2)\n", "def get_chance(n, x, a):\n output = 1\n for i in range(0,a):\n if n - i == x:\n return 0\n output *= (n-x-i)/(n-i)\n return round(output,2)", "def get_chance(n, x, a):\n c=0\n r=n-x\n p=1\n while c<a:\n b=r/n\n p=p*b\n r=r-1\n n=n-1\n c=c+1\n return round(p,2)"]
{"fn_name": "get_chance", "inputs": [[2, 1, 1], [4, 1, 3], [100, 10, 10], [1000, 150, 20], [25, 5, 5], [9, 3, 2], [4000, 200, 30], [10000, 100, 100], [1000000, 5000, 200], [1000000, 5000, 20000]], "outputs": [[0.5], [0.25], [0.33], [0.04], [0.29], [0.42], [0.21], [0.36], [0.37], [0.0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,724
def get_chance(n, x, a):
a055fcf7f36e87f0430d1379648598b5
UNKNOWN
~~~if:csharp,javascript,cfml,php Given a 2D array of size `m * n`. Your task is to find the sum of minimum value in each row. ~~~ ~~~if:cpp Given a 2D vector of size `m * n`. Your task is to find the sum of minimum value in each row. ~~~ ~~~if:python,ruby Given a 2D list of size `m * n`. Your task is to find the sum of minimum value in each row. ~~~ For Example: ```python [ [1, 2, 3, 4, 5], # minimum value of row is 1 [5, 6, 7, 8, 9], # minimum value of row is 5 [20, 21, 34, 56, 100] # minimum value of row is 20 ] ``` So, the function should return `26` because sum of minimums is as `1 + 5 + 20 = 26` ~~~if:javascript,php Note: You will be always given non-empty array containing Positive values. ~~~ ~~~if:python Note: You will be always given non-empty list containing Positive values. ~~~ ~~~if:cpp Note: You will be always given non-empty vector containing Positive values. ~~~ ~~~if:c# Note: You will be always given non-empty vector containing Positive values. ~~~ ~~~if:cfml Note: You will be always given non-empty array containing Positive values. ~~~ ENJOY CODING :)
["def sum_of_minimums(numbers):\n return sum(map(min, numbers))", "def sum_of_minimums(numbers):\n return sum([min(rows) for rows in numbers])", "def sum_of_minimums(numbers):\n return sum(min(xs) for xs in numbers)", "def sum_of_minimums(numbers):\n total = 0\n for nums in numbers:\n total += min(nums)\n return total", "def sum_of_minimums(numbers):\n return sum(min(row) for row in numbers)", "def sum_of_minimums(a):\n return sum(map(min, a))", "def sum_of_minimums(numbers):\n \n answer = []\n \n for array in numbers:\n answer.append(min(array))\n \n return sum(answer)", "def sum_of_minimums(numbers):\n return sum(min(v)for v in numbers)", "def sum_of_minimums(numbers):\n return sum([min(x) for x in numbers])", "def sum_of_minimums(numbers):\n return sum([min(l) for l in numbers])", "def sum_of_minimums(numbers):\n return sum([min(i) for i in numbers])", "from typing import List\n\ndef sum_of_minimums(numbers: List[int]) -> int:\n \"\"\" Find the sum of minimum value in each row. \"\"\"\n return sum(map(min, numbers))\n", "from typing import List\n\ndef sum_of_minimums(numbers: List[int]) -> int:\n \"\"\" Find the sum of minimum value in each row. \"\"\"\n return sum([min(_num_list) for _num_list in numbers])\n", "def sum_of_minimums(num): return sum([min(i) for i in num])", "sum_of_minimums=lambda l:sum(min(e)for e in l)", "def sum_of_minimums(a):\n return sum(min(sub_a) for sub_a in a)", "def sum_of_minimums(numbers):\n summ = 0\n for i in numbers:\n x = sorted(i)[0]\n summ+=x\n\n return summ", "def sum_of_minimums(numbers):\n pass\n print(('Input: ', numbers))\n x = 0\n mini = 0\n answer = []\n for i in numbers:\n mini = [min(numbers[x])]\n answer.append(mini)\n x+=1 \n res = [sum(i) for i in zip(*answer)] \n stringres = [str(i) for i in res]\n finalres = int(\"\".join(stringres))\n return int(finalres) \n", "def sum_of_minimums(arr):\n return sum(min(lst) for lst in arr)", "def sum_of_minimums(a):\n m=[]\n \n for i in a:\n m.append(min(i))\n \n return(sum(m))", "def sum_of_minimums(numbers):\n return sum([sorted(x)[0] for x in numbers])", "sum_of_minimums = lambda num: sum([sorted(i)[0] for i in num]) #This is a stupid comment from yours truly -Mr. Stupido", "def sum_of_minimums(numbers):\n output = 0\n for row in numbers:\n row.sort()\n output += row[0]\n return output ", "def sum_of_minimums(numbers): \n return sum(min(m) for m in numbers)", "def sum_of_minimums(numbers):\n return sum([sorted(numbers[i],reverse=True)[-1] for i in range(len(numbers))])", "def sum_of_minimums(numbers):\n return sum([min(sub) for sub in numbers])", "sum_of_minimums=lambda n:sum(map(min,n))", "def sum_of_minimums(numbers):\n results=[]\n for x in numbers:\n results.append(sorted(x)[0])\n return sum(results)\n", "def sum_of_minimums(numbers):\n sum = 0\n for i in range(len(numbers)):\n min = numbers[i][0]\n for j in range(1, len(numbers[i])):\n if numbers[i][j] < min:\n min = numbers[i][j]\n sum += min\n return sum", "from functools import reduce\n\ndef sum_of_minimums(numbers):\n return reduce(lambda x, y: min(y) + x, numbers, 0)", "def sum_of_minimums(numbers):\n minimos = map(min, numbers)\n suma_minimos = sum (minimos)\n return suma_minimos", "def sum_of_minimums(numbers):\n ms=0\n \n for i in range(len(numbers)):\n ms+=min(numbers[i])\n return ms", "def sum_of_minimums(numbers):\n return sum(sorted(i).pop(0) for i in numbers)", "def sum_of_minimums(numbers):\n return sum(sorted(i, reverse=True).pop() for i in numbers)", "def sum_of_minimums(numbers):\n new_list = [ ]\n mini = 0\n for i in numbers:\n mini = min(i)\n new_list.append(mini)\n return sum(new_list)", "def sum_of_minimums(numbers):\n sum = 0\n for i in numbers:\n new = sorted(i)\n sum += new[0]\n return sum\n", "def sum_of_minimums(n):\n return sum(min(e) for e in n)\n", "def sum_of_minimums(numbers):\n sum = 0\n for n in range(len(numbers)):\n sum += sorted(numbers[n])[0]\n return sum", "def sum_of_minimums(numbers):\n s = 0\n for el in numbers:\n min(el)\n s = s + min(el)\n return s", "def sum_of_minimums(numbers):\n s = 0\n for el in numbers:\n s = s + min(el)\n return s", "def sum_of_minimums(numbers):\n s = 0\n for el in numbers:\n s += min(el)\n return s", "def sum_of_minimums(numbers):\n mini = [min(el) for el in numbers]\n return sum(mini)", "def sum_of_minimums(numbers):\n count = []\n for n in numbers:\n count.append(min(n))\n return sum(count)\n", "def sum_of_minimums(nums):\n return sum(min(x) for x in nums)\n", "def sum_of_minimums(numbers):\n a = [min(x) for x in numbers]\n return sum(a)", "def sum_of_minimums(numbers):\n b = []\n for i in range(0, len(numbers)):\n b.append(min(numbers[i]))\n c = 0\n for j in range (0, len(b)):\n c += b[j]\n return c", "def sum_of_minimums(numbers):\n \n total_sum = 0\n i = 0\n while i < len(numbers):\n total_sum += min(numbers[i])\n i += 1\n return total_sum", "def sum_of_minimums(numbers):\n min_sum = int()\n for num in numbers:\n min_sum += min(num)\n return min_sum", "def sum_of_minimums(numbers):\n mini = []\n for i in range(len(numbers)):\n mini.append(min(numbers[i]))\n return sum(mini)", "def sum_of_minimums(nums):\n return sum([min(el) for el in nums])", "def sum_of_minimums(numbers):\n rs = 0\n for i in numbers:\n rs += (min(i))\n return rs", "import numpy as np\ndef sum_of_minimums(numbers):\n minimums = []\n for n in numbers:\n minimums.append(np.min(n))\n return np.sum(minimums)", "def sum_of_minimums(numbers):\n summ = 0\n \n for i in range(len(numbers)):\n mini = min(numbers[i])\n summ += mini\n return summ", "def sum_of_minimums(n):\n c=0\n for i in n:\n c+=min(i)\n return c", "def sum_of_minimums(numbers):\n sum=0\n \n for i in range(0,len(numbers)):\n sum=sum+min(numbers[i])\n i=i+1 \n \n return sum\n", "\ndef sum_of_minimums(numbers):\n suma = 0\n for arr in numbers:\n suma += min(arr)\n return suma", "def sum_of_minimums(numbers):\n sum1=0\n for nums in numbers:\n sum1+=min(nums)\n return sum1", "def sum_of_minimums(numbers):\n here = []\n for el in numbers:\n x = min(el)\n here.append(x)\n return sum(here)\n", "def sum_of_minimums(numbers):\n summ_of_minimums = 0\n for i in range(len(numbers)):\n numbers[i].sort()\n summ_of_minimums += numbers[i][0]\n return(summ_of_minimums)", "def sum_of_minimums(n):\n return sum(min(a) for a in n)", "def sum_of_minimums(numbers):\n result = []\n for counter, value in enumerate(numbers):\n num = min(numbers[counter])\n result.append(num)\n return sum(result)", "def sum_of_minimums(numbers):\n min = 0\n \n for n in numbers:\n n.sort()\n min += n[0]\n return min", "def sum_of_minimums(numbers):\n mins = []\n for lists in numbers:\n lists.sort()\n mins.append(lists[0])\n return sum(mins)\n \n", "def sum_of_minimums(numbers):\n l = list()\n for x in numbers:\n x.sort()\n l.append(x[0])\n answer = sum(l)\n return answer", "def sum_of_minimums(numbers):\n minimum = 0\n for i in range(len(numbers)):\n minimum +=min(numbers[i])\n return minimum", "def sum_of_minimums(arr):\n mx = 0\n for i in range(len(arr)):\n mn = min(arr[i])\n mx += mn\n return mx", "def sum_of_minimums(numbers):\n som = 0\n for element in numbers:\n som += min(element)\n return som", "def sum_of_minimums(numbers):\n val = 0\n for i in numbers:\n val += min(i)\n return val", "def sum_of_minimums(numbers):\n c = [min(c) for c in numbers]\n return sum(c)", "def sum_of_minimums(numbers):\n ans = 0\n for arr in numbers:\n ans += min(arr)\n return ans\n", "\ndef sum_of_minimums(numbers):\n return sum(min(zs) for zs in numbers)", "def sum_of_minimums(numbers):\n mns=[]\n for i in range(len(numbers)):\n mns.append(min(numbers[i]))\n return sum(mns)", "def sum_of_minimums(numbers):\n accumulator = 0\n for eachlist in numbers:\n accumulator = accumulator + min(eachlist)\n return accumulator", "def sum_of_minimums(numbers):\n return sum([min(group) for group in numbers])", "def sum_of_minimums(numbers):\n x = []\n for i in numbers:\n x.append(min(i))\n return sum(x)", "def sum_of_minimums(numbers):\n counter = 0\n for list in numbers:\n counter += min(list)\n return counter", "sum_of_minimums = lambda numbers: sum(min(arr) for arr in numbers)", "def sum_of_minimums(numbers):\n total = 0\n for value in range(len(numbers)):\n total += min(numbers[value])\n return total\n", "def sum_of_minimums(n):\n sum=0\n for i in n:\n sum+=min(i)\n return sum", "def sum_of_minimums(numbers):\n return sum(min(numbers[x]) for x in range(0,len(numbers)))", "def sum_of_minimums(numbers):\n t=0\n for i in range(len(numbers)):\n x = min(numbers[i])\n t += x\n return t", "def sum_of_minimums(numbers):\n return sum(sorted(numbers[i])[0] for i in range(len(numbers)))", "def sum_of_minimums(numbers):\n return sum(min(lst_numbers) for lst_numbers in numbers)", "def sum_of_minimums(numbers):\n Z=[]\n for i in numbers:\n Z.append(min(i))\n \n return(sum(Z))", "def sum_of_minimums(numbers):\n z = []\n for x in numbers:\n z.append(min(x))\n return sum(z)", "def sum_of_minimums(numbers):\n# for i in numbers:\n# x = min(i)\n return sum(min(i) for i in numbers)", "def sum_of_minimums(numbers):\n a = list()\n for i in numbers:\n a.append(min(i))\n return sum(a)", "def sum_of_minimums(numbers):\n sum_num = 0\n for item in range(len(numbers)):\n sum_num += min(numbers[item])\n return sum_num", "def sum_of_minimums (number):\n\n return sum([min(i) for i in number])", "def sum_of_minimums(numbers):\n n=0\n for lista in numbers:\n n+=min(lista)\n return n\n", "def sum_of_minimums(numbers):\n data = []\n for i in range(len(numbers)):\n data.append(min(numbers[i]))\n \n return (sum(data))", "def sum_of_minimums(numbers):\n l = []\n for a in numbers:\n l.append(min(a))\n su = sum(l)\n return su", "def sum_of_minimums(numbers):\n return sum(map(min, numbers))\n \nprint(sum_of_minimums([ [ 7,9,8,6,2 ], [6,3,5,4,3], [5,8,7,4,5] ]))", "def sum_of_minimums(argumento):\n suma_min = []\n\n while argumento !=[]:\n var = argumento.pop(0)\n minvar = min(var)\n suma_min.append(minvar)\n\n suma=sum(suma_min)\n\n return suma\n\n", "def sum_of_minimums(numbers):\n return sum(min(i for i in l) for l in numbers)\n", "def sum_of_minimums(numbers):\n return sum(min(sorted(subarray)) for subarray in numbers)", "def sum_of_minimums(numbers):\n a=[min(x) for x in numbers]\n return sum(a)\n #return min(numbers[0])+ min(numbers[1])+ min(numbers[2])\n pass", "def sum_of_minimums(numbers):\n minimum_arr = []\n for arr in numbers:\n minimum_arr.append(min(arr))\n return sum(minimum_arr)", "def sum_of_minimums(numbers):\n x = 0\n for lst in numbers:\n x += min(lst)\n return x", "sum_of_minimums = lambda n: sum( min(a) for a in n )"]
{"fn_name": "sum_of_minimums", "inputs": [[[[7, 9, 8, 6, 2], [6, 3, 5, 4, 3], [5, 8, 7, 4, 5]]], [[[11, 12, 14, 54], [67, 89, 90, 56], [7, 9, 4, 3], [9, 8, 6, 7]]]], "outputs": [[9], [76]]}
INTRODUCTORY
PYTHON3
CODEWARS
11,896
def sum_of_minimums(numbers):
021c8dbe44a19ef126f84a5bf52a8a38
UNKNOWN
This program tests the life of an evaporator containing a gas. We know the content of the evaporator (content in ml), the percentage of foam or gas lost every day (evap_per_day) and the threshold (threshold) in percentage beyond which the evaporator is no longer useful. All numbers are strictly positive. The program reports the nth day (as an integer) on which the evaporator will be out of use. **Note** : Content is in fact not necessary in the body of the function "evaporator", you can use it or not use it, as you wish. Some people might prefer to reason with content, some other with percentages only. It's up to you but you must keep it as a parameter because the tests have it as an argument.
["def evaporator(content, evap_per_day, threshold):\n n = 0\n current = 100\n percent = 1 - evap_per_day / 100.0\n while current > threshold:\n current *= percent\n n += 1\n return n", "import math\n\ndef evaporator(content, evap_per_day, threshold):\n return math.ceil(math.log(threshold / 100.0) / math.log(1.0 - evap_per_day / 100.0))\n", "from math import log,ceil\n\ndef evaporator(content, evap_per_day, threshold):\n return ceil(log(threshold/100,1-evap_per_day/100))", "import math\ndef evaporator(content, evap_per_day, threshold):\n return int(math.ceil(math.log(threshold/100.0, 1.0-evap_per_day/100.0)))", "def evaporator(content, evap_per_day, threshold):\n thresholdper = threshold/100\n amount_remaining = content\n days = 0\n while amount_remaining/content >= thresholdper:\n amount_remaining = amount_remaining * (1 - (evap_per_day/100))\n days += 1\n return days", "from math import *\ndef evaporator(content, evap_per_day, threshold):\n return ceil(log(threshold/100, 1-evap_per_day/100))", "def evaporator(content, evap_per_day, threshold):\n print(content, evap_per_day, threshold)\n i = 0\n c = 1\n while c >= threshold/100:\n c *= 1 - evap_per_day/100\n i += 1\n return i", "import math\ndef evaporator(content, evap_per_day, threshold):\n evap_per_day, threshold = evap_per_day / 100.0, threshold / 100.0\n return math.ceil(math.log(threshold) / math.log(1 - evap_per_day))", "from math import ceil, log\ndef evaporator(c, e, t):\n return ceil(log(t/100, 1-(e/100)))", "def evaporator(content, evap_per_day, threshold):\n thres = content * threshold/100\n count = 0\n while content > thres:\n content = content - content * evap_per_day/100\n count += 1\n return count", "def evaporator(content, evap_per_day, threshold):\n \n limit = (content * threshold) / 100\n days = 0\n while content > limit:\n days += 1\n content = content - ((content * evap_per_day)/100)\n return days", "from math import log2, ceil\ndef evaporator(content, evap_per_day, threshold):\n return ceil(log2(threshold/100.0) / log2((1-evap_per_day/100.0)))", "def evaporator(content, evap_per_day, threshold):\n day = 0\n p = content/100*threshold\n while content >= p:\n day+=1\n perc = content / 100 * evap_per_day\n content -= perc\n return day\n", "from math import log\n\ndef evaporator(_content, evap_per_day, threshold):\n return int(log(threshold / 100, 1 - evap_per_day / 100) + 1)", "def evaporator(content, evap_per_day, threshold):\n from math import log, ceil\n return ceil(log(threshold/100) / log(1 - evap_per_day/100))", "def evaporator(initial_volume, evap_per_day, threshold):\n threshold = float(threshold)\n \n def loop(current_volume):\n if (is_below_threshold(current_volume)):\n return 0\n else: \n return 1 + loop(decrement_volume(current_volume))\n\n def decrement_volume(current_volume): \n return current_volume * (1 - evap_per_day / 100.00)\n \n def is_below_threshold(current_volume):\n return (current_volume / initial_volume) < (threshold / 100.0)\n \n return loop(float(initial_volume))\n\n", "def evaporator(content, evap_per_day, threshold):\n d = 0\n p = content/100*threshold\n while content>p:\n content = content - content/100*evap_per_day\n d += 1\n\n return d", "def evaporator(c, e, t):\n tc = 100\n count = 0\n while tc > t:\n tc -= tc * (e/100)\n count += 1\n return count\n", "def evaporator(content, evap_per_day, threshold):\n \n day = 0\n maxUse = content * (threshold/100)\n evap = evap_per_day/100 \n while content > maxUse :\n content = content - content * evap\n day += 1\n \n return day", "from math import ceil, log\ndef evaporator(content, evap_per_day, threshold):\n return ceil(log(threshold/100.0, (100-evap_per_day)/100.0))", "def evaporator(content, evap, threshold):\n days = 0\n lost = 100\n \n while lost >= threshold:\n lost -= lost * evap / 100\n days += 1\n \n return days", "#!/usr/bin/env python3 \ndef evaporator(content, evap_per_day, threshold):\n \n day_counter = 0\n turn_off_level = content * (((threshold/100)))\n \n while content > turn_off_level:\n content = content * (1-(((evap_per_day)/100)))\n day_counter += 1 \n return day_counter\n\nevaporator(10, 10, 10)", "def evaporator(content, evap_per_day, threshold):\n t = content * threshold / 100\n counter = 0\n while content >= t:\n content = content - content * evap_per_day / 100\n counter += 1\n return counter\n", "def evaporator(content, evap_per_day, threshold):\n days = 1\n new_content = content\n while True:\n new_content = new_content - new_content * evap_per_day * 0.01\n if new_content / content < threshold * 0.01:\n return days\n else:\n days += 1", "def evaporator(content, evap_per_day, threshold):\n #It is important to remember that percent is a ratio and content is a volume\n critical_amount=(threshold/100)*content\n n=0\n while content >=critical_amount:\n content=content-(content*(evap_per_day/100))\n n+=1\n return n\n \n \n \n", "import math\n\ndef evaporator(content, evap_per_day, threshold):\n percent_loss = 1 - evap_per_day/100\n x = math.log(threshold/100)/math.log(percent_loss)\n x = math.ceil(x) \n return x", "def evaporator(content, evap_per_day, threshold):\n content_aux = (content * threshold) / 100\n days = 0\n while content > content_aux:\n content -= (content*evap_per_day)/100\n days += 1\n return days", "def evaporator(content, evap, threshold):\n day=0\n pos=content*threshold/100\n while pos<content:\n content=content-content*(evap)/100\n day=day+1\n return day", "def evaporator(content, evap_per_day, threshold):\n new_content = content\n thresh_quant = content * threshold / 100\n n_day_expire = 0\n while new_content > thresh_quant: \n new_content = new_content - (new_content * (evap_per_day / 100))\n n_day_expire += 1\n return n_day_expire", "def evaporator(content, evap_per_day, threshold):\n day = 0\n threshold = threshold*content/100\n while content > threshold:\n content -= content*evap_per_day/100\n day += 1\n return day", "def evaporator(content, evap_per_day, threshold):\n rem = content * 0.01 * threshold\n count = 0\n while content >= rem:\n content -= content * 0.01 * evap_per_day\n count += 1\n return count\n", "def evaporator(content, evap_per_day, threshold):\n a=int(content)\n b=0\n while content > (a/100)*threshold:\n content=content-(content/100)*evap_per_day\n b+=1\n return b\n \n \n \n", "def evaporator(content, evap_per_day, threshold):\n n = 0\n perc = 100\n perc_per_day = 1 - evap_per_day / 100\n while perc > threshold:\n perc *= perc_per_day\n n += 1\n return n", "def evaporator(content, evap_per_day, threshold):\n a = 0\n threshold *=content/100\n while content >= threshold:\n a += 1\n content*=(1-evap_per_day/100)\n return a", "def evaporator(content, evap_per_day, threshold):\n limit = content * threshold/100\n days = 0\n while content > limit:\n content -= content * evap_per_day/100\n days += 1\n return days", "def evaporator(content, evap_per_day, threshold):\n i = 0\n threshold = threshold * 0.01 * content\n while content > threshold:\n i += 1\n content -= content * evap_per_day * 0.01\n\n return i", "def evaporator(content, e_p_d, thresh):\n n = 0\n start_ = 100\n per_ = 1 - e_p_d / 100.0\n while start_ > thresh:\n start_ *= per_\n n += 1\n return n", "from math import log, ceil\ndef evaporator(content, e, t):\n return ceil(log(t/100,1-e/100))", "def evaporator(content, evap_per_day, threshold):\n cday=0\n left=content\n while left>content*(threshold/100):\n left=left-(left*(evap_per_day/100))\n cday+=1\n return cday", "def evaporator(content, evap_per_day, threshold):\n result = 0\n \n percent_change = 100\n \n while (percent_change > threshold):\n percent_change -= percent_change * (evap_per_day/100)\n result = result + 1\n return result\n\n", "def percent_convert(num):\n return num/100\n\ndef evaporator(content, evap_per_day, threshold):\n content= 1\n evap_per_day = percent_convert(evap_per_day)\n threshold = percent_convert(threshold)\n day_counter = 0\n while content > threshold:\n content = content * (1 - evap_per_day)\n day_counter+=1\n return day_counter", "def evaporator(content, evap_per_day, threshold):\n day_count = 0\n percentage_to_ml = content * threshold / 100\n \n while content >= percentage_to_ml:\n day_count += 1\n content -= content * evap_per_day / 100\n \n return day_count", "def evaporator(content, evap_per_day, threshold):\n \n days = 0\n current = content\n \n \n while content*threshold/100 < current:\n current *= (1-evap_per_day/100)\n days += 1\n \n return days\n", "def evaporator(content, evap_per_day, threshold):\n a = 100\n k = 0\n while a >= threshold:\n a -= a * evap_per_day / 100\n k += 1\n return k", "def evaporator(content, evap_per_day, threshold):\n day = 0\n contentRemaining = content\n \n while contentRemaining > threshold * content / 100:\n contentRemaining -= evap_per_day / 100 * contentRemaining\n day += 1\n \n return day", "def evaporator(content, evap, threshold):\n ilosc = 100\n day=0\n while ilosc > threshold:\n ilosc = ilosc * (1-evap/100)\n day+=1\n return day", "def evaporator(content, evap_per_day, threshold): #Jai Shree Ram!!!\n result=0\n n=content*threshold/100\n while content>n:\n content=content-(content*evap_per_day/100)\n result+=1\n return result ", "def evaporator(content, evap_per_day, threshold):\n hold = content*threshold / 100\n day = 0\n evap = evap_per_day / 100\n while (hold < content):\n content = content - content*evap\n day += 1\n return(day)", "def evaporator(content, evap_per_day, threshold):\n \n x = 0\n y = content\n while y > (content * (threshold/100)):\n y = y - (y * (evap_per_day/100))\n x = x + 1\n \n return x", "def evaporator(content, evap_per_day, threshold):\n remain = 100.0\n day = 0\n while True:\n day += 1\n remain = remain * (100.0 - evap_per_day) / 100.0\n if remain <= threshold:\n return day", "import math\ndef evaporator(content, e, t):\n return math.ceil(math.log(t/100)/math.log(1-e/100))\n \n \n", "def evaporator(content, evap_per_day, threshold):\n perc = 100\n days = 0\n \n while perc > threshold:\n perc = perc * (1 - evap_per_day/100)\n days += 1\n return days", "def evaporator(a, b, c):\n b /=100\n a_origin = a\n rem = a_origin\n day = 0\n trsh = c/100\n while rem >= trsh:\n day +=1\n pr = a * b\n a -=pr\n rem = a/a_origin\n return day\n", "def evaporator(content, evap_per_day, threshold):\n c = 0\n r = 1\n while threshold/100 < r:\n r -= (evap_per_day/100 * r)\n c += 1\n return c\n", "def evaporator(content, evap_per_day, threshold):\n critical = content * threshold/100\n days = 0\n while content > critical:\n days += 1\n content -= content * evap_per_day/100\n \n return days", "def evaporator(content, evap_per_day, threshold):\n p = lambda x: (100 - x) / 100\n x = 100\n times = 0\n while x >= threshold:\n x *= p(evap_per_day)\n times += 1\n return times", "def evaporator(content, evap_per_day, threshold):\n p = lambda x: (100 - x) / 100\n x = 100\n times = 0\n while x >= threshold:\n x *= p(evap_per_day)\n times += 1\n else:\n return times", "def evaporator(content, evap_per_day, threshold):\n n = 0\n ct = content * (threshold/100)\n while (content > ct):\n content -= (content * (evap_per_day/100))\n n += 1\n return n", "def evaporator(content, evap_per_day, treshold, original=None):\n if not original:\n original = content\n if content > original*treshold/100:\n content*=(1 - evap_per_day/100)\n return 1 + evaporator(content, evap_per_day, treshold, original)\n return 0", "def evaporator(content, evap_per_day, threshold,original=None):\n if not original:\n original = content\n if content > original*threshold/100:\n content*=(1-evap_per_day/100)\n return 1 + evaporator(content, evap_per_day, threshold, original)\n return 0", "def evaporator(content, evap_per_day, threshold):\n evap_per_day=evap_per_day/100\n threshold=threshold/100\n days=0\n min_content = content*threshold\n while content >= min_content:\n content -= content * evap_per_day\n days += 1\n return days\n \n \n \n \n", "def evaporator(content, evap_per_day, threshold):\n \n days = 0\n perc_content = 100\n new_content = content\n \n while perc_content > threshold:\n perct_evp = (evap_per_day / 100) * new_content\n print(perct_evp)\n new_content = new_content - perct_evp \n print(new_content)\n perc_content = (new_content / content) * 100\n print(perc_content)\n days += 1\n \n return days", "def evaporator(content, evap_per_day, threshold):\n n = 0\n perc = 100\n while perc > threshold:\n perc *= 1 - evap_per_day / 100\n n += 1\n return n", "def evaporator(content, evap_per_day, threshold):\n day=0\n not_useful=content*(threshold/100)\n while content>=not_useful:\n content-=(evap_per_day/100)*content\n day+=1\n return day\n", "def evaporator(x, y, z):\n content=x\n evap_per_day=y/100\n treshold=z/100\n days=0\n min_content = content*treshold\n while content >= min_content:\n content -= content * evap_per_day\n days += 1\n return days", "def evaporator(x, y, z):\n content=x\n evap_per_day=y\n treshold=z\n perc_th = (treshold)/100\n perc_evap = (evap_per_day)/100\n min_content= content*perc_th\n total_days = 0\n while content >= min_content:\n content -= content*perc_evap\n total_days += 1\n return total_days", "def evaporator(content, evap_per_day, threshold):\n q_threshold = content * threshold/100 \n days = 0\n \n while content >= q_threshold:\n q_evap_per_day = content * evap_per_day/100 \n content = content - q_evap_per_day\n days += 1\n return(days)\n\n \n", "def evaporator(content, evap_per_day, threshold):\n day=[]\n not_useful=content*(threshold/100)\n while content>=not_useful:\n content-=(evap_per_day/100)*content\n day.append(content)\n return(len(day))\n\n", "from itertools import count\n\ndef evaporator(content, evap_per_day, threshold):\n percentage = 100\n for day in count(start=1):\n percentage = percentage*(1 - evap_per_day/100)\n if percentage < threshold:\n return day", "def evaporator(content, evap_per_day, threshold):\n '''\n receives:\n - content of gas in ml.\n - percentaje of content lost every day.\n - threshold as a percentage of the original capacity below which the cooler does not work.\n \n returns:\n - the nth day on which the evaporator will be out of use.\n '''\n days = 0\n threshold_in_ml = content * threshold / 100\n \n while content > threshold_in_ml:\n days += 1\n content = content - (content * evap_per_day / 100)\n \n return days", "def evaporator(content, evap_per_day, threshold):\n percentage = 100\n for day in range(10000):\n percentage = percentage*(1 - evap_per_day/100)\n if percentage < threshold:\n return day + 1", "def evaporator(content, evap_per_day, threshold):\n counter_days = 0\n full = 100\n while full > threshold:\n full -= full*(evap_per_day/100)\n counter_days += 1 \n return counter_days", "def evaporator(content, evap_per_day, threshold):\n mlimit = content *(threshold/100)\n days = 0\n while content > mlimit:\n content -= content*(evap_per_day/100)\n days += 1\n print(content)\n return days", "def evaporator(content, evap_per_day, threshold):\n n=0\n daily_content=content\n threshold_vol=threshold/100*content\n while daily_content>threshold_vol:\n daily_content=daily_content-(evap_per_day/100*daily_content)\n n+=1 \n print(f\"The {n}th day the evaporator is useless\")\n return n", "def evaporator(content, evap_per_day, threshold):\n evap_per_day=(evap_per_day/100)\n threshold=content*(threshold/100)\n total=content\n days=0\n while total > threshold:\n total-=(total*evap_per_day)\n days+=1\n return days", "def evaporator(content, evap_per_day, threshold):\n total = 1\n days=0\n while (total>threshold/100):\n total-= total*evap_per_day/100\n days+=1\n return days\n", "def evaporator(content, evap_per_day, threshold):\n count = 0\n og = content\n while og * threshold / 100 < content:\n content -= content * evap_per_day / 100\n count += 1\n return count", "def evaporator(content, evap, threshold):\n counter = 0\n threshold = content * (threshold/100)\n evap = (evap/100)\n while content >= threshold:\n content -= content*evap\n counter += 1\n return counter\n", "def evaporator(content, evap_per_day, threshold):\n days = 0\n thrshld = content*threshold/100\n while content >= thrshld:\n content -= content*evap_per_day/100\n days += 1\n return days", "def evaporator(content, evap_per_day, threshold):\n days = 0\n contentLeft = content\n while (contentLeft > (content * (threshold/100))):\n contentLeft = contentLeft * (1 - evap_per_day/100)\n days += 1\n \n return days", "def evaporator(content, evap_per_day, threshold):\n maxthresh = content * threshold / 100\n amountevaporated = 0\n days = 0\n while content > maxthresh:\n percentage = evap_per_day / 100\n content = content - (content*percentage)\n days += 1\n return days", "def evaporator(content, evap_per_day, threshold):\n count = 0\n threshold = content * (threshold / 100)\n evap_per_day = evap_per_day / 100\n while content > threshold:\n content = content - content * evap_per_day\n count += 1\n return count", "def evaporator(content, evap_per_day, threshold):\n percent_of_content = 1\n days = 0\n while percent_of_content > threshold * 0.01:\n days += 1\n percent_of_content -= percent_of_content * evap_per_day * 0.01\n return days\n", "def evaporator(content, evap_per_day, threshold):\n th = threshold / 100\n thres = content * th\n evap = evap_per_day / 100\n count = 0\n while content > thres:\n content = content - (content * evap)\n count = count + 1\n return(count)\n", "def evaporator(content, evap_per_day, threshold):\n days = 0\n minimum = content * threshold / 100\n while content > minimum:\n days += 1\n content -= content * evap_per_day / 100\n return days", "def evaporator(content, evap_per_day, threshold):\n new_content = content\n for x in range(1,1000):\n new_content = new_content- new_content*(evap_per_day/100)\n if new_content < content*threshold/100:\n return x", "def evaporator(content, evap_per_day, threshold):\n \n counter,threshold =0, content*threshold/100\n while content >= threshold:\n counter+=1\n content-=content*evap_per_day/100\n return counter", "def evaporator(content, evap_per_day, threshold):\n total = 0\n threshold = content * (threshold / 100)\n evap_per_day = evap_per_day / 100\n while content > threshold:\n ev = content * evap_per_day\n content = content - ev\n total += 1\n return total", "def evaporator(content, evap_per_day, threshold):\n threshold = content * threshold / 100\n day = 0\n while content > threshold:\n content *= 1 - evap_per_day * 0.01\n day += 1\n return day", "def evaporator(content, evap_per_day, threshold):\n content_pct = 100\n days = 0\n while content_pct > threshold:\n content_pct -= (evap_per_day * content_pct) / 100.0\n days += 1\n return days", "def evaporator(content, evap_per_day, threshold):\n n = 0\n f = 100\n while f > threshold:\n f *= (1 - evap_per_day/100)\n n += 1\n return n", "def evaporator(content, evap_per_day, threshold):\n n = 0\n x = 1-evap_per_day/100\n while x > threshold/100:\n x = x * (1-evap_per_day/100)\n n = n + 1\n return n+1", "def evaporator(content, evap_per_day, threshold):\n content = 100\n t = (threshold / 100) * content\n epd = (evap_per_day / 100)\n n = 0\n while content > threshold:\n n += 1\n content *= 1-epd\n return n", "def evaporator(content, evap_per_day, threshold):\n \n days = 0\n current = 100.\n percent = 1 - evap_per_day / current\n \n while current > threshold:\n current *= percent\n days+=1\n \n return days", "def evaporator(co, ev, th):\n x = co*(th/100)\n day= 0\n while co > x:\n co = co - co*(ev/100)\n day += 1\n return day\n", "def evaporator(content, evap_per_day,threshold): \n days =0\n currentLt = content\n while currentLt >= content * threshold / 100.0 :\n currentLt = currentLt * (1 - evap_per_day/100.0)\n days += 1\n return days", "import numpy as np\ndef evaporator(content, evap_per_day, threshold):\n return np.ceil(np.log(threshold/100)/np.log(1-evap_per_day/100))", "def evaporator(content, evap_per_day, threshold):\n days = 0\n volume_threshold = content*(threshold/100)\n while content > volume_threshold:\n content -= content * (evap_per_day/100)\n days += 1\n return days", "def evaporator(content, evap_per_day, threshold):\n limit = content*threshold/100\n evap = evap_per_day/100\n c=0\n while content > limit:\n content = content - content*evap\n c+=1 \n return c", "def evaporator(content, evap_per_day, threshold):\n e = evap_per_day/100\n t = threshold/100\n h = (content*t)\n days = 0\n while content > h:\n content = content * (1 - e)\n days += 1\n \n return (days)"]
{"fn_name": "evaporator", "inputs": [[10, 10, 10], [10, 10, 5], [100, 5, 5], [50, 12, 1], [47.5, 8, 8], [100, 1, 1], [10, 1, 1], [100, 1, 5]], "outputs": [[22], [29], [59], [37], [31], [459], [459], [299]]}
INTRODUCTORY
PYTHON3
CODEWARS
23,245
def evaporator(content, evap_per_day, threshold):
5a130d5e88b1b671d26c8f0d2486df59
UNKNOWN
My grandfather always predicted how old people would get, and right before he passed away he revealed his secret! In honor of my grandfather's memory we will write a function using his formula! * Take a list of ages when each of your great-grandparent died. * Multiply each number by itself. * Add them all together. * Take the square root of the result. * Divide by two. ## Example ```R predict_age(65, 60, 75, 55, 60, 63, 64, 45) == 86 ``` ```python predict_age(65, 60, 75, 55, 60, 63, 64, 45) == 86 ``` Note: the result should be rounded down to the nearest integer. Some random tests might fail due to a bug in the JavaScript implementation. Simply resubmit if that happens to you.
["def predict_age(*ages):\n return sum(a*a for a in ages)**.5//2", "def predict_age(*age):\n return sum(a*a for a in age)**0.5//2", "import numpy as np\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n return np.sum(np.array([age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]) ** 2) ** 0.5 // 2", "import math\ndef predict_age(*args):\n return math.sqrt(sum(x*x for x in args))//2", "from numpy import linalg as LA\ndef predict_age(*ages):\n return LA.norm(ages) // 2", "predict_age=lambda *a:sum(e*e for e in a)**0.5//2", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n # your \n sum = 0\n listik = [age_1**2, age_2**2, age_3**2, age_4**2, age_5**2, age_6**2, age_7**2, age_8**2]\n for i in listik:\n sum += i\n return int((sum**(1/2))//2)", "import math\ndef predict_age(*ages):\n return int(math.sqrt(sum(age*age for age in ages)) / 2)", "import math\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n arr=[age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n result=int((math.sqrt(sum([i ** 2 for i in arr])))/2)\n return result", "def predict_age(*argv):\n return sum(x*x for x in argv)**(1/2) // 2", "def predict_age(*ages):\n return int(sum(age*age for age in ages) ** 0.5 / 2)", "def predict_age(*age):\n return sum([i**2 for i in age])**.5//2", "def predict_age(*ages):\n return (sum(a**2 for a in ages) ** 0.5) // 2", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age_1 = age_1 ** 2\n age_2 = age_2 ** 2\n age_3 = age_3 ** 2\n age_4 = age_4 ** 2\n age_5 = age_5 ** 2\n age_6 = age_6 ** 2\n age_7 = age_7 ** 2\n age_8 = age_8 ** 2\n total = age_1 + age_2 + age_3 + age_4 + age_5 + age_6 + age_7 + age_8\n total = math.sqrt(total)\n return int(total / 2)", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n import math\n oldAge = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8] \n newAge = []\n y = 0\n x = 0\n z = 0\n r = 0\n for i in range(0, len(oldAge)):\n newAge.append(oldAge[i]*oldAge[i])\n z = sum(newAge)\n y = math.sqrt(z)\n r = y/2\n x = math.floor(r)\n print(x)\n return x\n", "import math\n\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n\n list1 = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n list2 = []\n\n for x in list1:\n list2.append(x * x)\n\n list_sum = sum(list2)\n\n list_sum2 = math.sqrt(list_sum)/2\n\n print (int(list_sum2))\n return int(list_sum2)\n\n\npredict_age(65,60,75,55,60,63,64,45)", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n return int(math.sqrt(sum([age ** 2 for age in locals().values()])) / 2)", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n return(math.floor(math.sqrt(age_1**2 + age_2**2 + age_3**2 + age_4**2 + age_5**2 + age_6**2 + age_7**2 + age_8**2)/2.0))", "def predict_age(*ages):\n return ((sum([age*age for age in ages]))**0.5)//2", "from math import sqrt\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n s = sum([x*x for x in [age_1,age_2,age_3,age_4,age_5,age_6,age_7,age_8]])\n return sqrt(s)//2", "def predict_age(a1, a2, a3, a4, a5, a6, a7, a8):\n ages = [a1, a2, a3, a4, a5, a6, a7, a8]\n return sum([el**2 for el in ages])**0.5 // 2", "import math\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n new_list = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n \n mult_list = math.sqrt(sum([i**2 for i in new_list])) // 2\n \n return mult_list", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n # your\n sum = 0\n #calculate sum of ages\n sum += age_1**2 + age_2**2 + age_3**2 + age_4**2 + age_5**2 + age_6**2 + age_7**2 + age_8**2\n \n #square root and divide by 2\n return (sum**0.5)//2", "import math\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n ages = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n sum = 0\n for i in ages:\n sum = sum + i ** 2\n \n return math.floor(math.sqrt(sum)/2)", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age_multiplied_and_added = age_1 ** 2 + age_2 ** 2 + age_3 ** 2 + age_4 ** 2 + age_5 ** 2 + age_6 ** 2 + age_7 ** 2 + age_8 ** 2\n age_multiplied_and_added_and_squared = age_multiplied_and_added ** 0.5\n return int(age_multiplied_and_added_and_squared / 2)\n", "from math import sqrt\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n sum=0\n sum=age_1*age_1+age_2*age_2+age_3*age_3+age_4*age_4+age_5*age_5+age_6*age_6+age_7*age_7+age_8*age_8\n sum=sqrt(sum)/2\n return int(sum)", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n ages = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n \n return int(math.sqrt(sum(x*x for x in ages)) / 2)", "def predict_age(*age):\n lt = [i*i for i in age]\n return int((sum(lt)**0.5)/2)", "from math import sqrt, floor\ndef predict_age(a1, a2, a3, a4, a5, a6, a7, a8):\n ages = [a1,a2, a3, a4, a5, a6, a7, a8]\n return floor(sqrt(sum([x*x for x in ages]))/2)", "import math\ndef predict_age(q, w, e, r, t, y, u, i):\n x = [q,w,e,r,t,y,u,i]\n for i,j in enumerate(x):\n x[i] = j*j\n return int(str(math.sqrt(sum(x))/2).split(\".\")[0])", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age_1 *= age_1\n age_2 *= age_2\n age_3 *= age_3\n age_4 *= age_4\n age_5 *= age_5\n age_6 *= age_6\n age_7 *= age_7\n age_8 *= age_8\n\n age = age_1 + age_2 + age_3 + age_4 + age_5 + age_6 + age_7 + age_8\n return math.floor(math.sqrt(age)/2)", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n total = 0\n\n for i in range(0,len(age)):\n multi_itself = age[i] * age[i]\n total = total + multi_itself\n\n square_root = pow(total, 0.5)\n return int(square_root / 2)", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age=0\n return (math.sqrt(pow(age_1,2)+pow(age_2,2)+pow(age_3,2)+pow(age_4,2)+pow(age_5,2)+pow(age_6,2)\n +pow(age_7,2)+pow(age_8,2)))//2", "import math\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n return math.sqrt(sum([age_1 ** 2, age_2 ** 2, age_3 ** 2, age_4 ** 2, age_5 ** 2, age_6 ** 2, age_7 ** 2, age_8 ** 2])) // 2", "import math\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n return math.sqrt(sum([x**2 for x in age]))//2", "import math\ndef predict_age(a1, a2, a3, a4, a5, a6, a7, a8):\n l = [a1 ** 2, a2 ** 2, a3 ** 2, a4 ** 2, a5 ** 2, a6 ** 2, a7 ** 2, a8 ** 2]\n return int(math.sqrt(sum(l)) / 2)", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n all_ages = []\n all_ages.extend([age_1,age_2,age_3,age_4,age_5,age_6,age_7,age_8])\n x = 0\n for age in all_ages:\n age = age * age\n x += age\n y = math.sqrt(x)\n return int(y / 2)\n", "def predict_age(*xs): \n return int(sum(map(lambda x : x**2, xs)) ** 0.5 / 2)", "import math\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n result = 0\n result += age_1 * age_1\n result += age_2 * age_2\n result += age_3 * age_3\n result += age_4 * age_4\n result += age_5 * age_5\n result += age_6 * age_6\n result += age_7 * age_7\n result += age_8 * age_8\n result = math.sqrt(result)\n result = result/2 \n \n return int(result)", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n return math.floor((age_1**2+age_2**2+age_3**2+age_4**2+age_5**2+age_6**2+age_7**2+age_8**2)**.5/2)", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n n = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n s = sum([el * el for el in n])\n return (s ** 0.5) // 2\n", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n m = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n s = sum([el * el for el in m])\n return (s ** .5) // 2", "import math \ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n # your code\n list = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n sum=0\n for i in list:\n sum += i*i\n \n return math.floor(math.sqrt(sum)/2)", "import math\ndef predict_age(a1, a2, a3, a4, a5, a6, a7, a8):\n s=0\n s+=a1*a1+a2*a2+a3*a3+a4*a4+a5*a5+a6*a6+a7*a7+a8*a8\n s=math.sqrt(s)\n return s//2", "import math\ndef predict_age(*ages):\n return math.sqrt(sum(i*i for i in ages))//2", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n ages = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n value = 0\n for age in ages:\n sqw = age * age\n value += sqw\n value = value ** 0.5\n value = int(value // 2)\n return value ", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n \n ages = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n \n new_ages = []\n \n for i in ages:\n x = i * i\n new_ages.append(x)\n \n step3 = sum(new_ages)\n step4 = (step3 ** (1/2))\n step5 = (step4 // 2)\n return step5", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n ages = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n return int((math.sqrt(sum([i**2 for i in ages])))/2)", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n ages = (age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8)\n suma = 0 \n result = 0\n for age in ages:\n suma += age * age\n result = (math.sqrt(suma)) // 2\n return result", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n\n l = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n m = int((sum([i * i for i in l]) ** 0.5) /2)\n return m\n \n\nprint((predict_age(65, 60, 75, 55, 60, 63, 64, 45)))\n\n \n \n", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n arr = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n return sum([el*el for el in arr]) ** 0.5 // 2\n", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n return sum(map(lambda x: x * x, [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8])) ** 0.5 // 2", "import math\ndef predict_age(*args):\n return int(math.sqrt(sum(a*a for a in args))/2)", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n list =[age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n grand_secret = 0\n for age in list:\n grand_secret = grand_secret + (age**2)\n grand_secret = math.sqrt(grand_secret)\n grand_secret = grand_secret / 2\n return int(grand_secret)\n # your code\n", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n import math\n x=(age_1)**2+(age_2)**2+(age_3)**2+(age_4)**2+(age_5)**2+(age_6)**2+(age_7)**2+(age_8)**2\n return math.floor((x**0.5)/2)", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age=[age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n return int(sum(i**2 for i in age)**0.5/2)", "def predict_age(*args):\n \n return (sum([age ** 2 for age in args]) ** 0.5) // 2", "import math\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age_list = []\n squares = []\n age_list.append(age_1)\n age_list.append(age_2)\n age_list.append(age_3)\n age_list.append(age_4)\n age_list.append(age_5)\n age_list.append(age_6)\n age_list.append(age_7)\n age_list.append(age_8)\n for i in age_list:\n multiply = i**2\n squares.append(multiply)\n add = sum(squares)\n answer = (math.sqrt(add))/2\n round_answer = int(round(answer, 2))\n return round_answer\n", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age = int(((age_1 ** 2 + age_2 ** 2 + age_3 ** 2 + age_4 ** 2 + age_5 ** 2 + age_6 ** 2 + age_7 ** 2 + age_8 ** 2) ** 0.5)/2)\n return age", "from math import sqrt\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n age2 = []\n age3 = 0\n for i in age:\n age2.append(i*i)\n \n for i in age2:\n age3 += i\n \n return (int(sqrt(age3)/2))\n", "from math import sqrt\n\ndef predict_age(*ages):\n a = [pow(x, 2) for x in ages]\n a = sum(a)\n a = sqrt(a)\n a = a//2\n return a\n", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n x = age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8\n \n return math.sqrt(sum([i*i for i in x]))//2", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age1 = age_1 ** 2\n age2 = age_2 ** 2\n age3 = age_3 ** 2\n age4 = age_4 ** 2\n age5 = age_5 ** 2\n age6 = age_6 ** 2\n age7 = age_7 ** 2\n age8 = age_8 ** 2\n sumofages = age1 + age2+ age3+ age4+ age5+ age6+ age7+ age8\n sqrtofage = sumofages ** 0.5\n final = sqrtofage / 2\n return math.floor(final)\n\n", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n sum_mult = age_1*age_1 + age_2*age_2 + age_3*age_3 + age_4*age_4 + age_5*age_5 + age_6*age_6 + age_7*age_7 + age_8*age_8\n result = math.floor(math.sqrt(sum_mult)/2)\n return result", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n ages = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n ages1 = []\n for age in ages:\n age *= age\n ages1.append(age)\n age_sm = sum(ages1)\n return math.floor(math.sqrt(age_sm) / 2)", "import math\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n return int(math.sqrt(sum(a ** 2 for a in [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]))/2)", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n li = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n b = [x**2 for x in li]\n return(int((sum(b) ** 0.5 )/2))", "def predict_age(a,b,c,d,e,f,g,h):\n return sum(i**2 for i in [a,b,c,d,e,f,g,h])**0.5//2", "def predict_age(*args):\n return sum(x*x for x in args)**(1/2) // 2", "def predict_age(*args):\n result = 0\n for el in args:\n result += (el*el)\n return result**(1/2) // 2", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n \n z = []\n z.append(age_1)\n z.append(age_2)\n z.append(age_3)\n z.append(age_4)\n z.append(age_5)\n z.append(age_6)\n z.append(age_7)\n z.append(age_8)\n \n y = []\n \n for i in z:\n y.append(i*i)\n \n x = sum(y)\n \n x = math.sqrt(x)\n \n return (x//2)", "from math import *\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n a = age_1*age_1\n b = age_2*age_2\n c = age_3*age_3\n d = age_4*age_4\n e = age_5*age_5\n f = age_6*age_6\n g = age_7*age_7\n h = age_8*age_8\n i = a+b+c+d+e+f+g+h\n j = sqrt(i)\n h = floor(j/2)\n return h", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n a = (age_1 * age_1) + (age_2 * age_2) + (age_3 * age_3) + (age_4 * age_4) + (age_5 * age_5) + (age_6 * age_6) + (age_7 * age_7) + (age_8 * age_8)\n b = a**.5\n return int(b // 2)", "def predict_age(*ages):\n return pow(sum(a*a for a in ages), .5) // 2", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n import math\n a = [age_1, age_2,age_3, age_4, age_5, age_6, age_7, age_8 ]\n b= []\n for x in a:\n b.append(x*x)\n \n s = sum(b)\n \n s = math.sqrt(s)\n \n s = s/2\n return int(s)", "def predict_age(*ages):\n return int(sum(i*i for i in ages) ** 0.5 / 2)", "from math import sqrt\ndef predict_age(*ages):\n result = []\n for n in ages:\n result.append(n*n)\n return sqrt(sum(result)) // 2", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n ageList = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n return sum(i*i for i in ageList)**0.5//2", "import math\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n i = 0 \n ages = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n for j in ages:\n ages[i] = j**2\n i += 1\n return math.sqrt(sum(ages))//2", "def predict_age(*args):\n sum = 0\n for i in args:\n sum += i*i\n return sum ** 0.5 // 2", "import math\ndef predict_age(*args):\n res = 0\n for i in args:\n res+= (i *i)\n return math.floor(math.sqrt(res) / 2)", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age_1 = age_1 * age_1\n age_2 = age_2 * age_2\n age_3 = age_3 * age_3\n age_4 = age_4 * age_4\n age_5 = age_5 * age_5\n age_6 = age_6 * age_6\n age_7 = age_7 * age_7\n age_8 = age_8 * age_8\n output = age_1 + age_2 + age_3 + age_4 + age_5 + age_6 + age_7 + age_8\n output = math.sqrt(output)\n a = output // 2\n return math.floor(a)\n", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n starting_list = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n each_muliply_itself = []\n for age in starting_list:\n each_muliply_itself.append(age*age)\n total_multiplied_ages = sum(each_muliply_itself)\n square_root_result = total_multiplied_ages**(.5)\n result = square_root_result/2\n return int(result)", "from functools import reduce\nimport math\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n \n ages = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n \n res = math.sqrt(sum([x * x for x in ages]))\n\n return int (res / 2)\n", "import math\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n list = [age_1,age_2,age_3,age_4,age_5,age_6,age_7,age_8]\n squared_list = [a**2 for a in list]\n added_squared_list = math.sqrt(sum(squared_list)) / 2\n return int(added_squared_list)", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n l = [age_1 ** 2, age_2 ** 2, age_3 ** 2, age_4 ** 2, age_5 ** 2, age_6 ** 2, age_7 ** 2, age_8 ** 2]\n return sum(l) ** .5 // 2", "from math import sqrt\n\n\ndef predict_age(*ages):\n return int(sqrt(sum(map(lambda x: x**2, ages)))/2)", "from math import sqrt\n\n\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n ages = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n return int(sqrt(sum(map(lambda x: x**2, ages)))/2)", " \n\ndef predict_age(a,b,c,d,e,f,g,h):\n r = [a,b,c,d,e,f,g,h]\n rs = int((sum([i**2 for i in r]) ** 0.5) / 2)\n return rs\n", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n lst = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n second = []\n summ = 0\n for age in lst:\n first = age*age\n second.append(first)\n for product in second:\n summ += product\n summ = math.sqrt(summ)\n answer = summ/2\n return int(answer)", "import math \ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n k=age_1**2\n n=age_2**2\n g=age_3**2\n l=age_4**2\n t=age_5**2\n j=age_6**2\n i=age_7**2\n e=age_8**2\n b=k+n+g+l+t+j+i+e\n return math.sqrt(b)//2", "predict_age = lambda *a:sum(e**2 for e in a)**0.5//2", "import math\ndef predict_age(a1, a2, a3, a4, a5, a6, a7, a8):\n array= [a1,a2,a3,a4,a5,a6,a7,a8]\n return int(math.sqrt(sum(x**2 for x in array))/2)", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n sum_ages=0\n ages=[age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8] \n for x in ages:\n sum_ages+= x**2\n swaureroot= sum_ages**(1/2)\n return int(swaureroot/2)", "import math\ndef predict_age(*ages):\n return int(math.sqrt(sum([num*num for num in ages])) / 2)", "import math\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n ls = age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8\n return int(math.sqrt(sum([num*num for num in ls])) / 2)\n", "def predict_age(*args):\n return int((sum(n*n for n in args)**.5)//2)", "import math \ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n s_age = (( (age_1 ** 2) + (age_2 ** 2) + (age_3 ** 2) + (age_4 ** 2) + (age_5 ** 2) + (age_6 ** 2) + (age_7 ** 2) + (age_8 ** 2) )) ** 0.5\n return (math.floor(s_age / 2))", "from math import floor\ndef predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]\n return floor((sum(i**2 for i in age))**0.5/2)", "def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):\n age = age_1 ** 2 + age_2 ** 2 + age_3 ** 2 + age_4 ** 2 + age_5 ** 2 + age_6 ** 2 + age_7 ** 2 + age_8 ** 2\n age = age ** .5\n age = age / 2\n return int(age)"]
{"fn_name": "predict_age", "inputs": [[65, 60, 75, 55, 60, 63, 64, 45], [32, 54, 76, 65, 34, 63, 64, 45]], "outputs": [[86], [79]]}
INTRODUCTORY
PYTHON3
CODEWARS
21,936
def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):
8687b6b66c4f2a463f1658e980894106
UNKNOWN
You have a collection of lovely poems. Unfortuantely they aren't formatted very well. They're all on one line, like this: ``` Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. ``` What you want is to present each sentence on a new line, so that it looks like this: ``` Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. ``` Write a function, `format_poem()` that takes a string like the one line example as an argument and returns a new string that is formatted across multiple lines with each new sentence starting on a new line when you print it out. Try to solve this challenge with the [str.split()](https://docs.python.org/3/library/stdtypes.html#str.split) and the [str.join()](https://docs.python.org/3/library/stdtypes.html#str.join) string methods. Every sentence will end with a period, and every new sentence will have one space before the previous period. Be careful about trailing whitespace in your solution.
["def format_poem(poem):\n return \".\\n\".join(poem.split(\". \"))", "def format_poem(poem):\n return poem.replace(\". \", \".\\n\")\n", "def format_poem(poem):\n lines = poem.split('. ')\n return '.\\n'.join(lines)\n \n \n \n \n \n", "from re import sub\n\n# Try to solve this challenge with the str.split() and the str.join() string methods.\n# -> No\ndef format_poem(poem):\n return sub(r\"(?<=\\.)\\s\", \"\\n\", poem)", "def format_poem(poem):\n lines = poem.replace('. ','.\\n')\n return lines\n \n", "def format_poem(poem):\n poem = poem.split('. ')\n result = '.\\n'.join(poem)\n return result\n", "format_poem = lambda p:'.\\n'.join(p.split(\". \"))\n", "format_poem = __import__(\"functools\").partial(__import__(\"re\").sub, r\"(?<=\\.)\\s\", \"\\n\")", "def format_poem(poem):\n # Your code goes here.\n poem_new = poem.replace('. ', '.\\n') \n return poem_new\n \n", "def format_poem(s):\n a, r = s.split('.'), []\n for k,i in enumerate(a):\n if k == 0:r.append(i.lstrip())\n else:r.append('\\n'+i.lstrip())\n return ('.'.join(r)).rstrip('\\n')\n"]
{"fn_name": "format_poem", "inputs": [["Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated."], ["Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules."], ["Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess."], ["There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now."], ["If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!"]], "outputs": [["Beautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated."], ["Flat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules."], ["Although practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess."], ["There should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now."], ["If the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,145
def format_poem(poem):
d77369a1772e00ec5b2793da1818438c
UNKNOWN
Lexicographic permutations are ordered combinations of a set of items ordered in a specific way. For instance, the first 8 permutations of the digits 0123, in lexicographic order, are: ``` 1st 0123 2nd 0132 3rd 0213 4th 0231 5th 0312 6th 0321 7th 1023 8th 1032 ``` Your task is to write a function ```L( n, d )``` that will return a `string` representing the `nth` permutation of the `d` digit, starting with 0 (i.e. d=10 means all digits 0123456789). So for `d = 4`, `L(7,4)` should return `'1023'`, and `L(4,4)` should return `'0231'` . Some things to bear in mind: • The function should return a `string`, otherwise permutations beginning with a 0 will have it removed. • Test cases will not exceed the highest possible valid values for `n` • The function should work for any `d` between `1` and `10`. • A value of 1 for `n` means the 1st permutation, so `n = 0` is not a valid input. • Oh, and no itertools ;)
["import math\ndef nth_perm(n,d):\n digits = [str(i) for i in range(d)]\n out = ''\n for i in range(1, d):\n cycles = math.ceil(n/math.factorial(d-i))\n out += digits.pop((cycles % (d-i+1)) - 1)\n return out + digits.pop()", "def nth_perm(n,d):\n st, i, n, fc = list(map(str, range(d))), 1, n-1, ''\n while n:\n n, mod = divmod(n, i)\n fc = str(mod)+fc\n i += 1\n return ''.join([st.pop(int(i)) for i in fc.zfill(d)])", "def memoize(func):\n cache = {}\n def decorator(x):\n if not x in cache:\n cache[x] = func(x)\n return cache[x]\n return decorator \n\n@memoize\ndef permutations(d):\n if d < 1:\n return []\n if d == 1:\n return [\"0\"]\n return sorted(p[:i] + str(d - 1) + p[i:] for p in permutations(d - 1) for i in range(d))\n\ndef nth_perm(n, d):\n return permutations(d)[n - 1]\n", "def nth_perm(n, d):\n n -= 1\n _in, out_, f = [], [], []\n for x in range(d):\n f.append(not f or x * f[-1])\n _in.append(str(x))\n for x in range(d):\n i, n = divmod(n, f.pop())\n out_.append(_in.pop(i))\n return ''.join(out_)", "from math import factorial\ndef nth_perm(n,d):\n n = n-1\n lst = sorted(map(str, range(d)))\n f = factorial(d)\n ans = []\n while lst:\n f = f//len(lst)\n c, n = n//f, n%f\n ans += [lst.pop(c)]\n return ''.join(map(str, ans))", "import sys\np = sys.modules['iter''tools'].permutations\ndef nth_perm(n, d):\n return ''.join([*p('0123456789'[:d])][~-n])", "from math import factorial\n\ndef nth_perm(n, d):\n n, ds, res = n-1, list(range(d)), []\n for i in range(d - 1, -1, -1):\n p, n = divmod(n, factorial(i))\n res.append(ds.pop(p))\n return ''.join(map(str, res))", "def sil(a):\n b=1\n for i in range (1,a+1):\n b=b*i\n return b\n \ndef nth_perm(n,d):\n #tworzenie listy do permutacji\n lit=list(('0123456789')[:d])\n out=[]\n #iteracja pozycji\n for i in range(d):\n el=int((n-1)/sil(d-1))\n out.append(lit.pop(el))\n n=n-sil(d-1)*(el)\n d-=1\n\n return ''.join(out)", "from math import factorial\ndef nth_perm(n,d):\n a=list(range(d))\n i=d-1\n r=''\n while(i>=0):\n b=(n-1)//factorial(i)\n r+=str(a[b])\n a.remove(a[b])\n n-=b*factorial(i)\n i-=1\n return r"]
{"fn_name": "nth_perm", "inputs": [[1, 1], [12, 5], [1000, 7], [1000, 8], [1000000, 10], [874, 7], [100, 5], [400, 6], [900, 8], [3000000, 10], [1234567, 10], [654321, 10], [100000, 9], [33333, 8]], "outputs": [["0"], ["02431"], ["1325460"], ["02436571"], ["2783915460"], ["1234560"], ["40231"], ["314250"], ["02354761"], ["8241697530"], ["3469702158"], ["1827653409"], ["247815360"], ["64157203"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,442
def nth_perm(n,d):
04040398fa4ac644d96c383c5ab2881b
UNKNOWN
Given a side length `n`, traveling only right and down how many ways are there to get from the top left corner to the bottom right corner of an `n by n` grid? Your mission is to write a program to do just that! Add code to `route(n)` that returns the number of routes for a grid `n by n` (if n is less than 1 return 0). Examples: -100 -> 0 1 -> 2 2 -> 6 20 -> 137846528820 Note: you're traveling on the edges of the squares in the grid not the squares themselves. PS.If anyone has any suggestions of how to improve this kata please let me know.
["from math import factorial\n\ndef routes(n):\n return n > 0 and factorial(2*n) // factorial(n)**2", "from math import factorial as f\nroutes=lambda n:f(n*2) // (f(n)*f(n)) if n>0 else 0", "def routes(n):\n if(n < 1):\n return(0);\n \n res = 1;\n for i in range(1, n + 1):\n res = res*(n + i)//i;\n \n return(res);", "from math import factorial as f\n\ndef routes(n):\n return f(n * 2) // f(n)**2 if n > 0 else 0"]
{"fn_name": "routes", "inputs": [[156], [106], [108], [126], [165], [125], [103]], "outputs": [[376594020312425061595746241557406711201605603899894320577733841460621358204120168599683135056], [360262512886894560870925723424985925545493469115736766525399280], [5710703280600670271749409312650477833283445281465962347881848400], [363385715856739898597174879118845755433251497432024467186246395557048813504], [95995892383488599901870820732368671856306475542669347911637204757217297906428740013991568571288240], [91208366928185711600087718663295946582847985411225264672245111235434562752], [5710294458198606715524045745816008575257432967999860738082400]]}
INTRODUCTORY
PYTHON3
CODEWARS
435
def routes(n):
e8538092980978daf693ada513e0cd66
UNKNOWN
_Based on [Project Euler problem 35](https://projecteuler.net/problem=35)_ A circular prime is a prime in which every circular permutation of that number is also prime. Circular permutations are created by rotating the digits of the number, for example: `197, 971, 719`. One-digit primes are circular primes by definition. Complete the function that dertermines if a number is a circular prime. There are 100 random tests for numbers up to 10000.
["def circular_permutations(n):\n n = str(n)\n return [int(n[i:] + n[:i]) for i in range(len(n))]\n\ndef is_prime(n):\n return n > 1 and all(n % i != 0 for i in range(2, int(n**0.5)+1))\n\ndef circular_prime(n):\n return all(is_prime(x) for x in circular_permutations(n))\n", "def circular_prime(n):\n return n in [2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 97, 113, 131, 197, 199, 311, 337, 373, 719, 733, 919, 971, 991, 1193, 1931, 3119, 3779, 7793, 7937, 9311, 9377, 11939]", "def circular_prime(n):\n ns = str(n)\n lp = []\n for i in ns:\n ns = ns[1:] + ns[0]\n lp.append(ns)\n for i in lp:\n for j in range(2,int(i)):\n if int(i)%j == 0:\n return False\n return True and n != 1\n", "from collections import deque\n\ndef is_prime(n):\n return n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))\n \ndef circular_prime(n):\n items = deque(str(n))\n for _ in range(len(items)):\n items.rotate(1)\n if not is_prime(int(\"\".join(items))):\n return False\n return True", "def circular_permutations(n):\n s = str(n)\n return [int(s[i:] + s[:i]) for i in range(len(s))]\n\ndef is_prime(n):\n return n == 2 or pow(2, n - 1, n) == 1\n\ndef circular_prime(n):\n return all(is_prime(c) for c in circular_permutations(n))", "def is_prime(n):\n d = 2\n while d * d <= n:\n if n % d == 0:\n return False\n d += 1\n return n > 1\n\ndef rotate(l, n):\n return l[-n:] + l[:-n]\n\ndef circular_prime(number):\n \n number_list = [int(x) for x in str(number)]\n if is_prime(number):\n check_list = [True]\n for index in range(1,len(number_list)):\n number_rotated = rotate(number_list,index)\n number_join = int(''.join(map(str, number_rotated)))\n if is_prime(number_join):\n check_list.append(True)\n if (len(check_list) == len(number_list)): return True\n else: return False\n else: return False\n \n \n", "def circular_prime(n):\n #test is a number is a circular prime\n # uses 2 functions\n \n l=len(str(n)) # the length of the number \n \n for i in range (l):\n \n if is_prime(n): \n n=circul_num(n,l)\n else: # the num is not prime \n return False # return False\n return True\n\ndef circul_num(n,l):\n # one circular permutation of a num to left \n # input n: int number , l: length of number\n power =10**(l-1) # poer of 10 to cut the number at highst digit\n\n if len(str(n))<l: #if num is short, need a 0 at the end to compensate\n N=n*10 \n else: \n N=(n%power)*10+(n//power) # permutation to the left\n return N\n\ndef is_prime(n):\n # chek if a number is praime\n if n==1:\n return False \n\n for i in range(2,int(n**0.5)+1): #runs from 2 to the sqrt of n\n if n%i==0: \n return False \n \n return True\n", "circular_prime = {2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 97, 113, 131, 197, 199, 311, 337, 373, 719,\n 733, 919, 971, 991, 1193, 1931, 3119, 3779, 7793, 7937, 9311, 9377, 11939}.__contains__"]
{"fn_name": "circular_prime", "inputs": [[197], [179], [971], [222], [9377], [7], [213], [35], [1]], "outputs": [[true], [false], [true], [false], [true], [true], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,243
def circular_prime(n):
cfbf6456c932eddc2a004231aac23497
UNKNOWN
## Terminal game move function In this game, the hero moves from left to right. The player rolls the dice and moves the number of spaces indicated by the dice **two times**. ~~~if-not:sql Create a function for the terminal game that takes the current position of the hero and the roll (1-6) and return the new position. ~~~ ~~~if:sql In SQL, you will be given a table `moves` with columns `position` and `roll`. Return a table which uses the current position of the hero and the roll (1-6) and returns the new position in a column `res`. ~~~ ### Example: ```python move(3, 6) should equal 15 ``` ```if:bf ### BF: Since this is an 8kyu kata, you are provided a modified runBF function, numericRunBF, that automatically parses input and output for your ease. See the sample test cases to see what I mean: You can simply input two numbers and get a number as output (unless you're doing something wrong), so it should be convenient for you to modify the tests as you wish. Oh, and you won't have to worry about overflow, the correct answer will never be higher than 255. :) ```
["def move(position, roll):\n return position + 2*roll", "def move(position, roll):\n return position+roll*2", "move = lambda p,r: p+r*2", "def move(start, roll):\n return start + 2*roll", "def move(start, roll):\n return start + roll * 2", "def move(position, roll):\n return position+(roll<<1)", "move=lambda p,m:p+2*m", "move = lambda _, i: _ + 2 * i", "def move(position, roll):\n print(position)\n print(roll)\n position = position + roll * 2\n return position\n # your code here\n", "move = lambda position, roll: position + roll * 2", "def move(position, roll):\n x=position\n y=roll\n return x+(y*2)\n", "def move(position, roll):\n x = position + 2 * roll\n return x", "def move(position, roll):\n return 2 * roll + position", "def move(p,r):\n return p+(r*2)", "import unittest\n\n\ndef move(position, roll):\n return position + roll * 2\n \n \nclass TestMove(unittest.TestCase):\n def test_move(self):\n self.assertEqual(move(position=0, roll=4), 8)\n", "def move(position, roll):\n if roll < 1 or roll > 6:\n return \"Error\"\n else:\n new_position = position + (roll * 2)\n return(new_position)", "def move(position, roll):\n a = position\n b = roll\n c = (2*b)+a\n return c", "move = lambda p, r: ['there are bees on my knees', 2, 4, 6, 8, 10, 12].__getitem__(r) + p", "def move(pos, mov):\n return pos + 2*mov", "def move(position, roll):\n s = position + ( roll * 2)\n return s\n # your code here\n", "def move(position, roll):\n new_spot = roll*2 + position\n return new_spot", "def move(position, roll):\n return position + 2 * roll\nprint((move(1,4)))\n", "def move(position, roll):\n # my solution\n return position + 2 * roll\nprint(move(1, 4))", "def move(position, roll):\n a = position + roll + roll\n return a", "def move(position, roll):\n res = position+roll*2\n \n return res\n", "def move(p, r):\n return 2*r + p", "def move(position, roll):\n r = roll * 2\n return position + r", "def move(position, roll):\n delta = roll * 2\n return position + delta", "# player moves from left to right\n# The player rolls the dice and moves the number of spaces indicated by the dice two times.\n# input - two integers\n# output - integer\n\n#edge cases - die roll can only be (1-6), no numbers given\n\n# sample test (2, 7) = 16\n# 2 + (7 * 2)\n\ndef move(position, roll):\n return (roll * 2) + position ", "def move(pos, roll):\n return pos + 2*roll", "def move(position, roll):\n if roll < 7:\n return position + roll*2", "def move(position, roll):\n res = 0\n res = (roll * 2) + position\n return res ", "move = lambda pos, roll: pos + roll*2", "def move(position, roll):\n if roll == 1: \n return position + 2*roll\n if roll == 2: \n return position + 2*roll\n if roll == 3: \n return position + 2*roll\n if roll == 4: \n return position + 2*roll\n if roll == 5: \n return position + 2*roll\n if roll == 6: \n return position + 2*roll\n", "def move(position, roll):\n return roll * 2 if position == 0 else (position + roll) * 2 - position", "def move(position, roll):\n # your code here\n double = roll*2\n return position + double\n \nmove(1,1)", "move = lambda a, b: a + 2 * b", "def move(position, roll):\n # your code here\n move = roll*2\n sum = position + move\n return sum", "def move(position, roll):\n return position + roll*2\n # y\n", "def move(position, roll):\n n= position+roll+roll\n return n", "def move(position, roll):\n return roll + (position+roll)", "def move(position, roll):\n \"\"\"Return the new player position\"\"\"\n return position + 2 * roll", "def move(p, r):\n return (p+r)*2 - p", "def move(position, roll, moves=2):\n return move(position, roll, moves - 1) + roll if moves else position", "def move(position, roll):\n # your code here\n new_pos = position + (roll *2)\n return new_pos ", "def move(position, roll):\n currentSpace = roll * 2 + position\n return currentSpace", "def move(position, roll):\n return position + (roll * 2)\n # Zelf\n", "def move(P, R):\n return P + (2*R);", "def move(position, roll):\n roll *= 2\n return roll + position", "def move(p, r):\n # your code here\n p=p+2*r\n return p ", "def move(position, roll):\n n = roll * 2 + position\n return n", "def move(position, roll):\n moves = roll*2\n new_position = position + moves\n return new_position", "def move(position, roll):\n case = position + roll *2\n return case", "def move(position, roll):\n position += 2* roll\n return position", "def move(position, roll):\n if roll > 0:\n position += roll * 2\n elif roll < 0:\n position -= roll * 2\n else: \n position = position\n return position", "def move(position, roll):\n y = roll*2\n return position+y", "def move(position, roll):\n pos = position + 2 * roll\n return pos# your code here", "def move(position, roll):\n n = roll*2\n return position + n", "def move(position, roll):\n x = position\n y = roll\n new_pos = x + 2 * y\n return new_pos", "def move(position: int, roll: int) -> int:\n return position + 2 * roll", "def move(position, roll):\n # your code here\n goal = position + 2 * roll\n return goal;", "def move(position, roll):\n roll = roll * 2 \n return position + roll", "def move(position, roll):\n roll = roll*2\n new = position + roll\n return new", "def move(position, roll):\n diceOver = 2*roll\n newPos = diceOver + position\n return newPos", "def move(position, roll):\n i = 0\n for i in range(roll):\n position += 2\n return position\nmove(0, 4)", "def move(position, roll):\n # your code here\n sum = (position + 2*roll)\n return sum", "def move(position, roll):\n x = roll * 2\n newpos = x+position\n return newpos", "def move(position, roll):\n # your code here\n return position + roll * 2\n \nprint(move(3, 6))", "def move(position, roll):\n # your code here\n return position + 2 * roll\n \nprint(move(3, 6))", "def move(n, b):\n return n + 2*b", "def move(position, roll):\n result = roll * 2 + position\n return result", "def move(position, roll):\n new_pos = position + (roll*2)\n print(new_pos)\n return new_pos\n # your code here\n", "position = 0\nroll = 0\n\n\ndef move(position, roll):\n inp = position + roll * 2\n return inp\n\n\n\nmove(0, 4)", "def move(position, roll):\n new_position = position + roll + roll\n return new_position", "def move(position, roll):\n m = position+2*roll\n return(m)", "def move(position, roll):\n megfejtes = position + (roll*2)\n return(megfejtes)", "def move(position, roll):\n # your code here\n new_pos=position+2*roll\n return new_pos", "def move(x, y):\n return (y * 2) + x", "def move(position, roll):\n return position + (2.*roll)", "def move(position, roll):\n total_roll = roll * 2\n new_position = position + total_roll\n\n return new_position", "def move(position, roll):\n position = position + roll \n position = position + roll\n return position", "def move(position, roll):\n # Takes current p[osition and double the roll dice (1-6)\n return position + (roll * 2)", "def move(position, roll):\n final_pos=position+2*roll\n return final_pos", "def move(position, roll):\n position += roll + roll;\n return position;", "def move(position, roll):\n if roll:\n return position + (roll*2)", "def move(position, roll):\n position = roll * 2 + position\n return position", "def move(position, roll):\n\n intPosition = position + roll * 2\n\n return intPosition", "move = lambda x, n : x + 2 * n", "def move(position, roll):\n return position + int(roll * 2)", "def move(position, roll):\n final_position = position + 2 * roll\n return final_position\n", "def move(position, roll):\n a = position\n b = roll\n c = a+b*2\n return c", "def move(position, roll):\n move = int(position) + roll * 2\n return move", "def move(position, roll):\n # your code here\n return (position + 2 * roll)\n\nprint((move(2, 5)))\n", "def move(position, roll):\n pos = position + roll + roll\n return pos", "def move(position, roll):\n numMoved = roll * 2\n return position + numMoved", "def move(position, roll):\n a = position\n import random\n b = roll\n c =a+b+b\n return c\n", "def move(position, roll):\n y = int(roll) * 2\n x = int(position)\n equ = y + x\n return equ", "def move(position, roll):\n \n return (position + ( roll * 2))\n \n \n \nprint((move(0, 4)))\n", "def move(position, roll):\n new=position + (roll*2)\n return new", "def move(position, roll):\n if (roll >= 1) and (roll <= 6):\n position += (roll * 2)\n return position"]
{"fn_name": "move", "inputs": [[0, 4], [3, 6], [2, 5]], "outputs": [[8], [15], [12]]}
INTRODUCTORY
PYTHON3
CODEWARS
9,071
def move(position, roll):
f8802f2cbb2ea0579bd3bc30aa60de0a
UNKNOWN
Implement `String.eight_bit_signed_number?` (Ruby), `String.eightBitSignedNumber()` (Python), `eight_bit_signed_number()` (JS) or `StringUtils.isSignedEightBitNumber(String)` (Java) which should return `true/True` if given object is a number representable by 8 bit signed integer (-128 to -1 or 0 to 127), `false/False` otherwise. It should only accept numbers in canonical representation, so no leading `+`, extra `0`s, spaces etc.
["import re\ndef signed_eight_bit_number(number):\n return bool(re.match(\"(0|-128|-?([1-9]|[1-9]\\d|1[01]\\d|12[0-7]))\\Z\", number))", "def signed_eight_bit_number(number):\n if number in list(map(str,list(range(-128,128)))):\n return True\n return False\n \n", "import re\n\nSIGNED_BYTE_PATTERN = re.compile(r'''\n \\A\n (?:\n 0 |\n -? (?:\n 1 (?:\n [01] \\d? |\n 2 [0-7]? |\n [3-9] )? |\n [2-9] \\d? ) |\n -128 )\n \\Z\n''', re.X)\n\n\ndef signed_eight_bit_number(number):\n return bool(SIGNED_BYTE_PATTERN.search(number))\n", "def signed_eight_bit_number(s):\n try:\n return -128 <= int(s) <= 127 and str(int(s)) == s\n except ValueError:\n return False", "import re\n\ndef signed_eight_bit_number(n):\n return bool(re.fullmatch(r\"-?(1[01]\\d|12[0-7]|[1-9]\\d)|-(128|[1-9])|\\d\", n))\n", "import re\ndef signed_eight_bit_number(n):\n return re.match(r'-?\\d+$',n)and str(int(n))==n and -128<=int(n)<128 or False", "def signed_eight_bit_number(number):\n return number in list(map(str, list(range(-128, 128))))\n", "def signed_eight_bit_number(number):\n try:\n i = int(number)\n return (-128 <= i <= 127) and number == str(i)\n except:\n pass\n return False\n", "import re\n\ndef signed_eight_bit_number(number):\n return bool(re.fullmatch(r\"(-?(1(([2][0-7])|([01]\\d))|[1-9][0-9]))|\\d|-[1-9]|-128\", number))"]
{"fn_name": "signed_eight_bit_number", "inputs": [[""], ["0"], ["00"], ["-0"], ["55"], ["-23"], ["042"], ["127"], ["128"], ["999"], ["-128"], ["-129"], ["-999"], ["1\n"], ["1 "], [" 1"], ["1\n2"], ["+1"], ["--1"], ["01"], ["-01"]], "outputs": [[false], [true], [false], [false], [true], [true], [false], [true], [false], [false], [true], [false], [false], [false], [false], [false], [false], [false], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,505
def signed_eight_bit_number(number):
94d89fff42e8a2a85fabb202e9192152
UNKNOWN
Given two words and a letter, return a single word that's a combination of both words, merged at the point where the given letter first appears in each word. The returned word should have the beginning of the first word and the ending of the second, with the dividing letter in the middle. You can assume both words will contain the dividing letter. ## Examples ```python string_merge("hello", "world", "l") ==> "held" string_merge("coding", "anywhere", "n") ==> "codinywhere" string_merge("jason", "samson", "s") ==> "jasamson" string_merge("wonderful", "people", "e") ==> "wondeople" ```
["def string_merge(string1, string2, letter):\n return string1[:string1.index(letter)] + string2[string2.index(letter):]", "def string_merge(string1, string2, letter):\n \"\"\"given two words and a letter, merge one word that combines both at the first occurence of \n the letter\n >>> \"hello\",\"world\",\"l\"\n held\n >>> \"jason\",\"samson\",\"s\"\n jasamson \n \"\"\"\n return string1[0:(string1.find(letter))] + string2[(string2.find(letter)):]", "def string_merge(s1: str, s2: str, letter: str) -> str:\n return f\"{s1.partition(letter)[0]}{letter}{s2.partition(letter)[2]}\"\n", "string_merge=lambda a,b,l:a[:a.find(l)]+b[b.find(l):]", "def string_merge(str1, str2, l):\n i = str1.find(l)\n j = str2.find(l)\n return str1[:i] + str2[j:]", "def string_merge(string1, string2, letter):\n return f\"{string1.partition(letter)[0]}{letter}{string2.partition(letter)[-1]}\"", "def string_merge(str1, str2, letter):\n return str1[:str1.index(letter)] + str2[str2.index(letter):]"]
{"fn_name": "string_merge", "inputs": [["hello", "world", "l"], ["coding", "anywhere", "n"], ["jason", "samson", "s"], ["wonderful", "people", "e"], ["person", "here", "e"], ["apowiejfoiajsf", "iwahfeijouh", "j"], ["abcdefxxxyzz", "abcxxxyyyxyzz", "x"], ["12345654321", "123456789", "6"], ["JiOdIdA4", "oopopopoodddasdfdfsd", "d"], ["incredible", "people", "e"]], "outputs": [["held"], ["codinywhere"], ["jasamson"], ["wondeople"], ["pere"], ["apowiejouh"], ["abcdefxxxyyyxyzz"], ["123456789"], ["JiOdddasdfdfsd"], ["increople"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,002
def string_merge(string1, string2, letter):
6a26a50569e288c91ec3205db76b64ac
UNKNOWN
You certainly can tell which is the larger number between 2^(10) and 2^(15). But what about, say, 2^(10) and 3^(10)? You know this one too. Things tend to get a bit more complicated with **both** different bases and exponents: which is larger between 3^(9) and 5^(6)? Well, by now you have surely guessed that you have to build a function to compare powers, returning -1 if the first member is larger, 0 if they are equal, 1 otherwise; powers to compare will be provided in the `[base, exponent]` format: ```python compare_powers([2,10],[2,15])==1 compare_powers([2,10],[3,10])==1 compare_powers([2,10],[2,10])==0 compare_powers([3,9],[5,6])==-1 compare_powers([7,7],[5,8])==-1 ``` ```if:nasm int compare_powers(const int n1[2], const int n2[2]) ``` Only positive integers will be tested, incluing bigger numbers - you are warned now, so be diligent try to implement an efficient solution not to drain too much on CW resources ;)!
["from math import log\n\ndef compare_powers(*numbers):\n a,b = map(lambda n: n[1]*log(n[0]), numbers)\n return (a<b) - (a>b)", "from math import log\ndef compare_powers(n1, n2):\n val = n2[1] * log(n2[0]) - n1[1] * log(n1[0])\n return -1 if val < 0 else 1 if val > 0 else 0", "from math import log\n\ndef compare(x, y):\n if x == y:\n return 0\n if x < y:\n return 1\n if x > y:\n return -1\n \ndef compare_powers(x, y):\n a, c = x\n b, d = y\n x = (c * log(a)) / log(2)\n y = (d * log(b)) / log(2)\n return compare(x, y)", "from math import log\ndef compare_powers(n1,n2):\n a=n1[1]*log(n1[0])\n b=n2[1]*log(n2[0])\n if a==b: return 0\n if a>b: return -1\n return 1", "from math import log\ndef compare_powers(n1,n2):\n if n2[1]*log(n2[0]) > n1[1]*log(n1[0]): return 1\n elif n2[1]*log(n2[0]) < n1[1]*log(n1[0]): return -1\n else: return 0"]
{"fn_name": "compare_powers", "inputs": [[[2, 10], [2, 15]], [[1, 10], [3, 10]], [[2, 10], [2, 10]], [[3, 9], [1, 6]], [[1, 7], [1, 8]], [[2, 100], [2, 150]], [[2, 100], [3, 100]], [[2, 100], [2, 100]], [[34, 98], [51, 67]], [[1024, 97], [1024, 81]]], "outputs": [[1], [1], [0], [-1], [0], [1], [1], [0], [-1], [-1]]}
INTRODUCTORY
PYTHON3
CODEWARS
970
def compare_powers(n1,n2):
319347cc1c840285a45e049e2148e1b9
UNKNOWN
Consider the following numbers (where `n!` is `factorial(n)`): ``` u1 = (1 / 1!) * (1!) u2 = (1 / 2!) * (1! + 2!) u3 = (1 / 3!) * (1! + 2! + 3!) ... un = (1 / n!) * (1! + 2! + 3! + ... + n!) ``` Which will win: `1 / n!` or `(1! + 2! + 3! + ... + n!)`? Are these numbers going to `0` because of `1/n!` or to infinity due to the sum of factorials or to another number? ## Task Calculate `(1 / n!) * (1! + 2! + 3! + ... + n!)` for a given `n`, where `n` is an integer greater or equal to `1`. To avoid discussions about rounding, return the result **truncated** to 6 decimal places, for example: ``` 1.0000989217538616 will be truncated to 1.000098 1.2125000000000001 will be truncated to 1.2125 ``` ## Remark Keep in mind that factorials grow rather rapidly, and you need to handle large inputs. ## Hint You could try to simplify the expression.
["def going(n): \n s = 1.0\n for i in range(2, n + 1):\n s = s/i + 1\n return int(s * 1e6) / 1e6", "def going(n):\n factor = 1.0\n acc = 1.0\n for i in range(n, 1, -1):\n factor *= 1.0 / i\n acc += factor\n return int(acc * 1e6) / 1e6", "def going(n):\n a = 1.\n for i in range(2, n+1):\n a/=i\n a+=1\n return float(str(a)[:8])", "from itertools import accumulate as acc\nfrom math import floor\n\ndef going(n):\n return floor(1e6*(1 + sum(1/x for x in acc(range(n, 1, -1), lambda a, b: a*b))))/1e6", "import math\nfrom functools import reduce\ndef going(n):\n return math.floor(reduce(lambda r, i: r / float(i) + 1, range(1, n + 1), 0) * 1e6) / 1e6\n #return round(reduce(lambda r, i: r / float(i) + 1, xrange(1, n + 1), 0), 6)\n", "# truncate to 6 decimals\ndef trunc(n):\n return float(str(n)[:8])\n\ndef going(n):\n sum = 1\n fact = 1.0\n for i in range(1,n):\n fact = fact/(n-i+1)\n sum += fact\n return trunc(sum)", "from math import factorial, trunc\ndef going(n):\n sum, past = 1, 1\n for k in range(n, 1, -1):\n past *= 1/k\n sum += past\n return (trunc(sum*10**6))/(10**6)"]
{"fn_name": "going", "inputs": [[5], [6], [7], [8], [20], [30], [50], [113], [200], [523], [1011], [10110]], "outputs": [[1.275], [1.2125], [1.173214], [1.146651], [1.052786], [1.034525], [1.020416], [1.008929], [1.005025], [1.001915], [1.00099], [1.000098]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,211
def going(n):
656a163371aca962790f77f5fd78e3cb
UNKNOWN
The squarefree part of a positive integer is the largest divisor of that integer which itself has no square factors (other than 1). For example, the squareefree part of 12 is 6, since the only larger divisor is 12, and 12 has a square factor (namely, 4). Your challenge, should you choose to accept it, is to implement a `squareFreePart` function which accepts a number `n` and returns the squarefree part of `n`. In the case that `n = 1`, your function should return 1. Also, if the input doesn't make sense (e.g. if it is not a positive integer), the function should return `null/None`. Here are some examples: ```python square_free_part(2) # returns 2 square_free_part(4) # returns 2 square_free_part(24) # returns 6, since any larger divisor is divisible by 4, which is a square square_free_part("hi") # returns None square_free_part(0) # returns None ``` Good luck!
["def square_free_part(n):\n if type(n) != int or n < 1:return None\n for i in xrange(2, int(n ** 0.5) + 1):\n while n % (i ** 2) == 0:\n n /= i\n return n", "def square_free_part(n):\n\n fac = lambda n: [i for i in range(2, (n//2)+1) if n % i == 0] + [n]\n issquare = lambda n: True if str(n**.5)[-1] == '0' else False\n \n if isinstance(n, bool): return None\n if isinstance(n, int) and n > 0:\n if n == 1: return 1\n if n == 2: return 2\n for i in sorted(fac(n), reverse = True):\n if sum([issquare(f) for f in fac(i)]) == 0: \n return i\n else: return None", "def square_free_part(n):\n if type(n) != int or n < 1:\n return\n while n % 4 == 0:\n n //= 2\n k = 3\n while k * k <= n:\n while n % (k*k) == 0:\n n //= k\n k += 2\n return n\n", "def square_free_part(n):\n if type(n) == int and n > 0: # Meh...\n part = 1\n for p in range(2, int(n ** .5) + 1):\n if not n % p:\n part *= p\n while not n % p:\n n //= p\n return part * n", "def square_free_part(n):\n if type(n) != int or n <= 0: \n return None\n r, d = 1, 2\n while d * d <= n:\n if n % d == 0:\n while n % d == 0:\n n //= d\n r *= d\n d += 1\n return r * n if n > 1 else r", "def square_free_part(n):\n import math\n lst = []\n squares = []\n x = []\n if isinstance(n, int):\n if n > 1:\n for i in range(2, n // 2 + 1):\n if n % i == 0:\n lst.append(i)\n lst.append(n)\n lst.reverse()\n for elem in lst:\n if math.sqrt(elem).is_integer():\n squares.append(elem)\n for i in lst:\n for j in squares:\n if i % j == 0:\n break\n else:\n x.append(i)\n if len(x) > 0:\n return x[0]\n else:\n return lst[0]\n elif n is 1:\n return 1\n else:\n return None\n else:\n return None", "def square_free_part(n):\n if not isinstance(n, int): return None\n if n<1: return None\n \n for i in range (n,1,-1):\n if not n % i:\n b=True\n for j in range(i//2,1,-1):\n if not i % (j*j):\n b=False\n break\n if b:return i\n #return n\n", "def getAllPrimeFactors(n):\n if not isinstance(n, int): return []\n if n == 1: return [1]\n factors = []\n i = 2\n while i * i <= n:\n while n % i == 0:\n factors.append(i)\n n //= i\n i += 1\n if n > -1:\n factors.append(n)\n return factors\n\n\ndef getUniquePrimeFactorsWithCount(n):\n if n == 1: return [[1], [1]]\n lis = getAllPrimeFactors(n)\n if lis == []: return [[], []]\n return [sorted(set(lis)), [lis.count(i) for i in sorted(set(lis))]]\n\ndef get_factors(num):\n lis = []\n for i in range(2, num + 1):\n if num % i == 0:\n lis.append(i)\n return lis\n\ndef square_free_part(n):\n if not type(n) == int:\n return None\n if n == 1:\n return 1\n facs = get_factors(n)\n for factor in facs[::-1]:\n lis = getUniquePrimeFactorsWithCount(factor)\n if any(en > 1 for en in lis[1]):\n continue\n else:\n return factor", "def square_free_part(n):\n if type(n)!=int or n<1:\n return None\n result = 1\n divisor = 2\n while n>1:\n if n%divisor==0:\n result *= divisor\n n//=divisor\n while n%divisor==0:\n n//=divisor\n divisor += 1\n return result\n", "def square_free_part(n):\n if type(n)!=int or n<1: return \n ans=1\n for i in range(2,int(n**.5)+1):\n if n%i==0:\n ans*=i\n while n%i==0: n//=i\n if n>1: ans*=n\n return ans"]
{"fn_name": "square_free_part", "inputs": [[0], [-100], [2.5]], "outputs": [[null], [null], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,163
def square_free_part(n):
6bb3fe2fc22ee1bfddcfff74a1447f96
UNKNOWN
Given time in 24-hour format, convert it to words. ``` For example: 13:00 = one o'clock 13:09 = nine minutes past one 13:15 = quarter past one 13:29 = twenty nine minutes past one 13:30 = half past one 13:31 = twenty nine minutes to two 13:45 = quarter to two 00:48 = twelve minutes to one 00:08 = eight minutes past midnight 12:00 = twelve o'clock 00:00 = midnight Note: If minutes == 0, use 'o'clock'. If minutes <= 30, use 'past', and for minutes > 30, use 'to'. ``` More examples in test cases. Good luck!
["def solve(time):\n def number(n):\n if n > 20: return \"twenty {}\".format(number(n - 20))\n return [\n None, \"one\", \"two\", \"three\", \"four\",\n \"five\", \"six\", \"seven\", \"eight\", \"nine\",\n \"ten\", \"eleven\", \"twelve\", \"thirteen\",\n \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\",\n \"eighteen\", \"nineteen\", \"twenty\"][n]\n hours, minutes = (int(s) for s in time.split(':'))\n if minutes <= 30:\n direction = \"past\"\n else:\n hours = (hours + 1) % 24\n direction = \"to\"\n minutes = 60 - minutes\n hour = number((hours + 11) % 12 + 1) if hours else \"midnight\"\n if minutes == 0:\n return \"{} o'clock\".format(hour) if hours else hour\n if minutes == 15:\n return \"quarter {} {}\".format(direction, hour)\n if minutes == 30:\n return \"half past {}\".format(hour)\n return \"{} minute{} {} {}\".format(\n number(minutes), \"\" if minutes == 1 else \"s\", direction, hour)\n", "NUMS = [''] + '''\none two three four five six seven eight nine ten\neleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty\n'''.split()\nNUMS += [f'twenty {NUMS[i]}' for i in range(1, 10)]\nNUMS += ['thirty']\n\nMINUTES = [f'{x} minutes' for x in NUMS]\nMINUTES[1], MINUTES[15], MINUTES[30] = 'one minute', 'quarter', 'half'\n\nHOURS = ['midnight'] + NUMS[1:13] + NUMS[1:12]\n\ndef solve(time):\n h, m = map(int, time.split(':'))\n if h == m == 0:\n return 'midnight'\n if m == 0:\n return f\"{HOURS[h]} o'clock\"\n elif m <= 30:\n return f'{MINUTES[m]} past {HOURS[h]}'\n else:\n h = (h + 1) % 24\n return f'{MINUTES[60 - m]} to {HOURS[h]}'", "d = { 0 : 'midnight', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine',\n 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen',\n 15 : 'quarter', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen', 19 : 'nineteen',\n 20 : 'twenty', 30 : 'half' }\n\n# 20 - 29 can be computed from this dict\nfor i in range(1, 10):\n d[20 + i] = f'{d[20]} {d[i]}'\n\ndef solve(time):\n h, m = [int(x) for x in time.split(':')]\n\n # past or to ?\n to = m > 30\n past_to = 'past to'.split()[to]\n if to:\n h += 1\n m = 60 - m\n \n # 12 hour style from 24\n h = h % 12 if h != 12 else h\n \n # special case : o'clock\n if m == 0:\n oc = ' o\\'clock' if h else '' # 00:00 ==> midnight only\n return f'{d[h]}{oc}'\n \n s = 's' if m > 1 else ''\n min_word = f' minute{s}' if m not in [15, 30] else ''\n \n minutes = d[m]\n hour = d[h]\n \n return f'{minutes}{min_word} {past_to} {hour}'", "def solve(time):\n w = [\"midnight\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\",\"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\", \"twenty\", \"twenty one\", \"twenty two\", \"twenty three\", \"twenty four\", \"twenty five\", \"twenty six\", \"twenty seven\", \"twenty eight\", \"twenty nine\"]\n h,m = map(int,time.split(\":\"))\n a,b = w[12] if h == 12 else w[h%12], w[h+1] if h == 11 else w[(h+1)%12]\n if m == 0: return \"midnight\" if h == 0 else a + \" o'clock\"\n elif m <= 30: return w[m] + \" minute past \" + a if m == 1 else \"quarter past \" + a if m == 15 else \"half past \" + a if m == 30 else w[m] + \" minutes past \" + a\n else: return \"quarter to \" + b if m == 45 else \"one minute to \" + b if m == 59 else w[60-m] + \" minutes to \" + b", "def solve(time):\n harr = [\"midnight\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\",\n \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"one\", \"two\", \"three\", \"four\",\n \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"midnight\"]\n \n marr = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\",\n \"eighteen\", \"nineteen\", \"twenty\", \"twenty one\", \"twenty two\", \"twenty three\", \"twenty four\", \"twenty five\",\n \"twenty six\", \"twenty seven\", \"twenty eight\", \"twenty nine\"]\n \n hour, minute = list(map(int,time.split(\":\")))\n if minute == 0:\n if hour == 0:\n return \"midnight\"\n return harr[hour] + \" o'clock\"\n if minute == 15:\n return \"quarter past \" + harr[hour]\n if minute == 45:\n return \"quarter to \" + harr[1 + hour]\n if minute == 30:\n return \"half past \" + harr[hour]\n if minute == 1:\n return \"one minute past \" + harr[hour]\n if minute == 59:\n return \"one minute to \" + harr[1 + hour]\n if int(int(minute) < 30):\n return marr[minute] + \" minutes past \" + harr[hour]\n return marr[60 - minute] + \" minutes to \" + harr[1 + hour]\n \n", "def solve(time):\n harr = [\"midnight\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\",\n \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"one\", \"two\", \"three\", \"four\",\n \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"midnight\"]\n \n marr = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\",\n \"eighteen\", \"nineteen\", \"twenty\", \"twenty one\", \"twenty two\", \"twenty three\", \"twenty four\", \"twenty five\",\n \"twenty six\", \"twenty seven\", \"twenty eight\", \"twenty nine\"]\n \n hour = time[:2]\n minute = time[3:]\n if minute == \"00\":\n if hour == \"00\":\n return \"midnight\"\n return harr[int(hour)] + \" o'clock\"\n if minute == \"15\":\n return \"quarter past \" + harr[int(hour)]\n if minute == \"45\":\n return \"quarter to \" + harr[1 + int(hour)]\n if minute == \"30\":\n return \"half past \" + harr[int(hour)]\n if minute == \"01\":\n return \"one minute past \" + harr[int(hour)]\n if minute == \"59\":\n return \"one minute to \" + harr[1 + int(hour)]\n if int(int(minute) < 30):\n return marr[int(minute)] + \" minutes past \" + harr[int(hour)]\n return marr[60 - int(minute)] + \" minutes to \" + harr[1 + int(hour)]\n \n", "locale = ('midnight one two three four five six seven eight nine ten eleven twelve '\n 'thirteen fourteen quarter sixteen seventeen eighteen nineteen twenty').split()\nlocale += [f'{locale[-1]} {digit}'.rstrip() for digit in locale[1:10]] + \"half, o'clock, minutes, past , to \".split(',')\n\ndef solve(time):\n preposition, (hour, minute) = -2, list(map(int, time.split(':')))\n if minute > 30: preposition, hour, minute = preposition + 1, (hour + 1) % 24, 60 - minute\n if hour > 12: hour -= 12\n if not minute: return f'{locale[hour]}{locale[-4] * (hour > 0)}'\n return f'{locale[minute]}{locale[-3][:-(minute == 1) or None] * (minute not in (15, 30))}{locale[preposition]}{locale[hour]}'\n", "MINUTES = (\n 'zero,one,two,three,four,five,six,seven,eight,nine,' +\n 'ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,' +\n 'twenty'\n).split(',')\nMINUTES.extend([f'twenty {n}' for n in MINUTES[1:10]])\n\n# Should be\n# HOURS = ['midnight'] + MINUTES[1:12] + ['midday'] + MINUTES[1:12] \nHOURS = ['midnight'] + MINUTES[1:13] + MINUTES[1:12] \n\n# Special cases: minutes -> (string template, hour offset)\nQUARTERS = {\n 0: (\"{h} o'clock\", 0),\n 15: ('quarter past {h}', 0),\n 30: ('half past {h}', 0),\n 45: ('quarter to {h}', 1),\n}\n\ndef solve(time):\n hh, mm = list(map(int, time.split(':')))\n h = HOURS[hh]\n h1 = HOURS[(hh + 1) % 24]\n \n if mm in QUARTERS:\n # On an hour, quarter or half\n template, offset = QUARTERS[mm]\n if mm == 0 and hh == 0: # 12:00 should really be 'midday' too\n return h\n return template.format(h=h if offset == 0 else h1)\n \n if mm < 30:\n # x minute(s) past y\n return f\"{MINUTES[mm]} minute{'' if mm == 1 else 's'} past {h}\"\n\n # x minute(s) to y\n mm = 60 - mm\n return f\"{MINUTES[mm]} minute{'' if mm == 1 else 's'} to {h1}\"\n", "TRANSLATE = {0: \"midnight\", 1: \"one\", 2: \"two\", 3: \"three\", 4: \"four\", 5: \"five\", 6: \"six\",\n 7: \"seven\", 8: \"eight\", 9: \"nine\", 10: \"ten\", 11: \"eleven\", 12: \"twelve\",\n 13: \"thirteen\", 14: \"fourteen\", 15: \"fifteen\", 16: \"sixteen\", 17: \"seventeen\", 18: \"eighteen\",\n 19: \"nineteen\", 20: \"twenty\", 30: \"thirty\", 40: \"forty\", 50: \"fifty\"}\n\ndef solve(time):\n def hourRepr(hour):\n return TRANSLATE[hour if hour <= 12 else hour % 12]\n def minuteRepr(minute, toNextHour=False):\n relative_minute = minute if not toNextHour else 60 - minute\n def repr(minute):\n if minute < 20 or minute % 10 == 0:\n return TRANSLATE[minute]\n return f\"{TRANSLATE[minute // 10 * 10]} {TRANSLATE[minute % 10]}\"\n return f\"{repr(relative_minute)} minute{'s' if relative_minute > 1 else ''}\"\n hour, minute = [int(t) for t in time.split(\":\")]\n if minute == 0:\n return f\"{hourRepr(hour)} o'clock\" if hour != 0 else hourRepr(hour)\n elif minute == 30:\n return f\"half past {hourRepr(hour)}\"\n elif minute % 15 == 0:\n return f\"quarter past {hourRepr(hour)}\" if minute == 15 else f\"quarter to {hourRepr(hour + 1)}\"\n else:\n return f\"{minuteRepr(minute)} past {hourRepr(hour)}\" if minute < 30 else f\"{minuteRepr(minute, toNextHour=True)} to {hourRepr(hour + 1)}\"", "NUM = \"\"\"midnight one two three four five six seven eight nine\n ten eleven twelve thir_ four_ fif_ six_ seven_ eigh_ nine_\n twenty\"\"\".replace(\"_\", \"teen\").split()\nfor n in range(1, 10): NUM.append(f\"twenty {NUM[n]}\")\n\n\ndef solve(time):\n hh, mm = map(int, time.split(\":\"))\n if mm > 30: hh += 1\n \n hour = NUM[hh % 12] if hh % 12 else NUM[hh % 24]\n \n if mm == 0: min = \"\"\n elif mm == 15: min = \"quarter past \"\n elif mm == 30: min = \"half past \"\n elif mm == 45: min = \"quarter to \"\n elif 0 < mm < 30: min = f\"{NUM[mm]} minute{'s' if mm > 1 else ''} past \"\n else: min = f\"{NUM[60 - mm]} minute{'s' if mm < 59 else ''} to \"\n \n return min + hour + (\" o'clock\" if mm == 0 and hh > 0 else \"\")"]
{"fn_name": "solve", "inputs": [["13:00"], ["13:09"], ["13:15"], ["13:29"], ["13:30"], ["13:31"], ["13:45"], ["13:59"], ["00:48"], ["00:08"], ["12:00"], ["00:00"], ["19:01"], ["07:01"], ["01:59"], ["12:01"], ["00:01"], ["11:31"], ["23:31"], ["11:45"], ["11:59"], ["23:45"], ["23:59"], ["01:45"]], "outputs": [["one o'clock"], ["nine minutes past one"], ["quarter past one"], ["twenty nine minutes past one"], ["half past one"], ["twenty nine minutes to two"], ["quarter to two"], ["one minute to two"], ["twelve minutes to one"], ["eight minutes past midnight"], ["twelve o'clock"], ["midnight"], ["one minute past seven"], ["one minute past seven"], ["one minute to two"], ["one minute past twelve"], ["one minute past midnight"], ["twenty nine minutes to twelve"], ["twenty nine minutes to midnight"], ["quarter to twelve"], ["one minute to twelve"], ["quarter to midnight"], ["one minute to midnight"], ["quarter to two"]]}
INTRODUCTORY
PYTHON3
CODEWARS
10,909
def solve(time):
37e15862606e5ce50ae26741d73ff0bf
UNKNOWN
For building the encrypted string:Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String. Do this n times! Examples: ``` "This is a test!", 1 -> "hsi etTi sats!" "This is a test!", 2 -> "hsi etTi sats!" -> "s eT ashi tist!" ``` Write two methods: ```python def encrypt(text, n) def decrypt(encrypted_text, n) ``` ```Fsharp let encrypt (str:string) (n:int) -> string let decrypt (str:string) (n:int) -> string ``` For both methods: If the input-string is null or empty return exactly this value! If n is <= 0 then return the input text. This kata is part of the Simple Encryption Series: Simple Encryption #1 - Alternating Split Simple Encryption #2 - Index-Difference Simple Encryption #3 - Turn The Bits Around Simple Encryption #4 - Qwerty Have fun coding it and please don't forget to vote and rank this kata! :-)
["def decrypt(text, n):\n if text in (\"\", None):\n return text\n \n ndx = len(text) // 2\n\n for i in range(n):\n a = text[:ndx]\n b = text[ndx:]\n text = \"\".join(b[i:i+1] + a[i:i+1] for i in range(ndx + 1))\n return text\n\n\n\ndef encrypt(text, n):\n for i in range(n):\n text = text[1::2] + text[::2]\n return text", "def decrypt(s, n):\n if not s: return s\n o, l = len(s) // 2, list(s)\n for _ in range(n):\n l[1::2], l[::2] = l[:o], l[o:]\n return ''.join(l)\n\n\ndef encrypt(s, n):\n if not s: return s\n for _ in range(n):\n s = s[1::2] + s[::2]\n return s", "def decrypt(text, n):\n if not text: return text\n half = len(text) // 2\n arr = list(text)\n for _ in range(n):\n arr[1::2], arr[::2] = arr[:half], arr[half:]\n return ''.join(arr)\n\ndef encrypt(text, n):\n for i in range(n):\n text = text[1::2] + text[::2]\n return text", "def encrypt_once(s):\n h, t = \"\", \"\"\n for i in range(len(s)):\n if i % 2 == 0:\n h += s[i]\n else:\n t += s[i]\n return t + h\n\n\ndef decrypt_once(s):\n i = len(s) // 2\n j = 0\n \n result = \"\"\n \n for k in range(len(s)):\n if k % 2 == 0:\n result += s[i]\n i += 1\n else:\n result += s[j]\n j += 1\n \n return result\n\n\ndef decrypt(text, n):\n if not text or len(text) == 0 or n <= 0:\n return text\n\n for i in range(n):\n text = decrypt_once(text)\n\n return text\n\n\ndef encrypt(text, n):\n if not text or len(text) == 0 or n <= 0:\n return text\n \n for i in range(n):\n text = encrypt_once(text)\n \n return text\n", "def decrypt(encrypted_text, n):\n\n if n < 1:\n return encrypted_text\n \n half_len = len(encrypted_text)//2 \n \n left, right = encrypted_text[:half_len], encrypted_text[half_len:]\n \n encrypted_text = [''.join(i) for i in zip(right, left)]\n \n if len(right) > half_len:\n encrypted_text += right[-1]\n \n return decrypt(''.join(encrypted_text), n-1)\n \n\ndef encrypt(text, n):\n \n if n < 1:\n return text\n \n for _ in range(n):\n text = text[1::2] + text[0::2]\n \n return text", "def decrypt(text, n):\n if text:\n mid = len(text) // 2\n for _ in range(n):\n text = ''.join(sum(zip(text[mid:], list(text[:mid]) + ['']), ()))\n return text\n\n\ndef encrypt(text, n):\n if text:\n for _ in range(n):\n text = text[1::2] + text[::2]\n return text", "def decrypt(text, n):\n if text == None: return text\n \n decodeList = encrypt(list(range(len(text))),n)\n return ''.join( text[decodeList.index(i)] for i in range(len(text)) )\n\n\ndef encrypt(text, n):\n\n if text == None: return text\n return encrypt(text[1::2] + text[0::2],n-1) if n>0 else text", "from itertools import zip_longest\n\ndef encrypt(text, n):\n s = text\n if s:\n for _ in range(n):\n s = s[1::2] + s[::2]\n return s\n\ndef decrypt(encrypted_text, n):\n s = encrypted_text\n if s:\n m = len(s) // 2\n for _ in range(n):\n s = ''.join(c for s in zip_longest(s[m:], s[:m], fillvalue='') for c in s)\n return s\n", "def encrypt(text, n):\n print('dasd')\n if n <= 0 :\n return text\n new_str = text\n temp_str = ''\n for x in range (n):\n if len(new_str) % 2 == 1:\n iter_for_array_1 = 1\n iter_for_array_2 = 0 \n temp_str =''\n for z in range(int(len(new_str)/2)):\n temp_str += new_str[iter_for_array_1]\n iter_for_array_1 +=2\n for z in range(int(len(new_str)/2) + 1) :\n temp_str += new_str[iter_for_array_2]\n iter_for_array_2+=2\n new_str = temp_str \n else :\n iter_for_array_1 = 1\n iter_for_array_2 = 0 \n temp_str =''\n for z in range(int(len(new_str)/2)):\n temp_str += new_str[iter_for_array_1]\n iter_for_array_1 +=2\n for z in range(int(len(new_str)/2)):\n temp_str += new_str[iter_for_array_2]\n iter_for_array_2+=2\n new_str = temp_str \n return new_str \n\n\ndef decrypt(encrypted_text, n):\n print(1)\n if n <= 0 or encrypted_text == '':\n return encrypted_text\n new_str = encrypted_text\n \n for x in range (n):\n a = int(len (encrypted_text)/2) \n str1 = new_str[:a]\n str2 = new_str[a:]\n new_str = ''\n for new_X in range(a):\n new_str +=str2[new_X]\n new_str += str1[new_X]\n if len(encrypted_text) % 2 == 1: \n new_str += str2[-1]\n\n return new_str"]
{"fn_name": "decrypt", "inputs": [["This is a test!", 0], ["hsi etTi sats!", 1], ["s eT ashi tist!", 2], [" Tah itse sits!", 3], ["This is a test!", 4], ["This is a test!", -1], ["hskt svr neetn!Ti aai eyitrsig", 1], ["", 0], [null, 0]], "outputs": [["This is a test!"], ["This is a test!"], ["This is a test!"], ["This is a test!"], ["This is a test!"], ["This is a test!"], ["This kata is very interesting!"], [""], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,967
def decrypt(text, n):
326fa0d90aa33194445e0f6bdd66e822
UNKNOWN
You have been recruited by an unknown organization for your cipher encrypting/decrypting skills. Being new to the organization they decide to test your skills. Your first test is to write an algorithm that encrypts the given string in the following steps. 1. The first step of the encryption is a standard ROT13 cipher. This is a special case of the caesar cipher where the letter is encrypted with its key that is thirteen letters down the alphabet, i.e. `A => N, B => O, C => P, etc..` 1. Part two of the encryption is to take the ROT13 output and replace each letter with its exact opposite. `A => Z, B => Y, C => X`. The return value of this should be the encrypted message. Do not worry about capitalization or punctuation. All encrypted messages should be lower case and punctuation free. As an example, the string `"welcome to our organization"` should return `"qibkyai ty ysv yvgmzenmteyz"`. Good luck, and congratulations on the new position.
["def encrypter(strng):\n return ''.join( c if c==' ' else chr(122 - ((ord(c)-97)+13) % 26) for c in strng )", "from string import ascii_lowercase as abc\n\ndef encrypter(strng):\n return strng.translate(str.maketrans(abc[::-1], abc[13:] + abc[:13]))", "def encrypter(strng):\n z={0:'m',1:'l',2:'k',3:'j',4:'i',5:'h',6:'g',7:'f',8:'e',9:'d',10:'c',11:'b',12:'a',13:'z',14:'y',15:'x',16:'w',17:'v',18:'u',19:'t',20:'s',21:'r',22:'q',23:'p',24:'o',25:'n'}\n pt=''\n for i in strng:\n if ord(i)>=ord('a') and ord(i)<=ord('z'):\n pt+=z[ord(i)-ord('a')]\n else:\n pt=pt+i\n return pt#your code here", "from string import ascii_lowercase as al\n\ntbl1 = str.maketrans(al, al[13:] + al[:13])\ntbl2 = str.maketrans(al, al[::-1])\n\ndef encrypter(strng):\n return strng.translate(tbl1).translate(tbl2)", "from codecs import encode\nfrom string import ascii_lowercase as az\n\nOPPOSITES = dict(zip(az, reversed(az)))\n\n\ndef encrypter(strng):\n return ''.join(OPPOSITES.get(a, a) for a in encode(strng, 'rot13'))", "encrypter=lambda s: \"\".join([\"mlkjihgfedcbazyxwvutsrqpon\"[\"abcdefghijklmnopqrstuvwxyz\".index(a)] if a in \"abcdefghijklmnopqrstuvwxyz\" else a for a in s])", "encrypter=lambda s,a=list(range(97,123)):s.translate(dict(zip(a[::-1],a[13:]+a[:13])))"]
{"fn_name": "encrypter", "inputs": [["amz"], ["welcome to the organization"], ["hello"], ["my name is"], ["goodbye"]], "outputs": [["man"], ["qibkyai ty tfi yvgmzenmteyz"], ["fibby"], ["ao zmai eu"], ["gyyjloi"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,320
def encrypter(strng):
74ae4122afe3d2a46adc925efedbc5e0
UNKNOWN
The look and say sequence is a sequence in which each number is the result of a "look and say" operation on the previous element. Considering for example the classical version startin with `"1"`: `["1", "11", "21, "1211", "111221", ...]`. You can see that the second element describes the first as `"1(times number)1"`, the third is `"2(times number)1"` describing the second, the fourth is `"1(times number)2(and)1(times number)1"` and so on. Your goal is to create a function which takes a starting string (not necessarily the classical `"1"`, much less a single character start) and return the nth element of the series. ## Examples ```python look_and_say_sequence("1", 1) == "1" look_and_say_sequence("1", 3) == "21" look_and_say_sequence("1", 5) == "111221" look_and_say_sequence("22", 10) == "22" look_and_say_sequence("14", 2) == "1114" ``` Trivia: `"22"` is the only element that can keep the series constant.
["from re import sub\n\ndef look_and_say_sequence(s, n):\n for _ in range(1, n):\n s = sub(r'(.)\\1*', lambda m: str(len(m.group(0))) + m.group(1), s)\n return s", "def look_and_say_sequence(first, n): \n result = first\n \n for _ in range(n-1):\n \n sequence = result\n result = ''\n index = 0\n \n while index < len(sequence):\n \n pending = sequence[index]\n count = 0\n \n while index < len(sequence) and pending == sequence[index]:\n count += 1\n index += 1\n \n result += \"{}{}\".format(count, pending)\n \n return result", "from itertools import groupby\nfrom functools import reduce\ndef look_and_say_sequence(first_element, n):\n return reduce(lambda s, _: ''.join('%d%s' % (len(list(g)), n) for n, g in groupby(s)), range(n - 1), first_element)", "look_and_say_sequence=l=lambda s,n:n>1and l(''.join(str(len(list(g)))+k for k,g in __import__('itertools').groupby(s)),n-1)or s", "from itertools import groupby\n\ndef look_and_say_sequence(e, n):\n for i in range(n-1):\n e = ''.join(f'{len(list(grp))}{key}' for key, grp in groupby(e))\n return e\n", "import re\ndef look_and_say_sequence(element, n):\n return element if n == 1 else look_and_say_sequence(''.join(f'{len(e.group())}{e.group(1)}' for e in re.finditer(r'(\\d)\\1*',element)), n-1)", "import re\ndef look_and_say_sequence(data, n):\n return data if n == 1 else look_and_say_sequence(''.join(f'{len(e.group(0))}{e.group(1)}' for e in re.finditer(r\"(\\d)\\1*\", data)), n-1)\n", "from itertools import groupby\n\ndef look_and_say_sequence(seq, n):\n if seq == \"22\":\n return \"22\"\n for _ in range(1, n):\n seq = \"\".join(f\"{len(list(b))}{a}\" for a, b in groupby(seq))\n return seq\n \n", "from itertools import groupby\n\ndef look_and_say_sequence(first_element, n):\n if first_element == \"22\": return \"22\"\n for _ in range(n-1):\n first_element = ''.join(f\"{len(list(l))}{c}\" for c,l in groupby(first_element))\n return first_element", "def look_and_say_sequence(e, n):\n for i in range(1, n):\n e = look_and_say(e)\n return e\n \ndef look_and_say(e):\n current, count, seq = e[0], 0, ''\n \n for c in e:\n if c == current:\n count += 1\n else:\n seq += f'{count}{current}'\n count, current = 1, c\n \n return seq + f'{count}{current}'\n\n \n"]
{"fn_name": "look_and_say_sequence", "inputs": [["1", 1], ["1", 3], ["1", 5], ["22", 10], ["14", 2]], "outputs": [["1"], ["21"], ["111221"], ["22"], ["1114"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,572
def look_and_say_sequence(first_element, n):
12567cda01cbfc7709f70dcda0906c4e
UNKNOWN
Americans are odd people: in their buildings, the first floor is actually the ground floor and there is no 13th floor (due to superstition). Write a function that given a floor in the american system returns the floor in the european system. With the 1st floor being replaced by the ground floor and the 13th floor being removed, the numbers move down to take their place. In case of above 13, they move down by two because there are two omitted numbers below them. Basements (negatives) stay the same as the universal level. [More information here](https://en.wikipedia.org/wiki/Storey#European_scheme) ## Examples ``` 1 => 0 0 => 0 5 => 4 15 => 13 -3 => -3 ```
["def get_real_floor(n):\n if n <= 0: return n\n if n < 13: return n-1\n if n > 13: return n-2", "def get_real_floor(n):\n return n if n < 1 else n - 1 if n < 13 else n - 2", "def get_real_floor(n):\n return n - (1 if n < 13 else 2) if n > 0 else n", "def get_real_floor(n):\n return n - (n > 0) - (n > 13)", "def get_real_floor(n):\n return n-2 if n > 13 \\\n else n-1 if n > 0 \\\n else n", "def get_real_floor(n):\n if n > 0 and n >= 13:return n - 2\n elif n > 0 and n < 13: return n - 1 \n else: return n", "def get_real_floor(n):\n if n == 1:return 0\n elif n == 15:return 13\n elif n == 0:return 0\n else:\n if n > 0 and n < 13:return n - 1\n elif n > 0 and n > 13:return n - 2\n else:return n", "def get_real_floor(n):\n return n if n < 1 else (n - 2 if (n > 13) else n - 1)", "def get_real_floor(n):\n if n <= 0:\n return n\n return n - 1 - (n >= 13)", "def get_real_floor(n):\n if 1 <= n < 13:\n return n - 1\n if 13 <= n:\n return n - 2\n if n <= 0:\n return n", "def get_real_floor(n):\n if n<=0:\n return n\n elif n<14:\n return n-1\n elif n==14:\n return 12\n else:\n return n-2", "def get_real_floor(n):\n return n - 1 - (n > 13) if n > 0 else n", "def get_real_floor(n):\n \n return n - 1 * (n>0) - 1 * (n>13)", "def get_real_floor(n):\n if n <= 0: return n\n elif 0 < n < 13: return n - 1\n elif n > 13: return n - 2", "def get_real_floor(n):\n return n - 2 if n > 13 else n - 1 if n > 0 else n", "get_real_floor = lambda n: n - ((n > 0) + (n > 12))", "def get_real_floor(n):\n return n - (n > 0) * ((n > 0) + (n > 13))", "def get_real_floor(n):\n return n if n<0 else 0 if n <=1 else n-1 if n<13 else n-2", "def get_real_floor(n):\n return n - (n > 0) - (n > 12)", "def get_real_floor(n):\n if n<1:\n return n\n ls=[]\n for i in range(1,n+1):\n if i==13:\n pass\n else:\n ls.append(i)\n return ls.index(n) #I solved this Kata on 8/21/2019 11:07 PM...#Hussam'sCodingDiary", "get_real_floor = lambda n: n if n <= 0 else n - 1 - int(n >= 13)", "def get_real_floor(n):\n if n <= 0:\n return n\n \n else:\n ans = n - 1\n \n if n > 13:\n ans = ans - 1\n \n return ans", "def get_real_floor(n):\n return (n - 1) + (n <= 0) - (n > 13)", "def get_real_floor(n):\n if n > 0:\n return n - (1 + int(n >= 13))\n return n\n", "def get_real_floor(n):\n return [n, n-[2, 1][n < 13]][n > 0] # fun", "def get_real_floor(n):\n return [n, n-[2, 1][n < 13]][n > 0] # fun logic", "def get_real_floor(n):\n return n - [2,1][n < 13] if n > 0 else n", "get_real_floor = lambda n: n - (n > 0) - (n > 13)", "def get_real_floor(n: int) -> int:\n \"\"\" Get the floor in the european system based on the floor in the american system. \"\"\"\n return sum([n, {0 < n < 13: -1, n >= 13: -2}.get(True, 0)])", "def get_real_floor(n):\n if n >0 and n<13:\n return n-1\n elif n > 13:\n return n-2\n else:\n return n", "def get_real_floor(n):\n # code here\n if n ==0:\n return 0\n elif n>0 and n <= 13:\n n=n-1\n return n\n elif n>0 and n>13:\n n=n-2\n return n\n elif n < 0:\n return n", "def get_real_floor(n):\n return n - 1 - int(n >= 13) if n > 0 else n", "def get_real_floor(n):\n if n>13:\n f = n-2\n elif n>1 and n<13:\n f = n-1\n elif n<0:\n f = n\n else: f = 0\n return f", "def get_real_floor(n):\n # code here\n if n > 13:\n return n-2\n if n < 13 and n > 1:\n return n-1\n if n < 0:\n return n\n else: return 0", "def get_real_floor(n) :\n if n > 13:\n return n - 2 \n if n>1 and n<13:\n return n-1\n if n<0:\n return n \n else:\n return 0", "def get_real_floor(n):\n if (n < 13):\n if n < 0:\n o=n\n elif n == 0:\n o=0\n else:\n o = n-1\n elif n == 13:\n o = 0\n else:\n o = n-2\n return o", "def get_real_floor(n):\n if 1 <= n <= 12:\n n = n-1\n elif 14 <= n:\n n = n-2\n else: \n n = n\n \n return n", "def get_real_floor(n):\n if n == 0:\n return 0\n if 0 < n <= 13:\n return n-1\n \n return n-2 if n > 13 else n", "def get_real_floor(n):\n return 0 if n == 0 or n == 1 else n - 1 if 1 < n <= 13 else n - 2 if n > 13 else n", "def get_real_floor(n):\n if n == 15:\n return 13\n elif n == 0:\n return 0\n elif n >=1 and n < 14:\n return (n-1)\n elif n < 0:\n return n\n else:\n return (n-2)\n # code here\n", "def get_real_floor(n):\n if 0<n<=13:\n return n-1\n elif n>13:\n return n-2\n \n elif n<0:\n return n\n else:\n return 0", "def get_real_floor(n):\n if n <= 0:\n return n\n elif 0 < n <= 12:\n return n - 1\n elif n >= 13:\n return n - 2", "def get_real_floor(n):\n return n - 2 if n > 13 else n - 1 if n < 13 and n > 0 else n", "def get_real_floor(n):\n if (n < 0):\n return n\n if (n == 0 or n == 1):\n return 0\n elif (2 <= n <= 12):\n return n-1\n else:\n return n-2", "get_real_floor=lambda n:n-1-(n>12)+(n<=0)", "def get_real_floor(n):\n if n<0: return n\n elif n>0 and n<13: return n-1\n elif n==0: return 0\n else: return n-2", "def get_real_floor(n):\n if n > 13:\n return n - 2\n elif n > 1 and n < 13:\n return n - 1\n elif n == 1:\n return 0 \n else:\n return n", "def get_real_floor(n):\n return n - (n>0 and 1) - (n>13 and 1)", "def get_real_floor(n):\n return n - 2 if n > 13 else n - 1 if n >= 1 else n", "def get_real_floor(n):\n return n-1 if n<13 and n>0 else n if n<=0 else n-2 if n>13 else n", "def get_real_floor(n):\n # code here\n if n<0:\n return n\n elif n>0 and n<=12:\n return n-1\n elif n>12 :\n return n-2\n else:\n return 0 \n \n", "def get_real_floor(n):\n if n < 0:\n return n\n elif n == 0:\n return n\n elif n >= 13:\n return n-2\n else:\n return n-1", "def get_real_floor(n):\n if n > 13:\n return n - 2\n if n >= 1:\n return n - 1\n else:\n return n", "def get_real_floor(n):\n if 0 < n < 13:\n return n - 1 \n elif n > 13:\n return n - 2\n else:\n return n\n# return n-1 if 0 < n < 13 else\n", "def get_real_floor(n):\n if n>0:\n if n<13:\n n=n-1\n else:\n n=n-2\n \n return n", "def get_real_floor(n):\n floor=0\n if n>=1:\n floor-=1\n if n>=13:\n floor-=1\n return n + floor", "def get_real_floor(n):\n if n == 0:\n return 0\n elif n < 0:\n return n\n return n - 1 if n <= 13 else n - 2", "def get_real_floor(n):\n if n <= 0:\n return n\n if n > 0 and n < 14:\n return n-1\n else:\n return n-2", "def get_real_floor(n):\n if n == 0:\n return 0\n elif 13 > n > 0:\n return n - 1\n elif n > 13:\n return n - 2\n else:\n return n", "def get_real_floor(n):\n return n-1 if 0 < n < 13 else n-2 if n > 12 else n", "get_real_floor = lambda n: n-1 if n > 0 and n < 13 else n-2 if n > 12 else n", "def get_real_floor(n):\n if n == 1:\n return 0\n if n > 13:\n return n - 2\n if n < 0:\n return n\n if n > 0 and n < 13:\n return n - 1\n return 0", "def get_real_floor(n):\n if 1 <= n <= 12:\n return n - 1\n elif n <=0:\n return n\n else:\n return n - 2", "def get_real_floor(n):\n if n>0 and n<13:\n real_floor=n-1\n return real_floor\n if n >=13:\n real_floor=n-2\n return real_floor\n if n<=0:\n real_floor=n\n return real_floor", "def get_real_floor(n):\n return n-1 if 1 <= n <= 13 else n if n < 1 else n - 2", "def get_real_floor(n):\n if n == 0 or n == 1:\n return 0\n elif n < 0:\n return n\n elif n < 14:\n return n - 1\n else:\n return n - 2", "def get_real_floor(n):\n return n - 1 if (n > 0 and n <= 13) else n - 2 if n > 13 else n", "def get_real_floor(n):\n if n > 13:\n n = n - 1\n if n > 0:\n n = n - 1\n return n", "def get_real_floor(n):\n if n == 0: return 0\n elif n > 0: return n - 1 if n <= 13 else n - 2\n else: return n", "def get_real_floor(n):\n if n>0:\n return n-1 if n<13 else n-2\n if n<=0:\n return n", "def get_real_floor(n):\n floors = n-1\n top = n-2\n basement = n\n if n >= 1 and n < 13:\n return floors\n elif n <=0:\n return basement\n else:\n return top\n", "def get_real_floor(n):\n return n-1 if n>=1 and n<=12 else n-2 if n>12 else 0+n", "def get_real_floor(n):\n if n == 0 or n == 1:\n return 0\n elif n < 0:\n return n\n elif n > 13:\n return n-2\n elif n < 13:\n return n-1\n return n-1", "def get_real_floor(n):\n return 0 if n == 0 else 0 if n == 1 else n if n < 0 else n - 1 if n < 13 else n - 2", "def get_real_floor(n):\n print(n)\n if n == 0:\n return 0\n if n < 13 and n > 0:\n return n - 1\n elif n < 0:\n return n\n \n else:\n return n - 2", "def get_real_floor(n):\n if n<1:\n return n\n elif n==1:\n return 0\n elif n>1 and n<=13:\n return n-1\n elif n>13:\n return n-2", "def get_real_floor(n):\n if n == 0:\n return 0\n elif n < 0:\n return n\n elif n < 13:\n return n - 1\n return n - 2", "def get_real_floor(n):\n if n < 0:\n return n\n if n > 13:\n return n - 2\n else:\n return max(0, n - 1)", "def get_real_floor(n):\n if 0<=n<=1:\n return 0\n elif n>13:\n return n-2\n elif 1<n<=13:\n return n-1\n else:\n return n", "def get_real_floor(n):\n if n <= 0:\n return n\n if 0 < n < 13:\n return n-1\n if 13 < n:\n return n-2", "def get_real_floor(n):\n if 0<n<=13:\n return n-1\n if n>13:\n return n-2\n else:\n return n", "def get_real_floor(n):\n if n == 0:\n return 0 \n elif n > 0 and n <= 13:\n return n - 1\n elif n > 13:\n return n - 2\n else:\n return n", "def get_real_floor(n):\n if n < 14 and n >= 1:\n return n-1\n if n >= 14:\n return n-2\n if n == -1:\n return n+1 \n else:\n return n", "def get_real_floor(n):\n if n < 1:\n return n\n elif 1<=n<=12:\n return n-1\n elif n >= 13:\n return n-2", "def get_real_floor(n):\n if n < 1:\n return n\n return n-2 if n>13 else n-1", "def get_real_floor(n):\n if n == 0 or n ==1:\n print((0))\n return 0\n if n<13 and n>1:\n print((n-1))\n return n-1\n if n>13:\n print((n-2))\n return n-2\n return n\n", "def get_real_floor(n: int) -> int:\n return 0 if n == 1 or n == 0 else n - 2 if n > 13 else n if n < 0 else n - 1", "def get_real_floor(n):\n if 0 < n < 14:\n return n - 1\n if 13 < n:\n return n - 2\n else:\n return n", "def get_real_floor(n):\n if 0<n<13:\n return n-1\n elif n>=13:\n return n-2\n elif n <=0:\n return n", "def get_real_floor(n):\n if n<=0:\n return n\n elif n<=1 or n<=12:\n return n-1\n else:\n return n-2", "def get_real_floor(n):\n if 1 <= n <= 13:\n return n - 1\n elif n >= 14:\n return n - 2\n else:\n return n", "def get_real_floor(n):\n if 0 < n <= 13:\n return n -1\n elif n > 13:\n return n - 2\n\n return n", "def get_real_floor(n):\n if n<=0:\n return n\n elif(n>0 and n!=13 and n<14):\n return (n-1)\n else:\n return(n-2)", "def get_real_floor(n):\n if n < 0:\n return n\n return max(0, n - 1) if n < 13 else n - 2", "def get_real_floor(n):\n if 0 < n <= 13:\n n = n - 1\n else:\n if n > 13: \n n = n - 2\n return n", "def get_real_floor(n):\n if n >= 13:\n return n-2\n if n > 0:\n return n-1\n else:\n return n", "def get_real_floor(n):\n if n < 0:\n return n\n elif n == 0:\n return 0\n elif n == 1:\n return 0\n elif n < 13:\n return n - 1\n else:\n return n - 2", "def get_real_floor(n):\n if n == 0 or n < 0:\n return n\n elif n in range(1, 14):\n return n - 1\n elif n > 13:\n return n - 2", "def get_real_floor(n):\n if n == 1 or n == -1:\n return 0\n elif n <= 0:\n return n\n elif n < 13:\n return n - 1\n else:\n return n - 2", "def get_real_floor(n):\n if n <=0:\n return n\n elif n <= 13:\n return n - 1\n elif n == 15:\n return 13\n else:\n return n - 2"]
{"fn_name": "get_real_floor", "inputs": [[1], [0], [5], [10], [12], [14], [15], [37], [200], [-2], [-5]], "outputs": [[0], [0], [4], [9], [11], [12], [13], [35], [198], [-2], [-5]]}
INTRODUCTORY
PYTHON3
CODEWARS
13,344
def get_real_floor(n):
120f316a7a728ce45db74d9998d38a1a
UNKNOWN
Is the number even? If the numbers is even return `true`. If it's odd, return `false`. Oh yeah... the following symbols/commands have been disabled! use of ```%``` use of ```.even?``` in Ruby use of ```mod``` in Python
["def is_even(n):\n return not n & 1", "def is_even(n):\n return n // 2 * 2 == n", "def is_even(n): return n & 1 == 0 \n", "def is_even(n):\n return n/2 == int(n/2)", "def is_even(n):\n return str(n)[-1] in '02468'", "is_even=lambda n: n|1!=n", "def is_even(n):\n return str(bin(n)[2:])[-1] == '0'", "def is_even(n):\n return n & 1 ^ 1", "def is_even(n): return bin(n)[-1] == \"0\"", "def is_even(n):\n twos = []\n for i in range(0,1000000,2):\n twos.append(i)\n if n in twos:\n return True\n else:\n return False"]
{"fn_name": "is_even", "inputs": [[2], [3], [14], [15], [26], [27]], "outputs": [[true], [false], [true], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
565
def is_even(n):
54dbebcf90f2a29b2968e6d700105428
UNKNOWN
General primality test are often computationally expensive, so in the biggest prime number race the idea is to study special sub-families of prime number and develop more effective tests for them. [Mersenne Primes](https://en.wikipedia.org/wiki/Mersenne_prime) are prime numbers of the form: Mn = 2^(n) - 1. So far, 49 of them was found between M2 (3) and M74,207,281 which contains 22,338,618 digits and is (by September 2015) the biggest known prime. It has been found by GIMPS (Great Internet Mersenne Prime Search), wich use the test srudied here. (plus heuristics mentionned below) Lucas and Lehmer have developed a [simple test](https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test) for Mersenne primes: > for `p` (an odd prime), the Mersenne number Mp is prime if and only if `S(p − 1) = 0 mod Mp`, >where `S(n + 1) = S(n) * S(n) − 2` and `S(1) = 4` The goal of this kata is to implement this test. Given an integer `>=2`, the program should calculate the sequence `S(n)` up to `p-1` and calculate the remainder modulo `Mp`, then return `True` or `False` as a result of the test. The case `n = 2` should return `True`. You should take advantage of the fact that: ```k = (k mod 2^n + floor(k/2^n)) mod Mn``` Or in other words, if we take the least significant `n` bits of `k`, and add the remaining bits of `k`, and then do this repeatedly until at most `n` bits remain, we can compute the remainder after dividing `k` by the Mersenne number `2^n−1` without using division. This test can be improved using the fact that if `n` is not prime, `2^n-1` will not be prime. So in theory you can test for the primality of `n` beforehand. But in practice the test for the primality of `n` will rapidly outgrow in difficulty the Lucas-Lehmer test. So we can only use heuristics to rule out `n` with small factors but not complete factorization algorithm. You don't need to implement such heuristics here. The rapid growth of `s^2` makes javascript reach its integer limit quickly (coherent result for `n = 13`, but not `17`). Whereas python seems to be only limited by the execution time limit and let us see that M11,213 is prime (contains 3376 digits).
["def lucas_lehmer(n):\n return n in [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279,\n 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701,\n 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433,\n 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011,\n 24036583, 25964951, 30402457, 32582657, 3715666]", "# I mean, if you say we found less than 50 of them, there's no point in computing them again\nlucas_lehmer = {2, 3, 5, 7, 13, 17, 19, 31, 61, 89,\n 107, 127, 521, 607, 1279, 2203, 2281,\n 3217, 4253, 4423, 9689, 9941, 11213, 19937,\n 21701, 23209, 44497, 86243, 110503, 132049,\n 216091, 756839, 859433, 1257787, 1398269,\n 2976221, 3021377, 6972593, 13466917, 20996011,\n 24036583, 25964951, 30402457, 32582657, 37156667,\n 42643801, 43112609}.__contains__", "def lucas_lehmer(n):\n m = (1 << n) - 1\n s = 4\n for i in range(n - 2):\n s = s * s - 2\n while int.bit_length(s) > n:\n s = (s >> n) + (s&m)\n return s == m or n == 2", "def lucas_lehmer(n):\n if n == 2:\n return True\n m = 2**n - 1\n s = 4\n for i in range(2, n):\n sqr = s*s\n s = (sqr & m) + (sqr >> n)\n if s >= m:\n s -= m\n s -= 2\n return s == 0 ", "def lucas_lehmer(n,s=4):\n m=2**n-1\n for _ in range(2,n):\n s=s*s-2\n while m<s:s=(s&m)+(s>>n)\n return n==2or s in(0,m)", "lucas_lehmer=lambda p:p in[2,3,5,7,13,17,19,31,61,89,107,127,521,607,1279,2203,2281,3217,4253,4423,9689,9941,11213,19937]", "def isPrime(n):\n if n % 2 == 0 and n > 2: \n return False\n return all(n % i for i in range(3, int(n**.5 + 1), 2))\n \ndef S(n):\n if n==1: return 4\n return S(n-1) * S(n-1) - 2\n\ndef mod_equiv(n,p):\n binario = bin(n)[2:]\n suma = n\n while len(binario) > p:\n suma = int(binario[-p:],2) + int(binario[:-p],2)\n binario = bin(suma)[2:]\n return suma\n\n\ndef lucas_lehmer(n):\n if not isPrime(n): return False\n s = 4\n M = 2**n-1\n for i in range(n-2):\n # s = (s*s-2) % M\n s = (mod_equiv(s*s-2,n)) % M\n return s == 0 or n==2", "def lucas_lehmer(n):\n if n==1:\n return False\n elif n==2:\n return True\n s=4\n mp=(2**n-1)\n for i in range(n-2):\n s=s*s-2\n while(s>=mp):\n s=(s>>n)+(s&mp)\n if s==mp:\n s=0\n return s == 0", "def lucas_lehmer(n):\n if n == 2:\n return True\n m = 2 ** n - 1\n s = 4\n for i in range(2, n):\n ss = s * s\n s = (ss >> n) + (ss & m)\n if s >= m:\n s -= m\n s -= 2\n return s == 0"]
{"fn_name": "lucas_lehmer", "inputs": [[2], [3], [4], [5], [7], [10], [33], [101], [11213], [11215]], "outputs": [[true], [true], [false], [true], [true], [false], [false], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,854
def lucas_lehmer(n):
c4014126f701f17686655cbecacd2e18
UNKNOWN
Find the longest substring in alphabetical order. Example: the longest alphabetical substring in `"asdfaaaabbbbcttavvfffffdf"` is `"aaaabbbbctt"`. There are tests with strings up to `10 000` characters long so your code will need to be efficient. The input will only consist of lowercase characters and will be at least one letter long. If there are multiple solutions, return the one that appears first. Good luck :)
["import re\n\nreg = re.compile('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\ndef longest(s):\n return max(reg.findall(s), key=len)", "def longest(string):\n start = 0\n longest = string[0:1]\n length = len(string)\n for i in range(1, length):\n if string[i] < string[i - 1] or i == length - 1:\n if string[i] < string[i - 1]:\n last = string[start:i]\n start = i\n else:\n last = string[start:]\n if len(last) > len(longest):\n longest = last\n return longest", "import re\ndef longest(s):\n return max(re.findall(r'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*',s),key=len)", "def longest(s):\n k = []\n for i in range(len(s)-1):\n if s[i] <= s[i+1]:\n k.append(s[i])\n else:\n k.append(s[i])\n k.append(' ')\n k += s[-1]\n return max(''.join(k).split(), key=len)", "import re\n\ndef longest(s):\n regex = '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 group = lambda x: x.group()\n return max(map(group, re.finditer(regex, s)), key=len)", "def longest(s):\n chunks = []\n for c in s:\n if chunks and chunks[-1][-1] <= c:\n chunks[-1] += c\n else:\n chunks.append(c)\n return max(chunks, key=len)", "def longest(s):\n max_substring = \"\"\n substring = \"\"\n for ch in s:\n if substring == \"\" or ord(ch) >= ord(substring[-1]):\n substring += ch\n elif ord(ch) < ord(substring[-1]):\n substring = \"\".join(ch)\n if len(substring) > len(max_substring):\n max_substring = substring\n return max_substring", "longest=lambda s: max(''.join(c+' ' if c>d else c for c,d in (zip(s,s[1:]+' '))).split(), key=len)", "import re\ndef longest(s):\n myreg = '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 return max(re.findall(r'(' + myreg + ')', s), key=len)\n", "def longest(s):\n\n result = []\n ordx = 0\n \n for i in s:\n if ord(i) >= ordx:\n ordx = ord(i)\n result.append(i)\n else:\n result.append('|')\n result.append(i)\n\n ordx = ord(i)\n\n\n return max((\"\").join(result).split(\"|\"), key=len)\n\n"]
{"fn_name": "longest", "inputs": [["asd"], ["nab"], ["abcdeapbcdef"], ["asdfaaaabbbbcttavvfffffdf"], ["asdfbyfgiklag"], ["z"], ["zyba"]], "outputs": [["as"], ["ab"], ["abcde"], ["aaaabbbbctt"], ["fgikl"], ["z"], ["z"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,334
def longest(s):
e7f0e0c2ab51ea59bae5d8859cf308ee
UNKNOWN
Hi there! You have to implement the `String get_column_title(int num) // syntax depends on programming language` function that takes an integer number (index of the Excel column) and returns the string represents the title of this column. #Intro In the MS Excel lines are numbered by decimals, columns - by sets of letters. For example, the first column has the title "A", second column - "B", 26th - "Z", 27th - "AA". "BA"(53) comes after "AZ"(52), "AAA" comes after "ZZ". Excel? Columns? More details [here](https://en.wikipedia.org/wiki/Microsoft_Excel) #Input It takes only one argument - column decimal index number. Argument `num` is a natural number. #Output Output is the upper-case string represents the title of column. It contains the English letters: A..Z #Errors For cases `num < 1` your function should throw/raise `IndexError`. In case of non-integer argument you should throw/raise `TypeError`. In Java, you should throw `Exceptions`. Nothing should be returned in Haskell. #Examples Python, Ruby: ``` >>> get_column_title(52) "AZ" >>> get_column_title(1337) "AYK" >>> get_column_title(432778) "XPEH" >>> get_column_title() TypeError: >>> get_column_title("123") TypeError: >>> get_column_title(0) IndexError: ``` JS, Java: ``` >>> getColumnTitle(52) "AZ" >>> getColumnTitle(1337) "AYK" >>> getColumnTitle(432778) "XPEH" >>> getColumnTitle() TypeError: >>> getColumnTitle("123") TypeError: >>> getColumnTitle(0) IndexError: ``` #Hint The difference between the 26-digits notation and Excel columns numeration that in the first system, after "Z" there are "BA", "BB", ..., while in the Excel columns scale there is a range of 26 elements: AA, AB, ... , AZ between Z and BA. It is as if in the decimal notation was the following order: 0, 1, 2, .., 9, 00, 01, 02, .., 09, 10, 11, .., 19, 20..29..99, 000, 001 and so on. #Also The task is really sapid and hard. If you're stuck - write to the discussion board, there are many smart people willing to help.
["from string import ascii_uppercase as u\n\ndef get_column_title(n):\n assert isinstance(n, int) and n > 0\n col = []\n while n:\n n, r = divmod(n-1, 26)\n col.append(u[r])\n return ''.join(reversed(col))", "upper = __import__(\"string\").ascii_uppercase.__getitem__\n\ndef get_column_title(num=None):\n if not isinstance(num, int): raise TypeError()\n if num < 1: raise IndexError()\n res = []\n while num:\n num, r = divmod(num-1, 26)\n res.append(r)\n return ''.join(map(upper, reversed(res)))", "alpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\ndef get_column_title(n):\n if n < 1:\n raise ValueError\n l = []\n while n:\n n, m = divmod(n-1, 26)\n l.append(alpha[m])\n return \"\".join(l[::-1])\n", "from string import ascii_uppercase\n\ndef get_column_title(n):\n n -= 1\n result = []\n while n >= 0:\n result.append(ascii_uppercase[n % 26])\n n = n // 26 - 1\n if not result:\n raise ValueError('Not a valid number.')\n return ''.join(result[::-1])", "def get_column_title(num):\n if type(num) != int: raise TypeError\n if num < 1: raise IndexError\n \n abc = \" ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n col_title = \"\"\n while num > 0:\n letter_index = num % 26\n if letter_index == 0:\n letter_index = 26\n num -= 26\n num //= 26\n col_title = abc[letter_index] + col_title\n \n return col_title.strip()\n", "def get_column_title(number):\n if number <= 0: raise ValueError\n if number <= 26: return chr(number + 64)\n else: return get_column_title((number-1) // 26) + chr(65 + (number-1) % 26)", "alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\ndef get_column_title(number):\n result = []\n if not isinstance(number, int):\n raise TypeError\n\n def convert(num):\n\n if isinstance(num, list):\n n = num[0]\n # result = num\n else:\n if len(result) == 0:\n result.append(num)\n n = num\n\n if 0 < n <= 26:\n result.append(alphabet[n - 1])\n return result\n else:\n if n % 26 == 0:\n result[0] = convert(n // 26 - 1)\n else:\n result[0] = convert(n // 26)\n result.append(alphabet[n % 26 - 1])\n return result\n\n res = convert(number)\n result = []\n return ''.join(res[1::])", "def get_column_title(num):\n if num <= 0 :\n raise \"IndexError\"\n elif type(num)!=int:\n raise \"TypeError\"\n else:\n string = \"\"\n while num > 0:\n num, remainder = divmod(num - 1, 26)\n string = chr(65 + remainder) + string\n return string\n \n", "def get_column_title(num):\n if num<1: return error\n a = [num%26]\n while num>26:\n num = num//26-1\n a += [num%26+1]\n y = a+[num] if num>26 else a\n if y[0]==0 and len(y)>1: y[1]-=1\n return ''.join(['Z' if i==0 else chr(i+ord('A')-1) for i in y][::-1])\n", "from itertools import count\n\n\ndef get_column_title(num):\n if num<1:\n raise IndexError\n \n if num<=26:\n return chr(ord('A')+num-1)\n \n return get_column_title((num-1)//26) + get_column_title(1+(num-1)%26)\n \n \n"]
{"fn_name": "get_column_title", "inputs": [[1], [26], [52], [53], [702]], "outputs": [["A"], ["Z"], ["AZ"], ["BA"], ["ZZ"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,368
def get_column_title(num):
4252b405f308af6272308ed0dcc19d1d
UNKNOWN
What's in a name? ..Or rather, what's a name in? For us, a particular string is where we are looking for a name. Task Test whether or not the string contains all of the letters which spell a given name, in order. The format A function passing two strings, searching for one (the name) within the other. ``function nameInStr(str, name){ return true || false }`` Examples nameInStr("Across the rivers", "chris") --> true ^ ^ ^^ ^ c h ri s Contains all of the letters in "chris", in order. ---------------------------------------------------------- nameInStr("Next to a lake", "chris") --> false Contains none of the letters in "chris". -------------------------------------------------------------------- nameInStr("Under a sea", "chris") --> false ^ ^ r s Contains only some of the letters in "chris". -------------------------------------------------------------------- nameInStr("A crew that boards the ship", "chris") --> false cr h s i cr h s i c h r s i ... Contains all of the letters in "chris", but not in order. -------------------------------------------------------------------- nameInStr("A live son", "Allison") --> false ^ ^^ ^^^ A li son Contains all of the correct letters in "Allison", in order, but not enough of all of them (missing an 'l'). Note: testing will _not_ be case-sensitive.
["def name_in_str(str, name):\n it = iter(str.lower())\n return all(c in it for c in name.lower())", "def name_in_str(text, name):\n for c in text.lower():\n if c == name[0].lower():\n name = name[1:]\n if not name:\n return True\n return False", "def name_in_str(str, name):\n str = str.lower()\n name = name.lower()\n \n for n in name:\n try:\n ix = str.index(n)\n str = str[ix+1:]\n except:\n return False\n return True", "from re import search; name_in_str=lambda s,n: search(\".*\".join(list(n)),s,2) != None", "def name_in_str(strng, name):\n strng = strng.lower()\n for letter in name.lower():\n if letter not in strng:\n return False\n else:\n strng=strng[strng.find(letter)+1:]\n return True\n \n", "import re\ndef name_in_str(s, name):\n str_lst=re.findall('[a-z]',s.lower())\n i=0\n for c in name.lower():\n if not c in str_lst:\n return False\n else:\n i=str_lst.index(c)\n str_lst=str_lst[i+1:]\n return True", "def name_in_str(s, name):\n s = s.lower()\n name = name.lower()\n result = False\n x = 0\n helper = []\n\n for i in range(len(name)):\n for j in range(x, len(s)):\n if name[i] == s[j]:\n x = j + 1\n helper.append(name[i])\n break\n\n if list(name) == helper:\n result = True\n\n return result", "def name_in_str(str, name):\n name = list(reversed(name.lower()))\n for c in str.lower():\n if c == name[-1]: name.pop()\n if not name: return True\n return False", "def name_in_str(s, word):\n i,word,t = 0,word.lower(),\"\"\n for j in s.lower():\n if word[i] == j : t += j ; i += 1\n if t == word : return True\n return False", "def name_in_str(str, name):\n name = list(name.lower())[::-1]\n charFind = name.pop();\n for x in str.lower():\n if(x == charFind):\n if(len(name) == 0):\n return True;\n charFind = name.pop();\n return False;\n \n"]
{"fn_name": "name_in_str", "inputs": [["Across the rivers", "chris"], ["Next to a lake", "chris"], ["Under a sea", "chris"], ["A crew that boards the ship", "chris"], ["A live son", "Allison"], ["Just enough nice friends", "Jennifer"], ["thomas", "Thomas"], ["pippippi", "Pippi"], ["pipipp", "Pippi"], ["ppipip", "Pippi"]], "outputs": [[true], [false], [false], [false], [false], [false], [true], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,169
def name_in_str(str, name):
6e87a73656988e061c825d8107666c51
UNKNOWN
Write a function that takes in a binary string and returns the equivalent decoded text (the text is ASCII encoded). Each 8 bits on the binary string represent 1 character on the ASCII table. The input string will always be a valid binary string. Characters can be in the range from "00000000" to "11111111" (inclusive) Note: In the case of an empty binary string your function should return an empty string.
["def binary_to_string(binary):\n return \"\".join( [ chr( int(binary[i: i+8], 2) ) for i in range(0, len(binary), 8) ] )", "def binary_to_string(binary):\n return \"\".join(chr(int(binary[i:i+8],2)) for i in range(0,len(binary),8))\n", "def binary_to_string(binary):\n result = \"\"\n \n while binary:\n result += chr(int(binary[:8], 2))\n binary = binary[8:]\n \n return result", "binary_to_string=lambda b:''.join(__import__('binascii').unhexlify('%x' % int('0b'+b[i:i+8],base=2)).decode(\"utf-8\") for i in range(0,len(b),8))", "import re\n\ndef binary_to_string(binary):\n return re.sub(r'[01]{8}', lambda x: chr(int(x.group(), 2)), binary)", "binary_to_string = lambda b: \"\".join([[chr(l) for l in range(0, 127)][m] for m in [int(b[n: n+8],2) for n in range(0, len(b), 8)]])", "def binary_to_string(binary):\n return int(binary, 2).to_bytes(len(binary)//8, \"big\").decode() if binary else binary", "import re\n\ndef binary_to_string(bits):\n return ''.join(chr(int(byte, 2)) for byte in re.findall(r'\\d{8}', bits))", "import re\n\ndef binary_to_string(binary):\n return re.sub(r'.'*8, lambda e: chr(int(e.group(), 2)), binary)", "import re\ndef binary_to_string(binary):\n return ''.join(chr(int(e,2))for e in re.findall('.'*8, binary))\n"]
{"fn_name": "binary_to_string", "inputs": [[""], ["0100100001100101011011000110110001101111"], ["00110001001100000011000100110001"], ["0101001101110000011000010111001001101011011100110010000001100110011011000110010101110111001011100010111000100000011001010110110101101111011101000110100101101111011011100111001100100000011100100110000101101110001000000110100001101001011001110110100000100001"], ["0010000101000000001000110010010000100101010111100010011000101010001010000010100101010001010101110100010101110010011101000111100101010101010010010100111101001100011001000110011001100111011000100110001001101000011011100110110101001001010010110100001001001010010010110100100001001001010101010100111100101000001111110011111000111111001111000111111001111110011111100111111001111110001010010010100000101010001001100010010101011110001110010011100000110111001100010011001100101111001011010010111100101010001011010010101000101111"]], "outputs": [[""], ["Hello"], ["1011"], ["Sparks flew.. emotions ran high!"], ["!@#$%^&*()QWErtyUIOLdfgbbhnmIKBJKHIUO(?>?<~~~~~)(*&%^98713/-/*-*/"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,300
def binary_to_string(binary):
d9d82c5be7091c9b529520ef0cded15d
UNKNOWN
A [Narcissistic Number](https://en.wikipedia.org/wiki/Narcissistic_number) is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10). For example, take 153 (3 digits): ``` 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 ``` and 1634 (4 digits): ``` 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634 ``` The Challenge: Your code must return **true or false** depending upon whether the given number is a Narcissistic number in base 10. Error checking for text strings or other invalid inputs is not required, only valid positive non-zero integers will be passed into the function.
["def narcissistic(value):\n return value == sum(int(x) ** len(str(value)) for x in str(value))", "def narcissistic( value ):\n value = str(value)\n size = len(value)\n sum = 0\n for i in value:\n sum += int(i) ** size\n return sum == int(value)", "def narcissistic(value):\n return bool(value==sum([int(a) ** len(str(value)) for a in str(value)]))\n", "def narcissistic( value ):\n vstr = str(value)\n nvalue = sum(int(i)**len(vstr) for i in vstr)\n return nvalue == value\n", "def narcissistic(value):\n string = str(value)\n length = len(string)\n sum_of_i = 0\n for i in string:\n sum_of_i += int(i) ** length\n if sum_of_i == value:\n result = True\n else:\n result = False\n return result", "def narcissistic( value ):\n return value == sum(int(i) ** len(str(value)) for i in str(value))", "narcissistic = lambda n: sum([int(d) ** len(str(n)) for d in list(str(n))]) == n", "def narcissistic(value):\n num_str = str(value)\n length = len(num_str)\n return sum(int(a) ** length for a in num_str) == value\n", "def narcissistic( value ):\n string_of_number = str(value)\n length_of_number = len (string_of_number)\n\n total = 0\n for i in range (0 , length_of_number):\n count = int(string_of_number[i])**length_of_number\n total = count + total\n\n if total == value:\n return True\n else:\n return False"]
{"fn_name": "narcissistic", "inputs": [[1], [5], [7], [153], [370], [371], [1634]], "outputs": [[true], [true], [true], [true], [true], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,449
def narcissistic( value ):
f3f5ad1f7c25b1cad83927fd1e079a0d
UNKNOWN
For this exercise you will create a global flatten method. The method takes in any number of arguments and flattens them into a single array. If any of the arguments passed in are an array then the individual objects within the array will be flattened so that they exist at the same level as the other arguments. Any nested arrays, no matter how deep, should be flattened into the single array result. The following are examples of how this function would be used and what the expected results would be: ```python flatten(1, [2, 3], 4, 5, [6, [7]]) # returns [1, 2, 3, 4, 5, 6, 7] flatten('a', ['b', 2], 3, None, [[4], ['c']]) # returns ['a', 'b', 2, 3, None, 4, 'c'] ```
["def flatten(*a):\n r = []\n for x in a:\n if isinstance(x, list):\n r.extend(flatten(*x))\n else:\n r.append(x)\n return r", "def flatten(*args):\n return [x for a in args for x in (flatten(*a) if isinstance(a, list) else [a])]", "def flatten(*args):\n \n def _flat(lst):\n for x in lst:\n if isinstance(x,list): yield from _flat(x)\n else: yield x\n \n return list(_flat(args))", "def flatten(*args):\n result = []\n for arg in args:\n if type(arg) is list:\n result.extend(flatten(*arg))\n else:\n result.append(arg)\n return result", "def flatten(*a):\n r, s = [], [iter(a)]\n while s:\n it = s.pop()\n for v in it:\n if isinstance(v, list):\n s.extend((it, iter(v)))\n break\n else:\n r.append(v)\n return r", "def flatten(*arr):\n inputlist = list(arr)\n while (True):\n typelist =[]\n for i in inputlist:\n typelist.append(type(i))\n if list in typelist:\n inputlist = takeoff(inputlist)\n else:\n return inputlist\ndef takeoff(inputlist):\n output =[]\n for i in inputlist:\n if type(i)==list:\n output.extend(i)\n else:\n output.append(i)\n return output", "def flatten(*elements):\n lst = list(elements)\n while any(isinstance(x, list) for x in lst):\n for i, x in enumerate(lst):\n if isinstance(x, list):\n lst[i:i + 1] = x\n return lst", "def flatten(*args):\n flattened_list = [arg for arg in args]\n result = []\n while any(isinstance(element, list) for element in flattened_list):\n for element in flattened_list:\n if type(element) is list:\n for j in element:\n result.append(j)\n else:\n result.append(element)\n flattened_list = result[:]\n result.clear()\n return flattened_list", "def flatten(*args):\n return [a for arg in args for a in (flatten(*arg) if type(arg) is list else [arg])]", "def flatten(*args):\n return flat([], *args)\n\n\ndef flat(res, *args):\n for arg in args:\n if isinstance(arg, list):\n flat(res, *arg)\n else:\n res.append(arg)\n return res"]
{"fn_name": "flatten", "inputs": [[1, 2, 3], [1, 2], [5, "string"], [-4.5, -3, 1, 4], [[3, 4, 5], [1, 2, 3]], [[1], [], 2, [4, 5, 6]], [[4, "string", 9, 3, 1], [], [], [], [], ["string"]], [1, 2, ["9", [], []], null], [[1, 2], [3, 4, 5], [6, [7], [[8]]]], [["hello", 2, ["text", [4, 5]]], [[]], "[list]"]], "outputs": [[[1, 2, 3]], [[1, 2]], [[5, "string"]], [[-4.5, -3, 1, 4]], [[3, 4, 5, 1, 2, 3]], [[1, 2, 4, 5, 6]], [[4, "string", 9, 3, 1, "string"]], [[1, 2, "9", null]], [[1, 2, 3, 4, 5, 6, 7, 8]], [["hello", 2, "text", 4, 5, "[list]"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,437
def flatten(*args):
97b5d30d2ab0cdeb08402816dfd306a8
UNKNOWN
Create a function `sierpinski` to generate an ASCII representation of a Sierpinski triangle of order **N**. Seperate each line with `\n`. You don't have to check the input value. The output should look like this: sierpinski(4) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
["def sierpinski(n):\n t = ['*']\n for _ in range(n):\n t = [r.center(2*len(t[-1])+1) for r in t] + [r + ' ' + r for r in t]\n return '\\n'.join(t)", "def sierpinski(n):\n lines = [\"*\"]\n for i in range(2, n+2):\n lines = [l.center(2**i - 1) for l in lines] + [f\"{l} {l}\" for l in lines]\n return \"\\n\".join(lines)\n", "sierpinski=lambda n,pr=['*'],sp=3:sierpinski(n-1,pr+[(j+(' '*len(pr[-1-i]))+j)for i,j in enumerate(pr)],sp*2+1)if n else'\\n'.join([i.center(sp//2)for i in pr])", "def s(n):\n xs = [1]\n yield xs\n for i in range(n):\n while True:\n xs = [a^b for a, b in zip([0]+xs, xs+[0])]\n yield xs\n if all(xs):\n break\n\ndef sierpinski(n):\n xss = list(s(n))\n width = len(xss) * 2 - 1\n return '\\n'.join(\n ' '.join(' *'[x] for x in xs).center(width)\n for xs in xss\n )", "def sierpinski(n):\n return '\\n'.join(l.center(2**(n+1) - 1) for l in addrows(n, ['*']))\n \ndef addrows(n, t):\n for _ in range(n): t += [l.ljust(len(t[-1])) + \" \" + l for l in t] \n return t ", "def sierpinski(n):\n if n==0: return '*'\n s=sierpinski(n-1).split('\\n')\n ss=[]\n for i in range(2**n//2):\n ss.append(s[i].center(2**n*2-1))\n for i in range(2**n//2):\n ss.append(s[i]+' '+ s[i])\n return '\\n'.join(ss)", "def sierpinski(n):\n if n==1:\n return ' * \\n* *'\n s=sierpinski(n-1).split('\\n')\n n=len(s[0])\n r=[]\n for row in s:\n r.append(' '*((n+1)//2)+row+' '*((n+1)//2))\n for row in s:\n r.append(row+' '+row)\n return '\\n'.join(r)", "def sierpinski(n):\n if n==0:\n return '*'\n lower = sierpinski(n-1).splitlines()\n result = [s.center(2*len(s)+1) for s in lower]\n result += [s+' '+s for s in lower]\n return '\\n'.join(result)\n", "def sierpinski(n):\n if n == 0:\n return '*'\n lines = sierpinski(n - 1).split('\\n')\n upper = [' ' * (2 ** (n - 1)) + l + ' ' * (2 ** (n - 1)) for l in lines]\n lower = [l + ' ' + l for l in lines]\n return '\\n'.join(upper + lower)", "SIERPINSKI = {\n 1: [' * ', '* *']\n}\n\n\ndef join_lesser(fig):\n width = len(fig[-1]) + 1\n result = []\n for line in fig:\n padding = ' ' * (width // 2)\n result.append(padding + line + padding)\n for line in fig:\n result.append(line + ' ' * (width - len(line)) + line)\n return result\n\n\ndef get_sierpinski(n):\n if n in SIERPINSKI:\n return SIERPINSKI[n]\n\n lesser = get_sierpinski(n - 1)\n SIERPINSKI[n] = join_lesser(lesser)\n return SIERPINSKI[n]\n\n\ndef sierpinski(n):\n return '\\n'.join(get_sierpinski(n))\n"]
{"fn_name": "sierpinski", "inputs": [[1], [2], [3]], "outputs": [[" * \n* *"], [" * \n * * \n * * \n* * * *"], [" * \n * * \n * * \n * * * * \n * * \n * * * * \n * * * * \n* * * * * * * *"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,739
def sierpinski(n):
6809c29e6da7a892e90a9377fd56aa23
UNKNOWN
Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square! Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number. The result will be an array of arrays or of tuples (in C an array of Pair) or a string, each subarray having two elements, first the number whose squared divisors is a square and then the sum of the squared divisors. #Examples: ``` list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]] list_squared(42, 250) --> [[42, 2500], [246, 84100]] ``` The form of the examples may change according to the language, see `Example Tests:` for more details. **Note** 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.
["CACHE = {}\n\ndef squared_cache(number):\n if number not in CACHE:\n divisors = [x for x in range(1, number + 1) if number % x == 0]\n CACHE[number] = sum([x * x for x in divisors])\n return CACHE[number] \n \n return CACHE[number]\n\ndef list_squared(m, n):\n ret = []\n\n for number in range(m, n + 1):\n divisors_sum = squared_cache(number)\n if (divisors_sum ** 0.5).is_integer():\n ret.append([number, divisors_sum])\n\n return ret", "WOAH = [1, 42, 246, 287, 728, 1434, 1673, 1880, \n 4264, 6237, 9799, 9855, 18330, 21352, 21385, \n 24856, 36531, 39990, 46655, 57270, 66815, \n 92664, 125255, 156570, 182665, 208182, 212949, \n 242879, 273265, 380511, 391345, 411558, 539560, \n 627215, 693160, 730145, 741096]\n\nlist_squared = lambda HUH, YEAH: [[YES, DUH(YES)] for YES in WOAH if YES >= HUH and YES <= YEAH]\nDUH = lambda YEP: sum(WOW**2 for WOW in range(1, YEP + 1) if YEP % WOW == 0)", "from math import floor, sqrt, pow\n\ndef sum_squared_factors(n):\n s, res, i = 0, [], 1\n while (i <= floor(sqrt(n))):\n if (n % i == 0):\n s += i * i\n nf = n // i\n if (nf != i):\n s += nf * nf\n i += 1\n if (pow(int(sqrt(s)), 2) == s):\n res.append(n)\n res.append(s)\n return res\n else:\n return None\n \ndef list_squared(m, n):\n res, i = [], m\n while (i <= n):\n r = sum_squared_factors(i)\n if (r != None):\n res.append(r);\n i += 1\n return res\n \n", "\ndef get_divisors_sum(n):\n \"\"\"Get the divisors: iterate up to sqrt(n), check if the integer divides n with r == 0\n Return the sum of the divisors squared.\"\"\"\n divs=[1]\n for i in range(2,int(n**0.5)+1):\n if n%i == 0:\n divs.extend([i, int(n/i)])\n divs.extend([n])\n \n # Get sum, return the sum \n sm = sum([d**2 for d in list(set(divs))])\n return sm\n \n \ndef list_squared(m, n):\n \"\"\"Search for squares amongst the sum of squares of divisors of numbers from m to n \"\"\"\n out = []\n for j in range(m,n+1):\n s = get_divisors_sum(j) # sum of divisors squared.\n if (s ** 0.5).is_integer(): # check if a square.\n out.append([j, s])\n return out\n", "from itertools import chain\nfrom functools import reduce\n\n\ndef factors(n):\n return set(chain.from_iterable(\n [d, n // d] for d in range(1, int(n**0.5) + 1) if n % d == 0))\n\n\ndef square_factors(n):\n return reduce(lambda s, d: s + d**2, factors(n), 0)\n\n\ndef list_squared(m, n):\n l = []\n for x in range(m, n + 1):\n s = square_factors(x)\n if (s**0.5).is_integer():\n l.append([x, s])\n return l", "def list_squared(m, n):\n list=[]\n for i in range(m,n+1):\n sum=0\n s_list=[]\n for j in range(1,int(i**.5)+1):\n if i%j==0:\n div=i//j\n sum+=j**2\n if j!=div:\n sum+=div**2\n sqt=sum**.5\n if int(sqt)==sqt:\n s_list=[i,sum]\n list.append(s_list)\n return list", "def list_squared(m, n):\n out = []\n for i in range(m,n+1):\n # Finding all divisors below the square root of i\n possibles = set([x for x in range (1,int(i**0.5)+1) if i%x == 0])\n # And adding their counterpart\n possibles.update([i/x for x in possibles])\n # Doubles in the possibles are solved due to the set\n val = sum(x**2 for x in possibles)\n # Checking for exact square\n if (int(val**0.5))**2 == val: out.append([i, val])\n return out", "import math\n\n\ndef divisors(n):\n divs = [1, n]\n for i in range(2, int(math.sqrt(n))+1):\n if n % i == 0:\n divs.extend([i, int(n/i)])\n return set(divs)\n\n\ndef list_squared(m, n):\n sq_list = []\n for num in range(m, n):\n _sum = sum(item**2 for item in divisors(num))\n if math.sqrt(_sum).is_integer():\n sq_list.append([num, _sum])\n return sq_list", "def list_squared(m, n):\n list = [[1, 1], [42, 2500], [246, 84100], [287, 84100], [728, 722500], [1434, 2856100], [1673, 2856100], [1880, 4884100], [4264, 24304900], [6237, 45024100], [9799, 96079204], [9855, 113635600], [18330, 488410000], [21352, 607622500], [21385, 488410000], [24856, 825412900]]\n left = -1\n right = -1\n for i, r in enumerate(list):\n if left == -1 and r[0] >= m:\n left = i\n if right == -1 and r[0] >= n:\n right = i - 1\n print('left={0},right={1}'.format(m, n))\n return list[left: right + 1]", "def list_squared(m, n):\n result, divisors = [], {k: k*k + 1 for k in range(m, n+1)}\n divisors[1] = 1\n for d in range(2, int(n ** .5) + 1):\n for k in range(max(d*d, m + -m%d), n + 1, d):\n divisors[k] += d*d\n if k/d != d:\n divisors[k] += (k/d) ** 2\n for k in range(m, n + 1):\n if not divisors[k] ** .5 % 1:\n result.append([k, divisors[k]])\n return result", "def divi(n):\n fac = set()\n for i in range(1, int(n**.5)+1):\n if n % i == 0:\n fac.add(i**2)\n fac.add(int(n/i)**2)\n return fac\n\ndef list_squared(m, n):\n return [[i, sum(divi(i))] for i in range(m, n) if str(sum(divi(i))**.5)[-1] == '0']\n\n", "from math import sqrt\nfrom functools import reduce\n\ndef factors(n): \n return set(reduce(list.__add__, \n ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))\n \ndef list_squared(m, n):\n l = []\n for i in range(m, n):\n s = sum([x**2 for x in factors(i)])\n if sqrt(s) == int(sqrt(s)):\n l.append( [i, s] )\n return l\n", "import math\n\ndef store_diviors_squared_sum(func):\n store = {}\n def helper(integer):\n if integer not in store:\n store[integer] = func(integer)\n return store[integer]\n return helper\n\n@store_diviors_squared_sum\ndef divisors_squared_sum(integer):\n squared_divisors_sum = 1\n for number in range(2, integer+1):\n if integer % number == 0: squared_divisors_sum += number**2\n return squared_divisors_sum\n\n\ndef list_squared(m, n):\n return_array = []\n for integer in range(m, n+1):\n squared_divisors_sum = divisors_squared_sum(integer)\n if math.sqrt(squared_divisors_sum) % 1 == 0:\n return_array.append([integer, squared_divisors_sum])\n return return_array\n", "def list_squared(m, n):\n def f(number):\n divisor_list = []\n n = int(number ** 0.5) + 1\n for e in range(1,n):\n if number % e == 0:\n if int(number / e) == e:\n divisor_list.append(e**2)\n else:\n divisor_list.append(e**2)\n divisor_list.append((int(number / e))**2)\n \n summation = sum(divisor_list)\n \n if int(summation ** 0.5) == float(summation ** 0.5):\n return [True,summation]\n else:\n return [False,summation]\n list = []\n for i in range(m, n):\n d_l = f(i)\n if d_l[0]:\n list.append([i,d_l[1]])\n return list\n\n\n\n \n \n", "def list_squared(m, n):\n output = []\n for i in range(m,n):\n div = set() #using set to ignore duplicates (the square root of i)\n for d in range(1,int(i**0.5)+1): #going up to square root to save time. \n if i%d == 0:\n div.add(d) #if d is a divisor, i/d is also a divisor\n div.add(i/d)\n sumsqdiv = sum([a * a for a in div]) #using map/lambda to multiply all divisors. \n if (sumsqdiv**0.5).is_integer():\n output.append([i,sumsqdiv])\n return output\n", "from math import floor, sqrt\n\ndef list_squared(m, n):\n result = []\n for number in range(m, n):\n divisors = set()\n for divisor in range(1, floor(sqrt(number))+1):\n if number%divisor == 0:\n divisors.add(divisor) \n divisors.add(number//divisor)\n divisorsum = sum(x*x for x in divisors)\n if (sqrt(divisorsum))%1 == 0:\n result.append([number, divisorsum])\n return result", "def list_squared(m, n):\n # time complexity O(w*sqrt(k)) where k are the nums between m and n and w is the number of ints between m and n\n # space complexity O(w)\n res = []\n for num in range(m, n):\n div_sum = sum(i*i + ((num//i)*(num//i) if num//i != i else 0) for i in range(1, int(num**0.5) + 1) if num % i == 0)\n root = div_sum ** 0.5\n if root.is_integer(): \n res.append([num, div_sum])\n return res\n \n", "def list_squared(m, n):\n result = []\n for number in range(m, n+1):\n s = 0\n \n factors = {1,number}\n for x in range(2, int(number**0.5)+1):\n if number % x == 0:\n factors.add(x)\n factors.add(number/x)\n \n for i in factors:\n s = s + i**2\n if s**0.5 == int(s**0.5):\n result.append([number, s])\n return result", "from math import sqrt\n\ndef list_squared(m, n):\n result = []\n for a in range(m,n+1):\n total = 0\n for i in range(1,int(sqrt(a))+1):\n if a%i == 0:\n total += i**2\n if i < a/i:\n total += (a/i)**2\n if sqrt(total)%1 == 0:\n result.append([a, total])\n return result\n", "from math import ceil\nfrom functools import lru_cache\n \ndef find_square_sums(m, n):\n for x in range(m, n+1):\n c = candidate(x)\n if c:\n yield c\n\ndef candidate(n):\n total = sum(x**2 for x in divisors(n))\n if (total**0.5).is_integer():\n return [n, total]\n return False\n\n@lru_cache(maxsize=100000)\ndef divisors(n):\n divs = [1, n]\n for x in range(2, ceil((n+1)/2)):\n if x in divs: break\n if n % x == 0:\n divs.append(x)\n divs.append(int(n/x))\n return set(divs)\n\ndef list_squared(m, n):\n return list(find_square_sums(m, n))", "div=lambda n:sum(set(sum([[i**2,(n//i)**2] for i in range(2,int(n**.5)+1) if not n%i],[]))) + n*n + int(n!=1)\nd = {i: div(i) for i in range(10001)} \nlist_squared=lambda a,b:[[i,d[i]] for i in range(a,b+1) if (d[i]**.5).is_integer()]", "import math\n\ndef get_divisors(num):\n divisors = {1}\n \n if num == 1:\n return divisors\n \n for i in range(2, int(math.sqrt(num))+1):\n if num % i == 0:\n divisors.add(i)\n divisors.add(num/i)\n divisors.add(num)\n \n return list(divisors)\n\ndef list_squared(m, n):\n res = []\n \n for i in range(m,n+1):\n total = sum([x*x for x in get_divisors(i)])\n if int(math.sqrt(total))**2 == total:\n res.append([i,total])\n \n return res\n", "A={}\nfor n in range(1,12000):\n A[n] = [j**2 for j in list(range(1,int(n/2)+1))+[n] if (n/j).is_integer()]\n \ndef list_squared(m, n):\n return [[i,sum(A[i])] for i in range(m,n+1) if (sum(A[i])**(1/2)).is_integer()]\n", "def list_squared(m, n):\n return [[i, square_sum(i)] for i in range(m, n+1) if (square_sum(i)**0.5).is_integer()]\n\ndef square_sum(n):\n if n == 1: return 1\n div = []\n for i in range(1, int(n**0.5) + 1):\n if i in div: break\n if n%i == 0: div += [i, n//i] if i != n//i else [i]\n return sum(v**2 for v in div)", "from math import sqrt\n\ndef list_squared(m, n):\n ret_list = []\n for i in range(m, n):\n sum_divisors_2 = sum(\n x ** 2 + (i / x) ** 2 \n if x != i / x \n else x ** 2\n for x in range(1, int(sqrt(i)) + 1)\n if not i % x\n )\n if sqrt(sum_divisors_2).is_integer():\n ret_list.append([i, sum_divisors_2])\n return ret_list\n", "def list_squared(m, n):\n result = []\n for i in range(m, n+1):\n divisor = {1, i}\n for j in range(2, int(i ** 0.5)+1):\n if i % j == 0:\n divisor.add(j)\n divisor.add(int(i/j))\n div_sq_sum = sum([k ** 2 for k in divisor])\n if div_sq_sum ** 0.5 == int(div_sq_sum ** 0.5):\n result.append([i, div_sq_sum])\n return result", "def list_squared(m, n):\n a,b = {1:1,42:2500,246:84100,287:84100,728:722500,1434:2856100,1673:2856100,1880:4884100,4264:24304900,6237:45024100,9799:96079204,9855:113635600},[] \n for i in a.keys():\n if m <= i <= n:\n b.append([i,a[i]])\n return sorted(b)", "from math import sqrt\ndef list_squared(m, n):\n # your code\n def F(x): return sum(b**2 + ((x/b)**2 if b*b != x else 0) for b in [a for a in range(1,int(sqrt(x))+1) if x%a == 0])\n return [[d,F(d)] for d in range(m,n+1) if sqrt(F(d)).is_integer()]\n", "import math\n\ndef is_square(n):\n s = math.sqrt(n)\n return (s - math.floor(s)) == 0\n\ndef sds(n):\n s = 1 + (n**2 if n>1 else 0)\n l , r = 2, n//2\n while l < r:\n if (l*r) == n:\n s += l**2 + r**2\n l , r = l+1, n//(l+1)\n return s\n\ndef list_squared(m, n): \n res = []\n for i in range(m,n):\n s_sum = sds(i)\n if is_square(s_sum):\n res.append([i, s_sum])\n return res\n \n", "from math import ceil, sqrt\n\ndef squared(l):\n return [x**2 for x in l]\n\ndef divisors(m):\n s = sqrt(m)\n k = ceil(s)\n aux = [d for d in range(1, k) if m % d == 0]\n aux += [m // d for d in aux]\n if k == s:\n aux.append(k)\n return aux\n\ndef is_square(m):\n return ceil(sqrt(m))==sqrt(m)\n\ndef list_squared(m, n):\n return [[k, s] for (k, s) in [(k, sum(squared(divisors(k)))) for k in range(m, n + 1)] if is_square(s)]\n", "from math import sqrt\n\ndef divisors_squared(x):\n l2 = []\n y = int(sqrt(x))\n for a in range(1, y+1):\n if x % a == 0:\n divby = x//a\n if a != divby:\n l2.extend((a**2, divby**2))\n else:\n l2.append(a)\n return l2\n\ndef list_squared(x, y):\n arr = []\n for i in range(x, y+1):\n z = sum(divisors_squared(i))\n if (sqrt(z)).is_integer():\n arr.append([i, z])\n return arr \n", "def list_squared(m, n):\n lst = []\n for num in range(m, n):\n s = set()\n for div in range(1, int(num**0.5)+1):\n if not num%div: s.update({div**2, int(num/div)**2})\n summ = sum(s)\n if ((summ**0.5)//1)**2 == summ: lst.append([num, summ])\n return lst\n \n", "from math import sqrt\nfrom math import ceil\ndef list_squared(m, n):\n # your code\n final_list = []\n for x in range(m, n):\n divisors_sq = 0\n for y in range(1, ceil(sqrt(x))):\n if x % y == 0:\n divisors_sq += y**2\n if x !=1:\n divisors_sq += (x//y)**2\n if x == 1:\n divisors_sq = 1\n if round(sqrt(divisors_sq)) == sqrt(divisors_sq):\n final_list.append([x, divisors_sq])\n return final_list\n\nlist_squared(1, 250)\n", "from math import sqrt\n\ndef issquare(x):\n return sqrt(x)==int(sqrt(x))\n\ndef list_squared(m, n):\n out_list = []\n for x in range(m,n+1):\n sum_t=sum( (i**2 + (x//i)**2*(x/i!=i) ) for i in range(1,int(sqrt(x))+1) if x % i==0)\n if issquare(sum_t):\n out_list.append([x,sum_t])\n return out_list", "def gen_primes():\n D = {}\n q = 2\n while True:\n if q not in D:\n yield q\n D[q * q] = [q]\n else:\n for p in D[q]:\n D.setdefault(p + q, []).append(p)\n del D[q]\n q += 1\n\n\ndef factorize(n, primes):\n factors = []\n for p in primes:\n if p*p > n: break\n i = 0\n while n % p == 0:\n n //= p\n i+=1\n if i > 0:\n factors.append((p, i));\n if n > 1: \n factors.append((n, 1))\n return factors\n\n\ndef divisors(factors):\n div = [1]\n for (p, r) in factors:\n div = [d * p**e for d in div for e in range(r + 1)]\n return div\n\n\ndef list_squared(m, n):\n result = []\n for i in range(m, n + 1):\n sum_i = 0\n for d in divisors(factorize(i, gen_primes())):\n sum_i += d * d\n if is_sqrt(sum_i):\n result.append([i, sum_i])\n return result\n\n\ndef is_sqrt(n):\n x = n\n y = (x + 1) // 2\n while y < x:\n x = y\n y = (x + n // x) // 2\n return x * x == n\n", "def divisors_list(num):\n divisors = []\n for i in range(1,int(num**0.5)+1):\n if num % i == 0:\n divisors += [i,num/i]\n return set(divisors)\n\ndef sum_squares(nums):\n return sum(num**2 for num in nums)\n\ndef isSquarable(num):\n return (num**0.5).is_integer()\n\ndef list_squared(m, n):\n res = []\n for i in range(m,n+1):\n elems_sum = sum_squares(divisors_list(i))\n if isSquarable(elems_sum):\n res.append([i, elems_sum])\n return res", "def list_squared(m, n):\n a = []\n b = []\n for i in range(m,n):\n sum = 0\n for j in range(1,int(i**(0.5))+1):\n if i%j==0:\n sum+=j**2\n if i/j!=j:\n sum+=int(i/j)**2\n \n if (sum**(0.5)).is_integer():\n a.append(i)\n b.append(sum)\n\n return [list(i) for i in zip(a,b)]\n", "from math import sqrt,pow\nfrom functools import reduce\n\ndef list_squared(m, n):\n sqr_sum = lambda i: sum(set(reduce(list.__add__,\n ([pow(j,2), pow(i // j, 2)] for j in range(1, int(sqrt(i)) + 1) if i % j == 0))))\n return [[i, j] for i, j in zip(range(m, n + 1), map(sqr_sum, range(m, n + 1))) if sqrt(j) == int(sqrt(j))]", "import math\nsqrt = math.sqrt\n\ndef getDivisors(x):\n result = []\n i = 1\n while i*i <= x:\n if x % i == 0:\n result.append(i**2)\n if x/i != i:\n result.append((x/i)**2)\n i += 1\n return (result)\n\ndef isSquaredDivisor(n):\n squaredList = getDivisors(n)\n sumList = sum(squaredList)\n if sqrt(sumList) % 1 == 0:\n return [n,sumList]\n else:\n return 0\n\ndef list_squared(m, n):\n retList = []\n for i in range(m,n+1):\n res = isSquaredDivisor(i)\n if res != 0:\n retList.append(res)\n return retList", "from math import sqrt\n\n\ndef list_squared(m, n):\n\n def sum_divisors_squared(n):\n def divisors(n):\n for i in range(1, int(sqrt(n) + 1)):\n if n % i == 0:\n yield i\n if i*i != n:\n yield n / i\n\n return sum(i ** 2 for i in divisors(n))\n\n def is_square(n):\n return sqrt(n) % 1 == 0\n\n def gen_subarrays(m, n):\n for i in range(m, n):\n divisor_sum = sum_divisors_squared(i)\n if is_square(divisor_sum):\n yield [i, divisor_sum]\n return [subarray for subarray in gen_subarrays(m, n)]\n", "def map_sum_of_squqres(n):\n if n == 1:\n return [1,1]\n sum = 1 + n ** 2\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n sum += i ** 2\n if i != n / i:\n sum += (n/i) ** 2\n return [n, sum]\n \ndef is_square(n):\n return int(n ** 0.5) ** 2 == n\n\ndef list_squared(m, n):\n return [i for i in map(map_sum_of_squqres, range(m,n+1)) if is_square(i[1])]", "def list_squared(m, n):\n result=[]\n divisors=set()\n for i in range(m,n+1):\n a=1\n b=i/a\n divisors.clear()\n while a<=b:\n if b.is_integer():\n divisors.update((a,int(b)))\n a+=1\n b=i/a\n sqsum=sum(d**2 for d in divisors)\n if (sqsum**0.5).is_integer():\n result.append([i,sqsum])\n return result\n \n", "def list_squared(m, n):\n res = []\n pairs = [ [1, 1],\n [42, 2500],\n [246, 84100],\n [287, 84100],\n [728, 722500],\n [1434, 2856100],\n [1673, 2856100],\n [1880, 4884100],\n [4264, 24304900],\n [6237, 45024100],\n [9799, 96079204],\n [9855, 113635600]]\n for i in range(m, n + 1):\n for idx, x in enumerate(pairs):\n if i == x[0]:\n res.append(x)\n return res", "def getDivisors(num):\n res = []\n sum = 0\n for i in range(1,num+1):\n if num % i == 0:\n res.append(i)\n sum += i**2\n return (res,sum)\n\ndef list_squared(m, n):\n result = []\n nums = [1,42,246,287,728,1434,1673,1880,4264,6237,9799,9855,18330,21352,21385,24856,36531,39990,46655,57270,66815,92664]\n s = [1,2500,84100,84100,722500,2856100,2856100,4884100,24304900,45024100,96079204,113635600,488410000,607622500,488410000,825412900,1514610724,2313610000,2313610000,4747210000,4747210000,13011964900] \n for i in range(m,n+1):\n if i in nums:\n result.append([i, s[nums.index(i)]])\n return result", "import math\n\ndef list_squared(m, n):\n final = []\n for i in range(m, n+1):\n results = []\n for j in range(1, int(math.sqrt(i))+1):\n if i % j == 0:\n if int(i / j) != j:\n results.append(int(i / j) ** 2)\n results.append(j ** 2)\n summ = sum(results)\n if (math.sqrt(summ).is_integer()):\n final.append([i, summ])\n return final", "import functools\ndef list_squared(m, n):\n lista_final = []\n lst = []\n for i in range(m,n):\n dic = factors(i)\n for el in dic:\n lst.append(el**2) \n soma = sum(lst)\n numero = soma ** (0.5)\n if numero == int(numero):\n lista_final = lista_final + [[i, soma]]\n lst = []\n return lista_final\n\ndef factors(n): \n return set(functools.reduce(list.__add__, \n ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))\n \n", "import numpy as np;\nimport math;\n\ndef list_squared(m, n):\n\n validValues = [];\n\n #cycle through the values\n for testValue in range(m, n):\n divisorList = divisors(testValue);\n totalOfSquareDivisors = sum(np.power(divisorList, 2)) # NumPy again to square all\n\n #Does result have an even square root? - if so, add to the list\n if ( totalOfSquareDivisors % math.sqrt(totalOfSquareDivisors) == 0):\n validValues.append([testValue, totalOfSquareDivisors]);\n\n return validValues;\n\n# Use NumPy to determine the valid divisors\ndef divisors(n):\n r = np.arange(1, int(n ** 0.5) + 1)\n x = r[np.mod(n, r) == 0]\n result = set(np.concatenate((x, n / x), axis=None))\n return [int(i) for i in result] # Casts back to integer\n", "def list_squared(m, n):\n all = []\n for x in range(m, n):\n divisors = [i for i in range(1, int(x**0.5)+1) if x%i==0]\n divisors += [int(x/d) for d in divisors if x/d > x**0.5]\n sumExp = sum(d**2 for d in divisors)\n if sumExp**0.5%1==0:\n all.extend([[x,sumExp]])\n return all", "def list_squared(m, n):\n pool, sums = range(m, n), []\n\n for number in pool:\n # This way of calculating the divisors saves a lot of time\n divisors = [x for x in range(1, int(number**0.5 + 1)) if not number%x] \n divisors += [number/x for x in divisors if x != number/x] \n sums.append([number, sum([x**2 for x in divisors])])\n\n return [x for x in sums if x[1]**0.5 == int(x[1]**0.5)]", "import math\n \ndef list_squared(m, n):\n res = []\n for num in range(m, n):\n add = 0\n for i in range(1, math.ceil(math.sqrt(num))):\n if num % i == 0:\n add += i**2 + (num//i)**2\n if math.sqrt(num).is_integer():\n add += num \n if math.sqrt(add).is_integer():\n res.append([num, add]) \n return res\n", "import math\n\ndef divisors(n):\n for i in range(1, int(math.sqrt(n) + 1)):\n if n % i == 0:\n yield i\n if i*i != n:\n yield n/i\n\ndef list_squared(m, n):\n ret = []\n for i in range(m, n+1):\n div_sum = sum([j**2 for j in divisors(i)])\n if math.sqrt(div_sum).is_integer():\n ret.append([i, div_sum])\n return ret\n", "import math\n\ndef suma(i):\n return sum(x**2 + (i//x)**2 for x in range(1, math.ceil(i**0.5)) if not i%x) + (i if (i**0.5).is_integer() else 0)\n\ndef list_squared(m, n):\n return [[i, suma(i)] for i in range(m, n+1) if (suma(i)**0.5).is_integer()]", "import math\n\ndef list_squared(m, n):\n divs = []\n answer = []\n for x in range(m,n):\n divs = [1]\n for y in range(2,int(math.sqrt(x))+1):\n if x % y == 0 and math.sqrt(x) != y:\n divs.extend([y**2, int((x/y)**2)])\n if x != 1: divs.append((x*x))\n z = sum(divs) \n if math.sqrt(z) % 1 == 0: answer.append([x,z])\n return answer\n", "CACHE = [[i,sum([x**2 for x in range(1,i+1) if not(i%x)])] for i in range(1,10000) if sum([x**2 for x in range(1,i+1) if not(i%x)])**0.5 % 1 == 0]\n\ndef list_squared(m, n):\n return [e for e in CACHE if m <= e[0] <= n]", "def list_squared(m, n):\n squares = []\n for i in range(m, n):\n total = sum(get_divisors_sqrd(i))\n if (total ** (1/2)).is_integer():\n squares.append([i, total])\n return squares\n \ndef get_divisors_sqrd(n):\n divisors = []\n for i in range(1, int(n ** (1/2)) + 1):\n if n % i == 0:\n if i ** 2 not in divisors:\n divisors.append(i ** 2)\n if int(n/i) ** 2 not in divisors:\n divisors.append(int(n / i) ** 2)\n return divisors\n", "from math import sqrt\n\ndef sum_square_divisors(n):\n res = 0\n nn = n * n\n # odds have only odd divisors\n for i in range(1, int(sqrt(n)) + 1, n % 2 + 1):\n if n % i == 0:\n ii = i * i\n res += ii\n if ii != n:\n res += nn // ii\n return res\n\ndef list_squared(m, n):\n res = []\n for i in range(m, n + 1):\n sds = sum_square_divisors(i)\n r = int(sqrt(sds))\n if r * r == sds:\n res.append([i, sds])\n return res\n", "def list_squared(m, n, cache={}):\n get = range(m,n+1)\n check = set(get) - set(cache.keys())\n for y in check:\n sqr = sum(x**2 for x in range(1, y+1) if not y%x)\n root = sqr**.5\n cache[y] = None\n if root == int(root):\n cache[y] = sqr\n result = list([k,cache[k]] for k in get if cache[k])\n return result", "from collections import Counter\nfrom functools import reduce\nfrom operator import mul\nfrom random import randrange,randint\n\ndef primesbelow(n):\n c=n%6>1\n n={0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6]\n s=[True]*(n//3)\n s[0]=False\n for i in range(int(n**0.5)//3+1):\n if s[i]:\n k=(3*i+1)|1\n s[k*k//3::2*k]=[False]*((n//6-(k*k)//6-1)//k+1)\n s[(k*k+4*k-2*k*(i%2))//3::2*k]=[False]*((n//6-(k*k+4*k-2*k*(i%2))//6-1)//k+1)\n return [2,3]+[(3*i+1)|1 for i in range(1,n//3-c) if s[i]]\n\nmedsize=100000\nmedprimes=set(primesbelow(medsize))\nsmallprimes=sorted(p for p in medprimes if p<1000)\n\ndef isprime(n,precision=7):\n if n<1:\n return False\n elif n<=3:\n return n>=2\n elif n%2==0:\n return False\n elif n<medsize:\n return n in medprimes\n d=n-1\n s=0\n while d%2==0:\n d//=2\n s+=1\n for repeat in range(precision):\n a=randrange(2,n-2)\n x=pow(a,d,n)\n if x==1 or x==n-1: continue\n for r in range(s-1):\n x=pow(x,2,n)\n if x==1: return False\n if x==n-1: break\n else: return False\n return True\n\ndef pollard_brent(n):\n if n%2==0: return 2\n if n%3==0: return 3\n y,c,m=randint(1,n-1),randint(1,n-1),randint(1,n-1)\n g,r,q=1,1,1\n while g==1:\n x=y\n for i in range(r): y=(pow(y,2,n)+c)%n\n k=0\n while k<r and g==1:\n ys=y\n for i in range(min(m,r-k)):\n y=(pow(y,2,n)+c)%n\n q=q*abs(x-y)%n\n g=gcd(q,n)\n k+=m\n r*=2\n if g==n:\n while True:\n ys=(pow(ys,2,n)+c)%n\n g=gcd(abs(x-ys),n)\n if g>1: break\n return g\n\ndef primefactors(n):\n fs=[]\n for c in smallprimes:\n while n%c==0:\n fs.append(c)\n n//=c\n if c>n: break\n if n<2: return fs\n while n>1:\n if isprime(n):\n fs.append(n)\n break\n f=pollard_brent(n)\n fs.extend(primefactors(f))\n n//=f\n return fs\n\ndef factorization(n):\n return Counter(primefactors(n))\n\ndef ssd(n):\n return reduce(mul,((p**(2*e+2)-1)//(p*p-1) for p,e in factorization(n).items()),1)\n\ndef list_squared(m,n):\n return [a for a in ([x,ssd(x)] for x in range(m,n+1)) if (a[1]**0.5).is_integer()]", "import numpy as np\n\n \ndef binary_check(x):\n if x == 1: return True\n start = 0\n stop = x//2\n sol = []\n while start <= stop:\n mid = (start+stop) // 2\n \n if mid*mid == x:\n return True\n if mid*mid < x:\n start = mid + 1\n if mid*mid > x:\n stop = mid - 1\n\nimport collections\nimport itertools\n\n\ndef prime_factors(n):\n i = 2\n while i * i <= n:\n if n % i == 0:\n n /= i\n yield i\n else:\n i += 1\n\n if n > 1:\n yield n\n\n\ndef prod(iterable):\n result = 1\n for i in iterable:\n result *= i\n return result\n\n\ndef get_divisors(n):\n pf = prime_factors(n)\n\n pf_with_multiplicity = collections.Counter(pf)\n\n powers = [\n [factor ** i for i in range(count + 1)]\n for factor, count in list(pf_with_multiplicity.items())\n ]\n\n for prime_power_combo in itertools.product(*powers):\n yield prod(prime_power_combo)\n \ndef list_squared(m, n):\n sol = []\n \n for number in range(m,n):\n candidate = [i**2 for i in range(1,number+2) if number % i == 0]\n n = sum(candidate)\n if binary_check(n):\n sol.append([number,n])\n return sol\n\n\ndef list_squared(m, n):\n sol = []\n for number in range(m,n):\n candidate = [i*i for i in get_divisors(number)]\n n=int(sum(candidate))\n if binary_check(n):\n sol.append([number,n])\n return sol\n", "def list_squared(m, n):\n result = []\n for i in range(m, n + 1):\n# b = 0\n # \u5f00\u6839\u65b9\u6b21\u5faa\u73af\n a = sum(let * let + (i / let) * (i / let) for let in range(1, int(i ** 0.5) + 1) if i % let == 0)\n \n # \u5982\u679c\u672c\u8eab\u80fd\u88ab\u5f00\u6839\u65b9\uff0c\u5219\u51cf\u53bb\uff0c\u56e0\u4e3a\u5faa\u73af\u6c42\u548c\u65f6\u591a\u7b97\u4e86\u4e00\u6b21\n if (i ** 0.5) % 1 == 0:\n a = a - (i ** 0.5) * (i ** 0.5)\n\n if (a ** 0.5) % 1 == 0:\n result.append([i, int(a)])\n return result \n# r=[]\n# for i in range(m,n+1):\n# for x in range(1,int(i**0.5)+1):\n# if i%x==0:\n# a=sum([x*x+(i/x)*(i/x)])\n# if (i ** 0.5) % 1 == 0:\n# a = a - (i ** 0.5) * (i ** 0.5)\n\n# if (a ** 0.5) % 1 == 0:\n# r.append([i, int(a)])\n# return r \n", "def list_squared(m, n):\n result = []\n for i in range(m, n + 1):\n b = 0\n# for x in range(1,int(i**0.5)+1):\n# if i%x==0:\n# a=sum(x*x+(i/x)*(i/x))\n \n a = sum(let * let + (i / let) * (i / let) for let in range(1, int(i ** 0.5) + 1) if i % let == 0)\n\n if (i ** 0.5) % 1 == 0:\n a = a - (i ** 0.5) * (i ** 0.5)\n\n if (a ** 0.5) % 1 == 0:\n result.append([i, int(a)])\n return result \n", "import math\n\ndef divisorGenerator(n):\n large_divisors = []\n for i in range(1, int(math.sqrt(n) + 1)):\n if n % i == 0:\n yield i\n if i*i != n:\n large_divisors.append(n / i)\n for divisor in reversed(large_divisors):\n yield divisor\n\ndef is_square(n):\n if n == 0:return True\n if n == 1:return True\n x = n // 2\n seen = set([x])\n while x * x != n:\n x = (x + (n // x)) // 2\n if x in seen: return False\n seen.add(x)\n return True\n\ndef list_squared(m, n):\n out = []\n for a in range(m, n+1):\n divisor_sum = sum(int(r*r) for r in list(divisorGenerator(a)))\n if is_square(divisor_sum):\n out.append([a, divisor_sum])\n return out\n", "import math\n\ndef list_squared(m, n):\n print(f\"m: {m}, n: {n}\", flush=True)\n biglips = []\n for i in range(m,n):\n if i > 2000 and i < 4000:\n i = 4000\n max = i+1\n factors = []\n counter = 1\n while counter < max:\n if i % counter == 0:\n factors.append(counter)\n max = int(i/counter)\n if max != counter:\n factors.append(max)\n else:\n max -= 1\n counter += 1\n #factors = [i ** 2 for i in factors]\n factors = list(map(lambda x: x ** 2, factors))\n sumOf = sum(factors)\n root = math.sqrt(sumOf)\n if sumOf == int(root + 0.5) ** 2:\n biglips.append([i,sumOf])\n \n print(biglips)\n return biglips\n ", "import math\n\ndef list_squared(m, n):\n result = []\n for i in range(m, n + 1):\n divisors = set()\n for j in range(1, int(math.sqrt(i)+1)):\n if i % j == 0:\n divisors.add(j**2)\n divisors.add(int(i/j)**2)\n summa = sum(divisors)\n if (summa ** 0.5).is_integer():\n result.append([i, summa])\n return result", "import math\ndef list_squared(m, n):\n final = []\n for i in range(m,n):\n #find sum of squared divisiors\n divisors = find_divisors(i)\n sum_sqrd = sum([d*d for d in divisors])\n if math.sqrt(sum_sqrd).is_integer():\n final.append([i, sum_sqrd])\n \n return final\n\n\ndef find_divisors(x):\n i = 1\n divisors = []\n while i <= math.sqrt(x):\n if x % i == 0:\n if x / i == i:\n divisors.append(i)\n else:\n divisors.append(i)\n divisors.append(int(x/i))\n \n i += 1\n divisors.sort()\n return divisors", "def list_squared(m, n):\n ans = []\n sum = 0\n for i in range(m,n+1):\n sq = int(i ** 0.5)\n if sq > 1 and sq == (i ** 0.5):\n sq -= 1\n for j in range(1,sq+1):\n if i % j == 0:\n if j != int(i/j):\n sum += (j ** 2)+(int(i/j) **2)\n else:\n sum += (j ** 2)\n if sum > 0 and (sum ** 0.5) % 1 == 0:\n ans.append([i, sum])\n sum = 0\n return ans\n", "import math\n\ndef get_divisors(n):\n i = 1\n result = []\n while i <= math.sqrt(n):\n if (n % i == 0):\n if (n / i == i):\n result.append(i)\n else:\n result += [i, n/i]\n i += 1\n return result\n\ndef get_squared(n):\n return [x*x for x in n]\n\ndef list_squared(m, n):\n pairs = [[x, sum(get_squared(get_divisors(x)))] for x in range(m, n+1)]\n return list([x for x in pairs if math.sqrt(x[1]) % 1 == 0])\n", "import math\n\ndef squareDivisors(n) : \n list_divisors = []\n i = 1\n while i <= math.sqrt(n): \n if (n % i == 0) : \n # If divisors are equal, print only one \n if (n / i == i) : \n list_divisors.append(i**2) \n else : \n # Otherwise print both \n list_divisors.extend([i**2,(n//i)**2])\n i = i + 1\n return list_divisors\n\ndef list_squared(m, n):\n return [[i,sum(squareDivisors(i))] for i in range(m,n+1) if math.sqrt(sum(squareDivisors(i))).is_integer()]\n", "from math import sqrt\n\ndef sumsqrdivs(x):\n divs = []\n for i in range(1, int(sqrt(x)+1)):\n if x%i == 0 :\n divs.append(i)\n if i**2 != x :\n divs.append(int(x/i))\n return sum(div**2 for div in divs)\n\ndef list_squared(m, n):\n return [[i, sumsqrdivs(i)] for i in range(m, n+1) if sqrt(sumsqrdivs(i)).is_integer()]", "def factors(n):\n return set([f for i in range(1, int(n**0.5)+1) if n % i == 0 for f in [i, n//i]])\n\ndef list_squared(m, n):\n ans = []\n for i in range(m, n):\n sum_of_squares = sum(map(lambda x: x**2, factors(i)))\n if (sum_of_squares ** 0.5) % 1 == 0:\n ans.append([i, sum_of_squares])\n return ans", "import math\ndef list_squared(m, n):\n p = []\n for x in range(m, n+1):\n ds = sum(y**2 + (x/y)**2 for y in range(2,math.ceil(math.sqrt(x))) if x%y == 0) + x**2\n if x > 1:\n ds += 1\n if x%math.sqrt(x) == 0:\n ds += x\n if math.sqrt(ds).is_integer():\n p = p + [[x, ds]]\n return p", "import numpy as np\ndef list_squared(m, n):\n res = []\n for i in range(m, n+1):\n factor = []\n for k in range(1, int(i ** (1/2)) +1):\n if i % k == 0:\n if k != i//k:\n factor = factor + [k, i//k]\n else:\n factor = factor + [k]\n arr = np.array(factor)\n total = sum(arr ** 2)\n if total == int(total ** (1/2)) ** 2:\n res.append([i, total])\n return res", "def memoize(f):\n memo = {}\n def helper(*args):\n if args not in memo:\n memo[args] = f(*args)\n return memo[args]\n return helper\n\n@memoize\ndef sum_of_squares(n):\n squares = [x**2 for x in range(1, n+1) if n % x == 0]\n return sum(squares)\n\ndef list_squared(m, n):\n result = []\n for i in range(m, n):\n sums = sum_of_squares(i)\n if sums > 0 and sums**0.5 % 1 == 0:\n result.append([i, sums])\n return result\n", "def list_squared(m, n):\n result = []\n for i in range(m, n + 1):\n a = sum(x * x + (i / x) * (i / x) for x in range(1, int(i ** 0.5) + 1) if i % x == 0)\n \n if (i ** 0.5) % 1 == 0:\n a = a - (i ** 0.5) * (i ** 0.5)\n\n if (a ** 0.5) % 1 == 0:\n result.append([i, int(a)])\n return result ", "import math\ndef div(n):\n i = 1\n l = []\n m = []\n while i <= math.sqrt(n):\n if (n % i == 0):\n if (n / i == i):\n l.append(i)\n m.append(i ** 2)\n else:\n l.append(i)\n l.append(n // i)\n m.append(i ** 2)\n m.append((n // i) ** 2)\n i = i + 1\n if math.sqrt(sum(m)).is_integer():\n return [n, sum(m)]\n pass\ndef list_squared(m, n):\n b = []\n for j in range(m, n):\n if div(j):\n b.append(div(j))\n return b", "results = [[1, 1], [42, 2500], [246, 84100], [287, 84100], [728, 722500], [1434, 2856100], [1673, 2856100], [1880, 4884100], [4264, 24304900], [6237, 45024100], [9799, 96079204], [9855, 113635600]]\ndef list_squared(m, n):\n result = []\n i = 0;\n while i < len(results) and results[i][0] < n:\n if results[i][0] >= m and results[i][0] <= n:\n result.append(results[i])\n i += 1\n return result", "import math\n\ndef list_squared(m, n):\n result = []\n for x in range(m, n):\n divisors = make_divisors(x)\n squared_list = list(map(square, divisors))\n total = sum(squared_list)\n if math.sqrt(total).is_integer():\n result.append([x, total])\n return result\n \n \ndef square(n):\n return n * n\n \ndef make_divisors(n):\n lower_divisors , upper_divisors = [], []\n i = 1\n while i*i <= n:\n if n % i == 0:\n lower_divisors.append(i)\n if i != n // i:\n upper_divisors.append(n//i)\n i += 1\n return lower_divisors + upper_divisors[::-1]", "from math import *\ndef list_squared(m, n):\n def factors(x):\n lst = []\n for i in range(1, int(sqrt(x) + 1)):\n if x % i == 0:\n lst.append(i)\n if x != i ** 2:\n lst.append(x / i)\n return sum([k ** 2 for k in lst])\n return [[j, factors(j)] for j in range(m, n + 1) if sqrt(factors(j)) % 1 == 0] ", "from math import sqrt, pow\n\ndef list_divisors(n):\n s = set()\n i = 1\n while i <= sqrt(n):\n if i in s:\n continue\n div, mod = divmod(n, i)\n if (mod == 0) : \n s.add(i)\n if (div != i): \n s.add(div)\n i = i + 1\n \n return sorted(list(s))\n\n\ndef list_squared(m, n):\n result = []\n for i in range(m, n + 1):\n divs_sum = sum(pow(d, 2) for d in list_divisors(i))\n if sqrt(divs_sum).is_integer():\n result.append([i, divs_sum])\n return result\n \n", "def divisors(n):\n divs = []\n for x in range(1, int(n**0.5)+1): \n if n % x == 0:\n divs.extend([x**2, (n//x)**2])\n return sum(set(divs)) \n \ndef list_squared(start, stop):\n squares = []\n for x in range(start, stop+1):\n x_sum = divisors(x)\n if int(x_sum**0.5) **2 == x_sum: \n squares.append([x, x_sum])\n\n return squares\n", "from math import sqrt\nfrom functools import reduce\n\nCACHE = {}\n\ndef get_divisors_gen(number):\n if number in CACHE:\n return CACHE[number]\n \n divisors = []\n for i in range(1, int(number / 2) + 1):\n if number % i == 0:\n divisors.append(i)\n divisors.append(number)\n\n CACHE[number] = divisors\n \n return divisors\n \n\ndef list_squared(m, n):\n result = []\n for number in range(m, n+1):\n div_sq_sum = reduce(\n lambda acc, item: acc + item**2,\n get_divisors_gen(number)\n )\n if sqrt(div_sq_sum).is_integer():\n result.append([number, div_sq_sum])\n return result", "from functools import reduce\n\ndef factors(n): \n return set(reduce(list.__add__, \n ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))\n\ndef list_squared(m, n):\n ans = []\n \n for i in range(m,n):\n factor_sum = 0\n factor_ans = []\n \n for j in factors(i):\n factor_sum += j**2\n \n if (factor_sum**0.5).is_integer():\n factor_ans.append(i)\n factor_ans.append(factor_sum)\n ans.append(factor_ans)\n return ans\n \n \n \n \n \n \n \n \n \n", "def list_squared(m, n):\n # your code \n import numpy as np\n # find the divisors all together with array operarions instead of for loop (TOO SLOW!)\n def find_divisor_square(n):\n arr = np.arange(1,n+1)\n arr = n/arr\n divs = arr[arr == arr.astype(int)]\n return divs**2\n \n res = []\n for num in range(m,n):\n divs = find_divisor_square(num)\n sum_squres = divs.sum()\n if (sum_squres**0.5).is_integer(): # checks whether a float obj is an integer\n res.append([num, sum_squres])\n return res\n", "import math\n\ndef list_squared(m, n):\n result = []\n for number in range(m, n):\n divisors = []\n for div in range(1, int(math.sqrt(number) + 1)):\n if number % div == 0:\n divisors.append(div)\n upper_divisors = [int(number / i) for i in divisors if i*i != number]\n divisors.extend(upper_divisors[::-1])\n div_sum = sum([i**2 for i in divisors])\n if math.sqrt(div_sum).is_integer():\n result.append([number, div_sum])\n return result", "CACHE = {}\n\ndef squared_cache(number):\n if number not in CACHE:\n divisors = [x for x in range(1, round(number/2) + 1) if number % x == 0]\n CACHE[number] = sum([x * x for x in divisors]) + number ** 2\n return CACHE[number] \n \n return CACHE[number]\n\ndef list_squared(m, n):\n ret = []\n\n for number in range(m, n + 1):\n divisors_sum = squared_cache(number)\n if (divisors_sum ** 0.5).is_integer():\n ret.append([number, divisors_sum])\n\n return ret", "def list_squared(m, n):\n squared_divisors = []\n for i in range(m, n + 1):\n if i == 1:\n div = [1]\n else:\n div = [j for j in range(1, int(i**0.5) + 1) if i % j == 0 for j in (j, i//j) if i/j != j]\n tot = sum(k*k for k in div)**0.5\n if tot == int(tot):\n squared_divisors.append([i, int(tot**2)])\n return squared_divisors\n", "from math import sqrt\n\ndef list_squared(m, n):\n squares = []\n # Find all divisors\n for i in range(m,n):\n i_squares = 0\n for j in range(1,int(sqrt(i)//1)+1):\n if i%j == 0:\n i_squares += j**2\n if i//j != j:\n i_squares += (i//j)**2\n if i_squares%sqrt(i_squares) == 0 and i_squares/sqrt(i_squares) == sqrt(i_squares):\n squares.append([i,i_squares])\n return squares", "from functools import reduce\n\ndef factors(n): \n return set(reduce(list.__add__, \n ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))\n\ndef list_squared(m, n):\n result = []\n \n for i in range(m, n+1):\n factors_sq = [x**2 for x in factors(i)]\n sum_factors = sum(factors_sq)\n sum_factors_root = sum_factors ** 0.5\n if sum_factors_root == int(sum_factors_root):\n result.append([i, sum_factors])\n \n return result\n \n", "cache = {}\n\ndef sum_cache(n):\n if n not in cache:\n divs = [i for i in range(1, n+1) if n % i == 0]\n cache[n] = sum([x*x for x in divs])\n return cache[n]\n return cache[n]\n\n\ndef list_squared(m, n):\n # your code\n \n result = []\n for j in range(m, n+1):\n summ = sum_cache(j)\n if (summ ** 0.5).is_integer():\n result.append([j, summ])\n\n return result", "import math\n\ndef get_factors(m, n):\n cache = dict()\n for i in range(m, n + 1):\n factors = (j for j in range(1, 1 + i) if i % j == 0)\n total_sum = sum(j * j for j in factors)\n if math.sqrt(total_sum) % 1 == 0.:\n cache[i] = total_sum\n return cache\n \n \nFACTORS = get_factors(1, 10000)\n\ndef list_squared(m, n):\n return [[i, FACTORS[i]] for i in range(m, n + 1) if i in FACTORS]\n", "def list_squared(m, n):\n answer = []\n for i in range(m, n+1):\n root = sumSquares(factors(i)) ** 0.5\n if root == round(root):\n answer.append([i, int(root ** 2)])\n return answer\n \n# def factors(x):\n# factorsList = []\n# for i in range(1, x // 2 +1):\n# if x % i == 0:\n# factorsList.append(i)\n# factorsList.append(x)\n# return factorsList\n \nfrom functools import reduce\n \ndef factors(n): \n return set(reduce(list.__add__, \n ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))\n \ndef sumSquares(l):\n return sum(i ** 2 for i in l)", "def list_squared(m, n):\n answer = []\n for i in range(m, n+1):\n root = sumSquares(factors(i)) ** 0.5\n if root == round(root):\n answer.append([i, int(root ** 2)])\n return answer\n\nfrom functools import reduce\n\ndef factors(n): \n return set(reduce(list.__add__, \n ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))\n\ndef sumSquares(l):\n return sum(i ** 2 for i in l)"]
{"fn_name": "list_squared", "inputs": [[1, 250], [42, 250], [250, 500], [300, 600], [600, 1500], [1500, 1800], [1800, 2000], [2000, 2200], [2200, 5000], [5000, 10000]], "outputs": [[[[1, 1], [42, 2500], [246, 84100]]], [[[42, 2500], [246, 84100]]], [[[287, 84100]]], [[]], [[[728, 722500], [1434, 2856100]]], [[[1673, 2856100]]], [[[1880, 4884100]]], [[]], [[[4264, 24304900]]], [[[6237, 45024100], [9799, 96079204], [9855, 113635600]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
48,829
def list_squared(m, n):
b12e235bc69cf2946f7fdd00839a7cfa
UNKNOWN
Your task is to remove all duplicate words from a string, leaving only single (first) words entries. Example: Input: 'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta' Output: 'alpha beta gamma delta'
["def remove_duplicate_words(s):\n return ' '.join(dict.fromkeys(s.split()))", "def remove_duplicate_words(s):\n s = s.split(\" \")\n words = []\n for item in s:\n if item not in words:\n words.append(item)\n return \" \".join(words)\n", "def remove_duplicate_words(s):\n return ' '.join(sorted(set(s.split()), key = s.index))", "def remove_duplicate_words(s):\n a=[]\n [a.append(v) for v in s.split(\" \") if v not in a]\n return str(\" \").join(a)", "def remove_duplicate_words(s):\n def f():\n seen = set()\n for word in s.split():\n if word in seen:\n continue\n seen.add(word)\n yield word\n return ' '.join(f())", "from collections import OrderedDict\nremove_duplicate_words=lambda s:' '.join(OrderedDict.fromkeys(s.split(' ')))\n", "def remove_duplicate_words(s):\n new_list = []\n for word in s.split():\n if word not in new_list:\n new_list.append(word)\n return \" \".join(new_list)", "d = {}\nremove_duplicate_words = lambda s: \" \".join(d.setdefault(w, w) for w in s.split() if w not in d)", "remove_duplicate_words=lambda s:(lambda x:' '.join(e for i,e in enumerate(x)if e not in x[:i]))(s.split())", "def remove_duplicate_words(s):\n return ' '.join({i:0 for i in s.split()})", "def remove_duplicate_words(s):\n res = {}\n for i,n in enumerate(s.split()):\n if n not in res:\n res[n] = i\n \n return ' '.join(sorted(res, key=res.get))", "def remove_duplicate_words(s):\n return ' '.join(((s.split())[i] for i in range(len(s.split())) if (s.split())[i] not in (s.split())[0:i]))", "def remove_duplicate_words(s):\n present = []\n for word in s.split(\" \"):\n if word not in present: present.append(word)\n return \" \".join(present)", "def remove_duplicate_words(s):\n seen = set()\n result = []\n for word in list(s.split(\" \")):\n if word not in seen:\n seen.add(word)\n result.append(word)\n return \" \".join(result)", "def remove_duplicate_words(s):\n l = s.split()\n words = []\n for elt in l:\n if elt not in words:\n words.append(elt)\n return \" \".join(words)", "def remove_duplicate_words(s):\n s_list = s.split()\n new_list = []\n for word in s_list:\n if word not in new_list:\n new_list.append(word)\n return ' '.join(new_list)", "def remove_duplicate_words(s):\n s = s.split()\n unique = []\n for word in s:\n if word not in unique:\n unique.append(word)\n s = ' '.join(unique)\n\n\n return s", "def remove_duplicate_words(s):\n final = []\n for s in s.split():\n if s not in final:\n final.append(s)\n return ' '.join(final)", "def remove_duplicate_words(s):\n tot = []\n for i in s.split():\n if i not in tot:\n tot.append(i)\n return ' '.join(tot)\n \n return ' '.join(tot)", "from functools import reduce\ndef remove_duplicate_words(s):\n return ' '.join(reduce(lambda l, x: l+[x] if x not in l else l, s.split(' '), []))", "def remove_duplicate_words(s):\n arr = s.split()\n arr1 = []\n for el in arr:\n if not el in arr1:\n arr1.append(el)\n return \" \".join(arr1)\n", "def remove_duplicate_words(s):\n ss=list(set(s.split()))\n ss.sort(key=s.index)\n return ' '.join(ss)", "def remove_duplicate_words(s):\n o = []\n x = s.split()\n for y in x:\n if(y not in o):\n o.append(y)\n return ' '.join(o)", "def remove_duplicate_words(s):\n result = []\n [result.append(w) for w in s.split(' ') if not w in result]\n return ' '.join([x for x in result])", "remove_duplicate_words = lambda s:\" \".join(dict.fromkeys(s.split()))", "def remove_duplicate_words(s):\n a = []\n for i in s.split():\n if i not in a:\n a.append(i)\n return \" \".join(a)", "def remove_duplicate_words(s):\n array = s.split()\n output = []\n for word in array:\n if word not in output:\n output.append(word)\n return ' '.join(output)", "def remove_duplicate_words(s):\n result_list = []\n for word in s.split():\n if word not in result_list:\n result_list.append(word)\n return ' '.join(result_list)\n", "def remove_duplicate_words(s):\n my_set = []\n for word in s.split(\" \"):\n try:\n my_set.index(word)\n except ValueError:\n my_set.append(word)\n return \" \".join(my_set)", "def remove_duplicate_words(s):\n already = []\n for i in s.split():\n if i in already:\n continue\n if i not in already:\n already.append(i)\n return ' '.join(already)\n", "def remove_duplicate_words(s):\n output = []\n s = s.split()\n for word in s:\n if word not in output:\n output.append(word)\n return \" \".join(output)", "def remove_duplicate_words(s):\n d=s.split()\n d=list(dict.fromkeys(d))\n print(d)\n anwser = \" \".join(d)\n return anwser", "def remove_duplicate_words(s):\n lt = []\n for i in s.split():\n if i not in lt:\n lt.append(i)\n return \" \".join(lt)", "from functools import reduce\n\ndef remove_duplicate_words(s):\n return reduce(lambda res, curr: res if curr in res else res + ' ' + curr, s.split(), '').lstrip()", "def remove_duplicate_words(s):\n removed = s.split()\n newlist = []\n for i in removed:\n if(i not in newlist):\n newlist.append(i)\n newstring = \" \".join(newlist)\n return newstring\n \n\n", "def remove_duplicate_words(s):\n arr=s.split()\n new=[]\n for i in arr:\n if i not in new:\n new.append(i)\n return \" \".join(new)", "def remove_duplicate_words(s):\n arr = s.split()\n res_list = []\n for elem in arr:\n if not elem in res_list:\n res_list.append(elem)\n return \" \".join(res_list)", "def remove_duplicate_words(s):\n arr = s.split()\n new_arr = []\n for el in arr:\n if not el in new_arr:\n new_arr.append(el)\n return ' '.join(new_arr)\n \n \n", "def remove_duplicate_words(s):\n \n l = []\n \n for i in s.split():\n if not i in l:\n l.append(i)\n else:\n pass\n return ' '.join(l)", "def remove_duplicate_words(s):\n split = s.split(' ')\n end = []\n for word in split: \n if word in end:\n continue;\n end.append(word)\n return ' '.join(end)\n", "def remove_duplicate_words(s):\n single=[]\n for x in s.split():\n if x not in single:\n single.append(x)\n return ' '.join(single)\n", "def remove_duplicate_words(s):\n lst = s.split()\n lst_new = []\n for i in lst:\n if i not in lst_new:\n lst_new.append(i)\n \n \n return ' '.join(lst_new)", "def remove_duplicate_words(s):\n s_list = s.split()\n result_list = []\n \n for word in s_list:\n if word not in result_list:\n result_list.append(word)\n \n return \" \".join(result_list)", "def remove_duplicate_words(s):\n cadena = s.split()\n cadena2 = []\n cadena3 = \" \"\n for i in cadena:\n if i in cadena2:\n pass\n else:\n cadena2.append(i)\n cadena3 = cadena3.join(cadena2)\n return cadena3", "def remove_duplicate_words(s):\n new = ''\n sSplit = s.split(' ')\n print(sSplit)\n for i in sSplit:\n if i not in new:\n new += i + \" \"\n\n return new.rstrip()", "def remove_duplicate_words(s):\n s = s.split(' ')\n a = ''\n for x in range(len(s)):\n if s[x] not in a:\n a += s[x]+' '\n return a[:-1]", "def remove_duplicate_words(s):\n x=[s for s in s.split()]\n ans=[]\n for y in x:\n if y not in ans:\n ans.append(y)\n return \"\".join( x +\" \" for x in ans)[:-1]", "def remove_duplicate_words(s):\n list_of_words = s.split()\n compressed = []\n for word in list_of_words:\n if word not in compressed:\n compressed.append(word)\n else:\n pass\n\n compressed_to_string = ' '.join(compressed)\n return compressed_to_string", "def remove_duplicate_words(s):\n string = []\n for i in s.split():\n if i not in string:\n string.append(i)\n return ' '.join(string)", "#Non-regex solution\n\ndef remove_duplicate_words(sentence):\n lst=[sentence][0].split() #split sentence by words and turn into list\n \n no_dbls=list(dict.fromkeys(lst)) #remove doubles from list\n \n return (' '.join(no_dbls)) #turn list back to sentence", "def remove_duplicate_words(s):\n output = []\n for word in s.split():\n if not word in output: output.append(word)\n return ' '.join(output)", "def remove_duplicate_words(x):\n y = []\n for i in x.split():\n if i in y:\n pass\n else:\n y.append(i)\n \n return ' '.join(y)", "def remove_duplicate_words(s):\n no_dup = []\n no_dup1 = []\n for c in s.split(' '):\n if c not in no_dup:\n no_dup.append(c)\n else:\n no_dup1.append(c)\n return ' '.join(no_dup)", "def remove_duplicate_words(s):\n return ' '.join(i for loop, i in enumerate(s.split()) if s.split().index(i) == loop)", "def remove_duplicate_words(s):\n words = s.split()\n new_list = []\n for i in words:\n if i not in new_list:\n new_list.append(i)\n new_list = \" \".join(new_list) \n return new_list\n", "def remove_duplicate_words(s):\n return \" \".join(list({x:1 for x in s.split(' ')}))", "def remove_duplicate_words(s):\n split = s.split()\n newL = []\n for i in split:\n if i not in newL:\n newL.append(i)\n \n return ' '.join(newL)", "def remove_duplicate_words(s):\n seperated = s.split()\n mylist = list( dict.fromkeys(seperated))\n return ' '.join(mylist)", "def remove_duplicate_words(s):\n s1 = s.split()\n return ' '.join([s1[i] for i in range(len(s1)) if s1[i] not in s1[:i]])", "from collections import Counter\ndef remove_duplicate_words(strr):\n input = strr.split(\" \") \n for i in range(0, len(input)): \n input[i] = \"\".join(input[i]) \n UniqW = Counter(input) \n s = \" \".join(UniqW.keys()) \n return s", "def remove_duplicate_words(s):\n undupped = []\n for i in s.split():\n if i not in undupped:\n undupped.append(i)\n return ' '.join(undupped)", "\ndef remove_duplicate_words(s):\n words = set()\n stree = \"\"\n for word in s.split():\n if word not in words:\n stree += word + \" \"\n words.add(word)\n return stree[0:-1]", "def remove_duplicate_words(s):\n seen = set()\n words = []\n for word in s.split(\" \"):\n if word not in seen:\n seen.add(word)\n words.append(word)\n return \" \".join(words)\n", "def remove_duplicate_words(s):\n result = []\n s = s.split(' ')\n for i, word in enumerate(s):\n if word not in result:\n result.append(word)\n else:\n pass\n return ' '.join(result)", "def remove_duplicate_words(s):\n s=s.split()\n m=[]\n for i in s:\n if i not in m:\n m.append(i)\n return \" \".join(m)", "def remove_duplicate_words(str):\n l=str.split()\n s=[]\n r=[]\n for i in range(len(l)):\n if l[i] not in s:\n s.append(l[i])\n r.append(l[i])\n satr = ' '.join([elem for elem in r])\n return satr ", "from collections import OrderedDict\nfrom collections import Counter\ndef remove_duplicate_words(s):\n s=s.split(\" \")\n s = OrderedDict.fromkeys(s)\n return \" \".join(s)", "from collections import OrderedDict\ndef remove_duplicate_words(s):\n spliter = s.split()\n return \" \".join(OrderedDict.fromkeys(spliter))\n", "def remove_duplicate_words(s):\n d = dict((i,s.split(' ').count(i)) for i in s.split(' '))\n return ' '.join(d.keys())", "def remove_duplicate_words(s):\n \n z = []\n s = s.split()\n \n for i in s:\n if i not in z:\n z.append(i)\n \n return \" \".join(z)", "def remove_duplicate_words(s):\n s1 = []\n [s1.append(x) for x in s.split() if x not in s1]\n return ' '.join(s1)", "def remove_duplicate_words(s):\n res = []\n s = s.split()\n visited = set()\n for w in s:\n if w not in visited:\n res.append(w)\n visited.add(w)\n return \" \".join(res)\n", "def remove_duplicate_words(s):\n list = s.split()\n new = []\n for x in list:\n if x not in new and new.count(x) ==0:\n new.append(x)\n s=\" \"\n return (s.join(new)) \n", "def remove_duplicate_words(s):\n final = []\n for w in s.split(' '):\n if w not in final:\n final.append(w)\n return ' '.join(final)\n \n", "def remove_duplicate_words(s):\n \n D = []\n words = s.split(\" \")\n \n for word in words:\n \n if word not in D:\n D.append(word)\n else:\n pass\n \n return \" \".join(D)\n", "import re\ndef remove_duplicate_words(s):\n s_list = []\n s_2 = ''\n all = s.split()\n for word in s.split():\n if word not in s_list:\n s_2 += ' ' + word\n s_list.append(word)\n\n return s_2.strip()", "def remove_duplicate_words(s):\n q = \"\"\n a = s.split(\" \")\n for i in a:\n if i not in q:\n q += i + \" \"\n return q[:-1]", "def remove_duplicate_words(s):\n s = s.split(\" \")\n lst = []\n for item in s:\n if item not in lst:\n lst.append(item)\n return \" \".join(lst)", "from collections import Counter\ndef remove_duplicate_words(s):\n new=[]\n for i in Counter(s.split(' ')):\n new.append(i)\n return \" \".join(new)", "import re\ndef remove_duplicate_words(s):\n sx=[]\n for i in s.split():\n if i not in sx:\n sx.append(i)\n return \" \".join(sx)", "def remove_duplicate_words(s):\n \n split_string = s.split()\n \n new_string = \"\"\n \n for word in split_string:\n if word not in new_string:\n new_string+=word + \" \"\n else:\n continue\n \n return new_string.rstrip()\n \n", "def remove_duplicate_words(s):\n t = set()\n s = s.split()\n r = []\n for w in s:\n if w not in t : t.add(w); r.append(w)\n return ' '.join(r)", "def remove_duplicate_words(s):\n list = s.split()\n index = 0\n empty = []\n while index < len(list):\n if list[index] not in list[0:index]:\n empty.append(list[index])\n index += 1\n return ' '.join(empty)", "def remove_duplicate_words(s):\n no_dup=set()\n lstt=[]\n for i in s.split():\n print(i)\n if i not in lstt:\n lstt.append(i)\n \n f=' '.join(lstt)\n return f ", "def remove_duplicate_words(s):\n a=[]\n c=s.split(\" \")\n for i in c:\n if i not in a:\n a.append(i)\n return \" \".join(a)", "def remove_duplicate_words(s):\n nlist = []\n for i in s.split():\n if i not in nlist:\n nlist.append(i)\n return ' '.join(nlist)", "def remove_duplicate_words(x):\n a=''\n for i in x.split():\n if i not in a:\n a+=i +' '\n return a[:-1]", "def remove_duplicate_words(s):\n nwrd = []\n for i in s.split(' '):\n if i in nwrd:\n pass\n else:\n nwrd.append(i)\n return \" \".join(nwrd)", "def remove_duplicate_words(s):\n uniq = []\n for word in s.split():\n if word not in uniq:\n uniq.append(word)\n return ' '.join(uniq)", "def remove_duplicate_words(s):\n res = []\n s = s.split(' ')\n \n for w in s:\n if w not in res:\n res.append(w)\n \n erg = \"\"\n for r in res:\n erg += r + \" \"\n \n return erg[:-1]", "def remove_duplicate_words(s):\n dictionary = s.split()\n dictionary = dict.fromkeys(dictionary)\n return ' '.join(dictionary)", "def remove_duplicate_words(string):\n string = string.split(\" \")\n lst = []\n for word in string:\n if word not in lst:\n lst.append(word)\n\n return \" \".join(lst)\n", "def remove_duplicate_words(s):\n res = \"\"\n k = s.split()\n for i in k:\n if i not in res:\n res += i + \" \"\n \n return res.rstrip()", "import re\n\ndef remove_duplicate_words(s):\n result = []\n s_l = s.split(' ')\n \n for x in s_l:\n if x not in result:\n result.append(x)\n \n result = \" \".join(result)\n return result\n", "def remove_duplicate_words(s):\n S = []\n for word in s.split():\n if word in S:\n continue\n S.append(word)\n return ' '.join(S)\n", "from collections import OrderedDict\ndef remove_duplicate_words(s):\n a = s.split(\" \")\n return \" \".join(list(OrderedDict.fromkeys(a)))", "from collections import OrderedDict\n\ndef remove_duplicate_words(s):\n return ' '.join(OrderedDict((x,None) for x in s.split()).keys())", "def remove_duplicate_words(s):\n return ' '.join(list({i: True for i in s.split(' ')}))", "def remove_duplicate_words(str):\n return \" \".join(sorted(set(str.split()), key=str.split().index)) ", "def remove_duplicate_words(s):\n list1=[]\n [list1.append(x) for x in s.split() if x not in list1]\n return ' '.join(list1)\n"]
{"fn_name": "remove_duplicate_words", "inputs": [["alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta"], ["my cat is my cat fat"]], "outputs": [["alpha beta gamma delta"], ["my cat is fat"]]}
INTRODUCTORY
PYTHON3
CODEWARS
17,872
def remove_duplicate_words(s):
a192d89a2de6e243aae977b04e897a50
UNKNOWN
Write a function that accepts two square matrices (`N x N` two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size `N x N` (square), containing only integers. How to sum two matrices: Take each cell `[n][m]` from the first matrix, and add it with the same `[n][m]` cell from the second matrix. This will be cell `[n][m]` of the solution matrix. Visualization: ``` |1 2 3| |2 2 1| |1+2 2+2 3+1| |3 4 4| |3 2 1| + |3 2 3| = |3+3 2+2 1+3| = |6 4 4| |1 1 1| |1 1 3| |1+1 1+1 1+3| |2 2 4| ``` ## Example
["import numpy as np\ndef matrix_addition(a, b):\n return(np.mat(a)+np.mat(b)).tolist()", "def matrix_addition(a, b):\n for row in range(len(a)):\n for index in range(len(a)):\n a[row][index] += b[row][index]\n return a\n", "def matrix_addition(a, b):\n return [[sum(xs) for xs in zip(ra, rb)] for ra, rb in zip(a, b)]\n", "def matrix_addition(a, b):\n return [ [a[row][col] + b[row][col] for col in range(len(a[0]))]\n for row in range(len(a)) ]", "from numpy import matrix\n\ndef matrix_addition(a, b):\n return (matrix(a) + matrix(b)).tolist()", "def matrix_addition(a, b):\n return [[a[i][j] + b[i][j] for j in range(len(a))] for i in range(len(a))]", "def matrix_addition(A, B):\n return [[cellA + cellB for cellA, cellB in zip(rowA, rowB)] for rowA, rowB in zip(A, B)]", "import numpy as np\ndef matrix_addition(a, b):\n S = np.array(a) + np.array(b) \n return S.tolist()", "def matrix_addition(a, b):\n \n result = [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))] \n \n return result", "def matrix_addition(a, b):\n \n return [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]"]
{"fn_name": "matrix_addition", "inputs": [[[[1, 2, 3], [3, 2, 1], [1, 1, 1]], [[2, 2, 1], [3, 2, 3], [1, 1, 3]]], [[[1, 2], [1, 2]], [[2, 3], [2, 3]]], [[[1]], [[2]]]], "outputs": [[[[3, 4, 4], [6, 4, 4], [2, 2, 4]]], [[[3, 5], [3, 5]]], [[[3]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,212
def matrix_addition(a, b):
d68ae6c097f6319db8abc2d6cdf230bb
UNKNOWN
# Introduction A grille cipher was a technique for encrypting a plaintext by writing it onto a sheet of paper through a pierced sheet (of paper or cardboard or similar). The earliest known description is due to the polymath Girolamo Cardano in 1550. His proposal was for a rectangular stencil allowing single letters, syllables, or words to be written, then later read, through its various apertures. The written fragments of the plaintext could be further disguised by filling the gaps between the fragments with anodyne words or letters. This variant is also an example of steganography, as are many of the grille ciphers. Wikipedia Link ![Tangiers1](https://upload.wikimedia.org/wikipedia/commons/8/8a/Tangiers1.png) ![Tangiers2](https://upload.wikimedia.org/wikipedia/commons/b/b9/Tangiers2.png) # Task Write a function that accepts two inputs: `message` and `code` and returns hidden message decrypted from `message` using the `code`. The `code` is a nonnegative integer and it decrypts in binary the `message`.
["def grille(msg, code):\n return ''.join(msg[-1-i] for i,c in enumerate(bin(code)[::-1]) if c == '1' and i < len(msg))[::-1]", "def grille(message, code):\n binary = bin(code)[2:][-len(message):].zfill(len(message))\n return ''.join(char for char, code in zip(message, binary) if code == '1')", "def grille(m, c):\n return \"\".join(i[0] for i in zip(m[::-1],bin(c)[2:][::-1]) if i[1]==\"1\")[::-1]", "def grille(message, code):\n binary = bin(code)[2:][::-1]\n return(''.join([j for i, j in enumerate(message[::-1]) if i < len(binary) and binary[i] == '1'])[::-1])\n", "def grille(message, code):\n l = len(message)\n return \"\".join(c for c, b in zip(message, f\"{code:{l}b}\"[-l:]) if b == \"1\")", "from itertools import compress\n\ndef grille(message, code):\n l = len(message)\n code = list(map(int, bin(code)[2:].zfill(l)))\n return ''.join(list(compress(message, [code, code[l:]][l <len(code)] )))\n", "from itertools import compress\n\ndef grille(message, code):\n n = len(message)\n grille = map(int, '{:0{}b}'.format(code, n)[-n:])\n return ''.join(compress(message, grille))", "def grille(message, code):\n binary = str(bin(code)[2:].zfill(len(message)))\n print(str(bin(code)[2:]))\n i = 0\n decoded = \"\"\n if( len(binary) > len(message) ):\n while ( i < len(message) ):\n if ( binary[i + (len(binary) - len(message))] == '1' ):\n decoded += message[i]\n i += 1\n while ( i < len(message) ):\n if ( binary[i] == '1' ):\n decoded += message[i]\n i += 1\n return decoded", "def grille(s, code):\n return ''.join(c for c, k in zip(s[::-1], bin(code)[2:][::-1]) if k == '1')[::-1]", "def grille(message, code):\n return ''.join(c for i, c in enumerate(message) if 1<<(len(message)-i-1) & code)"]
{"fn_name": "grille", "inputs": [["abcdef", 5], ["", 5], ["abcd", 1], ["0abc", 2], ["ab", 255], ["ab", 256], ["abcde", 32], ["tcddoadepwweasresd", 77098]], "outputs": [["df"], [""], ["d"], ["b"], ["ab"], [""], [""], ["codewars"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,846
def grille(message, code):
426727953286b0a3253c37a12b52f0a1
UNKNOWN
In this Kata, we define an arithmetic progression as a series of integers in which the differences between adjacent numbers are the same. You will be given an array of ints of `length > 2` and your task will be to convert it into an arithmetic progression by the following rule: ```Haskell For each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1 or it can be left unchanged. ``` Return the minimum number of changes needed to convert the array to an arithmetic progression. If not possible, return `-1`. ```Haskell For example: solve([1,1,3,5,6,5]) == 4 because [1,1,3,5,6,5] can be changed to [1,2,3,4,5,6] by making 4 changes. solve([2,1,2]) == 1 because it can be changed to [2,2,2] solve([1,2,3]) == 0 because it is already a progression, and no changes are needed. solve([1,1,10) == -1 because it's impossible. solve([5,6,5,3,1,1]) == 4. It becomes [6,5,4,3,2,1] ``` More examples in the test cases. Good luck!
["def solve(arr):\n res = []\n for first in (arr[0]-1, arr[0], arr[0]+1):\n for second in (arr[1]-1, arr[1], arr[1]+1):\n val, step, count = second, second-first, abs(arr[0]-first) + abs(arr[1]-second)\n for current in arr[2:]:\n val += step\n if abs(val-current) > 1: break\n count += abs(val-current)\n else:\n res.append(count)\n return min(res, default=-1)", "def solve(arr):\n def isProgression(array):\n prevstep = array[1] - array[0]\n for j, v in enumerate(array[1:]):\n curstep = array[j + 1] - array[j]\n if curstep != prevstep:\n return False\n prevstep = curstep\n\n return True\n\n if isProgression(arr):\n return 0\n\n lst = [arr]\n chg = [0]\n good = [isProgression(arr)]\n\n for j in range(len(arr)):\n for k in range(len(lst)):\n if j>2 and isProgression(lst[k][:j-1]) is not True:\n continue\n lstp1 = lst[k][:j] + [lst[k][j] + 1] + lst[k][j + 1:]\n lst.append(lstp1)\n chg.append(chg[k] + 1)\n good.append(isProgression(lstp1))\n\n lstm1 = lst[k][:j] + [lst[k][j] - 1] + lst[k][j + 1:]\n lst.append(lstm1)\n chg.append(chg[k] + 1)\n good.append(isProgression(lstm1))\n\n filtered_lst = [x for j, x in enumerate(lst) if good[j]]\n filtered_chg = [x for j, x in enumerate(chg) if good[j]]\n\n if len(filtered_lst) == 0:\n return -1\n\n return min(filtered_chg)", "solve=lambda a,d={-1,0,1}:min((sum(l)for l in([abs(a[0]+u+(a[1]+v-a[0]-u)*n-x)for n,x in enumerate(a)]for u in d for v in d)if set(l)<=d),default=-1)", "solve=lambda a,d=(-1,0,1):min((sum(l)for l in([abs(a[0]+u+q*n-x)for n,x in enumerate(a)]for u in d for q,r in(divmod(a[-1]+v-a[0]-u,len(a)-1)for v in d)if r<1)if all(x in d for x in l)),default=-1)", "def solve(arr):\n n = len(arr)\n k, s = n - 1, n + 1\n d = arr[k] - arr[0]\n for d in range((d - 2) // k, (d + 2) // k + 1):\n for i in (-1, 0, 1):\n p = [abs(arr[0] + i + d * k - q) for k, q in enumerate(arr)]\n if max(p) < 2: s = min(s, sum(p))\n return (-1 if s > n else s)", "def solve(arr):\n\n head = arr[0]\n tail = arr[-1]\n \n check = [(i,j) for i in range(head-1,head+2) for j in range(tail-1,tail+2)]\n \n possibles = []\n for start, end in check:\n if (end-start)%(len(arr)-1) == 0:\n possibles.append((start,end))\n \n global_changes = float('inf')\n \n for start, end in possibles:\n \n diff = int((end-start)/(len(arr)-1))\n \n if diff == 0: tester = [start]*len(arr)\n else: tester = list(range(start, end+diff, diff))\n \n current_changes = 0\n \n for i in range(len(tester)):\n if abs(tester[i] - arr[i]) > 1:\n current_changes = float('inf')\n break\n elif abs(tester[i] - arr[i]) == 1:\n current_changes += 1\n \n global_changes = min(current_changes, global_changes)\n \n \n return global_changes if global_changes != float('inf') else -1", "import numpy as np\ndef solve(arr):\n l = len(arr)\n fst = arr[0]\n lst = arr[l-1]\n diff_range = lst - fst\n diffs = []\n for diff in range(diff_range - 2, diff_range + 3):\n if diff == 0:\n diffs.append(diff)\n elif diff % (l - 1) == 0:\n diffs.append(diff)\n \n progs = []\n for diff in diffs:\n for i in range(-1, 2):\n for j in range(-1, 2):\n if fst + i + diff == lst + j:\n seq = []\n if diff == 0:\n seq = l * [fst+i]\n else:\n k = 1\n if diff < 0:\n k = -1 \n seq = list(np.arange(fst + i, lst + j + k, diff / (l - 1)))\n if len(seq) == l:\n progs.append(seq)\n \n changes = []\n for seq in progs:\n change = 0\n complete = True\n for a,b in zip(seq,arr):\n diff = abs(a-b)\n if diff > 1:\n complete = False\n continue\n if diff != 0:\n change += 1\n if complete:\n changes.append(change)\n \n if len(changes) == 0:\n return -1\n return min(changes)\n", "from itertools import product\n\ndef solve(arr):\n res = []\n for p, q in product([-1, 0, 1], repeat=2):\n step = (arr[-1] + q - (arr[0] + p)) / (len(arr) - 1)\n if step.is_integer():\n exp = range(arr[0]+p, arr[-1]+q+int(step), int(step)) if step else [arr[0]+p] * len(arr)\n res.append(sum(abs(a - e) if abs(a - e) in (0, 1) else float('inf') for a, e in zip(arr, exp)))\n return min(res) if min(res, default=float('inf')) != float('inf') else -1", "def solve(a):\n r = []\n for i in range(-1, 2):\n for j in range(-1, 2):\n curr_diff = a[-1]-a[0]+j-i\n if curr_diff%(len(a)-1) == 0:\n curr_a = [a[0]+i] + a[1:-1] + [a[-1]+j] \n k = curr_diff//(len(a)-1)\n t = [abs(curr_a[0]+i*k-a[i]) for i in range(len(a))] \n if max(t) <= 1: r.append(sum(t))\n \n return min(r) if r else -1", "def solve(ls):\n result = [ls[each]-ls[each-1] for each in range(1, len(ls))] \n gap = round(sum(result)/len(result))\n tries = [ls[0]+1, ls[0], ls[0]-1] \n answer = []\n \n while True:\n count = 0 \n copy_ls = ls[:]\n \n copy_ls[0] = tries.pop(0)\n if copy_ls[0] != ls[0]:\n count += 1\n \n for each in range(len(ls)-1):\n sub_gap = copy_ls[each+1] - copy_ls[each]\n if sub_gap < gap:\n copy_ls[each+1] += 1\n count += 1\n elif sub_gap > gap:\n copy_ls[each+1] -= 1\n count += 1\n \n result = [copy_ls[each]-copy_ls[each-1] for each in range(1, len(ls))]\n \n if len(set(result)) == 1:\n answer.append(count)\n if len(tries) == 0:\n if len(answer) == 0:\n return -1\n else:\n answer.sort()\n return answer[0]"]
{"fn_name": "solve", "inputs": [[[1, 1, 3, 5, 6, 5]], [[2, 1, 2]], [[1, 2, 3]], [[1, 1, 10]], [[24, 21, 14, 10]], [[3, 2, 1, 1, 1]], [[1, 3, 6, 9, 12]], [[0, 0, 0, 0, 0]], [[5, 4, 3, 2, 1, 1]], [[1, 2, 1]], [[1, 2, 3, 1, 1]], [[1, 3, 6, 8, 10]], [[5, 6, 5, 3, 1, 1]]], "outputs": [[4], [1], [0], [-1], [3], [4], [1], [0], [1], [1], [4], [2], [4]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,525
def solve(arr):
52686cc21a564619c54be891c9fd7b70
UNKNOWN
In this kata you will be given a random string of letters and tasked with returning them as a string of comma-separated sequences sorted alphabetically, with each sequence starting with an uppercase character followed by `n-1` lowercase characters, where `n` is the letter's alphabet position `1-26`. ## Example ```python alpha_seq("ZpglnRxqenU") -> "Eeeee,Ggggggg,Llllllllllll,Nnnnnnnnnnnnnn,Nnnnnnnnnnnnnn,Pppppppppppppppp,Qqqqqqqqqqqqqqqqq,Rrrrrrrrrrrrrrrrrr,Uuuuuuuuuuuuuuuuuuuuu,Xxxxxxxxxxxxxxxxxxxxxxxx,Zzzzzzzzzzzzzzzzzzzzzzzzzz" ``` ## Technical Details - The string will include only letters. - The first letter of each sequence is uppercase followed by `n-1` lowercase. - Each sequence is separated with a comma. - Return value needs to be a string.
["def alpha_seq(s):\n return \",\".join( (c * (ord(c)-96)).capitalize() for c in sorted(s.lower()) )", "def alpha_seq(string):\n alpha = 'abcdefghijklmnopqrstuvwxyz'\n output = ''\n for s in ''.join(sorted((string.lower()))):\n output += s.upper()\n output += s * alpha.find(s)\n output += ','\n return output.strip(',')", "def alpha_seq(string):\n alpha = 'abcdefghijklmnopqrstuvwxyz'\n string = string.lower()\n l = []\n for i in sorted(string):\n l.append(i.capitalize() + i*(alpha.find(i)))\n return ','.join(l)", "alpha_seq=lambda s:','.join(e.upper()+e*(ord(e)-97) for e in sorted(s.lower()))", "def alpha_seq(string):\n o = ord(\"a\") -1\n return \",\".join((c * (ord(c) - o)).capitalize() for c in sorted(string.lower()))", "def elongate(c):\n u = c.upper()\n return '{0}{1}'.format(u, c.lower()*(ord(u)-65))\n \ndef alpha_seq(s):\n return ','.join(sorted([elongate(c) for c in s]))", "def alpha_seq(string):\n return ','.join(a * (ord(a) - 96) for a in sorted(string.lower())).title()", "def alpha_seq(string):\n memo, output = {}, []\n \n for char in sorted(string.lower()):\n if char not in memo:\n memo[char] = char.upper() + char * (ord(char) - 97)\n output.append(memo[char])\n \n return ','.join(output)", "from string import ascii_lowercase\n\npos = {x: i for i, x in enumerate(ascii_lowercase)}\n\ndef alpha_seq(string):\n return ','.join(x.upper() + x.lower() * pos[x] for x in sorted(string.lower()))", "alpha_seq=lambda s:','.join((c.upper()+c*(ord(c)-97))for c in sorted(s.lower()))"]
{"fn_name": "alpha_seq", "inputs": [["BfcFA"], ["ZpglnRxqenU"], ["NyffsGeyylB"], ["MjtkuBovqrU"], ["EvidjUnokmM"], ["HbideVbxncC"]], "outputs": [["A,Bb,Ccc,Ffffff,Ffffff"], ["Eeeee,Ggggggg,Llllllllllll,Nnnnnnnnnnnnnn,Nnnnnnnnnnnnnn,Pppppppppppppppp,Qqqqqqqqqqqqqqqqq,Rrrrrrrrrrrrrrrrrr,Uuuuuuuuuuuuuuuuuuuuu,Xxxxxxxxxxxxxxxxxxxxxxxx,Zzzzzzzzzzzzzzzzzzzzzzzzzz"], ["Bb,Eeeee,Ffffff,Ffffff,Ggggggg,Llllllllllll,Nnnnnnnnnnnnnn,Sssssssssssssssssss,Yyyyyyyyyyyyyyyyyyyyyyyyy,Yyyyyyyyyyyyyyyyyyyyyyyyy,Yyyyyyyyyyyyyyyyyyyyyyyyy"], ["Bb,Jjjjjjjjjj,Kkkkkkkkkkk,Mmmmmmmmmmmmm,Ooooooooooooooo,Qqqqqqqqqqqqqqqqq,Rrrrrrrrrrrrrrrrrr,Tttttttttttttttttttt,Uuuuuuuuuuuuuuuuuuuuu,Uuuuuuuuuuuuuuuuuuuuu,Vvvvvvvvvvvvvvvvvvvvvv"], ["Dddd,Eeeee,Iiiiiiiii,Jjjjjjjjjj,Kkkkkkkkkkk,Mmmmmmmmmmmmm,Mmmmmmmmmmmmm,Nnnnnnnnnnnnnn,Ooooooooooooooo,Uuuuuuuuuuuuuuuuuuuuu,Vvvvvvvvvvvvvvvvvvvvvv"], ["Bb,Bb,Ccc,Ccc,Dddd,Eeeee,Hhhhhhhh,Iiiiiiiii,Nnnnnnnnnnnnnn,Vvvvvvvvvvvvvvvvvvvvvv,Xxxxxxxxxxxxxxxxxxxxxxxx"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,633
def alpha_seq(string):
86d3e2e33386bf0aac5bab75c4c2dffb
UNKNOWN
Given an `array` of digital numbers, return a new array of length `number` containing the last even numbers from the original array (in the same order). The original array will be not empty and will contain at least "number" even numbers. For example: ``` ([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) => [4, 6, 8] ([-22, 5, 3, 11, 26, -6, -7, -8, -9, -8, 26], 2) => [-8, 26] ([6, -25, 3, 7, 5, 5, 7, -3, 23], 1) => [6] ```
["def even_numbers(arr,n):\n return [i for i in arr if i % 2 == 0][-n:] ", "def even_numbers(arr, n):\n result = []\n a = list(reversed(arr))\n for number in a:\n if n == 0:\n break\n if number % 2 == 0:\n result.append(number)\n n -= 1\n return list(reversed(result))", "def even_numbers(arr,n):\n return list(filter(lambda n: n % 2 == 0, arr))[-n:]", "def even_numbers(arr,n):\n s = [num for num in arr if num % 2 == 0]\n return s[-n:]", "def even_numbers(arr,n):\n return [x for x in arr if x % 2 == 0][-n:]\n", "def even_numbers(arr,n):\n return [a for a in arr if a%2 < 1][-n:]", "def even_numbers(arr,n):\n return [even for even in arr if even%2 ==0][-n:]\n", "from typing import List\n\n\ndef even_numbers(arr: List[int],n:int)->List[int]:\n res = []\n \n for a in reversed(arr):\n if a % 2 == 0:\n res.insert(0, a)\n if len(res) == n:\n return res", "def even_numbers(arr,n):\n even = []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n return even[len(even) - n:len(arr)]", "def even_numbers(arr,n):\n return list(filter(lambda x: x % 2 == 0, arr))[-n:len(arr)]", "def even_numbers(arr,n):\n return list(filter(lambda n: not n & 1, arr))[-n:]", "def even_numbers(lst, n):\n return [num for num in lst if not num % 2][-n:]", "even_numbers = lambda a,n:[e for e in a if 1-e%2][-n:]", "def even_numbers(arr,n):\n return [a for a in arr if a % 2 == 0][-n:]", "def even_numbers(arr,n):\n return [i for i in arr if not i%2][-n:]", "def even_numbers(arr,n):\n lista = []\n for i in arr[::-1]:\n if i % 2 == 0:\n lista.append(i)\n if len(lista) == n:\n return lista[::-1]", "def even_numbers(arr,n):\n x=[]\n for i in arr[::-1]:\n if len(x)<n and i%2 ==0:\n x.append(i) \n else:\n pass\n return x[::-1]", "def even_numbers(arr,n):\n return list(filter(lambda x: not x % 2, arr))[-n:]", "def even_numbers(arr, n):\n if not arr or n == 0:\n return []\n if arr[-1] % 2 == 0:\n v = n - 1\n tail = [arr[-1]]\n else:\n v = n\n tail = []\n return even_numbers(arr[:-1], v) + tail", "def even_numbers(arr,n):\n newarr = [i for i in arr if i%2 == 0]\n return newarr[-n:]", "def even_numbers(arr,n):\n return [i for i in arr if i&1^1][-n:]", "def even_numbers(arr,n): \n return [number for number in arr if number%2==0][::-1][:n][::-1]", "def even_numbers(array, requiredResultLength):\n return [number for number in array if not number % 2][-requiredResultLength:]", "def even_numbers(arr,n):\n even = [a for a in arr if not a%2]\n return even[len(even)-n::]", "def even_numbers(arr,n):\n arr=arr[::-1]\n ans=[]\n for x in arr:\n if x%2==0:\n ans.append(x)\n if len(ans)==n:\n return ans[::-1]", "def even_numbers(arr,n):\n x = []\n for i in range(len(arr)):\n if arr[i] % 2 == 0:\n x.append(arr[i])\n res = len(x) - n\n return x[res:]", "def even_numbers(arr,n):\n arr = arr[::-1]\n number = []\n for x in range(len(arr)):\n if arr[x]%2==0: \n if len(number)<n:number.append(arr[x])\n else: break\n return number[::-1]", "def even_numbers(arr,n):\n return [x for x in arr if not x%2][::-1][:n][::-1]", "def even_numbers(arr, n):\n return list([e for e in arr if e % 2 == 0])[-n::]\n", "def even_numbers(arr,n):\n return [even_num for even_num in arr if even_num % 2 == 0][-n:]", "def even_numbers(arr,n):\n newarr = []\n for i in arr:\n if i % 2 == 0:\n newarr.append(i)\n return newarr[-n:]", "def even_numbers(arr,n):\n return [i for i in arr if not i%2][-1*n:]", "def even_numbers(arr,n):\n result = []\n for i in range(len(arr)-1, -1, -1):\n if arr[i] % 2 == 0:\n result.insert(0, arr[i])\n if len(result) == n:\n return result\n return result", "def even_numbers(arr,n):\n res = []\n \n for elem in arr[::-1]:\n if elem % 2 == 0:\n res.insert(0, elem)\n if len(res) == n:\n break\n \n return res", "def even_numbers(arr,n):\n last_n_even_numbers=list()\n for num in arr[::-1]:\n if not num%2:\n last_n_even_numbers.append(num)\n if len(last_n_even_numbers)==n:\n return last_n_even_numbers[::-1]\n", "def even_numbers(arr,n):\n last_n_even_numbers=list()\n for num in arr[::-1]:\n if not num%2 and len(last_n_even_numbers)<n:\n last_n_even_numbers.append(num)\n if len(last_n_even_numbers)==n:\n return last_n_even_numbers[::-1]\n", "def even_numbers(arr,n):\n out = []\n count = 0\n for el in arr[::-1]:\n if el % 2 == 0 and count < n:\n out.append(el)\n count += 1\n return out[::-1]\n", "def even_numbers(array, number):\n a = []\n index = len(array) - 1\n while len(a) < number:\n if array[index] % 2 == 0:\n a.append(array[index])\n index -= 1\n return a[::-1]", "def even_numbers(arr,n):\n res = [i for i in arr if i%2==0]\n while len(res)>n:\n res.pop(0)\n return res", "def even_numbers(arr,n):\n return [i for i in arr if i % 2 == 0][::-1][0:n:][::-1]", "def even_numbers(arr,n):\n print(([a for a in arr if (a % 2 == 0)][-n:]))\n return [a for a in arr if (a % 2 == 0)][-n:]\n \n", "def even_numbers(arr,n):\n return [i for i in arr if i % 2 == 0][-1*n:]", "def even_numbers(A,n):\n return [e for e in A if not e%2][-n:]", "def even_numbers(arr,n):\n ans = []\n for i in arr[::-1]:\n if n ==0:\n break\n if i%2 ==0:\n ans.append(i)\n n -=1\n return ans[::-1]", "def even_numbers(arr,n):\n numberlist = []\n for eachnumber in arr[::-1]:\n if eachnumber % 2 == 0:\n numberlist.append(eachnumber)\n if len(numberlist) == n:\n numberlist.reverse()\n return numberlist\n", "def even_numbers(arr,n):\n evens = []\n for i in arr:\n if i % 2 == 0:\n evens.append(i)\n if len(evens) == n:\n return evens\n else:\n del evens[:-n]\n return evens", "def even_numbers(arr,n):\n res=[]\n for i in range(1,len(arr)+1):\n if arr[-i]%2==0:\n res.append(arr[-i])\n if len(res)==n:\n break\n \n return res[::-1]\n", "def even_numbers(arr,n):\n\n a = [i for i in arr if i % 2 == 0]\n \n return a[-n::]", "def even_numbers(arr,n):\n c = 0\n res = []\n for i in range(len(arr)-1, -1, -1):\n if c == n:\n break\n elif arr[i] % 2 == 0:\n res.append(arr[i])\n c += 1\n return res[::-1]", "def even_numbers(arr, n):\n x = [k for k in arr if k % 2 == 0]\n while len(x) > n:\n for k in x:\n x.remove(k)\n break\n return x", "def even_numbers(arr,n):\n result = []\n for x in reversed(arr):\n if x%2 == 0:\n result.append(x)\n if len(result) == n:\n break\n return list(reversed(result))\n", "def even_numbers(arr,n):\n L = [i for i in arr if i%2 == 0]\n return L[-n:]", "def even_numbers(arr,n):\n x = -1\n result = []\n while n > 0:\n if arr[x] % 2 == 0:\n result.append(arr[x])\n n -= 1\n x -= 1\n else:\n x -= 1\n return list(reversed(result))", "def even_numbers(a, n):\n return [x for x in a[::-1] if x % 2 == 0][:n][::-1]\n", "def even_numbers(arr,n):\n return list(reversed(list(reversed(list(filter(lambda x : (x%2==0), arr))))[:n]))", "def even_numbers(arr,n):\n \n# =============================================================================\n# This function given an array of digital numbers, returns a new array of\n# length n containing the last even numbers from the original array \n# (in the same order). \n# \n# The original array will be not empty and will contain at least \"n\" \n# even numbers.\n# \n# Example:\n# ([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) ==> [4, 6, 8]\n# ([-22, 5, 3, 11, 26, -6, -7, -8, -9, -8, 26], 2) ==> [-8, 26]\n# ([6, -25, 3, 7, 5, 5, 7, -3, 23], 1) ==> [6]\n# =============================================================================\n \n result = []\n \n myList = arr\n evensList = [x for x in myList if x % 2 ==0] # extract even nums from arr\n \n evensList = evensList[::-1]\n \n for i in range(0,n):\n \n result.append(evensList[i])\n \n return result[::-1]", "def even_numbers(arr,n):\n newl = []\n r = arr[::-1]\n for i in r:\n if i % 2 == 0:\n newl.append(i)\n if len(newl) == n:\n return newl[::-1]\n else:\n continue", "def even_numbers(arr,n):\n res = []\n\n for ele in reversed(arr):\n if ele % 2 == 0:\n res.append(ele)\n\n return list(reversed(res[:n]))\n", "def even_numbers(arr,n):\n arr.reverse()\n output = []\n i = 0\n while len(output) < n:\n if arr[i] % 2 == 0:\n output.append(arr[i])\n i += 1\n output.reverse()\n return output", "def even_numbers(arr,n):\n s = []\n for e in arr:\n if e%2 == 0:\n s.append(e)\n s1 = s[:-n-1:-1]\n s2 = s1[::-1]\n return s2", "def even_numbers(arr,n):\n return [k for k in arr if k%2==0][-n:]\n", "def even_numbers(arr,n):\n '''Returns the last n numbers of a list of even numbers from array arr'''\n output = []\n for num in arr:\n if num % 2 == 0:\n output.append(num)\n return output[-n:]", "def even_numbers(arr,n):\n li = [x for x in arr if x%2==0]\n li = li[::-1]\n result = li[:n]\n return result[::-1]\n", "def even_numbers(arr,n):\n x = []\n for i in arr:\n if i % 2 == 0:\n x.append(i)\n return x[-n:]", "def even_numbers(arr,n):\n ans =[]\n for i in arr:\n if i % 2 == 0:\n ans.append(i)\n return ans[-n:]", "even_numbers = lambda lst, k: [n for n in lst if not n & 1][-k:]", "def even_numbers(arr, num):\n return [n for n in arr if n % 2 == 0][-num:]", "def even_numbers(arr,n):\n answer =[]\n for num in arr:\n if num % 2 == 0:\n answer.append(num)\n return answer[-n:]", "def even_numbers(arr,n):\n even_list = []\n for num in arr:\n if num % 2 == 0:\n even_list.append(num)\n return even_list[-n:]\n \n", "def even_numbers(arr: list,n: int):\n arr.reverse()\n arr = [i for i in arr if not i % 2]\n arr = arr[:n]\n arr.reverse()\n return arr", "def even_numbers(arr,n):\n evenlist = []\n for x in arr:\n if x % 2 == 0:\n evenlist.append(x)\n return evenlist[-n:]\n", "def even_numbers(arr,n):\n output = [i for i in arr if i % 2 == 0]\n return output[-n:]", "def even_numbers(arr, length):\n return [n for n in arr if n % 2 == 0][-length:]", "def even_numbers(arr,n):\n lst = [num for i, num in enumerate(arr) if not num % 2]\n return [lst[i] for i in range(len(lst) - n, len(lst))]", "def even_numbers(arr, n):\n res = [x for x in arr if not x & 1]\n return res[-n:]", "def even_numbers(arr,n):\n a = []\n for i in arr:\n if i % 2 == 0:\n a.append(i)\n return a[len(a) - n:]", "def even_numbers(arr,n):\n even_nums=list(filter(lambda x: x%2==0,arr))\n return even_nums[-n:]", "def even_numbers(arr,n):\n list = []\n for number in reversed(arr):\n if number % 2 == 0:\n list.append(number)\n if len(list) == n:\n return list[::-1]\n", "def even_numbers(arr,n):\n even = []\n for num in arr:\n if num % 2 == 0:\n even.append(num)\n return even[len(even)-n:]", "def even_numbers(arr,n):\n pass\n \n e = []\n \n l = len(e)\n \n for i in range(0,len(arr)):\n \n if arr[i]%2==0 :\n \n \n e.append(arr[i])\n \n return e[l-n::]\n \n \n", "def even_numbers(arr, num):\n new = []\n for i in arr:\n if i % 2 == 0:\n new.append(i)\n return new[-num:]", "def even_numbers(arr,n):\n p = arr[::-1]\n z = []\n \n for i in p:\n if i % 2 == 0:\n z.append(i)\n \n c = len(z) - n\n for f in range(0,c):\n z.pop()\n \n return z[::-1]", "def even_numbers(arr,n):\n even_numbers_in_arr = []\n new_even_numbers = []\n for number in arr:\n if number % 2 == 0:\n even_numbers_in_arr.append(number)\n even_numbers_in_arr.reverse()\n for i in range(n):\n new_even_numbers.append(even_numbers_in_arr[i])\n new_even_numbers.reverse()\n return new_even_numbers\n", "def even_numbers(arr,n):\n new_arr = []\n even = []\n\n for i in arr:\n if i % 2 == 0:\n new_arr.append(i)\n\n for j in range(n):\n even.append(new_arr[-(j+1)])\n even.reverse()\n return even\n \n\n", "def even_numbers(arr,n):\n evens_arr = [x for x in arr if x % 2 == 0]\n return evens_arr[len(evens_arr)-n:]", "def even_numbers(arr,n):\n even =[]\n for number in arr[::-1]:\n if number % 2 == 0:\n even.append(number)\n if len(even) == n:\n break\n return even[::-1]", "def even_numbers(arr,n):\n result = []\n for num in arr[::-1]:\n if len(result) < n: \n if num % 2 == 0:\n result.append(num)\n return result[::-1]", "def even_numbers(arr,n):\n even_count=0\n result=[]\n \n for i in range(len(arr)-1,-1,-1):\n if arr[i]%2==0:\n result.insert(0,arr[i])\n even_count+=1\n if even_count==n:\n break\n \n return result\n \n \n \n", "def even_numbers(arr,n):\n res=[]\n for i in arr[::-1]:\n if n==0:\n break\n if i%2==0:\n res.append(i)\n n-=1\n return res[::-1]", "def even_numbers(arr,n):\n l = []\n counter = 1\n while len(l) != n:\n if arr[-counter] % 2 == 0:\n l.append(arr[-counter])\n counter +=1\n return l[::-1]\n \n \n", "def even_numbers(arr,n):\n lst = []\n for i in arr:\n if i % 2 == 0:\n lst.append(i)\n return lst[-n:]", "def even_numbers(arr,n):\n new = [c for c in arr if c % 2 == 0]\n return new[-n:]", "def even_numbers(arr,n):\n return [x for x in arr[::-1] if not x%2][:n][::-1]", "def even_numbers(arr,n):\n lst = []\n for i in arr:\n if i%2==0:\n lst.append(i)\n print(lst)\n lst.reverse()\n print(lst)\n lst = lst[0:n]\n print(lst)\n lst.reverse()\n return lst\n", "def even_numbers(arr,n):\n return list(reversed([x for x in arr if x%2==0][-1:-(n+1):-1]))", "def even_numbers(arr,n):\n even_steven = []\n for element in arr[::-1]:\n if element % 2 == 0 and len(even_steven) < n:\n even_steven.append(element) \n return even_steven[::-1]", "def even_numbers(arr,n):\n A = []\n while len(A) < n and arr:\n temp = arr.pop()\n if temp % 2 == 0:\n A = [temp] + A \n return A\n", "def even_numbers(arr,n):\n arr = arr[::-1]\n solution = []\n for i in arr:\n if i % 2 == 0:\n solution.append(i)\n if len(solution) == n:\n solution = solution[::-1]\n return solution", "def even_numbers(arr,n):\n cont = 0\n m = []\n x = -1\n \n while cont < n:\n if arr[x] % 2 == 0:\n m.append(arr[x])\n cont += 1\n x = x - 1\n m.reverse()\n return m\n", "def even_numbers(arr,n):\n res = []\n cnt = 0\n idx = len(arr)-1\n while cnt != n:\n if arr[idx] % 2 == 0:\n cnt+=1\n res = [arr[idx]] + res\n idx = idx-1\n return res\n \n"]
{"fn_name": "even_numbers", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9], 3], [[-22, 5, 3, 11, 26, -6, -7, -8, -9, -8, 26], 2], [[6, -25, 3, 7, 5, 5, 7, -3, 23], 1]], "outputs": [[[4, 6, 8]], [[-8, 26]], [[6]]]}
INTRODUCTORY
PYTHON3
CODEWARS
16,352
def even_numbers(arr,n):
d3c08501d7f1ba85109bdf7d8de28c3f
UNKNOWN
With one die of 6 sides we will have six different possible results:``` 1, 2, 3, 4, 5, 6``` . With 2 dice of six sides, we will have 36 different possible results: ``` (1,1),(1,2),(2,1),(1,3),(3,1),(1,4),(4,1),(1,5), (5,1), (1,6),(6,1),(2,2),(2,3),(3,2),(2,4),(4,2), (2,5),(5,2)(2,6),(6,2),(3,3),(3,4),(4,3),(3,5),(5,3), (3,6),(6,3),(4,4),(4,5),(5,4),(4,6),(6,4),(5,5), (5,6),(6,5),(6,6) ``` So, with 2 dice of 6 sides we get 36 different events. ``` ([6,6] ---> 36) ``` But with 2 different dice we can get for this case, the same number of events. One die of ```4 sides``` and another of ```9 sides``` will produce the exact amount of events. ``` ([4,9] ---> 36) ``` We say that the dice set ```[4,9]``` is equivalent to ```[6,6]``` because both produce the same number of events. Also we may have an amount of three dice producing the same amount of events. It will be for: ``` [4,3,3] ---> 36 ``` (One die of 4 sides and two dice of 3 sides each) Perhaps you may think that the following set is equivalent: ```[6,3,2]``` but unfortunately dice have a **minimum of three sides** (well, really a tetrahedron with one empty side) The task for this kata is to get the amount of equivalent dice sets, having **2 dice at least**,for a given set. For example, for the previous case: [6,6] we will have 3 equivalent sets that are: ``` [4, 3, 3], [12, 3], [9, 4]``` . You may assume that dice are available from 3 and above for any value up to an icosahedral die (20 sides). ``` [5,6,4] ---> 5 (they are [10, 4, 3], [8, 5, 3], [20, 6], [15, 8], [12, 10]) ``` For the cases we cannot get any equivalent set the result will be `0`. For example for the set `[3,3]` we will not have equivalent dice. Range of inputs for Random Tests: ``` 3 <= sides <= 15 2 <= dices <= 7 ``` See examples in the corresponding box. Enjoy it!!
["import numpy as np\n\ndef products(n, min_divisor, max_divisor): \n if n == 1:\n yield []\n for divisor in range(min_divisor, max_divisor+1):\n if n % divisor == 0:\n for product in products(n // divisor, divisor, max_divisor):\n yield product + [divisor] \n\ndef eq_dice(set):\n product = np.prod(set)\n lista = list(products(product, 3, min(product-1, 20)))\n return len(lista) - 1 if len(set) > 1 else len(lista)", "from functools import reduce\n\ndef getDivisors(n):\n lst, p = [], 2\n while n > 1:\n while not n%p:\n lst.append(p)\n n //= p\n p += 1 + (p!=2)\n return lst\n \n \ndef eq_dice(diceSet):\n events = reduce(int.__mul__, diceSet)\n lstDivs = getDivisors(events)\n combos = set(genCombDices(tuple(lstDivs), set()))\n return len(combos - {tuple(sorted(diceSet))})\n\n \ndef genCombDices(tup, seens):\n \n if tup[0] != 2: yield tup\n \n if len(tup) > 2:\n for i,a in enumerate(tup):\n for j,b in enumerate(tup[i+1:],i+1):\n m = a*b\n t = tuple(sorted(tup[:i] + tup[i+1:j] + tup[j+1:] + (m,)))\n if m > 20 or t in seens: continue\n seens.add(t)\n yield from genCombDices(t, seens)", "from itertools import combinations_with_replacement\nfrom pprint import pprint\n\ndef multiples(f):\n m = []\n for i in range(2,8):\n m.append(combinations_with_replacement(f,i))\n return m\n \ndef eq_dice(set_):\n mul = 1\n for e in set_:\n mul *= e\n facts = [x for x in range(3, 21) if not mul % x]\n count = 0\n for r in multiples(facts):\n for m in r:\n mu = 1\n for e in m:\n mu *= e\n if mu == mul and set(m) != set(set_):\n print(m)\n count += 1\n print(count)\n return count", "from functools import reduce\n\ndef eq_dice(set_):\n n = reduce(int.__mul__, [s for s in set_ if s not in (11, 13)])\n stack = [[n, [s for s in set_ if s in (11, 13)]]]\n result = set()\n while stack:\n n, status = stack.pop()\n if (3 <= n <= 20) and (len(status) > 0):\n result.add(tuple(sorted(status + [n])))\n for i in range(3, min(20, int(n//3))+1):\n if (n % i == 0) and (n // i >= 3):\n stack.append([n//i, sorted(status + [i])])\n result.discard(tuple(sorted(set_)))\n return len(result)", "from math import floor, sqrt\nfrom numpy import prod\n\ndef f(n, l=3):\n if n < l:\n return\n for p in range(l, min(floor(sqrt(n)) + 1, 21)):\n if not n % p:\n for l in f(n // p, p):\n yield [p] + l\n if n <= 20:\n yield [n]\n\ndef eq_dice(l):\n return sum(1 for l in f(prod(l)) if len(l) > 1) - (len(l) > 1)", "from functools import reduce\nfrom math import floor, sqrt\n\ndef f(n, l=3):\n if n < l:\n return\n for p in range(l, min(floor(sqrt(n)) + 1, 21)):\n if not n % p:\n for l in f(n // p, p):\n yield [p] + l\n if n <= 20:\n yield [n]\n\ndef eq_dice(l):\n return sum(1 for l in f(reduce(lambda p, n: p * n, l, 1)) if len(l) > 1) - (len(l) > 1)", "def product (dice):return dice[int()]*product(dice[1:]) if len(dice)>1 else dice[int()]\ndef eq_dice(dice):return len(recursive(product(dice),[],[]))-1 if len(dice)>1 else len(recursive(product(dice),[],[]))\ndef recursive(num,x,y,dice=3):\n if 3>num//3:return y\n while dice<=num//dice and dice<21:\n if num%dice==int():\n if sorted(x+[dice,num//dice]) not in y and num//dice<21:\n y.append(sorted(x+[dice,num//dice]))\n y=recursive(num//dice,x+[dice],y)\n dice+=1\n return y", "from functools import reduce\ndef get_factors(m):\n li, j = [], 2\n while j * j <= m:\n if m % j:\n j += 1\n continue\n m //= j\n li.append(j)\n return li+([m] if m>1 else [])\n\ndef divide(arr, cache):\n store = []\n for i in range(len(arr)):\n for j in range(i + 1, len(arr)):\n m = arr[:i] + arr[i + 1:j] + [arr[i] * arr[j]] + arr[j + 1:]\n tp = tuple(sorted(m))\n if m != arr and len(m)>1 and tp not in cache:\n cache.add(tp)\n store.extend([tp] + divide(m,cache))\n return store\n\ndef eq_dice(arr):\n m, arr = reduce(lambda x, y: x * y, arr), tuple(sorted(arr))\n return sum(1 for i in set(divide(get_factors(m),set())) if i!=arr and all(2<k<21 for k in i))", "from itertools import combinations_with_replacement\nfrom numpy import prod\n\ndef eq_dice(set_):\n lst = sorted(set_)\n eq, dice, count = 0, [], prod(lst)\n \n for sides in range(3, 21):\n if count % sides == 0: dice.append(sides)\n \n for num_dice in range(2, 8): \n for c in combinations_with_replacement(dice, num_dice):\n if prod(c) == count and sorted(c) != lst: eq += 1\n \n return eq"]
{"fn_name": "eq_dice", "inputs": [[[6, 6]], [[5, 6, 4]], [[3, 15, 8, 20]], [[6]], [[3, 3]], [[20]], [[3, 6]]], "outputs": [[3], [5], [44], [0], [0], [1], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,100
def eq_dice(set_):
089ea0a0608201da19d75fbf09867700
UNKNOWN
This kata focuses on the Numpy python package and you can read up on the Numpy array manipulation functions here: https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.array-manipulation.html You will get two integers `N` and `M`. You must return an array with two sub-arrays with numbers in ranges `[0, N / 2)` and `[N / 2, N)` respectively, each of them being rotated `M` times. ``` reorder(10, 1) => [[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]] reorder(10, 3) => [[2, 3, 4, 0, 1], [7, 8, 9, 5, 6]] reorder(10, 97) => [[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]] ```
["import numpy as np\n\n\ndef reorder(a, b):\n return np.roll(np.arange(a).reshape(2, -1), b, 1).tolist()\n", "from collections import deque\n\n\ndef reorder(n, m):\n a, b = deque(range(n // 2)), deque(range(n // 2, n))\n a.rotate(m)\n b.rotate(m)\n return [list(a), list(b)]", "# Numpy?\n# https://media.tenor.com/images/36c2be302f423c792ead1cca7018fe88/tenor.png\ndef reorder(N, M):\n L1 = list(range(N>>1))\n L2 = list(range(N>>1, N))\n R = M % (N >> 1)\n return [L1[-R:] + L1[:-R], L2[-R:] + L2[:-R]]", "def reorder(a, b):\n a >>= 1\n b %= a\n return [[d+(i-b)%a for i in range(a)] for d in (0,a)]", "import numpy as np\n\ndef reorder(a, b):\n if a % 2:\n m = a // 2\n new_array = np.array([number for number in range(0, a)])\n c = np.array_split(new_array, len(new_array) / m)\n d = [list(np.roll(c[0], b)), list(np.roll(c[1], b))]\n else:\n new_array = np.array([number for number in range(0, a)])\n c = np.array_split(new_array, len(new_array) / (a // 2))\n d = [list(np.roll(c[0], b)), list(np.roll(c[1], b))]\n return d", "reorder = lambda a, b: [x[-b%len(x):] + x[:-b%len(x)] for x in map(list, (range(a//2), range(a//2, a)))]", "def reorder(a, b):\n arr1, arr2 = list(range(a // 2)), list(range(a // 2, a))\n for _ in range(b): arr1, arr2 = [arr1[-1]] + arr1[:-1], [arr2[-1]] + arr2[:-1]\n return [arr1, arr2]", "import numpy\ndef reorder(a, b):\n result = [list(numpy.roll([i for i in range(0, a//2)], b)), list(numpy.roll([i for i in range(a//2, a)], b))]\n return result", "import numpy\ndef reorder(a, b):\n first = numpy.roll(numpy.array([i for i in range(0, int(a/2))]), b)\n second = numpy.roll(numpy.array([i for i in range(int(a/2), a)]), b)\n \n result = [[i for i in first], [j for j in second]]\n return result", "def reorder(a, b):\n import numpy\n return [list(numpy.roll(numpy.split(numpy.arange(a), 2)[0],b)),list(numpy.roll(numpy.split(numpy.arange(a), 2)[1],b))]"]
{"fn_name": "reorder", "inputs": [[10, 1], [10, 3], [10, 97]], "outputs": [[[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]], [[[2, 3, 4, 0, 1], [7, 8, 9, 5, 6]]], [[[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,023
def reorder(a, b):
c535f32edb6e882551658e9dd5f9bbe2
UNKNOWN
In this Kata, you will be given a string and two indexes (`a` and `b`). Your task is to reverse the portion of that string between those two indices inclusive. ~~~if-not:fortran ``` solve("codewars",1,5) = "cawedors" -- elements at index 1 to 5 inclusive are "odewa". So we reverse them. solve("cODEWArs", 1,5) = "cAWEDOrs" -- to help visualize. ``` ~~~ ~~~if:fortran ``` solve("codewars",2,6) = "cawedors" -- elements at indices 2 to 6 inclusive are "odewa". So we reverse them. solve("cODEWArs", 2,6) = "cAWEDOrs" -- to help visualize. ``` ~~~ Input will be lowercase and uppercase letters only. The first index `a` will always be lower that than the string length; the second index `b` can be greater than the string length. More examples in the test cases. Good luck! Please also try: [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2) [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7) ~~~if:fortran *NOTE: You may assume that all input strings will* **not** *contain any (redundant) trailing whitespace. In return, your returned string is* **not** *permitted to contain any (redundant) trailing whitespace.* ~~~
["def solve(s,a,b):\n return s[:a]+s[a:b+1][::-1]+s[b+1:]", "def solve(st,a,b):\n return st[:a]+st[a:b+1][::-1]+ st[b+1:]", "def solve(st,a,b):\n return f'{st[:a]}{st[a : b + 1][::-1]}{st[b + 1 :]}'", "def solve(st,a,b):\n sub, rev = st[a:b+1], st[a:b+1][::-1]\n return st.replace(sub, rev)", "def solve(st,a,b):\n sub = st[a:b+1]\n rev = sub[::-1]\n return st.replace(sub, rev)", "def solve(s, m, n):\n return s[n::-1] + s[n+1:] if m == 0 else s[:m] + s[n:m-1:-1] + s[n+1:]", "def solve(st,a,b):\n str = st[a:b+1]\n st = st.replace(st[a:b+1], str[::-1])\n return st", "def solve(st,a,b):\n c = st[a:b+1]\n front = st[:a]\n back = st[b+1::]\n \n everything = front + c[::-1] + back\n return everything", "solve = lambda st,a,b: st[:a]+st[a:b+1][::-1]+st[b+1:]", "def solve(st,a,b):\n str=st[a:b+1]\n str_new=str[::-1]\n res=st.replace(str,str_new)\n return res\n"]
{"fn_name": "solve", "inputs": [["codewars", 1, 5], ["codingIsFun", 2, 100], ["FunctionalProgramming", 2, 15], ["abcefghijklmnopqrstuvwxyz", 0, 20], ["abcefghijklmnopqrstuvwxyz", 5, 20]], "outputs": [["cawedors"], ["conuFsIgnid"], ["FuargorPlanoitcnmming"], ["vutsrqponmlkjihgfecbawxyz"], ["abcefvutsrqponmlkjihgwxyz"]]}
INTRODUCTORY
PYTHON3
CODEWARS
931
def solve(st,a,b):
f09f6f211912d6355118e932b6f967ed
UNKNOWN
A **pandigital number** is one that has its digits from ```1``` to ```9``` occuring only once (they do not have the digit 0). The number ```169```, is the first pandigital square, higher than ```100```, having its square root, ```13```, pandigital too. The number ```1728``` is the first pandigital cubic, higher than ```1000```, having its cubic root, ```12```, pandigital too. Make the function ```pow_root_pandigit()```, that receives three arguments: - a minimum number, ```val``` - the exponent of the n-perfect powers to search, ```n``` - ```k```, maximum amount of terms that we want in the output The function should output a 2D-array with an amount of k pairs of numbers(or an array of an only pair if we have this case). Each pair has a nth-perfect power pandigital higher than val with its respective nth-root that is pandigital, too. The function should work in this way: ```python pow_root_pandigit(val, n, k) = [[root1, pow1], [root2, pow2], ...., [rootk, powk]] """ root1 < root2 <.....< rootk val < pow1 < pow2 < ....< powk root1 ^ n = pow1 // root2 ^ n = pow2 //........// rootk ^ n = powk all pairs rooti, powi are pandigitals """ ``` Let's see some examples: ```python pow_root_pandigit(388, 2, 3)== [[23, 529], [24, 576], [25, 625]] # 3 pairs (k = 3) ``` For a different power: ```python pow_root_pandigit(1750, 3, 5) == [[13, 2197], [17, 4913], [18, 5832], [19, 6859], [21, 9261]] # 5 pairs (k = 5) ``` The output in not inclusive for val. ```python pow_root_pandigit(1728, 3, 4) == [[13, 2197], [17, 4913], [18, 5832], [19, 6859]] # ∛1728 = 12 ``` The result may have less terms than the required: ```python pow_root_pandigit(600000000, 2, 5) == [25941, 672935481] # If the result has an only one pair, the output is an array ``` Furthermore, if the minimum value, ```val``` is high enough, the result may be an empty list: ```python pow_root_pandigit(900000000, 2, 5) == [] ``` You may suposse that the input ```val```, ```n``` will be always: ```val > 10``` and ```n > 2```. Enjoy it!!
["def is_pandigital(n):\n s = str(n)\n return not '0' in s and len(set(s)) == len(s)\n\ndef pow_root_pandigit(val, n, k):\n res = []\n current = int(round(val ** (1.0 / n), 5)) + 1\n while len(res) < k and current <= 987654321 ** (1.0 / n):\n if is_pandigital(current):\n p = current ** n\n if is_pandigital(p):\n res += [[current, p]]\n current += 1\n return res if len(res) != 1 else res[0]", "def is_pandigital(n):\n s = set(c for c in str(n) if c != \"0\" )\n if len(s) != len(str(n)): return False\n else: return True\n\ndef pow_root_pandigit(val, n, k):\n\n i, l = int(val**(1.0/n))-1, []\n while len(l) < k:\n if i**n > val and is_pandigital(i) and is_pandigital(i**n):\n l.append([i, i**n])\n i += 1\n \n # largest possible\n if i**n > 987654321: \n break\n \n if len(l) == 1: return l[0]\n else: return l", "def pow_root_pandigit(v,n,k):\n r,i=[],int(v**(1.0/n))\n while len(r)<k and i<25942:\n i+=1\n s=str(i)\n if '0' not in s and len(s)==len(set(s)):\n j=i**n\n if j<=v:continue\n t=str(j)\n if '0' not in t and len(t)==len(set(t)):\n r+=[[i,j]]\n return [] if not r else r if len(r)>1 else r[0]", "from itertools import permutations as p\n\nn_str = '123456789'\nformt = lambda n: sorted(list(map(''.join, list(filter(set, p(n_str, n))))))\ndb = formt(1) + formt(2) + formt(3) + formt(4) + formt(5)\nhs = {1:0, 2:9, 3:81, 4:585, 5:3609}\n\ndef next_pandigital(lp):\n if lp in db:\n return db[db.index(lp):]\n while 1:\n lp = str(int(lp) + 1)\n if lp in db[hs[len(lp)]:]:\n break\n return db[db.index(lp):]\n\ndef is_pandigital(lp):\n return len(set(lp)) == len(lp) and '0' not in lp\n\ndef pow_root_pandigit(val, n, k):\n l = []\n low = int(val ** (1 / n) + 0.0001) + 1\n for p in next_pandigital(str(low)):\n v = int(p) ** n\n if is_pandigital(str(v)):\n l.append([int(p), v])\n if len(l) == k:\n return l\n return l[0] if len(l) == 1 else l", "import math\n\ndef is_pandigit(val):\n val = str(val)\n return ('0' not in val) and len(val)==len(set(val))\n\ndef pow_root_pandigit(val, n, k):\n result = []\n rt = math.ceil((val+1) ** (1/n))\n for r in range(rt, math.ceil(10**(9/n))):\n if is_pandigit(r):\n x = r**n\n if is_pandigit(x):\n result.append([r, x])\n if len(result)==k:\n break \n return result if len(result)!=1 else result[0]", "from math import *\n\ndef pow_root_pandigit(val, n, k):\n '''\n Create a function to give k smaller couples of the root - pandigital numbers with the power n\n and bigger than val.\n '''\n # Create the empty list to return\n l = []\n # Put the value to zero\n if val < 0:\n val = 0\n # Case where val is bigger than the bigger pandigital number\n if val > 987654321:\n return l\n r = 1./n\n # Look for all the powers bigger than val and stop when it reach the len of the list or the\n # end of the possibility\n for i in range(int(ceil(((val+1) ** r))), int(987654322 ** r)):\n string = str(i ** n)\n if len(set(string)) == len(string) and '0' not in string and '0' not in str(i) and len(set(str(i))) == len(str(i)): \n l.append([i, int(string)])\n if len(l) == k : break\n # Check if only one element\n if len(l) == 1:\n l = l[0]\n return l\n \n"]
{"fn_name": "pow_root_pandigit", "inputs": [[388, 2, 3], [1750, 3, 5], [1728, 3, 4], [600000000, 2, 5], [900000000, 2, 5]], "outputs": [[[[23, 529], [24, 576], [25, 625]]], [[[13, 2197], [17, 4913], [18, 5832], [19, 6859], [21, 9261]]], [[[13, 2197], [17, 4913], [18, 5832], [19, 6859]]], [[25941, 672935481]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,650
def pow_root_pandigit(val, n, k):