Start a new Kumite
AllAgda (Beta)BF (Beta)CCFML (Beta)ClojureCOBOL (Beta)CoffeeScriptCommonLisp (Beta)CoqC++CrystalC#D (Beta)DartElixirElm (Beta)Erlang (Beta)Factor (Beta)Forth (Beta)Fortran (Beta)F#GoGroovyHaskellHaxe (Beta)Idris (Beta)JavaJavaScriptJulia (Beta)Kotlinλ Calculus (Beta)LeanLuaNASMNim (Beta)Objective-C (Beta)OCaml (Beta)Pascal (Beta)Perl (Beta)PHPPowerShell (Beta)Prolog (Beta)PureScript (Beta)PythonR (Beta)RacketRaku (Beta)Reason (Beta)RISC-V (Beta)RubyRustScalaShellSolidity (Beta)SQLSwiftTypeScriptVB (Beta)
Show only mine

Kumite (ko͞omiˌtā) is the practice of taking techniques learned from Kata and applying them through the act of freestyle sparring.

You can create a new kumite by providing some initial code and optionally some test cases. From there other warriors can spar with you, by enhancing, refactoring and translating your code. There is no limit to how many warriors you can spar with.

A great use for kumite is to begin an idea for a kata as one. You can collaborate with other code warriors until you have it right, then you can convert it to a kata.

Ad
Ad
Code
Diff
  • #include<bits/stdc++.h>
    using namespace std;
    
    long add_arr(vector<int> arr)
    {
      return std::accumulate(begin(arr),end(arr),0);
    }
    • #include <vector>
    • #include <numeric>
    • #include<bits/stdc++.h>
    • using namespace std;
    • long
    • add_arr(std::vector<int> arr)
    • long add_arr(vector<int> arr)
    • {
    • return std::accumulate(arr.begin(),arr.end(),0);
    • return std::accumulate(begin(arr),end(arr),0);
    • }
Code
Diff
  • PLAYER_1 = 1
    PLAYER_2 = 2
    
    
    class NoughtsAndCrosses(object):
        """Basic implementation of Noughts and Crosses"""
        WIN_COMBOS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
        EMPTY_BOARD = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    
        def __init__(self):
            self.current_board = self.EMPTY_BOARD.copy()
            self.current_player = PLAYER_1  # game always starts with PLAYER_1
            self.player_names = {}
            self.location_lists = {
                PLAYER_1: [],
                PLAYER_2: []
            }
            self.player_markers = {
                PLAYER_1: "X",
                PLAYER_2: "O",
            }
        
        def _print_board(self):
            """Prints the current board"""
            print("--- Noughts and Crosses ---")
            print(f'{self.current_board[0]} : {self.current_board[1]} : {self.current_board[2]}')
            print("..........")
            print(f'{self.current_board[3]} : {self.current_board[4]} : {self.current_board[5]}')
            print("..........")
            print(f'{self.current_board[6]} : {self.current_board[7]} : {self.current_board[8]}')
        
        def play(self):
            self._print_welcome_message()
            self._get_player_names()
            while True:
                self._let_current_player_move()
                if self._player_has_won(self.current_player):
                    print(f"{self.player_names[self.current_player]}, you have won!")
                    break
                self._switch_current_player()
    
        def _let_current_player_move(self):
            print("Hi", self.player_names[self.current_player])
            while True:
                chosen_board_index = self._get_next_move()
                if self._location_is_taken(chosen_board_index):
                    print('>>> Position taken, try again!')
                    continue
                else:
                    self._update_board_and_location_lists(chosen_board_index)
                    self._print_board()
                    break
    
        def _update_board_and_location_lists(self, chosen_board_index):
            self.current_board[chosen_board_index] = self.player_markers[self.current_player]
            self.location_lists[self.current_player].append(chosen_board_index)
    
        @staticmethod
        def _print_welcome_message():
            print("*" * 50)
            print("Welcome to our Noughts and Crosses Game!")
            print("*" * 50)
    
        def _get_player_names(self):
            self.player_names[1] = input("Enter the name of the first player:\n> ")
            self.player_names[2] = input("Enter the name of the second player:\n> ")
    
        def _switch_current_player(self):
            if self.current_player == PLAYER_1:
                self.current_player = PLAYER_2
            else:
                self.current_player = PLAYER_1
    
        def _location_is_taken(self, board_index):
            return self.current_board[board_index] in self.player_markers.values()
    
        def _player_has_won(self, player):
            for win_combo in self.WIN_COMBOS:
                if set(win_combo) <= set(self.location_lists[player]):
                    return True
            return False  # if no winning combinations was found
    
        @staticmethod
        def _get_next_move():
            while True:
                chosen_location = input("Cross location(choose 1 - 9):\n> ")
                if not chosen_location.isdigit() or int(chosen_location) not in range(10):
                    print('>>> Invalid input!')
                    continue
                else:
                    chosen_location = int(chosen_location) - 1  # adjust for array index to start at 0 not 1
                    return chosen_location
    
    
    if __name__ == '__main__':
        NoughtsAndCrosses().play()
    
    • # constants
    • WIN_COMBOS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
    • BOARD = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    • def make_board():
    • """This function creates the board"""
    • print("--- Noughts and Crosses ---")
    • print(f'{BOARD[0]:<2}: {BOARD[1]:<2}: {BOARD[2]:>1}')
    • print("..........")
    • print(f'{BOARD[3]:<2}: {BOARD[4]:<2}: {BOARD[5]:>1}')
    • print("..........")
    • print(f'{BOARD[6]:<2}: {BOARD[7]:<2}: {BOARD[8]:>1}')
    • def main():
    • # Main menu
    • print("*" * 50)
    • print("Welcome to our Noughts and Crosses Game!")
    • print("*" * 50)
    • play_loc_list1 = []
    • play_loc_list2 = []
    • # Get player's names
    • player_1 = input("Enter the name of the first player:\n> ")
    • player_2 = input("Enter the name of the second player:\n> ")
    • while True:
    • turn = 1
    • # Player 1 turn
    • while turn == 1:
    • print("Hi", player_1)
    • while True:
    • make_board()
    • while True:
    • # User input validation loop:
    • loc_x = input("Cross location(choose 1 - 9):\n> ")
    • if not loc_x.isdigit() or int(loc_x) not in range(10):
    • print('>>> Invalid input!')
    • continue
    • else:
    • loc_x = int(loc_x)
    • break # break User input validation loop:
    • # Check if position is empty:
    • if BOARD[loc_x - 1] == 'X' or BOARD[loc_x - 1] == 'O':
    • print('>>> Position taken, try again!')
    • continue
    • else:
    • BOARD[loc_x - 1] = "X"
    • break # Break player 1 turn:
    • # Check win combos:
    • loc_attempt = loc_x - 1
    • play_loc_list1.append(loc_attempt)
    • play_loc_list1.sort()
    • for i in range(0, len(WIN_COMBOS)):
    • if WIN_COMBOS[i] == play_loc_list1:
    • print("You have won!")
    • break
    • make_board()
    • turn = 2
    • # Player 2 turn:
    • while turn == 2:
    • print("Hi", player_2)
    • while True:
    • make_board()
    • while True:
    • # User input validation loop:
    • loc_y = input("Noughts location(choose 1 - 9):\n> ")
    • if not loc_y.isdigit() or int(loc_y) not in range(10):
    • print('>>> Invalid input')
    • continue
    • else:
    • loc_y = int(loc_y)
    • break # break User input validation loop:
    • # Check if position is empty:
    • if BOARD[loc_y - 1] == 'X' or BOARD[loc_y - 1] == 'O':
    • print('>>> Position taken, try again!')
    • continue
    • else:
    • BOARD[loc_y - 1] = "O"
    • break # Break player 2 turn:
    • # Check win combos:
    • loc_attempt = loc_y - 1
    • play_loc_list2.append(loc_attempt)
    • play_loc_list2.sort()
    • for i in range(0, len(WIN_COMBOS)):
    • if WIN_COMBOS[i] == play_loc_list2:
    • print("You have won!")
    • break
    • PLAYER_1 = 1
    • PLAYER_2 = 2
    • make_board()
    • turn = 1
    • class NoughtsAndCrosses(object):
    • """Basic implementation of Noughts and Crosses"""
    • WIN_COMBOS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
    • EMPTY_BOARD = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    • def __init__(self):
    • self.current_board = self.EMPTY_BOARD.copy()
    • self.current_player = PLAYER_1 # game always starts with PLAYER_1
    • self.player_names = {}
    • self.location_lists = {
    • PLAYER_1: [],
    • PLAYER_2: []
    • }
    • self.player_markers = {
    • PLAYER_1: "X",
    • PLAYER_2: "O",
    • }
    • def _print_board(self):
    • """Prints the current board"""
    • print("--- Noughts and Crosses ---")
    • print(f'{self.current_board[0]} : {self.current_board[1]} : {self.current_board[2]}')
    • print("..........")
    • print(f'{self.current_board[3]} : {self.current_board[4]} : {self.current_board[5]}')
    • print("..........")
    • print(f'{self.current_board[6]} : {self.current_board[7]} : {self.current_board[8]}')
    • def play(self):
    • self._print_welcome_message()
    • self._get_player_names()
    • while True:
    • self._let_current_player_move()
    • if self._player_has_won(self.current_player):
    • print(f"{self.player_names[self.current_player]}, you have won!")
    • break
    • self._switch_current_player()
    • def _let_current_player_move(self):
    • print("Hi", self.player_names[self.current_player])
    • while True:
    • chosen_board_index = self._get_next_move()
    • if self._location_is_taken(chosen_board_index):
    • print('>>> Position taken, try again!')
    • continue
    • else:
    • self._update_board_and_location_lists(chosen_board_index)
    • self._print_board()
    • break
    • def _update_board_and_location_lists(self, chosen_board_index):
    • self.current_board[chosen_board_index] = self.player_markers[self.current_player]
    • self.location_lists[self.current_player].append(chosen_board_index)
    • @staticmethod
    • def _print_welcome_message():
    • print("*" * 50)
    • print("Welcome to our Noughts and Crosses Game!")
    • print("*" * 50)
    • def _get_player_names(self):
    • self.player_names[1] = input("Enter the name of the first player:\n> ")
    • self.player_names[2] = input("Enter the name of the second player:\n> ")
    • def _switch_current_player(self):
    • if self.current_player == PLAYER_1:
    • self.current_player = PLAYER_2
    • else:
    • self.current_player = PLAYER_1
    • def _location_is_taken(self, board_index):
    • return self.current_board[board_index] in self.player_markers.values()
    • def _player_has_won(self, player):
    • for win_combo in self.WIN_COMBOS:
    • if set(win_combo) <= set(self.location_lists[player]):
    • return True
    • return False # if no winning combinations was found
    • @staticmethod
    • def _get_next_move():
    • while True:
    • chosen_location = input("Cross location(choose 1 - 9):\n> ")
    • if not chosen_location.isdigit() or int(chosen_location) not in range(10):
    • print('>>> Invalid input!')
    • continue
    • else:
    • chosen_location = int(chosen_location) - 1 # adjust for array index to start at 0 not 1
    • return chosen_location
    • if __name__ == '__main__':
    • main()
    • NoughtsAndCrosses().play()

Test cases with more than two groups added.

Games
Arrays
Algorithms
Code
Diff
  • fn required_energy(heights: Vec<i64>) -> i64 {
        heights
            .windows(2)
            .map(|y| (y[0] - y[1]).abs())
            .sum()
    }
    • fn required_energy(heights: Vec<i64>) -> i64 {
    • heights
    • .windows(2)
    • .map(|y| (y[1] - y[0]).abs())
    • .sum::<i64>()
    • .map(|y| (y[0] - y[1]).abs())
    • .sum()
    • }
Code
Diff
  • import re
    
    is_palindrome = lambda s: re.sub(r'[^a-zA-Z0-9]', '', s.lower()) == re.sub(r'[^a-zA-Z0-9]', '', s.lower())[::-1]
    
    • import string
    • is_palindrome = lambda s: (x := s.replace(' ', '').lower().translate(str.maketrans('', '', string.punctuation))) == x[::-1]
    • import re
    • is_palindrome = lambda s: re.sub(r'[^a-zA-Z0-9]', '', s.lower()) == re.sub(r'[^a-zA-Z0-9]', '', s.lower())[::-1]

Ask and you shall recieve!

Code
Diff
  • eval(compile((_ := __import__("ast")).fix_missing_locations(_.Module(body=[_.Assign(targets=[_.Name(id='KumiteFoo', ctx=_.Store())], value=_.Call(func=_.Name(id='type', ctx=_.Load()), args=[_.Constant(value=''), _.Tuple(elts=[], ctx=_.Load()), _.Dict(keys=[_.Constant(value='__init__'), _.Constant(value='solution')], values=[_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='s'), _.arg(arg='p')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.Call(func=_.Attribute(value=_.Name(id='s', ctx=_.Load()), attr='__setattr__', ctx=_.Load()), args=[_.Constant(value='c'), _.IfExp(test=_.Name(id='p', ctx=_.Load()), body=_.Subscript(value=_.Tuple(elts=[_.Constant(value='No'), _.Constant(value='Yes')], ctx=_.Load()), slice=_.Compare(left=_.BinOp(left=_.Call(func=_.Name(id='sum', ctx=_.Load()), args=[_.Call(func=_.Name(id='map', ctx=_.Load()), args=[_.Name(id='ord', ctx=_.Load()), _.Call(func=_.Attribute(value=_.Name(id='p', ctx=_.Load()), attr='lower', ctx=_.Load()), args=[], keywords=[])], keywords=[])], keywords=[]), op=_.Mod(), right=_.Constant(value=324)), ops=[_.Eq()], comparators=[_.Constant(value=0)]), ctx=_.Load()), orelse=_.Constant(value='No'))], keywords=[])), _.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='s')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.Attribute(value=_.Name(id='s', ctx=_.Load()), attr='c', ctx=_.Load()))])], keywords=[]))], type_ignores=[])), "your mom", "exec"))
    • KumiteFoo=type('',(),{"__init__":lambda s,p:s.__setattr__('c',('No', 'Yes')[sum(map(ord,p.lower()))%324==0]if p else 'No'),"solution":lambda s:s.c})
    • eval(compile((_ := __import__("ast")).fix_missing_locations(_.Module(body=[_.Assign(targets=[_.Name(id='KumiteFoo', ctx=_.Store())], value=_.Call(func=_.Name(id='type', ctx=_.Load()), args=[_.Constant(value=''), _.Tuple(elts=[], ctx=_.Load()), _.Dict(keys=[_.Constant(value='__init__'), _.Constant(value='solution')], values=[_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='s'), _.arg(arg='p')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.Call(func=_.Attribute(value=_.Name(id='s', ctx=_.Load()), attr='__setattr__', ctx=_.Load()), args=[_.Constant(value='c'), _.IfExp(test=_.Name(id='p', ctx=_.Load()), body=_.Subscript(value=_.Tuple(elts=[_.Constant(value='No'), _.Constant(value='Yes')], ctx=_.Load()), slice=_.Compare(left=_.BinOp(left=_.Call(func=_.Name(id='sum', ctx=_.Load()), args=[_.Call(func=_.Name(id='map', ctx=_.Load()), args=[_.Name(id='ord', ctx=_.Load()), _.Call(func=_.Attribute(value=_.Name(id='p', ctx=_.Load()), attr='lower', ctx=_.Load()), args=[], keywords=[])], keywords=[])], keywords=[]), op=_.Mod(), right=_.Constant(value=324)), ops=[_.Eq()], comparators=[_.Constant(value=0)]), ctx=_.Load()), orelse=_.Constant(value='No'))], keywords=[])), _.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='s')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.Attribute(value=_.Name(id='s', ctx=_.Load()), attr='c', ctx=_.Load()))])], keywords=[]))], type_ignores=[])), "your mom", "exec"))

What's really going on here is the code:


globals().update({
"solution": lambda _: len([__ for __ in _ if __ is bool(1 << 4 | 3)]) > 1
})

Was turned into ast components, and the compile function compiles it back down into native python and runs it with eval, putting the solution function into globals for the tests to find.

Code
Diff
  • eval(compile((_ := __import__("ast")).fix_missing_locations(_.Module(body=[_.Expr(value=_.Call(func=_.Attribute(value=_.Call(func=_.Name(id='globals', ctx=_.Load()), args=[], keywords=[]), attr='update', ctx=_.Load()), args=[_.Dict(keys=[_.Constant(value='solution')], values=[_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='_')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.Compare(left=_.Call(func=_.Name(id='len', ctx=_.Load()), args=[_.ListComp(elt=_.Name(id='__', ctx=_.Load()), generators=[_.comprehension(target=_.Name(id='__', ctx=_.Store()), iter=_.Name(id='_', ctx=_.Load()), ifs=[_.Compare(left=_.Name(id='__', ctx=_.Load()), ops=[_.Is()], comparators=[_.Call(func=_.Name(id='bool', ctx=_.Load()), args=[_.BinOp(left=_.BinOp(left=_.Constant(value=1), op=_.LShift(), right=_.Constant(value=4)), op=_.BitOr(), right=_.Constant(value=3))], keywords=[])])], is_async=0)])], keywords=[]), ops=[_.Gt()], comparators=[_.Constant(value=1)]))])], keywords=[]))], type_ignores=[])), "", 'exec'))
    • def solution(param: list) -> bool:
    • return len([x for x in param if x is bool('codewarz strikes back!')]) > 1
    • eval(compile((_ := __import__("ast")).fix_missing_locations(_.Module(body=[_.Expr(value=_.Call(func=_.Attribute(value=_.Call(func=_.Name(id='globals', ctx=_.Load()), args=[], keywords=[]), attr='update', ctx=_.Load()), args=[_.Dict(keys=[_.Constant(value='solution')], values=[_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='_')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.Compare(left=_.Call(func=_.Name(id='len', ctx=_.Load()), args=[_.ListComp(elt=_.Name(id='__', ctx=_.Load()), generators=[_.comprehension(target=_.Name(id='__', ctx=_.Store()), iter=_.Name(id='_', ctx=_.Load()), ifs=[_.Compare(left=_.Name(id='__', ctx=_.Load()), ops=[_.Is()], comparators=[_.Call(func=_.Name(id='bool', ctx=_.Load()), args=[_.BinOp(left=_.BinOp(left=_.Constant(value=1), op=_.LShift(), right=_.Constant(value=4)), op=_.BitOr(), right=_.Constant(value=3))], keywords=[])])], is_async=0)])], keywords=[]), ops=[_.Gt()], comparators=[_.Constant(value=1)]))])], keywords=[]))], type_ignores=[])), "", 'exec'))