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.
#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;
longadd_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);
- }
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()
# constantsWIN_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 menuprint("*" * 50)print("Welcome to our Noughts and Crosses Game!")print("*" * 50)play_loc_list1 = []play_loc_list2 = []# Get player's namesplayer_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 turnwhile 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!')continueelse: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!')continueelse:BOARD[loc_x - 1] = "X"break # Break player 1 turn:# Check win combos:loc_attempt = loc_x - 1play_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!")breakmake_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')continueelse: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!')continueelse:BOARD[loc_y - 1] = "O"break # Break player 2 turn:# Check win combos:loc_attempt = loc_y - 1play_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.
import static org.junit.jupiter.api.Assertions.*; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; class Tests { final String allChars = "abcdefghijklmnopqrstuvwxyz1234567890"; @Test void test() { doTest(1, "12345 98212"); doTest(1, "9999"); doTest(-1, "abcdefg"); doTest(-1,"zzzzzzz213 9ppppopppo2"); doTest(0,"abcdef 12345"); doTest(-1,"abcd 12345 xy"); } @Test void hiddenTest() { doTest(0,""); doTest(0," "); doTest(0,"a1"); doTest(1,"a1b2c3 d4e5f6"); doTest(0,"a1b2c3 5y5"); doTest(0,"a1b2c3 5y5"); doTest(0,"5y5 a1b2c3 "); doTest(1,"9%$@"); doTest(-1,"~$@#a"); doTest(0,"~$@#"); doTest(0,"0"); doTest(-1,"abcd 12345 xa"); doTest(-1,"abcd 12345 xy a bc"); doTest(-1,"abcd 12345 xy bb aa aa"); } @RepeatedTest(100) void randomTests() { String randomString = generateRandomString(); int sol = sol(randomString); doTest(sol, randomString); } private String generateRandomString() { Random rnd = new Random(); StringBuilder randomString = new StringBuilder(); int finalStringLength =rnd.nextInt(100); for(int i=0;i<finalStringLength;i++) { int currentWordLength = rnd.nextInt(20); for(int j=0;j<currentWordLength;j++) { randomString.append(allChars.charAt(rnd.nextInt(36))); } randomString.append(" "); } return randomString.toString().trim(); } private void doTest(int expected, String str) { int actual = NumbersVsLetters.numbersVsLetters(str); String msg = String.format( "Incorrect answer for String = %s\n Expected: %s\n Actual: %s\n", str, expected, actual); assertEquals(expected, actual, msg); } private static int sol(String str) { if (str.isEmpty() || str.isBlank()) return 0; Map<Character, Integer> allChars = fillMap(); int score = 0; int numberMultiplication = -1; int characterSum = 0; for (char c : str.toCharArray()) { if (c == ' ') { if (numberMultiplication > 0) score += Integer.compare(numberMultiplication, characterSum); else if (characterSum > 0) score--; numberMultiplication = -1; characterSum = 0; } else if (Character.isDigit(c)) numberMultiplication = Character.getNumericValue(c) * Math.abs(numberMultiplication); else if (Character.isAlphabetic(c)) characterSum += allChars.get(c); } if (numberMultiplication > 0) score += Integer.compare(numberMultiplication, characterSum); else if (characterSum > 0) score--; return Integer.compare(score, 0); } private static Map<Character, Integer> fillMap(){ Map<Character, Integer> allChars = new HashMap<>(); for (int i = 0; i < 26; i++) { char c = (char) ('a' + i); allChars.put(c, i + 1); } return allChars; } }
- import static org.junit.jupiter.api.Assertions.*;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Random;
- import org.junit.jupiter.api.RepeatedTest;
- import org.junit.jupiter.api.Test;
- class Tests {
- final String allChars = "abcdefghijklmnopqrstuvwxyz1234567890";
- @Test
- void test() {
- doTest(1, "12345 98212");
- doTest(1, "9999");
- doTest(-1, "abcdefg");
- doTest(-1,"zzzzzzz213 9ppppopppo2");
- doTest(0,"abcdef 12345");
- doTest(-1,"abcd 12345 xy");
- }
- @Test
- void hiddenTest() {
- doTest(0,"");
- doTest(0," ");
- doTest(0,"a1");
- doTest(1,"a1b2c3 d4e5f6");
- doTest(0,"a1b2c3 5y5");
- doTest(0,"a1b2c3 5y5");
- doTest(0,"5y5 a1b2c3 ");
- doTest(1,"9%$@");
- doTest(-1,"~$@#a");
- doTest(0,"~$@#");
- doTest(0,"0");
- doTest(-1,"abcd 12345 xa");
- doTest(-1,"abcd 12345 xy a bc");
- doTest(-1,"abcd 12345 xy bb aa aa");
- }
- @RepeatedTest(100)
- void randomTests() {
- String randomString = generateRandomString();
- int sol = sol(randomString);
- doTest(sol, randomString);
- }
- private String generateRandomString() {
- Random rnd = new Random();
- StringBuilder randomString = new StringBuilder();
- int finalStringLength =rnd.nextInt(100);
- for(int i=0;i<finalStringLength;i++) {
- int currentWordLength = rnd.nextInt(20);
- for(int j=0;j<currentWordLength;j++) {
- randomString.append(allChars.charAt(rnd.nextInt(36)));
- }
- randomString.append(" ");
- }
- return randomString.toString().trim();
- }
- private void doTest(int expected, String str) {
- int actual = NumbersVsLetters.numbersVsLetters(str);
- String msg = String.format( "Incorrect answer for String = %s\n Expected: %s\n Actual: %s\n", str, expected, actual);
- assertEquals(expected, actual, msg);
- }
- private static int sol(String str) {
- if (str.isEmpty() || str.isBlank()) return 0;
- Map<Character, Integer> allChars = fillMap();
- int score = 0;
- int numberMultiplication = -1;
- int characterSum = 0;
- for (char c : str.toCharArray()) {
- if (c == ' ') {
- if (numberMultiplication > 0) score += Integer.compare(numberMultiplication, characterSum);
- else if (characterSum > 0) score--;
- numberMultiplication = -1;
- characterSum = 0;
- } else if (Character.isDigit(c)) numberMultiplication = Character.getNumericValue(c) * Math.abs(numberMultiplication);
- else if (Character.isAlphabetic(c)) characterSum += allChars.get(c);
- }
- if (numberMultiplication > 0) score += Integer.compare(numberMultiplication, characterSum);
- else if (characterSum > 0) score--;
- return Integer.compare(score, 0);
- }
- private static Map<Character, Integer> fillMap(){
- Map<Character, Integer> allChars = new HashMap<>();
- for (int i = 0; i < 26; i++) {
- char c = (char) ('a' + i);
- allChars.put(c, i + 1);
- }
- return allChars;
- }
- }
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 stringis_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!
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.
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'))