_id
stringlengths
2
5
partition
stringclasses
2 values
text
stringlengths
5
289k
language
stringclasses
1 value
meta_information
dict
title
stringclasses
1 value
d1701
train
class DynamicConnectivity(object): par = [] def __init__(self, n): self.par = [i for i in range(n)] def union(self, p, q): if self.root(p) != self.root(q): self.par[self.root(p)] = q def root(self, p): pp = p while self.par[pp] != pp: pp = self.par[pp] return pp def connected(self, p, q): return True if self.root(p)==self.root(q) else False
PYTHON
{ "starter_code": "\ndef __init__(self, n):\n\t", "url": "https://www.codewars.com/kata/58936eb3d160ee775d000018" }
d1702
train
from operator import add, sub, mul, floordiv as div, and_, or_, xor OP = {'add':add, 'sub':sub, 'mul':mul, 'div':div, 'and':and_, 'or':or_, 'xor':xor} class Machine(object): def __init__(self, cpu): self.cpu = cpu def execute(self, instruction): cmd, a, b = (instruction.replace(',', ' ') + ' 0 0').split()[:3] v = self.cpu.read_reg(a) if a in 'abcd' else int(a) if cmd == 'mov': self.cpu.write_reg(b, v) elif cmd == 'pop': self.cpu.write_reg(a, self.cpu.pop_stack()) if a in 'abcd' else self.cpu.pop_stack() elif cmd == 'push': self.cpu.write_stack(v) elif cmd in ['pushr', 'pushrr']: for r in ('abcd' if cmd == 'pushr' else 'dcba'): self.cpu.write_stack(self.cpu.read_reg(r)) elif cmd in ['popr', 'poprr']: for r in ('abcd' if cmd == 'poprr' else 'dcba'): self.cpu.write_reg(r, self.cpu.pop_stack()) else: r = self.cpu.pop_stack() if cmd[-1] != 'a' else self.cpu.read_reg('a') for _ in range(v-1): r = OP[cmd if cmd[-1] != 'a' else cmd[:-1]](r, self.cpu.pop_stack()) self.cpu.write_reg(b if b in 'abcd' else 'a', r)
PYTHON
{ "starter_code": "\ndef __init__(self, cpu):\n\t", "url": "https://www.codewars.com/kata/54c1bf903f0696f04600068b" }
d1703
train
import math class Sudoku(object): def __init__(self, board): self.board = board def is_valid(self): if not isinstance(self.board, list): return False n = len(self.board) rootN = int(round(math.sqrt(n))) if rootN * rootN != n: return False isValidRow = lambda r : (isinstance(r, list) and len(r) == n and all([type(x) == int for x in r])) if not all(map(isValidRow, self.board)): return False oneToN = set(range(1, n + 1)) isOneToN = lambda l : set(l) == oneToN tranpose = [[self.board[j][i] for i in range(n)] for j in range(n)] squares = [[self.board[p+x][q+y] for x in range(rootN) for y in range(rootN)] for p in range(0, n, rootN) for q in range(0, n, rootN)] return (all(map(isOneToN, self.board)) and all(map(isOneToN, tranpose)) and all(map(isOneToN, squares)))
PYTHON
{ "starter_code": "\ndef __init__(self, board):\n\t", "url": "https://www.codewars.com/kata/540afbe2dc9f615d5e000425" }
d1704
train
import re def brainfuck_to_c(source): # remove comments source = re.sub('[^+-<>,.\[\]]', '', source) # remove redundant code before = '' while source != before: before = source source = re.sub('\+-|-\+|<>|><|\[\]', '', source) # check braces status braces = re.sub('[^\[\]]', '', source) while braces.count('[]'): braces = braces.replace('[]', '') if braces: return 'Error!' # split code into commands commands = re.findall('\++|-+|>+|<+|[.,\[\]]', source) # translate to C output = [] indent = 0 for cmd in commands: if cmd[0] in '+-<>': line = ('%sp %s= %s;\n' % ('*' if cmd[0] in '+-' else '', '+' if cmd[0] in '+>' else '-', len(cmd))) elif cmd == '.': line = 'putchar(*p);\n' elif cmd == ',': line = '*p = getchar();\n' elif cmd == '[': line = 'if (*p) do {\n' elif cmd == ']': line = '} while (*p);\n' indent -= 1 output.append(' ' * indent + line) if cmd == '[': indent += 1 return ''.join(output)
PYTHON
{ "starter_code": "\ndef brainfuck_to_c(source_code):\n\t", "url": "https://www.codewars.com/kata/58924f2ca8c628f21a0001a1" }
d1705
train
class PokerHand(object): CARD = "23456789TJQKA" RESULT = ["Loss", "Tie", "Win"] def __init__(self, hand): values = ''.join(sorted(hand[::3], key=self.CARD.index)) suits = set(hand[1::3]) is_straight = values in self.CARD is_flush = len(suits) == 1 self.score = (2 * sum(values.count(card) for card in values) + 13 * is_straight + 15 * is_flush, [self.CARD.index(card) for card in values[::-1]]) def compare_with(self, other): return self.RESULT[(self.score > other.score) - (self.score < other.score) + 1]
PYTHON
{ "starter_code": "\ndef __init__(self, hand):\n\t", "url": "https://www.codewars.com/kata/5739174624fc28e188000465" }
d1706
train
def spidey_swings(building_params): buildings = get_buildings(building_params) end_position = get_total_length(buildings) latch_positions = [] jump_position = 0 while is_not_possible_to_reach_the_end(buildings, jump_position, end_position): candidate_jumps = [ building.get_variables_for_max_displacement(jump_position) for building in buildings if building.is_reachable(jump_position) ] candidate_jumps.sort(reverse=True) _, latch_position, jump_position = candidate_jumps[0] latch_positions.append(latch_position) candidate_final_jumps = [ building.get_variables_aiming_end(jump_position, end_position) for building in buildings if (building.is_reachable(jump_position) and building.is_possible_to_reach_the_end(jump_position, end_position)) ] candidate_final_jumps.sort(reverse=True) _, latch_position = candidate_final_jumps[0] latch_positions.append(latch_position) return latch_positions def get_buildings(building_params): pos = 0 buildings = [] for (height, width) in building_params: building = Building(height, width, pos) buildings.append(building) pos += width return buildings def get_total_length(buildings): return sum(building.width for building in buildings) def is_not_possible_to_reach_the_end(buildings, jump_position, end_position): return not any(building.is_possible_to_reach_the_end(jump_position, end_position) for building in buildings) class Building: def __init__(self, height, width, pos): self.height = height self.width = width self.pos = pos def max_rope_length(self): return self.height - 20 def distance_to_rooftop(self): return self.height - 50 def max_horizontal_displacement(self): hypotenuse = self.max_rope_length() vertical = self.distance_to_rooftop() return (hypotenuse ** 2 - vertical ** 2) ** .5 def latch_pos_for_max_displacement(self, jump_pos): if jump_pos < self.pos - self.max_horizontal_displacement(): return None if jump_pos < self.pos + self.width - self.max_horizontal_displacement(): return int(jump_pos + self.max_horizontal_displacement()) if jump_pos < self.pos + self.width: return int(self.pos + self.width) return None def rope_length_for_max_displacement(self, jump_pos): horizontal = (self.latch_pos_for_max_displacement(jump_pos) - jump_pos) vertical = self.distance_to_rooftop() return (horizontal ** 2 + vertical ** 2) ** .5 def advanced_distance_for_max_displacement(self, jump_pos): return (self.latch_pos_for_max_displacement(jump_pos) - jump_pos) * 2 def ratio_max_displacement_rope(self, jump_pos): return (self.advanced_distance_for_max_displacement(jump_pos) / self.rope_length_for_max_displacement(jump_pos)) def get_variables_for_max_displacement(self, pos): latch_pos = self.latch_pos_for_max_displacement(pos) next_jump_pos = pos + self.advanced_distance_for_max_displacement(pos) ratio = self.ratio_max_displacement_rope(pos) return ratio, latch_pos, next_jump_pos def latch_pos_aiming_end(self, jump_pos, end_pos): max_latch_pos = (jump_pos + end_pos) / 2 if jump_pos < self.pos - self.max_horizontal_displacement(): return None if jump_pos <= max_latch_pos: max_latch_pos = max(max_latch_pos, self.pos) return int(max_latch_pos + .5) return None def rope_length_aiming_end(self, pos, end_pos): horizontal = self.latch_pos_aiming_end(pos, end_pos) - pos vertical = self.distance_to_rooftop() return (horizontal ** 2 + vertical ** 2) ** .5 def ratio_aiming_end(self, pos, end_pos): horizontal = end_pos - pos rope = self.rope_length_aiming_end(pos, end_pos) ratio = horizontal / rope return ratio def get_variables_aiming_end(self, pos, end_pos): latch_pos = self.latch_pos_aiming_end(pos, end_pos) ratio = self.ratio_aiming_end(pos, end_pos) return ratio, latch_pos def is_possible_to_reach_the_end(self, pos, end_pos): if not self.is_reachable(pos): return False return pos + self.advanced_distance_for_max_displacement(pos) >= end_pos def is_reachable(self, pos): return self.latch_pos_for_max_displacement(pos) is not None
PYTHON
{ "starter_code": "\ndef spidey_swings(building_params):\n\t", "url": "https://www.codewars.com/kata/59cda1eda25c8c4ffd000081" }
d1707
train
def rectangle_rotation(a, b): a //= 2**0.5 b //= 2**0.5 r = (a + 1) * (b + 1) + a * b return r + r % 2 - 1
PYTHON
{ "starter_code": "\ndef rectangle_rotation(a, b):\n\t", "url": "https://www.codewars.com/kata/5886e082a836a691340000c3" }
d1708
train
def cut_log(p, n): log = [0] for _ in range(n): log.append(max(pi + li for pi, li in zip(p[1:], log[::-1]))) return log[n]
PYTHON
{ "starter_code": "\ndef cut_log(p, n):\n\t", "url": "https://www.codewars.com/kata/54b058ce56f22dc6fe0011df" }
d1709
train
''' some useful information about memory allocation in operating system ->There are various algorithms which are implemented by the Operating System in order to find out the holes(continuous empy blocks) \ in the linked list(array in this kata) and allocate them to the processes. ->various algorithms used by operating system: 1. First Fit Algorithm => First Fit algorithm scans the linked list and whenever it finds the first big enough hole to store a process, it stops scanning and load the process into that hole. 2. Next Fit Algorithm => Next Fit algorithm is similar to First Fit algorithm except the fact that, Next fit scans the linked list from the node where it previously allocated a hole. ( if i have allocated memory of size 8 in previous turn and initial pointer is 3 \ then in next turn os will start searching for next empty hole from position 11(3+8=11) ) 3. Best Fit Algorithm => The Best Fit algorithm tries to find out the smallest hole possible in the list that can accommodate the size requirement of the process. 4. Worst Fit Algorithm => it is opposite of Best Fit Algorithm meaning that \ (The worst fit algorithm scans the entire list every time and tries to find out the biggest hole in the list which can fulfill the requirement of the process.) The first fit and best fit algorithms are the best algorithm among all PS. I HAVE IMPLEMENTED Best Fit Algorithm IN JAVASCRIPT AND IMPLEMENTED Next Fit Algorithm in PYTHON :) ''' #Next fit Algorithm class MemoryManager: def __init__(self, memory): self.storage = [True] * len(memory) self.previous_allocated_index = 0 self.allocated = {} self.data = memory def allocate(self, size): find_next = self.process_allocate(self.previous_allocated_index, len(self.data) - size + 1, size) # start searching from previously allocated block if find_next is not None : return find_next from_start = self.process_allocate(0, self.previous_allocated_index - size + 1, size) # if we cant find from last index then start searching from starting to previously allocated index if from_start is not None : return from_start raise IndexError('caused by insufficient space in storage') def process_allocate(self, initial, end, size): for i in range(initial, end): if all(self.storage[i:i + size]): self.previous_allocated_index = i self.storage[i:i + size] = [False] * size self.allocated[i] = i + size return i def release(self, pointer): if self.storage[pointer] : raise RuntimeError('caused by providing incorrect pointer for releasing memory') size = self.allocated[pointer] - pointer self.storage[pointer:size] = [True] * size self.data[pointer:size] = [None] * size del self.allocated[pointer] def read(self, pointer): if self.storage[pointer] : raise RuntimeError('caused by providing incorrect pointer for reading memory') return self.data[pointer] def write(self, pointer, value): if self.storage[pointer] : raise RuntimeError('caused by providing incorrect pointer for writing memory') self.data[pointer] = value
PYTHON
{ "starter_code": "\ndef __init__(self, memory):\n\t", "url": "https://www.codewars.com/kata/536e7c7fd38523be14000ca2" }
d1710
train
def sum_for_list(lst): factors = {i for k in lst for i in xrange(2, abs(k)+1) if not k % i} prime_factors = {i for i in factors if not [j for j in factors-{i} if not i % j]} return [[p, sum(e for e in lst if not e % p)] for p in sorted(prime_factors)]
PYTHON
{ "starter_code": "\ndef sum_for_list(lst):\n\t", "url": "https://www.codewars.com/kata/54d496788776e49e6b00052f" }
d1711
train
class Warrior(): def __init__(self): self._experience = 100 self.rs = ["Pushover", "Novice", "Fighter", "Warrior", "Veteran", "Sage", "Elite", "Conqueror", "Champion", "Master", "Greatest"] self.achievements = [] def training(self, train): if(train[2] > self.level) : return "Not strong enough"; self._experience += train[1] self.achievements.append(train[0]) return train[0] def battle(self, lvl): diff = lvl - self.level if(0 >= lvl or lvl > 100): return "Invalid level" if(diff >= 5 and (lvl // 10) > (self.level // 10)): return "You've been defeated" if(diff > 0) : self._experience += 20 * diff * diff return "An intense fight" if(diff > -2): self._experience += 5 if diff == -1 else 10 return "A good fight" return "Easy fight" @property def level(self): return self.experience // 100 @property def rank(self): return self.rs[self.experience // 1000] @property def experience(self): return min(10000, self._experience)
PYTHON
{ "starter_code": "\ndef __init__(self):\n\t", "url": "https://www.codewars.com/kata/5941c545f5c394fef900000c" }
d1712
train
class Cons: def __init__(self, head, tail): self.head = head self.tail = tail def to_array(self): return [self.head] + (self.tail.to_array() if self.tail is not None else []) @classmethod def from_array(cls, arr): if not arr: return None return Cons(arr.pop(0), Cons.from_array(arr) if arr else None) def filter(self, fn): return Cons.from_array(list(filter(fn, self.to_array()))) def map(self, fn): return Cons.from_array(list(map(fn, self.to_array())))
PYTHON
{ "starter_code": "\ndef __init__(self, head, tail):\n\t", "url": "https://www.codewars.com/kata/529a92d9aba78c356b000353" }
d1713
train
def puzzle_solver(pieces, w, h): memo, D, result = {}, {None: (None, None)}, [[None]*w for _ in range(h)] for (a, b), (c, d), id in pieces: memo[(a, b, c)] = id D[id] = (c, d) for i in range(h): for j in range(w): a, b = D[result[i-1][j]] _, c = D[result[i][j-1]] result[i][j] = memo[(a, b, c)] return list(map(tuple, result))
PYTHON
{ "starter_code": "\ndef puzzle_solver(pieces, width, height):\n\t", "url": "https://www.codewars.com/kata/5ef2bc554a7606002a366006" }
d1714
train
import sys def count_calls(func, *args, **kwargs): """Count calls in function func""" calls = [ -1 ] def tracer(frame, event, arg): if event == 'call': calls[0] += 1 return tracer sys.settrace(tracer) rv = func(*args, **kwargs) return calls[0], rv
PYTHON
{ "starter_code": "\ndef count_calls(func, *args, **kwargs):\n\t", "url": "https://www.codewars.com/kata/53efc28911c36ff01e00012c" }
d1715
train
def hull_method(points): sorted_points = sorted(points) return half_hull(sorted_points) + half_hull(reversed(sorted_points)) def half_hull(sorted_points): hull = [] for p in sorted_points: while len(hull) > 1 and not is_ccw_turn(hull[-2], hull[-1], p): hull.pop() hull.append(p) hull.pop() return hull def is_ccw_turn(p0, p1, p2): return (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]) > 0
PYTHON
{ "starter_code": "\ndef hull_method(pointlist):\n\t", "url": "https://www.codewars.com/kata/5657d8bdafec0a27c800000f" }
d1716
train
def justify(text, width): length = text.rfind(' ', 0, width+1) if length == -1 or len(text) <= width: return text line = text[:length] spaces = line.count(' ') if spaces != 0: expand = (width - length) / spaces + 1 extra = (width - length) % spaces line = line.replace(' ', ' '*expand) line = line.replace(' '*expand, ' '*(expand+1), extra) return line + '\n' + justify(text[length+1:], width)
PYTHON
{ "starter_code": "\ndef justify(text, width):\n\t", "url": "https://www.codewars.com/kata/537e18b6147aa838f600001b" }
d1717
train
from itertools import permutations def equal_to_24(*aceg): ops = '+-*/' for b in ops: for d in ops: for f in ops: for (a,c,e,g) in permutations(aceg): for s in make_string(a,b,c,d,e,f,g): try: if eval(s + '== 24'): return s except: pass return "It's not possible!" def make_string(a,b,c,d,e,f,g): return [f"(({a} {b} {c}) {d} {e}) {f} {g}", f"({a} {b} {c}) {d} ({e} {f} {g})", f"{a} {b} ({c} {d} ({e} {f} {g}))"]
PYTHON
{ "starter_code": "\ndef equal_to_24(a,b,c,d):\n\t", "url": "https://www.codewars.com/kata/574be65a974b95eaf40008da" }
d1718
train
from collections import Counter import re def top_3_words(text): c = Counter(re.findall(r"[a-z']+", re.sub(r" '+ ", " ", text.lower()))) return [w for w,_ in c.most_common(3)]
PYTHON
{ "starter_code": "\ndef top_3_words(text):\n\t", "url": "https://www.codewars.com/kata/51e056fe544cf36c410000fb" }
d1719
train
MOVES = {(0,1), (0,-1), (1,0), (-1,0)} def has_exit(maze): posSet = {(x,y) for x in range(len(maze)) for y in range(len(maze[x])) if maze[x][y] == 'k'} if len(posSet) != 1: raise ValueError("There shouldn't be more than one kate") seen = set(posSet) while posSet: x,y = posSet.pop() if any(not (0 <= x+dx < len(maze) and 0 <= y+dy < len(maze[x+dx])) for dx,dy in MOVES): return True neighbors = {(x+dx, y+dy) for dx,dy in MOVES if 0 <= x+dx < len(maze) and 0 <= y+dy < len(maze[x+dx]) and maze[x+dx][y+dy] == ' ' and (x+dx, y+dy) not in seen} posSet |= neighbors seen |= neighbors return False
PYTHON
{ "starter_code": "\ndef has_exit(maze):\n\t", "url": "https://www.codewars.com/kata/56bb9b7838dd34d7d8001b3c" }
d1720
train
def zeroes (base, number): pzeros = [] for p in range(2, base+1): e = 0 while base % p == 0: base /= p e += 1 if e: f, m = 0, number while m: m /= p f += m pzeros.append(f / e) return min(pzeros)
PYTHON
{ "starter_code": "\ndef zeroes (base, number):\n\t", "url": "https://www.codewars.com/kata/55c4eb777e07c13528000021" }
d1721
train
import string from collections import OrderedDict class RomanNumerals: @classmethod def to_roman(self, num): conversions = OrderedDict([('M',1000), ('CM',900), ('D', 500), ('CD',400), ('C',100), ('XC',90), ('L',50), ('XL',40), ('X',10), ('IX',9), ('V',5), ('IV',4), ('I',1)]) out = '' for key, value in conversions.items(): while num >= value: out += key num -= value return out @classmethod def from_roman(self, roman): conversions = OrderedDict([('CM',900), ('CD',400), ('XC',90), ('XL',40), ('IX',9), ('IV',4), ('M',1000), ('D',500), ('C',100), ('L',50), ('X',10), ('V',5), ('I',1)]) out = 0 for key, value in conversions.items(): out += value * roman.count(key) roman = string.replace(roman, key, "") return out
PYTHON
{ "starter_code": "\ndef to_roman(n):\n\t", "url": "https://www.codewars.com/kata/51b66044bce5799a7f000003" }
d1722
train
def create_number_class(alphabet): n = len(alphabet) class Number(object): def __init__(self, s): if isinstance(s, str): v = 0 for c in s: v = v * n + alphabet.index(c) else: v = s self.value = v def __add__(self, other): return Number(self.value + other.value) def __sub__(self, other): return Number(self.value - other.value) def __mul__(self, other): return Number(self.value * other.value) def __floordiv__(self, other): return Number(self.value // other.value) def __str__(self): ret = [] v = int(self.value) while v: (v, r) = divmod(v, n) ret.append(alphabet[r]) return ''.join(reversed(ret or alphabet[0])) def convert_to(self, cls): return cls(self.value) return Number
PYTHON
{ "starter_code": "\ndef create_number_class(alphabet):\n\t", "url": "https://www.codewars.com/kata/54baad292c471514820000a3" }
d1723
train
class Machine: def __init__(self): self.cmd = dict() self._actions = [lambda x: x + 1, lambda x: 0, lambda x: x / 2, lambda x: x * 100, lambda x: x % 2] def command(self, cmd, num): self.last_cmd = cmd if cmd in self.cmd: return self._actions[self.cmd[cmd]](num) else: self.cmd[cmd] = 0 return self._actions[self.cmd[cmd]](num) def response(self,res): if res == False: self.cmd[self.last_cmd] += 1
PYTHON
{ "starter_code": "\ndef __init__(self):\n\t", "url": "https://www.codewars.com/kata/5695995cc26a1e90fe00004d" }
d1724
train
class Segment: # Instead of an abstract class, make it the implementation for all three subclasses def __init__(self, *coords): self.control_points = coords # IMHO a getter/setter is overkill here def control_points_at(self, t): # Helper function p = self.control_points result = [] while p: result.extend(p[:2]) p = [v + (p[i+2] - v) * t for i, v in enumerate(p[:-2])] return result def point_at(self, t): return tuple(self.control_points_at(t)[-2:]) def sub_segment(self, t): return self.__class__(*self.control_points_at(t)) class Line(Segment): pass class Quad(Segment): pass class Cubic(Segment): pass
PYTHON
{ "starter_code": "\ndef control_points(self):\n\t", "url": "https://www.codewars.com/kata/5a47391c80eba865ea00003e" }
d1725
train
def blast_sequence(aliensStart,position): def moveAliens(aliens, furthest): lst, shootPath = [], [] for x,y,s in aliens: y += s if not (0 <= y < N): #Out of the grid: move down and reverse x, s = x+1, -s y = -y-1 if y < 0 else 2*N-y-1 (shootPath if y == Y else lst).append((x,y,s)) if x > furthest: furthest = x return lst, shootPath, furthest def shootTarget(shootPath): if shootPath: z = max(shootPath, key=lambda a: (a[0], abs(a[2]), a[2])) # Furthest, fastest, going right is considered the highest shootPath.remove(z) # MUTATION shots.append(turn) # MUTATION (X,Y), N = position, len(aliensStart[0]) aliens = [(x,y,s) for x,r in enumerate(aliensStart) for y,s in enumerate(r) if s] shots, furthest, turn = [], 0, -1 while aliens and furthest < X: turn += 1 aliens, shootPath, furthest = moveAliens(aliens, furthest) # Move all the aliens, splitting them in 2 groups: those facing "my" ship (shootPath) and the others shootTarget(shootPath) # Extract the target in shootPath and pop it if possible (mutation). Mutate 'shots' list at the same time aliens += shootPath # Put the remaining aliens in the list return shots if not aliens else None
PYTHON
{ "starter_code": "\ndef blast_sequence(aliens, position):\n\t", "url": "https://www.codewars.com/kata/59fabc2406d5b638f200004a" }
d1726
train
mod = 12345787 mat = [([1,1],[0,1,3]), ([2,1,-1],[0,2,6,11]), ([2,3,-1,-1],[0,2,10,23,70]), ([3,3,-4,-1,1],[0,3,15,42,155,533]), ([3,6,-4,-5,1,1],[0,3,21,69,301,1223,5103])] for i in range(100): [m.append(sum(k*m[-1-i] for i,k in enumerate(c))%mod) for c,m in mat] def circular_limited_sums(max_n, max_fn): return mat[max_fn-1][1][max_n]
PYTHON
{ "starter_code": "\ndef circular_limited_sums(max_n, max_fn):\n\t", "url": "https://www.codewars.com/kata/59951f21d65a27e95d00004f" }
d1727
train
def path_finder(maze): matrix = list(map(list, maze.splitlines())) stack, length = [[0, 0]], len(matrix) while len(stack): x, y = stack.pop() if matrix[x][y] == '.': matrix[x][y] = 'x' for x, y in (x, y-1), (x, y+1), (x-1, y), (x+1, y): if 0 <= x < length and 0 <= y < length: stack.append((x, y)) return matrix[length-1][length-1] == 'x'
PYTHON
{ "starter_code": "\ndef path_finder(maze):\n\t", "url": "https://www.codewars.com/kata/5765870e190b1472ec0022a2" }
d1728
train
def find_word(board, word): grid = [l+[''] for l in board] + [[''] * (len(board[0]) + 1)] def rc(x, y, i): if i == len(word): return True if grid[x][y] != word[i]: return False grid[x][y] = '' r = any(rc(x + u, y + v, i + 1) for u in range(-1, 2) for v in range(-1, 2)) grid[x][y] = word[i] return r return any(rc(x, y, 0) for x in range(len(board)) for y in range(len(board[x])))
PYTHON
{ "starter_code": "\ndef find_word(board, word):\n\t", "url": "https://www.codewars.com/kata/57680d0128ed87c94f000bfd" }
d1729
train
class PlayerMovement: PREC = [8, 2, 4, 6] # Order of precedence I_KEYS = {8: 0, 2: 1, 4: 2, 6: 3} # Index of the keys in self.pressed MOVES = {8: (0,1), 2: (0,-1), 4: (-1,0), 6: (1,0)} # Moves directions def __init__(self, x, y): self.position = Tile(x, y) # Current position self.direction = 8 # Current direction of move self.pressed = [0,0,0,0] # Keys currently pressed or not (True/False) self.stack = [] # Stack representing the order of the pressed keys (according to pressing order AND precedence if multiple pressing at the same time) def update(self): state = [Input.get_state(d) for d in self.PREC] # State of the art at update time newPressed = [ d for i,d in enumerate(self.PREC) if not self.pressed[i] and state[i] ] # All keys freshly pressed notReleased = next((d for d in self.stack[::-1] if self.pressed[self.I_KEYS[d]] and state[self.I_KEYS[d]]), None) # Last key that has not been released yet (according to the order of the stack[::-1] because one search for the last pressed) releasedLst = [ d for i,d in enumerate(self.PREC) if self.pressed[i] and not state[i] ] # All keys freshly released if newPressed: # If new key pressed: self.direction = newPressed[0] # Update direction with higher precedence for t in newPressed[::-1]: self.stack.append(t) # append all the new kleys to the stack, lower preccedence first elif self.direction in releasedLst: # If the current direction has been released: self.direction = notReleased or self.direction # upadte direction. If no pressed key remain, do not update elif notReleased: # If current direction still pressed and no other key pressed in the meantime: self.position = Tile(*( z+dz for z,dz in zip([self.position.x, self.position.y], self.MOVES[notReleased]) )) # MOVE! self.pressed = state # Archive current state of keys for t in releasedLst: self.stack.remove(t) # remove all the released keys from the stack, whatever their position in the stack is
PYTHON
{ "starter_code": "\ndef __init__(self, x, y):\n\t", "url": "https://www.codewars.com/kata/59315ad28f0ebeebee000159" }
d1730
train
import re class Me(object): def __init__(self): self.x, self.y, self.dx, self.dy = 0,0,-1,0 def move(self, n): self.x += n*self.dx ; self.y += n*self.dy def back(self): self.dx *= -1 ; self.dy *= -1 def turn(self, d): self.dx,self.dy = (self.dy * (-1)**(d=='l'), 0) if self.dy else (0, self.dx * (-1)**(d=='r')) def where(self): return [self.x, self.y] def __str__(self): return f'x,y={self.x},{self.y} (dx,dy={self.dx},{self.dy})' me = Me() def i_am_here(path): for v in re.findall(r'\d+|.', path): if v in 'RL': me.back() elif v in 'rl': me.turn(v) else: me.move(int(v)) return me.where()
PYTHON
{ "starter_code": "\ndef i_am_here(path):\n\t", "url": "https://www.codewars.com/kata/5a0573c446d8435b8e00009f" }
d1731
train
def two_by_n(n, k): vv, vh, hv, hh = k-1, (k-1)*(k-2), k-2, (k-1)*(k-2) + 1 va, ha, vb, hb = 0, 0, 1, 1 for i in range(n - 1): va, ha, vb, hb = vb, hb, vv*vb + vh*ha, hv*vb + hh*ha return (k * vb + k*(k-1) * ha) % 12345787
PYTHON
{ "starter_code": "\ndef two_by_n(n, k):\n\t", "url": "https://www.codewars.com/kata/5a59e029145c46eaac000062" }
d1732
train
from random import choice def interpret(code): code = [list(l) for l in code.split('\n')] x, y = 0, 0 dx, dy = 1, 0 output = '' stack = [] string_mode = False while True: move = 1 i = code[y][x] if string_mode: if i == '"': string_mode = False else: stack.append(ord(i)) else: if i.isdigit(): stack.append(int(i)) elif i == '+': stack[-2:] = [stack[-2] + stack[-1]] elif i == '-': stack[-2:] = [stack[-2] - stack[-1]] elif i == '*': stack[-2:] = [stack[-2] * stack[-1]] elif i == '/': stack[-2:] = [stack[-2] and stack[-2] / stack[-1]] elif i == '%': stack[-2:] = [stack[-2] and stack[-2] % stack[-1]] elif i == '!': stack[-1] = not stack[-1] elif i == '`': stack[-2:] = [stack[-2] > stack[-1]] elif i in '><^v?': if i == '?': i = choice('><^v') if i == '>': dx, dy = 1, 0 elif i == '<': dx, dy = -1, 0 elif i == '^': dx, dy = 0, -1 elif i == 'v': dx, dy = 0, 1 elif i == '_': dx, dy = (-1 if stack.pop() else 1), 0 elif i == '|': dx, dy = 0, (-1 if stack.pop() else 1) elif i == '"': string_mode = True elif i == ':': stack.append(stack[-1] if stack else 0) elif i == '\\': stack[-2:] = stack[-2:][::-1] elif i == '$': stack.pop() elif i == '.': output += str(stack.pop()) elif i == ',': output += chr(stack.pop()) elif i == '#': move += 1 elif i == 'p': ty, tx, tv = stack.pop(), stack.pop(), stack.pop() code[ty][tx] = chr(tv) elif i == 'g': ty, tx = stack.pop(), stack.pop() stack.append(ord(code[ty][tx])) elif i == '@': return output for _ in range(move): x = (x + dx) % len(code[y]) y = (y + dy) % len(code)
PYTHON
{ "starter_code": "\ndef interpret(code):\n\t", "url": "https://www.codewars.com/kata/526c7b931666d07889000a3c" }
d1733
train
from collections import defaultdict from functools import reduce import re P_EQ = re.compile("(?P<eq>=)|(?P<coef>[+-]?\d*)(?P<var>[a-zA-Z]*)") def solve(*equations): eqsMap = list(map(parse, equations)) # Transform each string in a dict {'var': coef} vars = reduce(set.union, (set(e) for e in eqsMap)) # Extract all the variables vars = list(set(vars)-{''}) + [''] # Push the "constants" at the end of the list if len(vars)-1 > len(equations): return None # Not enough equations to solve the system m = [ [eqm[v] for v in vars] for eqm in eqsMap] # Build the matrix return solveMatrix(m, vars) # Solve using Gauss elimination def parse(eq): rev, dct = 1, defaultdict(int) for m in P_EQ.finditer(eq.replace(" ","")): if m['eq']: rev = -1 else: gc, gv = m['coef'], m['var'] if gc or gv: coef = 1 if not gc or gc == '+' else -1 if gc == '-' else int(gc) dct[ m['var'] ] += coef * rev return dct def solveMatrix(m, vars): EPS = 1e-10 pivots = {} # dict of the indexes of the pivots (avoid to have to move the raws) toDo = set(range(len(m))) # set with the indexes of all the lines where the pivot will have to be sought for for y in range(len(vars)-1): # "-1" to avoid the constants _,px = max( ((abs(m[x][y]),x) for x in toDo if abs(m[x][y]) > 0), default=(-1,-1)) if px == -1: continue # No pivot found pivots[px] = y toDo.remove(px) maxP, m[px][y] = m[px][y], 1 for j in range(y+1,len(vars)): # Update the line of the current pivot m[px][j] /= maxP if abs(m[px][j]) < EPS: m[px][j] = 0 # Handle floating point errors for x in range(0,len(m)): # Update all the lines, doing the elimination if x==px: continue # Skip the line of the current pivot coef, m[x][y] = m[x][y], 0 for j in range(y+1,len(vars)): # Update the line of the current pivot m[x][j] -= coef * m[px][j] if abs(m[x][j]) < EPS: m[x][j] = 0 # Handle floating point errors, again... solvedDct = {} for x in range(len(m)): # Build the solution dict yP = pivots.get(x, None) if yP is None: continue solvedDct[ vars[yP] ] = -m[x][-1] if len(solvedDct) == len(vars)-1: return solvedDct # Valid only if all the variables have been used as pivots
PYTHON
{ "starter_code": "\ndef solve(*equations):\n\t", "url": "https://www.codewars.com/kata/56d6d927c9ae3f115b0008dd" }
d1734
train
from collections import deque moves = ((1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)) def knight(p1, p2): x, y = ord(p2[0])-97, int(p2[1])-1 left, seen = deque([(ord(p1[0])-97, int(p1[1])-1, 0)]), set() while left: i, j, v = left.popleft() if i==x and j==y: return v if (i, j) in seen: continue seen.add((i, j)) for a,b in moves: if 0 <= i+a < 8 and 0 <= j+b < 8: left.append((i+a, j+b, v+1))
PYTHON
{ "starter_code": "\ndef knight(p1, p2):\n\t", "url": "https://www.codewars.com/kata/549ee8b47111a81214000941" }
d1735
train
class User (): def __init__ (self): self.RANKS = [-8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8] self.rank = -8 self.rank_index = 0 self.progress = 0 def inc_progress (self, rank): rank_index = self.RANKS.index(rank) if rank_index == self.rank_index: self.progress += 3 elif rank_index == self.rank_index - 1: self.progress += 1 elif rank_index > self.rank_index: difference = rank_index - self.rank_index self.progress += 10 * difference * difference while self.progress >= 100: self.rank_index += 1 self.rank = self.RANKS[self.rank_index] self.progress -= 100 if self.rank == 8: self.progress = 0 return
PYTHON
{ "starter_code": "\ndef __init__(self):\n\t", "url": "https://www.codewars.com/kata/51fda2d95d6efda45e00004e" }
d1736
train
from heapq import * MOVES = tuple( (dx,dy) for dx in range(-1,2) for dy in range(-1,2) if dx or dy) def shallowest_path(river): lX,lY = len(river), len(river[0]) pathDct = {} cost = [ [(float('inf'),float('inf'))]*lY for _ in range(lX) ] for x in range(lX): cost[x][0] = (river[x][0],1) q = [ (river[x][0], lY==1, 1, (x,0)) for x in range(lX)] heapify(q) while not q[0][1]: c,_,steps,pos = heappop(q) x,y = pos for dx,dy in MOVES: a,b = new = x+dx,y+dy if 0<=a<lX and 0<=b<lY: check = nC,nS = max(c, river[a][b]), steps+1 if cost[a][b] > check: cost[a][b] = check pathDct[new] = pos heappush(q, (nC, b==lY-1, nS, new)) path, pos = [], q[0][-1] while pos: path.append(pos) pos = pathDct.get(pos) return path[::-1]
PYTHON
{ "starter_code": "\ndef shallowest_path(river):\n\t", "url": "https://www.codewars.com/kata/585cec2471677ee42c000296" }
d1737
train
def is_incrementing(number): return str(number) in '1234567890' def is_decrementing(number): return str(number) in '9876543210' def is_palindrome(number): return str(number) == str(number)[::-1] def is_round(number): return set(str(number)[1:]) == set('0') def is_interesting(number, awesome_phrases): tests = (is_round, is_incrementing, is_decrementing, is_palindrome, awesome_phrases.__contains__) for num, color in zip(range(number, number+3), (2, 1, 1)): if num >= 100 and any(test(num) for test in tests): return color return 0
PYTHON
{ "starter_code": "\ndef is_interesting(number, awesome_phrases):\n\t", "url": "https://www.codewars.com/kata/52c4dd683bfd3b434c000292" }
d1738
train
from collections import Counter def runoff(voters): while voters[0]: poll = Counter(ballot[0] for ballot in voters) winner, maxscore = max(poll.items(), key = lambda x: x[1]) minscore = min(poll.values()) if maxscore * 2 > len(voters): return winner voters = [[c for c in voter if poll[c] > minscore] for voter in voters]
PYTHON
{ "starter_code": "\ndef runoff(voters):\n\t", "url": "https://www.codewars.com/kata/52996b5c99fdcb5f20000004" }
d1739
train
from collections import defaultdict from itertools import combinations def norme(vect): return sum( v**2 for v in vect )**.5 def vectorize(pt1, pt2): return [b-a for a,b in zip(pt1, pt2)] def isInCircle(d, r): return d < r and (r-d)/r > 1e-10 def crossProd(v1, v2): return [v1[0]*v2[1] - v1[1]*v2[0], v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2] ] def biggest_triang_int(point_list, center, radius): filteredPts = [ pt for pt in point_list if isInCircle(norme(vectorize(pt, center)), radius) ] dctTriangles = defaultdict(list) for threePts in combinations(filteredPts, 3): area = abs( norme(crossProd(vectorize(*threePts[:2]), vectorize(*threePts[1:]))) / 2.0 ) if area > 1e-8: dctTriangles[area].append(list(threePts)) maxArea = max(dctTriangles.keys()) if dctTriangles else 0 return [] if not dctTriangles else [sum(map(len, dctTriangles.values())), maxArea, sorted(dctTriangles[maxArea]) if len(dctTriangles[maxArea]) > 1 else dctTriangles[maxArea][0] ]
PYTHON
{ "starter_code": "\ndef biggest_triang_int(points, center, r):\n\t", "url": "https://www.codewars.com/kata/57deba2e8a8b8db0a4000ad6" }
d1740
train
def decodeBits(bits): import re # remove trailing and leading 0's bits = bits.strip('0') # find the least amount of occurrences of either a 0 or 1, and that is the time hop time_unit = min(len(m) for m in re.findall(r'1+|0+', bits)) # hop through the bits and translate to morse return bits[::time_unit].replace('111', '-').replace('1','.').replace('0000000',' ').replace('000',' ').replace('0','') def decodeMorse(morseCode): return ' '.join(''.join(MORSE_CODE[l] for l in w.split()) for w in morseCode.split(' '))
PYTHON
{ "starter_code": "\ndef decodeBits(bits):\n\t", "url": "https://www.codewars.com/kata/54b72c16cd7f5154e9000457" }
d1741
train
class family: def __init__(self): self.names = {} def male(self, n): return self.setsex(n, 'm') def female(self, n): return self.setsex(n, 'f') def is_male(self, n): return self.names[n]['sex'] == 'm' if n in self.names else False def is_female(self, n): return self.names[n]['sex'] == 'f' if n in self.names else False def get_parents_of(self, n): return sorted(self.names[n]['childof']) if n in self.names else [] def get_children_of(self, n): return sorted(self.names[n]['parentof']) if n in self.names else [] def updatesex(self): for n in [n for n in self.names if len(self.names[n]['childof']) == 2]: for a, b in [self.names[n]['childof'], self.names[n]['childof'][::-1]]: if self.names[a]['sex'] and not self.names[b]['sex']: self.names[b]['sex'] = 'f' if self.names[a]['sex'] == 'm' else 'm' self.updatesex() def setsex(self, name, sex): if name not in self.names: self.names[name] = {'sex':'', 'parentof':[], 'childof':[]} if not self.names[name]['sex']: self.names[name]['sex'] = sex self.updatesex() return self.names[name]['sex'] == sex def set_parent_of(self, c, p): # Create child and/or parent if they do not exist for n in [c, p]: if n not in self.names: self.names[n] = {'sex':'', 'parentof':[], 'childof':[]} if p in self.names[c]['childof']: return True if c == p or len(self.names[c]['childof']) == 2: return False # descendants and ancestors for tree, direction, name in [(self.names[c]['parentof'], 'parentof', p), (self.names[p]['childof'], 'childof', c)]: while tree: if name in tree: return False tree = [e for d in tree for e in self.names[d][direction]] if len(self.names[c]['childof']) == 1: old_p, new_sex = self.names[c]['childof'][0], self.names[p]['sex'] if new_sex + self.names[old_p]['sex'] in ['mm', 'ff']: return False # Check for clashing parents # Get all couple and create a putative sex dictionary S couples = {tuple(self.names[n]['childof']) for n in self.names if len(self.names[n]['childof']) > 1} | {tuple((old_p, p))} S = {p:new_sex or 'm'} while any(parent in S for couple in couples for parent in couple): newcouples = [] for a, b in couples: if a in S or b in S: if b not in S: S[b] = 'f' if S[a] == 'm' else 'm' if a not in S: S[a] = 'f' if S[b] == 'm' else 'm' if S[a] == S[b]: return False else: newcouples.append((a, b)) couples = newcouples self.names[p]['parentof'] += [c] self.names[c]['childof'] += [p] self.updatesex() return True
PYTHON
{ "starter_code": "\ndef __init__(self):\n\t", "url": "https://www.codewars.com/kata/5b602842146a2862d9000085" }
d1742
train
import numpy as np def five_by_2n(n): x=np.array([[1,1,1,1,1,1,1,1],[1,2,1,1,1,2,2,1],[1,1,2,1,1,1,2,1],[1,1,1,2,1,1,2,1],[1,1,1,1,2,1,2,2],[1,2,1,1,2,1,6,1],[1,2,1,1,2,1,6,1],[1,2,1,1,2,1,6,1]]) y=np.array([1,1,1,1,1,1,1,1]) z=y for i in range(n-1): z=np.mod(x@z,12345787*y) return z.T@y%12345787
PYTHON
{ "starter_code": "\ndef five_by_2n(n):\n\t", "url": "https://www.codewars.com/kata/5a77f76bfd5777c6c300001c" }
d1743
train
def combos(n, m = 1): if n < m:return [] res = [[n]] for i in xrange(m, n): l = [i] for j in combos(n - i, i): res += [l + j] return res
PYTHON
{ "starter_code": "\ndef combos(n):\n\t", "url": "https://www.codewars.com/kata/555b1890a75b930e63000023" }
d1744
train
def collatz_steps(n, steps): while True: str = '' result = n while bool(str != steps) ^ bool(str != steps[:len(str)]): if result % 2 == 0: result = result/2 str += 'D' else: result = (3*result + 1)/2 str += 'U' if str != steps: n += 2**(len(str)-1) else: return n
PYTHON
{ "starter_code": "\ndef collatz_steps(n, steps):\n\t", "url": "https://www.codewars.com/kata/5992e103b1429877bb00006b" }
d1745
train
def fusc(n): a, b = 1, 0 for i in bin(n)[2:]: if i == '1': b += a else: a += b return b
PYTHON
{ "starter_code": "\ndef fusc(n):\n\t", "url": "https://www.codewars.com/kata/57040e445a726387a1001cf7" }
d1746
train
import re ADDSUB, MULDIV = '+-', '*$' def calculate(expression): return "400: Bad request" if re.search(r'[^+*$\d.-]', expression) else parseAndEval(expression, ADDSUB) def parseAndEval(expression, ops): v = 0 for op,part in re.findall(r'([{0}])?([^{0}]+)'.format(ops), expression): if not op: v = float(part) if ops == MULDIV else parseAndEval(part, MULDIV) elif op=='*': v *= float(part) elif op=='$': v /= float(part) elif op=='+': v += parseAndEval(part, MULDIV) elif op=='-': v -= parseAndEval(part, MULDIV) return v
PYTHON
{ "starter_code": "\ndef calculate(expression):\n\t", "url": "https://www.codewars.com/kata/581bc0629ad9ff9873000316" }
d1747
train
def rpg(field, actions): p = Player(field) try: for m in actions: if m=='A': p.attack() elif m in 'HCK': p.use(m) elif m in '<^>v': p.rotate(m) p.checkDmgsAndAlive() if m=='F': p.move() except Exception as e: return None return p.state() class Player: DIRS = dict(list(zip('<>^v',((0,-1),(0,1),(-1,0),(1,0))))) def __init__(self,field): self.h, self.atk, self.d, self.bag, self.xps = 3,1,1,[],0 self.field = field self.pngs = {} for x,r in enumerate(self.field): for y,c in enumerate(r): if c in self.DIRS: self.x,self.y,self.c=x,y,c ; self.dx,self.dy=self.DIRS[c] elif c=='D': self.pngs[(x,y)] = {'h':10, 'atk':3} elif c=='E': self.pngs[(x,y)] = {'h':1, 'atk':2} elif c=='M': self.pngs['M'] = {'coins':3} def state(self): return self.field, self.h, self.atk, self.d, sorted(self.bag) def rotate(self,c): self.dx, self.dy = self.DIRS[c] self.c = self.field[self.x][self.y] = c def move(self): self.field[self.x][self.y] = ' ' self.x += self.dx self.y += self.dy c = self.field[self.x][self.y] assert c not in '#ED-|M' and self.x>=0 and self.y>=0 if c!=' ': self.takeThis(c) self.field[self.x][self.y] = self.c def checkAhead(self,what): x,y = self.x+self.dx, self.y+self.dy assert self.field[x][y] in what return x,y def takeThis(self,c): if c not in 'SX': self.bag.append(c) if c=='S': self.d += 1 elif c=='X': self.atk += 1 def use(self,c): self.bag.remove(c) if c=='C': x,y = self.checkAhead('M') self.pngs['M']['coins'] -= 1 if not self.pngs['M']['coins']: self.field[x][y] = ' ' elif c=='H': assert self.h<3 self.h = 3 elif c=='K': x,y = self.checkAhead('|-') self.field[x][y] = ' ' def attack(self): x,y = nmy = self.checkAhead('ED') self.pngs[nmy]['h'] -= self.atk if self.pngs[nmy]['h']<1: del self.pngs[nmy] self.field[x][y] = ' ' lvlUp,self.xps = divmod(self.xps+1,3) self.atk += lvlUp def checkDmgsAndAlive(self): for dx,dy in list(self.DIRS.values()): nmy = self.x+dx, self.y+dy if nmy in self.pngs: self.h -= max(0,self.pngs[nmy]['atk'] - self.d) assert self.h>0
PYTHON
{ "starter_code": "\ndef rpg(field, actions):\n\t", "url": "https://www.codewars.com/kata/5e95b6e90663180028f2329d" }
d1748
train
def crosstable(players, scores): points, le = {j:sum(k or 0 for k in scores[i]) for i, j in enumerate(players)}, len(players) SB = {j:sum(points[players[k]] / ([1, 2][l == 0.5]) for k, l in enumerate(scores[i]) if l) for i, j in enumerate(players)} SORTED, li = [[i, players.index(i)] for i in sorted(players, key=lambda x: (-points[x], -SB[x], x.split()[1]))], [] ps = [format(i, '.1f') for i in points.values()] Ss = [format(i, '.2f') for i in SB.values()] digit = len(str(le)) name = len(max(players, key=len)) pts = len(str(max(ps, key=lambda x: len(str(x))))) sb = len(str(max(Ss, key=lambda x: len(str(x))))) for i, j in enumerate(SORTED): ten_ = [" ", " "][le >= 10] index = [str(i + 1), " "][points[j[0]] == points[SORTED[i - 1][0]] and SB[j[0]] == SB[SORTED[i - 1][0]]].rjust(digit) name_ = j[0].ljust(name) team = ten_.join(['1=0 '[[1, 0.5, 0, None].index(scores[j[1]][l])] or '_' for k, l in SORTED]) pt = str(format(points[j[0]], ".1f")).rjust(pts) Sb = str(format(SB[j[0]], ".2f")).rjust(sb) li.append(f'{index} {name_}{[" ", " "][le >= 10]}{team} {pt} {Sb}') fline = ' '.join(['#'.rjust(digit) + ' ' + 'Player'.ljust(name) + [' ', ' '][len(players) >= 10] + ''.join([[' ', ' '][i < 10 and le >= 10] + str(i) for i in range(1, le + 1)]).strip() + ' ' + 'Pts'.center(pts) + ' ' + 'SB'.center(sb - [0, 2][sb & 1])]).rstrip() return '\n'.join([fline, '=' * len(max(li, key=len))] + li)
PYTHON
{ "starter_code": "\ndef crosstable(players, results):\n\t", "url": "https://www.codewars.com/kata/5a392890c5e284a7a300003f" }
d1749
train
import collections class Tower: def __init__(self): indicesOfAlienPath = [] shots = 0 class GameStats: def __init__(self): alienPath = collections.deque() towers = [] waves = collections.deque() DirEOL = 0 DirLeft = 1 DirRight = 2 DirUp = 3 DirDown = 4 def tower_defense(grid, turrets, aliens): game = FromBattlefield(grid, turrets, aliens) numSurvivedAliens = 0 while AnalysisIsRunning(game.alienPath, game.remainingWaves): game = PrepareRound(game) game.alienPath = KillAliens(game.alienPath, game.towers) numSurvivedAliens = numSurvivedAliens + CountAliensLeavingPath(game.alienPath) return numSurvivedAliens def FromBattlefield(grid, turrets, aliens): coords = DeterminePathCoordinates(grid) game = GameStats() game.alienPath = collections.deque([0 for a in range(len(coords))]) game.towers = CreateTowers(grid, turrets, coords) game.remainingWaves = collections.deque(aliens) return game def DeterminePathCoordinates(grid): result = [] coord = GetCoordFor(grid, '0') result.append(coord) dir = LookForPath(grid, coord, DirEOL) while dir != DirEOL: coord = GetCoordinate(coord, dir) result.append(coord) dir = LookForPath(grid, coord, dir) return result def GetCoordFor(grid, id): n = len(grid) for row in range(n): for col in range(n): if grid[row][col] == id: return (col, row) return (0,0) def LookForPath(grid, c, dir): if IsOnPath(grid, (c[0]+1, c[1])) and dir != DirLeft: return DirRight elif IsOnPath(grid, (c[0]-1, c[1])) and dir != DirRight: return DirLeft elif IsOnPath(grid, (c[0], c[1]-1)) and dir != DirDown: return DirUp elif IsOnPath(grid, (c[0], c[1]+1)) and dir != DirUp: return DirDown return DirEOL def GetCoordinate(orig, dir): if dir == DirLeft: return (orig[0]-1, orig[1]) elif dir == DirRight: return (orig[0]+1, orig[1]) elif dir == DirUp: return (orig[0], orig[1]-1) elif dir == DirDown: return (orig[0], orig[1]+1) return orig def IsOnPath(grid, c): n = len(grid) return c[1] < n and c[0] < n and c[1] >= 0 and c[0] >= 0 and (grid[c[1]][c[0]] == '1' or grid[c[1]][c[0]] == '0') def CreateTowers(grid, turrets, alienPathCoords): towers = [] for name in sorted(turrets.keys()): towerCoords = GetCoordFor(grid, name) pathIdxInRange = DetermineIndicesOfAlienPathInRange(alienPathCoords, towerCoords, turrets[name][0]) towers.append((pathIdxInRange, turrets[name][1])) return towers def DetermineIndicesOfAlienPathInRange(alienPathCoords, towerCoords, dist): result = [] sqrDist = dist*dist startY = max(0, towerCoords[1] - dist) startX = max(0, towerCoords[0] - dist) for y in range(startY, towerCoords[1] + dist+1): for x in range(startX, towerCoords[0] + dist+1): cur = (x, y) if cur in alienPathCoords and SqrDistance(cur, towerCoords) <= sqrDist: result.append(alienPathCoords.index(cur)) return sorted(result) def SqrDistance(left, right): y = left[1] - right[1] x = left[0] - right[0] return x*x + y*y def AnalysisIsRunning(alienPath, waves): return len(waves) > 0 or any(alienPath) def PrepareRound(game): game.alienPath.pop() if len(game.remainingWaves) > 0: game.alienPath.appendleft(game.remainingWaves.popleft()) else: game.alienPath.appendleft(0) return game def KillAliens(alienPath, towers): activeTowers = towers.copy() while CanShootAgain(activeTowers): alienPath, activeTowers = ShootWithTowers(alienPath, activeTowers) activeTowers = FilterInactiveTowers(alienPath, activeTowers) return alienPath def CanShootAgain(towers): return len(towers) > 0 def ShootWithTowers(alienPath, towers): towersShot = [] for t in towers: alienPath, t = ShootAliensInFormostPosition(alienPath, t) towersShot.append(t) return alienPath, towersShot def ShootAliensInFormostPosition(alienPath, tower): for idx in reversed(tower[0]): if alienPath[idx] > 0: shots = tower[1] - 1 alienPath[idx] = alienPath[idx] - 1 return alienPath, (tower[0], shots) return alienPath, tower def FilterInactiveTowers(alienPath, towers): result = [] for t in towers: if t[1] > 0 and AreAliensInRange(alienPath, t[0]): result.append(t) return result def AreAliensInRange(alienPath, towerRange): for idx in towerRange: if alienPath[idx] > 0: return True return False def CountAliensLeavingPath(alienPath): return alienPath[-1]
PYTHON
{ "starter_code": "\ndef __init__(self):\n\t", "url": "https://www.codewars.com/kata/5a57faad880385f3b60000d0" }
d1750
train
def isqrt(num): '''Compute int(sqrt(n)) for n integer > 0 O(log4(n)) and no floating point operation, no division''' res, bit = 0, 1 while bit <= num: bit <<= 2 bit >>= 2 while bit: if num >= res + bit: num -= res + bit res += bit << 1 res >>= 1 bit >>= 2 return res def factorize(n): for q in 2, 3: m = 0 while not n % q: m += 1 n //= q if m: yield q, m m, d, q, maxq = 0, 4, 1, isqrt(n) while q <= maxq: q, d = q + d, 6 - d while not n % q: m += 1 n //= q if m: yield q, m m, d, q, maxq = 0, 4, 1, isqrt(n) if n > 1: yield n, 1 def count_factor(n, f): s = 0 while n >= f: n //= f s += n return s trailing_zeros = lambda n, b: min(count_factor(n, f)//m for f, m in factorize(b))
PYTHON
{ "starter_code": "\ndef trailing_zeros(num, base):\n\t", "url": "https://www.codewars.com/kata/544483c6435206617a00012c" }
d1751
train
def mystery(n): return n ^ (n >> 1) def mystery_inv(n): mask = n >> 1 while mask != 0: n = n ^ mask mask = mask >> 1 return n; def name_of_mystery(): return "Gray code"
PYTHON
{ "starter_code": "\ndef mystery(n):\n\t", "url": "https://www.codewars.com/kata/56b2abae51646a143400001d" }
d1752
train
from heapq import * from itertools import starmap from collections import deque, namedtuple Army = namedtuple('Army', 'i,q') Soldier = namedtuple('Soldier', 'i,speed') def queue_battle(d, *args): armies = [ Army(i, deque(starmap(Soldier,enumerate(q))) ) for i,q in enumerate(args)] bullets = [[] for _ in range(len(armies))] # bullet[i] shoots at armies[i+1] t = 0 while len(armies)>1: t += 1 alives = [1]*len(armies) for i,q in enumerate(bullets): if q and q[0]<=t: alives[ (i+1)%len(armies) ] = 0 while q and q[0]<=t: heappop(q) emptyArmies = False for i,alive in enumerate(alives): if alive: heappush(bullets[i], t + d/armies[i].q[0].speed) armies[i].q.rotate(-1) else: armies[i].q.popleft() emptyArmies |= not armies[i].q if emptyArmies: armies = [army for army in armies if army.q] bullets = [[] for _ in range(len(armies))] if not armies: return (-1,()) win = armies.pop() return (win.i, tuple(soldier.i for soldier in win.q))
PYTHON
{ "starter_code": "\ndef queue_battle(dist,*armies):\n\t", "url": "https://www.codewars.com/kata/5d617c2fa5e6a2001a369da2" }
d1753
train
from itertools import product ADJACENTS = ('08', '124', '2135', '326', '4157', '52468', '6359', '748', '85790', '968') def get_pins(observed): return [''.join(p) for p in product(*(ADJACENTS[int(d)] for d in observed))]
PYTHON
{ "starter_code": "\ndef get_pins(observed):\n\t", "url": "https://www.codewars.com/kata/5263c6999e0f40dee200059d" }
d1754
train
def least_bribes(bribes): mem = {} def s(n1, n2): if n1 >= n2: return 0 if (n1, n2) in mem: return mem[n1, n2] r = min(bribes[i] + max(s(n1, i), s(i + 1, n2)) for i in range(n1, n2)) mem[n1, n2] = r return r return s(0, len(bribes))
PYTHON
{ "starter_code": "\ndef least_bribes(bribes):\n\t", "url": "https://www.codewars.com/kata/56d5078e945d0d5d35001b74" }
d1755
train
def valid(a): d = {} day_length = len(a[0]) group_size = len(a[0][0]) golfers = {g for p in a[0] for g in p} for day in a: if len(day) != day_length: return False for group in day: if len(group) != group_size: return False for player in group: if player not in golfers: return False if player not in d: d[player] = set(group) else: if len(d[player] & set(group)) > 1: return False else: d[player].add(group) return True
PYTHON
{ "starter_code": "\ndef valid(a):\n\t", "url": "https://www.codewars.com/kata/556c04c72ee1147ff20000c9" }
d1756
train
def splitlist(l): half = sum(l) // 2 sums = [(0, [])] for i, n in enumerate(l): sums = sums + [(m + n, a + [i]) for m, a in sums if m + n <= half] if max(s[0] for s in sums) == half: break sums.sort(key=lambda v: abs(v[0] - half)) indices = sums[0][1] return [n for i, n in enumerate(l) if i in indices], [n for i, n in enumerate(l) if i not in indices]
PYTHON
{ "starter_code": "\ndef splitlist(lst):\n\t", "url": "https://www.codewars.com/kata/586e6b54c66d18ff6c0015cd" }
d1757
train
def handle(func, success, failure, *exceptions): class manager: def __enter__(self): pass def __exit__(self, type, value, traceback): if isinstance(value, exceptions): failure(func, value) return True return not value with manager(): success(func, func())
PYTHON
{ "starter_code": "\ndef handle(func, success, failure, *exceptions):\n\t", "url": "https://www.codewars.com/kata/5950eec3a100d72be100003f" }
d1758
train
def knights_tour(start, size): MOVES = [(-2,1), (-2,-1), (-1,-2), (1,-2), (2,-1), (2,1), (1,2), (-1,2)] def genNeighs(pos): return ((pos[0]+dx, pos[1]+dy) for dx,dy in MOVES if (pos[0]+dx, pos[1]+dy) in Warnsdorf_DP) def travel(pos): neighs = sorted( (Warnsdorf_DP[n], n) for n in genNeighs(pos) ) for nSubNeighs,neigh in neighs: del Warnsdorf_DP[neigh] path.append(neigh) subNeighs = list(genNeighs(neigh)) for n in subNeighs: Warnsdorf_DP[n] -= 1 travel(neigh) if not Warnsdorf_DP: break else: for n in subNeighs: Warnsdorf_DP[n] += 1 Warnsdorf_DP[path.pop()] = nSubNeighs path, Warnsdorf_DP = [start], {(x,y): 0 for x in range(size) for y in range(size) if (x,y) != start} for pos in Warnsdorf_DP: Warnsdorf_DP[pos] = sum(1 for _ in genNeighs(pos)) travel(start) return path
PYTHON
{ "starter_code": "\ndef knights_tour(start, size):\n\t", "url": "https://www.codewars.com/kata/5664740e6072d2eebe00001b" }
d1759
train
import itertools def permutations(string): return list("".join(p) for p in set(itertools.permutations(string)))
PYTHON
{ "starter_code": "\ndef permutations(string):\n\t", "url": "https://www.codewars.com/kata/5254ca2719453dcc0b00027d" }
d1760
train
from collections import defaultdict def setter(prep,k,v,supSetter): if callable(v): def wrap(*args): f = prep.d[k][len(args)] if isinstance(f,int): raise AttributeError() return f(*args) prep.d[k][v.__code__.co_argcount] = v v = wrap supSetter(k,v) class Prep(dict): def __init__(self): self.d = defaultdict(lambda: defaultdict(int)) def __setitem__(self,k,v): setter(self, k, v, super().__setitem__) class Meta(type): @classmethod def __prepare__(cls,*args, **kwds): return Prep() def __new__(metacls, name, bases, prep, **kwargs): prep['_Meta__DCT'] = prep return super().__new__(metacls, name, bases, prep, **kwargs) def __setattr__(self,k,v): setter(self.__DCT, k, v, super().__setattr__)
PYTHON
{ "starter_code": "\ndef setter(prep,k,v,supSetter):\n\t", "url": "https://www.codewars.com/kata/5f24315eff32c4002efcfc6a" }
d1761
train
from collections import defaultdict def count(chessBoard): # Initialize: board = chessBoard.copy() tally = defaultdict(int) # Compute Longest square ending in bottom right corner of each element and tally up: for i, row in enumerate(board): for j, element in enumerate(row): # Edge detection: if i == 0 or j == 0: continue # Compute & Tally: if element: n = board[i][j] = min(board[i - 1][j], board[i][j - 1], board[i - 1][j - 1]) + 1 for x in range(n, 1, -1): tally[x] += 1 return tally
PYTHON
{ "starter_code": "\ndef count(chessBoard):\n\t", "url": "https://www.codewars.com/kata/5bc6f9110ca59325c1000254" }
d1762
train
idx, n, seq = 2, 6, [1, 2, 4, 6] while n < 2 ** 41: idx += 1 seq.extend(range(n + idx, n + (seq[idx] - seq[idx-1]) * idx + 1, idx)) n += (seq[idx] - seq[idx-1]) * idx from bisect import bisect def find(n): return bisect(seq, n)
PYTHON
{ "starter_code": "\ndef find(n):\n\t", "url": "https://www.codewars.com/kata/5f134651bc9687000f8022c4" }
d1763
train
def add_point(ori,dis,c): lastPoint = c[-1] if ori == "N": c.append((lastPoint[0],lastPoint[1]+dis)) elif ori == "S": c.append((lastPoint[0],lastPoint[1]-dis)) elif ori == "E": c.append((lastPoint[0]+dis,lastPoint[1])) else: c.append((lastPoint[0]-dis,lastPoint[1])) def check_corner(l_o): ini = l_o[0] fin = l_o[-1] if ini==fin: return False if ini == "N" or ini =="S": ini = "V" else: ini = "H" if fin == "N" or fin =="S": fin = "V" else: fin = "H" if ini==fin: return False return True def check_intersect(rectas): u=rectas[-1] ux=[u[0][0],u[1][0]] ux.sort() uy=[u[0][1],u[1][1]] uy.sort() oriU = "" if ux[0] == ux[1]: oriU = "V" if uy[0] == uy[1]: oriU = "H" for r in rectas[:-2]: rx=[r[0][0],r[1][0]] rx.sort() ry=[r[0][1],r[1][1]] ry.sort() oriR = "" if rx[0] == rx[1]: oriR = "V" if ry[0] == ry[1]: oriR = "H" if oriU==oriR: if oriU == "V" and ux[0]==rx[0]: if ry[0] <= uy[0] <= ry[1] or ry[0] <= uy[1] <= ry[1] : return True if uy[0] < ry[0] and uy[1] > ry[1]: return True if oriU =="H" and uy[0]==ry[0]: if rx[0] <= ux[0] <= rx[1] or rx[0] <= ux[1] <= rx[1] : return True if ux[0] < rx[0] and ux[1] > rx[1]: return True elif oriU =="V": if uy[0]<=ry[0]<=uy[1]: if rx[0] < ux[0] and rx[1] > ux[0]: return True elif oriU =="H": if ux[0]<=rx[0]<=ux[1]: if ry[0] < uy[0] and ry[1] > uy[0]: return True else: return False def calc_area(camino): parN=camino[-1][0]*camino[0][1] - camino[-1][1] * camino[0][0] for p in range(1,len(camino)): par=camino[p-1][0]*camino[p][1] - camino[p-1][1]*camino[p][0] parN+=par return abs(parN)/2 def mouse_path(s): camino=[(0,0)] distancia = 0 listaOrientaciones = ["E"] rectas = [] for c in s: orientacion = listaOrientaciones[-1] if c.isdigit(): distancia=distancia*10 + int(c) else: add_point(orientacion,distancia,camino) rectas.append((camino[-2],camino[-1])) if check_intersect(rectas): return None if c == "L": if orientacion == "N": listaOrientaciones.append("O") elif orientacion == "S": listaOrientaciones.append("E") elif orientacion == "E": listaOrientaciones.append("N") else: listaOrientaciones.append("S") else: if orientacion == "N": listaOrientaciones.append("E") elif orientacion == "S": listaOrientaciones.append("O") elif orientacion == "E": listaOrientaciones.append("S") else: listaOrientaciones.append("N") distancia = 0 add_point(orientacion,distancia,camino) rectas.append((camino[-2],camino[-1])) if check_intersect(rectas): return None if camino[-1] != (0,0): return None if not check_corner(listaOrientaciones): return None return calc_area(camino)
PYTHON
{ "starter_code": "\ndef mouse_path(s):\n\t", "url": "https://www.codewars.com/kata/5d2f93da71baf7000fe9f096" }
d1764
train
from functools import reduce from operator import mul def insane_inc_or_dec(x): return (reduce(mul,[x + i + i * (i == 10) for i in range(1, 11)]) // 3628800 - 10 * x - 2) % 12345787
PYTHON
{ "starter_code": "\ndef insane_inc_or_dec(x):\n\t", "url": "https://www.codewars.com/kata/5993e6f701726f0998000030" }
d1765
train
#THanks to easter eggs kata ;* def height(n, m): if n >= m: return (2 ** (min(n, m)) - 1) f = 1 res = 0 for i in range(n): f = f * (m - i) // (i + 1) res += f return res def solve(emulator): m = emulator.drops n = emulator.eggs h = 0 tryh = 0 while n and m: tryh = height(n - 1, m - 1) + 1 if emulator.drop(h + tryh): n -= 1 else: h += tryh m -= 1 return(h + 1) # continue here
PYTHON
{ "starter_code": "\ndef solve(emulator):\n\t", "url": "https://www.codewars.com/kata/56d3f1743323a8399200063f" }
d1766
train
def partitions(n): c = [[1]] for x in range(1, n + 1): c.append([0]) for m in range(1, x + 1): c[x].append(c[x][m - 1] + c[x - m][min(m, x - m)]) return c[n][n]
PYTHON
{ "starter_code": "\ndef partitions(n):\n\t", "url": "https://www.codewars.com/kata/546d5028ddbcbd4b8d001254" }
d1767
train
def b(n): if not n: return '0' r = [] while n: r.append(n % 2) n = (n - n % 2) / -2 return ''.join(str(c) for c in r[::-1]) def d(n): r = 0 for c in n: r = -2 * r + int(c) return r def skrzat(base, n): if base == 'b': return 'From binary: %s is %d' % (n, d(n)) if base == 'd': return 'From decimal: %d is %s' % (n, b(n)) raise ValueError('unknown base')
PYTHON
{ "starter_code": "\ndef skrzat(base, number):\n\t", "url": "https://www.codewars.com/kata/528a0762f51e7a4f1800072a" }
d1768
train
from collections import Counter def solution(tiles): return "".join( tile for tile in "123456789" if tiles.count(tile) < 4 and list(meld(meld(meld(meld(pair(Counter(map(int, tiles+tile)))))))) ) def pair(c): yield from (c - Counter([t,t]) for t in c if c[t] > 1) def meld(C): yield from ( c - m for c in C for t in [min(c.keys())] for m in (Counter((t,t+d,t+d+d)) for d in (0,1)) if (c&m) == m)
PYTHON
{ "starter_code": "\ndef solution(tiles):\n\t", "url": "https://www.codewars.com/kata/56ad7a4978b5162445000056" }
d1769
train
from itertools import chain def fit_bag(H, W, items): def deploy(item): X,Y = len(item), len(item[0]) v = (set(chain.from_iterable(item))-{0}).pop() deltas = [(x,y) for x,r in enumerate(item) for y,n in enumerate(r) if n] return (len(deltas), X*Y, max(X,Y), min(X,Y), X,Y,deltas,v) def dfs(i=0): if i==len(items): yield bag _,_,_,_,X,Y,deltas,v = items[i] for x in range(H-X+1): for y in range(W-Y+1): if all(not bag[x+dx][y+dy] for dx,dy in deltas): for dx,dy in deltas: bag[x+dx][y+dy] = v yield from dfs(i+1) for dx,dy in deltas: bag[x+dx][y+dy] = 0 bag = [ [0]*W for _ in range(H) ] items = sorted(map(deploy,items), reverse=True) return next(dfs())
PYTHON
{ "starter_code": "\ndef fit_bag(height:\n\t", "url": "https://www.codewars.com/kata/5e9c8a54ae2b040018f68dd9" }
d1770
train
from collections import defaultdict def shortestPath(gra, srs, des): Q, paths, d = [[0, srs]], [], defaultdict(list) while Q: vrt = Q.pop(0) if vrt[-1] == des: paths.append(vrt) continue for v, c in gra[vrt[-1]].items(): if v not in vrt: Q.append([vrt[0]+c] + vrt[1:] + [v]) for i in paths: d[i[0]].append(i[1:]) ml, f = len(min(d[min(d)], key = len)), [] for i in d[min(d)]: if len(i) == ml: f.append(i) return [sorted(i) for i in f] if len(f) > 2 else f
PYTHON
{ "starter_code": "\ndef shortestPath(topology, startPoint, endPoint):\n\t", "url": "https://www.codewars.com/kata/5709aa85fe2d012f1d00169c" }
d1771
train
def path_finder(maze): lst = maze.split('\n') X, Y = len(lst)-1, len(lst[0])-1 seen = {(x,y) for x,row in enumerate(lst) for y,c in enumerate(row) if c=='W'} | {(0,0)} end, bag, turn = (X,Y), {(0,0)}, 0 while bag and end not in bag: bag = { (a,b) for a,b in {(x+dx,y+dy) for x,y in bag for dx,dy in ((0,1), (0,-1), (1,0), (-1,0))} if 0 <= a <= X and 0 <= b <= Y} - seen seen |= bag turn += 1 return bool(bag) and turn
PYTHON
{ "starter_code": "\ndef path_finder(maze):\n\t", "url": "https://www.codewars.com/kata/57658bfa28ed87ecfa00058a" }
d1772
train
from heapq import heappush, heappop def closure_gen(*s): q = sorted(s) m = set(s) while q: curr = heappop(q) yield curr for i in s: t = curr * i if t not in m: heappush(q, t) m.add(t)
PYTHON
{ "starter_code": "\ndef closure_gen(*s):\n\t", "url": "https://www.codewars.com/kata/58febc23627d2f48de000060" }
d1773
train
from itertools import cycle class VigenereCipher (object): def __init__(self, key, alphabet): self.key = key.decode('utf-8') self.alphabet = alphabet.decode('utf-8') def cipher(self, mode, str): return ''.join(self.alphabet[(self.alphabet.index(m) + mode * self.alphabet.index(k)) % len(self.alphabet)] if m in self.alphabet else m for m, k in zip(str.decode('utf-8'), cycle(self.key))).encode('utf-8') def encode(self, str): return self.cipher(1, str) def decode(self, str): return self.cipher(-1, str)
PYTHON
{ "starter_code": "\ndef __init__(self, key, alphabet):\n\t", "url": "https://www.codewars.com/kata/52d1bd3694d26f8d6e0000d3" }
d1774
train
def validSolution(board): boxes = validate_boxes(board) cols = validate_cols(board) rows = validate_rows(board) return boxes and cols and rows def validate_boxes(board): for i in range(0, 9, 3): for j in range(0, 9, 3): nums = board[i][j:j+3] + board[i+1][j:j+3] + board[i+2][j:j+3] if not check_one_to_nine(nums): return False return True def validate_cols(board): transposed = zip(*board) for row in transposed: if not check_one_to_nine(row): return False return True def validate_rows(board): for row in board: if not check_one_to_nine(row): return False return True def check_one_to_nine(lst): check = range(1,10) return sorted(lst) == check
PYTHON
{ "starter_code": "\ndef validSolution(board):\n\t", "url": "https://www.codewars.com/kata/529bf0e9bdf7657179000008" }
d1775
train
class Funnel(object): SIZE = 5 def __init__(self): self.fun = [ [None] * (x+1) for x in range(self.SIZE) ] def fill(self, *args): genBlanks = ((x,y) for x,r in enumerate(self.fun) for y,v in enumerate(r) if v is None) for v,(x,y) in zip(args, genBlanks): self.fun[x][y] = v def drip(self): y,cnt = 0, sum(v is not None for row in self.fun for v in row) drop = self.fun[0][0] for x in range(self.SIZE-1): left = cnt - sum( self.fun[xx][y+xx-x] is not None for xx in range(x,self.SIZE)) right = cnt - sum( self.fun[xx][y] is not None for xx in range(x,self.SIZE)) ySwp, cnt = (y,left) if left >= right else (y+1,right) self.fun[x][y] = self.fun[x+1][ySwp] y = ySwp if not cnt: break self.fun[x+1][y] = None return drop def __str__(self): return '\n'.join( f'{" "*x}\\{" ".join( " " if v is None else str(v) for v in r)}/' for x,r in enumerate(reversed(self.fun)) )
PYTHON
{ "starter_code": "\ndef __init__(self):\n\t", "url": "https://www.codewars.com/kata/585b373ce08bae41b800006e" }
d1776
train
from itertools import permutations, chain def solve_puzzle (clues): size = 4 for poss in permutations(permutations(list(range(1, size+1)), size), size): for i in range(size): if len(set(row[i] for row in poss)) < size: break else: cols_top = [[row[i] for row in poss] for i in range(size)] rows_right = [list(reversed(row)) for row in poss] cols_btm = [[row[i] for row in reversed(poss)] for i in reversed(list(range(size)))] rows_left = list(reversed(poss)) for i, row in enumerate(chain(cols_top, rows_right, cols_btm, rows_left)): if not clues[i]: continue visible = 0 for j, v in enumerate(row): visible += v >= max(row[:j+1]) if visible != clues[i]: break else: return poss
PYTHON
{ "starter_code": "\ndef solve_puzzle (clues):\n\t", "url": "https://www.codewars.com/kata/5671d975d81d6c1c87000022" }
d1777
train
def roll_dice (rolls, sides, threshold): dp = [0] * (rolls * sides + 1) for i in range(1, sides+1): dp[i] = 1 for _ in range(rolls-1): for x in range((rolls * sides), 0, -1): dp[x] = sum(dp[max(1, x-sides):x]) return sum(dp[threshold:]) / sum(dp[1:])
PYTHON
{ "starter_code": "\ndef roll_dice (rolls, sides, threshold):\n\t", "url": "https://www.codewars.com/kata/55d18ceefdc5aba4290000e5" }
d1778
train
''' Challenge Fun #20: Edge Detection https://www.codewars.com/kata/58bfa40c43fadb4edb0000b5/train/python For a rectangular image given in run-length encoding (RLE) as described below, return a RLE of the image processed by replacing each pixel by the maximum absolute value of the difference between it and each neighboring pixel (a simple form of edge detection). For a RLE encoding string "7 15 4 100 15 25 2 ...", 7 ----> image width 15 4 ----> a pair(color value + pixel count) 100 15 ----> a pair(color value + pixel count) 25 2 ----> a pair(color value + pixel count) ... ... where the image width is > 0 and the sum of all the pixel counts is a multiple of the width. -------------------- Design of solution Read the rle-encoded values into a buffer of rows of the given width, with an important optimization trick. In the case of long runs of the same value, where three or more rows would be filled with identical data, store just three rows of data, and remember (using another data structure) which is the middle of the three rows, and how many copies of it (the "row count") were in the original image. For example, suppose the image width is 10, and the image has a run of 73 copies of the value 7, and the run starts with the last two values in row 34. The buffer would look like this: ... 34 [ some previous data ... 7, 7 ] 35 [ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 ] 36 [ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 ] 37 [ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 ] 38 [ 7, ... start of new data ... ] ... and elsewhere a note is made that row 36 has a row count of 5. With long runs arranged this way, the edge-detection transformation can be run on the buffer without having to worry about row counts. Row counts are used later, when encoding the transformed values back into a run-length encoding. ''' import itertools def edge_detection(image): data = [int(datum) for datum in image.split(' ')] width = data.pop(0) (inbuf, rowcounts) = fill_buffer(width, data) outbuf = detect_edges(inbuf) outdata_list = encode(outbuf, rowcounts) outdata = [str(datum) for datum in outdata_list] return str(width) + ' ' + ' '.join(outdata) def fill_buffer(width, data): buf = [] rowcounts = dict() # row: rowcount row, row_ndx = [], 0 while data: val, runlen = data.pop(0), data.pop(0) if row == [] and runlen > 3 * width: buf += [[val] * width] * 3 # There's a top, middle, and bottom row; middle has a row count rowcounts[row_ndx + 1] = (runlen // width) - 2 row_ndx += 3 # Values from run that didn't fit in the above rows. row = [val] * (runlen % width) continue take = min(runlen, width - len(row)) runlen -= take row += [val] * take if len(row) < width: continue # Here, row is full, with mixed values, and there may be some # (many!) values left over from the last (val, runlen) pair that # was read from data. buf.append(row) row_ndx += 1 row = [] if row == [] and runlen > 3 * width: buf += [[val] * width] * 3 # There's a top, middle, and bottom row; middle has a row count rowcounts[row_ndx + 1] = (runlen // width) - 2 row_ndx += 3 # Values from run that didn't fit in the above rows. row = [val] * (runlen % width) continue while runlen > 0: take = min(runlen, width - len(row)) runlen -= take row += [val] * take if len(row) == width: buf.append(row) row_ndx += 1 row = [] return buf, rowcounts def pairs_from(iterable, fillvalue=None): ''' Yields iterable's elements in pairs. If iterable is exhausted after an odd number of elements, completes the last pair with fillvalue. ''' # This is the 'grouper' recipe from the itertools documentation. args = [iter(iterable)] * 2 return itertools.zip_longest(*args, fillvalue=fillvalue) def detect_edges(inbuf): length = len(inbuf) width = len(inbuf[0]) outbuf = [([-1] * width).copy() for _ in range(length)] # Single pixel if 1 == width == length: return [[0]] # Single row if 1 == length: outbuf[0][0] = abs(inbuf[0][0] - inbuf[0][1]) outbuf[0][width - 1] = abs(inbuf[0][width - 2] - inbuf[0][width - 1]) for col in range(1, width - 1): val = inbuf[0][col] outbuf[0][col] = max(abs(val - inbuf[0][col - 1]), abs(val - inbuf[0][col + 1])) return outbuf # Single column if 1 == width: outbuf[0][0] = abs(inbuf[0][0] - inbuf[1][0]) outbuf[length - 1][0] = abs(inbuf[length - 2][0] - inbuf[length - 1][0]) for row in range(1, length - 1): val - inbuf[row][0] outbuf[row][0] = max(abs(val - inbuf[row - 1][0]), abs(val - inbuf[row + 1][0])) return outbuf # At least a 2 x 2 image. Unroll what we'd rather do in loops and # list comprehensions. BOT = length - 1 # convenience; last data row RT = width - 1 # convenience; last data column # Corners top_lf, top_rt = inbuf[0][0], inbuf[0][RT] bot_lf, bot_rt = inbuf[BOT][0], inbuf[BOT][RT] outbuf[0][0] = max(abs(top_lf - inbuf[0][1]), abs(top_lf - inbuf[1][0]), abs(top_lf - inbuf[1][1])) outbuf[0][RT] = max(abs(top_rt - inbuf[0][RT - 1]), abs(top_rt - inbuf[1][RT - 1]), abs(top_rt - inbuf[1][RT])) outbuf[BOT][0] = max(abs(bot_lf - inbuf[BOT - 1][0]), abs(bot_lf - inbuf[BOT - 1][1]), abs(bot_lf - inbuf[BOT][1])) outbuf[BOT][RT] = max(abs(bot_rt - inbuf[BOT - 1][RT - 1]), abs(bot_rt - inbuf[BOT - 1][RT]), abs(bot_rt - inbuf[BOT][RT])) # Top and bottom (except corners) for col in range(1, RT): val = inbuf[0][col] outbuf[0][col] = max(abs(val - inbuf[0][col - 1]), abs(val - inbuf[0][col + 1]), abs(val - inbuf[1][col - 1]), abs(val - inbuf[1][col]), abs(val - inbuf[1][col + 1])) val = inbuf[BOT][col] outbuf[BOT][col] = max(abs(val - inbuf[BOT - 1][col - 1]), abs(val - inbuf[BOT - 1][col]), abs(val - inbuf[BOT - 1][col + 1]), abs(val - inbuf[BOT][col - 1]), abs(val - inbuf[BOT][col + 1])) # Left edge (except corners) for row in range(1, BOT): val = inbuf[row][0] outbuf[row][0] = max(abs(val - inbuf[row - 1][0]), abs(val - inbuf[row - 1][1]), abs(val - inbuf[row][1]), abs(val - inbuf[row + 1][0]), abs(val - inbuf[row + 1][1])) val = inbuf[row][RT] outbuf[row][RT] = max(abs(val - inbuf[row - 1][RT - 1]), abs(val - inbuf[row - 1][RT]), abs(val - inbuf[row][RT - 1]), abs(val - inbuf[row + 1][RT -1]), abs(val - inbuf[row + 1][RT])) # Finallly! The interior for row in range(1, BOT): for col in range(1, RT): val = inbuf[row][col] outbuf[row][col] = max(abs(val - inbuf[row - 1][col - 1]), abs(val - inbuf[row - 1][col]), abs(val - inbuf[row - 1][col + 1]), abs(val - inbuf[row][col - 1]), abs(val - inbuf[row][col + 1]), abs(val - inbuf[row + 1][col - 1]), abs(val - inbuf[row + 1][col]), abs(val - inbuf[row + 1][col + 1]), ) # Now wasn't that fun? return outbuf def encode(buf, rowcounts): width = len(buf[0]) # Initial list of (value, runlength) pairs. Not necessarily a # run-length encoding, as successive values might be equal. val_rl = list() for row_ndx in range(len(buf)): encoded_row = [(val, len(list(grp))) for (val, grp) in itertools.groupby(buf[row_ndx])] if row_ndx in rowcounts: val_rl.append((encoded_row[0][0], width * rowcounts[row_ndx])) else: for (val, count) in encoded_row: val_rl.append((val, count)) encoding = list() # Now condense val_rl into a true run-length encoding. (old_val, old_rl) = val_rl.pop(0) for (val, rl) in val_rl: if val == old_val: old_rl += rl else: encoding += (old_val, old_rl) (old_val, old_rl) = val, rl encoding += (old_val, old_rl) return encoding
PYTHON
{ "starter_code": "\ndef edge_detection(image):\n\t", "url": "https://www.codewars.com/kata/58bfa40c43fadb4edb0000b5" }
d1779
train
from collections import Counter def get_key_length(cipher_text, max_key_length): avg_IC_by_keylen = {} for key_len in range(1, max_key_length+1): ICs = [] for i in range(key_len): sub_str = cipher_text[i::key_len] freq = Counter(sub_str) IC = sum(v * (v-1) for k, v in freq.items()) / (len(sub_str) * (len(sub_str)-1) ) ICs.append(IC) avg_IC_by_keylen[key_len] = sum(ICs) / key_len return max(avg_IC_by_keylen, key=avg_IC_by_keylen.get)
PYTHON
{ "starter_code": "\ndef get_key_length(text, max_key_length):\n\t", "url": "https://www.codewars.com/kata/55d6afe3423873eabe000069" }
d1780
train
def balanced_parens(n): return list(dfs([],0,0,n)) def dfs(s, open, close, maxP): if close==maxP: yield "".join(s) return if open > close: s.append(')') yield from dfs(s,open,close+1,maxP) s.pop() if open < maxP: s.append('(') yield from dfs(s,open+1,close,maxP) s.pop()
PYTHON
{ "starter_code": "\ndef balanced_parens(n):\n\t", "url": "https://www.codewars.com/kata/5426d7a2c2c7784365000783" }
d1781
train
def prod(n): ret = [{1.}] for i in range(1, n+1): ret.append({(i - x) * j for x, s in enumerate(ret) for j in s}) return ret[-1] def part(n): p = sorted(prod(n)) return "Range: %d Average: %.2f Median: %.2f" % \ (p[-1] - p[0], sum(p) / len(p), (p[len(p)//2] + p[~len(p)//2]) / 2)
PYTHON
{ "starter_code": "\ndef prod(u):\n\t", "url": "https://www.codewars.com/kata/55cf3b567fc0e02b0b00000b" }
d1782
train
def who_wins_beggar_thy_neighbour(*hands, special_cards='JQKA'): hands = [list(reversed(hand)) for hand in hands] player, deck_length = 0, sum(map(len, hands)) deal_start, deal_value, common = None, 0, [] while len(hands[player]) < deck_length: # Deal ends and current player wins common pile if deal_start == player: hands[player] = common[::-1] + hands[player] deal_start, deal_value, common = None, 0, [] continue # Cards are drawn and deal begins if penalty occurs for _ in range(min(deal_value or 1, len(hands[player]))): card = hands[player].pop() common.append(card) if card[0] in special_cards: deal_start, deal_value = player, special_cards.index(card[0]) + 1 break player = (player + 1) % len(hands) return player
PYTHON
{ "starter_code": "\ndef who_wins_beggar_thy_neighbour(hand_1, hand_2):\n\t", "url": "https://www.codewars.com/kata/58dbea57d6f8f53fec0000fb" }
d1783
train
import re class Simplexer(object): ORDERED_TOKENS = [ {"type": "integer", "reg": r'\d+'}, {"type": "boolean", "reg": r'true|false'}, {"type": "string", "reg": r'\".*\"'}, {"type": "operator", "reg": r'[-+*/%\)\(=]'}, {"type": "keyword", "reg": r'if|else|for|while|return|func|break'}, {"type": "whitespace", "reg": r'\s+'}, {"type": "identifier", "reg": r'[$_a-zA-Z][$\w]*'}] PATTERN = re.compile(r'|'.join( "(?P<{}>{})".format(dct["type"], dct["reg"]) for dct in ORDERED_TOKENS )) def __init__(self, s): self.iterable = Simplexer.PATTERN.finditer(s) def __iter__(self): return self def __next__(self): for m in self.iterable: for k,s in m.groupdict().items(): if s is None: continue return Token(s,k) raise StopIteration
PYTHON
{ "starter_code": "\ndef __init__(self, expression):\n\t", "url": "https://www.codewars.com/kata/54b8204dcd7f514bf2000348" }
d1784
train
from functools import total_ordering @total_ordering class PokerHand(object): CARDS = "AKQJT987654321" RANKS = {card: idx for idx, card in enumerate(CARDS)} def score(self, hand): values, suits = zip(*hand.split()) idxs, ordered = zip(*sorted((self.RANKS[card], card) for card in values)) is_straight = ''.join(ordered) in self.CARDS is_flush = len(set(suits)) == 1 return (-2 * sum(values.count(card) for card in values) - 13 * is_straight - 15 * is_flush, idxs) def __init__(self, hand): self.hand = hand self.score = min(self.score(hand), self.score(hand.replace('A', '1'))) def __repr__(self): return self.hand def __eq__(self, other): return self.score == other.score def __lt__(self, other): return self.score < other.score
PYTHON
{ "starter_code": "\ndef __repr__(self):\n\t", "url": "https://www.codewars.com/kata/586423aa39c5abfcec0001e6" }
d1785
train
class CurryPartial: def __init__(self, func, *args): self.func = func self.args = args def __call__(self, *args): return CurryPartial(self.func, *(self.args + args)) def __eq__(self, other): try: return self.func(*self.args) == other except TypeError: return CurryPartial(self.func, *self.args[:-1]) == other def curry_partial(f,*initial_args): "Curries and partially applies the initial arguments to the function" return CurryPartial(f, *initial_args)
PYTHON
{ "starter_code": "\ndef curry_partial(f,*args):\n\t", "url": "https://www.codewars.com/kata/53cf7e37e9876c35a60002c9" }
d1786
train
def dithering(width, height, x=0, y=0, c=1): if width <= c and height <= c: if x < width and y < height: yield x, y return for u, v in (0,0), (c,c), (c,0), (0,c): for p, q in dithering(width, height, x+u, y+v, c+c): yield p, q
PYTHON
{ "starter_code": "\ndef dithering(width, height):\n\t", "url": "https://www.codewars.com/kata/5426006a60d777c556001aad" }
d1787
train
import numpy as np def slope(p1, p2): dx, dy = vectorize(p1, p2) return dy/dx if dx else float("inf") def vectorize(p1, p2): return [b-a for a,b in zip(p1, p2)] def getArea (p1, p2, p3): return np.cross(vectorize(p1, p2), vectorize(p1, p3)) / 2 def isConcave(p1, pivot, p2): return getArea(pivot, p1, p2) >= 0 def convex_hull_area(points): if len(points) < 3: return 0 Z = min(points) # Leftmost point in the graph (lowest if several ones at the same x) q = sorted( (pt for pt in points if pt != Z), key = lambda pt: (-slope(pt, Z), -np.linalg.norm(vectorize(Z, pt)))) # sorted points accordingly to the slope of the line formed by "pt" and "Z" (in reversed order) hull = [Z, q.pop()] # Construct the convex hull (Graham Scan) while q: pt = q.pop() while len(hull) > 1 and isConcave(hull[-2], hull[-1], pt): hull.pop() hull.append(pt) area = sum( getArea(Z, hull[i], hull[i+1]) for i in range(1, len(hull)-1) ) # Calculate area of the hull by adding the area of all the triangles formed by 2 consecutive points in the hull and having Z as summit return round(area, 2)
PYTHON
{ "starter_code": "\ndef cross(p1,p2,p):\n\t", "url": "https://www.codewars.com/kata/59c1d64b9f0cbcf5740001ab" }
d1788
train
from functools import reduce class Datamining: def __init__(self, train_set): self.p = train_set[:5] def lagrange_interp(self, x): return sum(reduce(lambda p,n: p*n, [(x-xi)/(xj-xi) for (i,(xi,yi)) in enumerate(self.p) if j!=i], yj) for (j,(xj,yj)) in enumerate(self.p)) def predict(self, x): return self.lagrange_interp(x)
PYTHON
{ "starter_code": "\ndef __init__(self, train_set):\n\t", "url": "https://www.codewars.com/kata/591748b3f014a2593d0000d9" }
d1789
train
from operator import xor def choose_move(game_state): """Chooses a move to play given a game state""" x = reduce(xor, game_state) for i, amt in enumerate(game_state): if amt ^ x < amt: return (i, amt - (amt ^ x))
PYTHON
{ "starter_code": "\ndef choose_move(game_state):\n\t", "url": "https://www.codewars.com/kata/54120de842dff35232000195" }
d1790
train
from re import sub ignoreList = ["THE", "OF", "IN", "FROM", "BY", "WITH", "AND", "OR", "FOR", "TO", "AT", "A"] def generate_bc(url, separator): # remove leading http(s):// and trailing / url = sub("https?://", "", url.strip("/")) # skip index files url = sub("/index\..+$", "", url) # split url for processing url = url.split("/") # remove file extensions, anchors and parameters url[-1] = sub("[\.#\?].*", "", url[-1]) # first element is always "home" menu = ["HOME"] # generate breadcrumb items for item in url[1:]: # replace dashes and set to uppercase item = sub("-", " ", item.upper()) # create acronym if too long if len(item) > 30: item = "".join([w[0] for w in item.split() if w not in ignoreList]) menu.append(item) # generate paths path = ["/"] for i in range(len(url) - 1): path.append(path[i] + url[i+1] + "/") # generate html code html = [] for i in range(len(url) - 1): html.append("<a href=\"" + path[i] + "\">" + menu[i] +"</a>") html.append("<span class=\"active\">" + menu[-1] +"</span>") return separator.join(html)
PYTHON
{ "starter_code": "\ndef generate_bc(url, separator):\n\t", "url": "https://www.codewars.com/kata/563fbac924106b8bf7000046" }
d1791
train
from collections import deque class Graph(): def __init__(self, vertices_num): self.v = vertices_num def adjmat_2_graph(self, adjm): d = {f'A{i}': [] for i in range(self.v)} for i, j in enumerate(adjm): for k, l in enumerate(j): if l : d[f'A{i}'].append((f'A{k}', l)) return d def graph_2_mat(self, graph): mat = [[0 for _ in range(self.v)] for _ in range(self.v)] for i, j in graph.items(): for k, l in j: mat[int(i[1])][int(k[1])] = l return mat def graph_2_list(self, graph): return [[i, j] for i, j in sorted(graph.items())] def list_2_graph(self, lst): return {i: x for i, x in lst} def mat_2_list(self, mat): return self.graph_2_list(self.adjmat_2_graph(mat)) def list_2_mat(self, lst): return self.graph_2_mat(self.list_2_graph(lst)) def find_all_paths(self, graph, start, end): graph = {i: [k[0] for k in j] for i, j in graph.items()} Q, paths = deque([[start, []]]), [] while Q: node, path = Q.popleft() path.append(node) if node == end: paths.append('-'.join(path)) for n in graph[node]: if n not in path: Q.append([n, path[:]]) return sorted(paths, key=len)
PYTHON
{ "starter_code": "\ndef __init__(self, vertices_num):\n\t", "url": "https://www.codewars.com/kata/5aaea7a25084d71006000082" }
d1792
train
from collections import deque from numpy import cross, dot MOVES = ((1,0), (-1,0), (0,1), (0,-1)) DIRS = ( 'v', '^', '>', '<') def escape(maze): start = x,y = next( (x,y) for x,row in enumerate(maze) for y,c in enumerate(row) if c not in '# ' ) X, Y, dir = len(maze), len(maze[0]), MOVES[ DIRS.index(maze[x][y]) ] q, seens = deque([(start, dir)]), {} if not x or x==X-1 or not y or y==Y-1: return [] # Already at the end, do nothing noPath = True while q: (x,y), dir = q.popleft() for dx,dy in MOVES: xx,yy = pos = (x+dx,y+dy) if 0 <= xx < X and 0 <= yy < Y and maze[xx][yy]==' ' and pos not in seens: q.append( (pos, (dx,dy)) ) seens[pos] = ((x,y), dir, (dx,dy)) # data: (origin position, direction before origin, direction after origin) if not xx or xx==X-1 or not yy or yy==Y-1: # Escaped! q, noPath = [], False # reset the queue to stop it, "from the for loop" break if noPath: return [] # No path, no chocolate... path = [] while pos != start: pos, dir, nextDir = seens[pos] scal = dot(dir, nextDir) # scalar prouct > 0 <=> go ahead, otherwise, turn back prod = cross(dir, nextDir) # cross product > 0 <=> turn left, otherwise, turn right if scal: path.append('FB' if scal < 0 else 'F') # dot != 0 => both directions are colinear else: path.append('FL' if prod > 0 else 'FR') # orthogonal directions, take a turn return list(''.join(path)[::-1])
PYTHON
{ "starter_code": "\ndef escape(maze):\n\t", "url": "https://www.codewars.com/kata/5877027d885d4f6144000404" }
d1793
train
def three_by_n(n): A = [1, 2] + [0]*(n-1) B = [0, 1] + [0]*(n-1) C = [1, 0] + [0]*(n-1) D = [0, 1] + [0]*(n-1) for i in range(2, n+1): A[i] = A[i-2] + 2*B[i-1] + 2*C[i-1] + 2*D[i] + 2*D[i-2] B[i] = A[i-1] + B[i-2] + C[i-2] + D[i-1] C[i] = C[i-2] + 2*D[i-1] D[i] = C[i-1] + D[i-2] return A[n] % 12345787
PYTHON
{ "starter_code": "\ndef three_by_n(n):\n\t", "url": "https://www.codewars.com/kata/5993dcfca6a7632807000017" }
d1794
train
from math import factorial as fac cards = [ "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "TD", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "TH", "JH", "QH", "KH", "AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "TS", "JS", "QS", "KS" ] chars = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ' chars_len = len(chars) facs = [1] for x in range(1, 53, 1): facs.append(facs[-1] * x) class PlayingCards: # Takes a String containing a message, and returns an array of Strings representing # a deck of playing cards ordered to hide the message, or None if the message is invalid. def encode(self, message): mlen = len(message) rem = 0 for i in range(mlen): if message[i] not in chars: return None rem = rem + chars_len ** (mlen - i - 1) * chars.index(message[i]) if rem >= facs[-1]: return None for i in range(1, 53): if rem < facs[i]: break remaining_cards = cards[53 - i - 1:] output_cards = cards[:53 - i - 1] for j in range(i - 1, -1, -1): idx = rem // facs[j] output_cards.append(remaining_cards.pop(idx)) rem = rem % facs[j] return output_cards # Takes an array of Strings representing a deck of playing cards, and returns # the message that is hidden inside, or None if the deck is invalid. def decode(self, deck): if len(deck) != 52: return None remaining_cards = cards.copy() rem = 0 for i in range(len(deck)): if deck[i] not in remaining_cards: return None idx = remaining_cards.index(deck[i]) rem = rem + facs[51 - i] * idx remaining_cards.pop(idx) output_message = [] if rem == 0 : return '' while rem > 0: output_message.insert(0, chars[rem % chars_len]) rem = rem // chars_len return ''.join(output_message)
PYTHON
{ "starter_code": "\ndef encode(self, message):\n\t", "url": "https://www.codewars.com/kata/59b9a92a6236547247000110" }
d1795
train
def is_prime(n): return n == 2 or n % 2 != 0 and all(n % k != 0 for k in range(3, root(n) + 1, 2)) def root(p): return int(p ** 0.5) def statement1(s): return not(s % 2 == 0 or is_prime(s - 2)) def statement2(p): return sum(statement1(i + p / i) for i in range(2, root(p) + 1) if p % i == 0) == 1 def statement3(s): return sum(statement2(i * (s - i)) for i in range(2, s / 2 + 1)) == 1 def is_solution(a, b): return statement1(a + b) and statement2(a * b) and statement3(a + b)
PYTHON
{ "starter_code": "\ndef statement1(s):\n\t", "url": "https://www.codewars.com/kata/56f6380a690784f96e00045d" }
d1796
train
def nQueen(n): if n==2 or n==3: return [] r, odds, evens = n%6, list(range(1,n,2)), list(range(0,n,2)) if r==2: evens[:2] = evens[:2][::-1] evens.append(evens.pop(2)) if r==3: odds.append(odds.pop(0)) evens.extend(evens[:2]) del evens[:2] return odds+evens
PYTHON
{ "starter_code": "\ndef nQueen(n):\n\t", "url": "https://www.codewars.com/kata/52cdc1b015db27c484000031" }
d1797
train
def to_postfix (infix): prec = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3, '(': 0} postfix = [] stack = [] for ch in infix: if ch in '0123456789': postfix.append(ch) elif ch in '(': stack.append(ch) elif ch in ')': while stack and stack[-1] != '(': postfix.append(stack.pop()) stack.pop() else: while stack and prec[stack[-1]] >= prec[ch]: postfix.append(stack.pop()) stack.append(ch) while stack: postfix.append(stack.pop()) return ''.join(postfix)
PYTHON
{ "starter_code": "\ndef to_postfix (infix):\n\t", "url": "https://www.codewars.com/kata/52e864d1ffb6ac25db00017f" }
d1798
train
def hamming(n): bases = [2, 3, 5] expos = [0, 0, 0] hamms = [1] for _ in range(1, n): next_hamms = [bases[i] * hamms[expos[i]] for i in range(3)] next_hamm = min(next_hamms) hamms.append(next_hamm) for i in range(3): expos[i] += int(next_hamms[i] == next_hamm) return hamms[-1]
PYTHON
{ "starter_code": "\ndef hamming(n):\n\t", "url": "https://www.codewars.com/kata/526d84b98f428f14a60008da" }
d1799
train
def get(cells, i, j): return cells[i][j] if i > -1 and j > -1 and i < len(cells) and j < len(cells[0]) else 0 def num_neighbors(cells, i, j): return (get(cells, i, j+1) + get(cells, i, j-1) + get(cells, i+1, j) + get(cells, i-1, j) + get(cells, i-1, j-1) + get(cells, i-1, j+1) + get(cells, i+1, j-1) + get(cells, i+1, j+1)) def next_cell(cell, i, j): n = num_neighbors(cell, i, j) return int(0 if n < 2 or n > 3 else 1 if cell[i][j] else n == 3) def expand(cells): row = [0]*(len(cells[0])+2) return [row] + [[0] + r + [0] for r in cells] + [row] def trim(cells): while not any(cells[0]): del cells[0] while not any(cells[-1]): del cells[-1] while not any([row[0] for row in cells]): list(map(lambda x: x.pop(0), cells)) while not any([row[-1] for row in cells]): list(map(lambda x: x.pop(), cells)) def next_gen(cells): cells = expand(cells) cells = [[next_cell(cells, i, j) for j in range(len(cells[i]))] for i in range(len(cells))] trim(cells) return cells def get_generation(cells, generations): for i in range(generations): cells = next_gen(cells) if not cells: return [[]] return cells
PYTHON
{ "starter_code": "\ndef get_generation(cells, gen):\n\t", "url": "https://www.codewars.com/kata/52423db9add6f6fc39000354" }
d1800
train
def queens(fixQ, S): def areClashing(i,x): j,y = qs[i],qs[x] return j==y or abs(i-x)==abs(j-y) def dfs(i=0): if i==iQ: return dfs(i+1) if i==len(qs): return 1 for y in range(S): qs[i]=y if ( not any(areClashing(i,ii) for ii in range(i)) and (iQ<i or not areClashing(i,iQ)) and dfs(i+1) ): return 1 iQ,yQ = ord(fixQ[0])-97, (int(fixQ[1]) or 10)-1 qs = [yQ if i==iQ else 0 for i in range(S)] dfs() return ','.join( f"{ chr(x+97) }{ str(y+1)[-1] }" for x,y in enumerate(qs))
PYTHON
{ "starter_code": "\ndef queens(position, size):\n\t", "url": "https://www.codewars.com/kata/561bed6a31daa8df7400000e" }