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.
Here is a leaner, more idiomatic implementation that still satisfies the requirement “accept anything convertible to str/int”, passes the tests, and is much easier to maintain
from typing import Any class Pet: def __init__( self, name: Any, species: Any, gender: Any = "not defined", age: Any = 0, n_legs: Any = 4, ) -> None: # Go through the setters so we reuse validation/conversion logic self.name = name self.species = species self.gender = gender self.age = age self.n_legs = n_legs # --- string-like fields ------------------------------------------------- @property def name(self) -> str: return self._name @name.setter def name(self, value: Any) -> None: try: self._name = str(value) except Exception as exc: raise ValueError("name must be convertible to str") from exc @property def species(self) -> str: return self._species @species.setter def species(self, value: Any) -> None: try: self._species = str(value) except Exception as exc: raise ValueError("species must be convertible to str") from exc @property def gender(self) -> str: return self._gender @gender.setter def gender(self, value: Any) -> None: try: self._gender = str(value) except Exception as exc: raise ValueError("gender must be convertible to str") from exc # --- int-like fields ---------------------------------------------------- @property def age(self) -> int: return self._age @age.setter def age(self, value: Any) -> None: try: self._age = int(value) except (TypeError, ValueError) as exc: raise ValueError("age must be convertible to int") from exc @property def n_legs(self) -> int: return self._n_legs @n_legs.setter def n_legs(self, value: Any) -> None: try: self._n_legs = int(value) except (TypeError, ValueError) as exc: raise ValueError("n_legs must be convertible to int") from exc # --- behaviour ---------------------------------------------------------- def have_birthday(self, b_day: Any = 1) -> int: try: increment = int(b_day) except (TypeError, ValueError) as exc: raise ValueError("birthday increment must be convertible to int") from exc self.age += increment return self.age def __str__(self) -> str: return ( f"{self.name} the {self.gender} {self.species}, " f"age {self.age} has {self.n_legs} legs!" )from typing import Protocol, runtime_checkable# Protocols are used to check if a class/object have a specific method- from typing import Any
@runtime_checkable # allow protocols to be used inside isinstanceclass SupportsInt(Protocol):def __int__(self) -> int: ...@runtime_checkableclass SupportsStr(Protocol):def __str__(self) -> str: ...- class Pet:
def __init__(self, name: str, species: str, gender: str = "not defined", age: int = 0, n_legs: int = 4):self.__name = nameself.__species = speciesself.__gender = genderself.__age = ageself.__n_legs = n_legs- def __init__(
- self,
- name: Any,
- species: Any,
- gender: Any = "not defined",
- age: Any = 0,
- n_legs: Any = 4,
- ) -> None:
- # Go through the setters so we reuse validation/conversion logic
- self.name = name
- self.species = species
- self.gender = gender
- self.age = age
- self.n_legs = n_legs
- # --- string-like fields -------------------------------------------------
- @property
- def name(self) -> str:
return self.__name- return self._name
- @name.setter
def name(self, val: SupportsStr) -> None:if not isinstance(val, SupportsStr):raise ValueError("Name, must be a String")self.__name = val.__str__()- def name(self, value: Any) -> None:
- try:
- self._name = str(value)
- except Exception as exc:
- raise ValueError("name must be convertible to str") from exc
- @property
- def species(self) -> str:
return self.__species- return self._species
- @species.setter
def species(self, val: SupportsStr) -> None:if not isinstance(val, SupportsStr):raise ValueError("Species, must be a String")self.__species = val.__str__()- def species(self, value: Any) -> None:
- try:
- self._species = str(value)
- except Exception as exc:
- raise ValueError("species must be convertible to str") from exc
- @property
- def gender(self) -> str:
return self.__gender- return self._gender
- @gender.setter
def gender(self, val: SupportsStr) -> None:if not isinstance(val, SupportsStr):raise ValueError("Gender, must be a String")self.__gender = val.__str__()- def gender(self, value: Any) -> None:
- try:
- self._gender = str(value)
- except Exception as exc:
- raise ValueError("gender must be convertible to str") from exc
- # --- int-like fields ----------------------------------------------------
- @property
- def age(self) -> int:
return self.__age- return self._age
- @age.setter
def age(self, val: SupportsInt) -> None:if not isinstance(val, SupportsInt):raise ValueError("Age, must be an Integer")self.__age = val.__int__()- def age(self, value: Any) -> None:
- try:
- self._age = int(value)
- except (TypeError, ValueError) as exc:
- raise ValueError("age must be convertible to int") from exc
- @property
- def n_legs(self) -> int:
return self.__n_legs- return self._n_legs
- @n_legs.setter
def n_legs(self, val: SupportsInt) -> None:if not isinstance(val, SupportsInt):raise ValueError("N_legs, must be an Integer")self.__n_legs = val.__int__()def have_birthday(self, b_day: SupportsInt = 1) -> int:self.age += b_day.__int__()- def n_legs(self, value: Any) -> None:
- try:
- self._n_legs = int(value)
- except (TypeError, ValueError) as exc:
- raise ValueError("n_legs must be convertible to int") from exc
- # --- behaviour ----------------------------------------------------------
- def have_birthday(self, b_day: Any = 1) -> int:
- try:
- increment = int(b_day)
- except (TypeError, ValueError) as exc:
- raise ValueError("birthday increment must be convertible to int") from exc
- self.age += increment
- return self.age
- def __str__(self) -> str:
return f"{self.name} the {self.gender} {self.species}, age {self.age} has {self.n_legs} legs!"- return (
- f"{self.name} the {self.gender} {self.species}, "
- f"age {self.age} has {self.n_legs} legs!"
- )
import codewars_test as test from solution import Pet def defaultPet(): return Pet("Bob", "Dog", "Male", 5) @test.describe("Core behaviour") def core_tests(): @test.it("String representation and defaults") def test_str_and_defaults(): p = defaultPet() test.assert_equals( str(p), "Bob the Male Dog, age 5 has 4 legs!", ) # Default values p2 = Pet("Unnamed", "Unknown") test.assert_equals( str(p2), "Unnamed the not defined Unknown, age 0 has 4 legs!", ) @test.it("Growing legs and aging") def test_mutation(): p = defaultPet() p.n_legs = 6 test.assert_equals( str(p), "Bob the Male Dog, age 5 has 6 legs!", ) age = p.have_birthday() test.assert_equals(age, 6) test.assert_equals( str(p), "Bob the Male Dog, age 6 has 6 legs!", ) # Multiple increment, from int and from str p.have_birthday(3) test.assert_equals(p.age, 9) p.have_birthday("2") test.assert_equals(p.age, 11) @test.it("Gender and species updates") def test_gender_species(): p = defaultPet() p.gender = "Female" test.assert_equals( str(p), "Bob the Female Dog, age 5 has 4 legs!", ) p.gender = "Prefer not to Specify" test.assert_equals( str(p), "Bob the Prefer not to Specify Dog, age 5 has 4 legs!", ) p.species = "Cat" test.assert_equals( str(p), "Bob the Prefer not to Specify Cat, age 5 has 4 legs!", ) @test.describe("Type conversion and flexibility") def conversion_tests(): @test.it("Name, species, gender convertible to str") def test_str_like_fields(): p = Pet(123, ["Dog"], gender=("M", "ale")) test.assert_equals(p.name, "123") test.assert_equals(p.species, "['Dog']") test.assert_equals(p.gender, "('M', 'ale')") # Using setters p.name = 3.14 p.species = {"type": "Dragon"} p.gender = None test.assert_equals(p.name, "3.14") test.assert_equals(p.species, "{'type': 'Dragon'}") test.assert_equals(p.gender, "None") @test.it("Age and n_legs convertible to int") def test_int_like_fields(): p = Pet("X", "Y", age="10", n_legs="8") test.assert_equals(p.age, 10) test.assert_equals(p.n_legs, 8) p.age = 7.9 # int(7.9) == 7 p.n_legs = True # int(True) == 1 test.assert_equals(p.age, 7) test.assert_equals(p.n_legs, 1) # have_birthday conversions p.have_birthday("5") test.assert_equals(p.age, 12) p.have_birthday(2.3) # int(2.3) == 2 test.assert_equals(p.age, 14) @test.it("Custom objects with __str__ and __int__") def test_custom_objects(): class NameLike: def __str__(self): return "Fluffy" class IntLike: def __int__(self): return 42 p = Pet(NameLike(), "Dog", age=IntLike(), n_legs=IntLike()) test.assert_equals(p.name, "Fluffy") test.assert_equals(p.age, 42) test.assert_equals(p.n_legs, 42) @test.describe("Validation and error handling") def error_tests(): @test.it("Invalid age and n_legs should raise ValueError") def test_invalid_int_conversion(): def make_pet_bad_age(): Pet("X", "Y", age="not-an-int") def make_pet_bad_legs(): Pet("X", "Y", n_legs="four") p = defaultPet() def set_bad_age(): p.age = "old" def set_bad_legs(): p.n_legs = object() # int(object()) fails test.expect_error("age must be convertible to int", make_pet_bad_age) test.expect_error("n_legs must be convertible to int", make_pet_bad_legs) test.expect_error("setting age to non-int-like should fail", set_bad_age) test.expect_error("setting n_legs to non-int-like should fail", set_bad_legs) @test.it("Invalid birthday increment should raise ValueError") def test_invalid_birthday_increment(): p = defaultPet() def bad_bday_nan(): p.have_birthday("NaN") def bad_bday_obj(): p.have_birthday(object()) test.expect_error("birthday increment 'NaN' should fail", bad_bday_nan) test.expect_error("birthday increment object() should fail", bad_bday_obj) @test.it("Name/species/gender: extremely unlikely to fail, but still guarded") def test_invalid_str_conversion(): class BadStr: def __str__(self): raise RuntimeError("boom") p = defaultPet() def set_bad_name(): p.name = BadStr() def set_bad_species(): p.species = BadStr() def set_bad_gender(): p.gender = BadStr() test.expect_error("bad __str__ on name should fail", set_bad_name) test.expect_error("bad __str__ on species should fail", set_bad_species) test.expect_error("bad __str__ on gender should fail", set_bad_gender)- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import Pet
- def defaultPet():
- return Pet("Bob", "Dog", "Male", 5)
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")def test_group():@test.it("Dog")def test_case():p = defaultPet()test.assert_equals("Bob the Male Dog, age 5 has 4 legs!", f"{p}")@test.it("Growing Legs")def change_n_legs():- @test.describe("Core behaviour")
- def core_tests():
- @test.it("String representation and defaults")
- def test_str_and_defaults():
- p = defaultPet()
p.n_legs = 6test.assert_equals("Bob the Male Dog, age 5 has 6 legs!", f"{p}")@test.it("Aging")def happy_birthday():- test.assert_equals(
- str(p),
- "Bob the Male Dog, age 5 has 4 legs!",
- )
- # Default values
- p2 = Pet("Unnamed", "Unknown")
- test.assert_equals(
- str(p2),
- "Unnamed the not defined Unknown, age 0 has 4 legs!",
- )
- @test.it("Growing legs and aging")
- def test_mutation():
- p = defaultPet()
- p.n_legs = 6
- test.assert_equals(
- str(p),
- "Bob the Male Dog, age 5 has 6 legs!",
- )
- age = p.have_birthday()
test.assert_equals(6, age)- test.assert_equals(age, 6)
- test.assert_equals(
- str(p),
- "Bob the Male Dog, age 6 has 6 legs!",
- )
- # Multiple increment, from int and from str
- p.have_birthday(3)
test.assert_equals("Bob the Male Dog, age 9 has 4 legs!", f"{p}")@test.it("Gender Identity Matters")def assigned_at_birth():- test.assert_equals(p.age, 9)
- p.have_birthday("2")
- test.assert_equals(p.age, 11)
- @test.it("Gender and species updates")
- def test_gender_species():
- p = defaultPet()
- p.gender = "Female"
test.assert_equals("Bob the Female Dog, age 5 has 4 legs!", f"{p}")p.gender ="Prefer not to Specify"test.assert_equals("Bob the Prefer not to Specify Dog, age 5 has 4 legs!", f"{p}")@test.it("Pokemon Evolution")def miracle():p = defaultPet()- test.assert_equals(
- str(p),
- "Bob the Female Dog, age 5 has 4 legs!",
- )
- p.gender = "Prefer not to Specify"
- test.assert_equals(
- str(p),
- "Bob the Prefer not to Specify Dog, age 5 has 4 legs!",
- )
- p.species = "Cat"
test.assert_equals("Bob the Male Cat, age 5 has 4 legs!", f"{p}")- test.assert_equals(
- str(p),
- "Bob the Prefer not to Specify Cat, age 5 has 4 legs!",
- )
- @test.describe("Type conversion and flexibility")
- def conversion_tests():
- @test.it("Name, species, gender convertible to str")
- def test_str_like_fields():
- p = Pet(123, ["Dog"], gender=("M", "ale"))
- test.assert_equals(p.name, "123")
- test.assert_equals(p.species, "['Dog']")
- test.assert_equals(p.gender, "('M', 'ale')")
- # Using setters
- p.name = 3.14
- p.species = {"type": "Dragon"}
- p.gender = None
- test.assert_equals(p.name, "3.14")
- test.assert_equals(p.species, "{'type': 'Dragon'}")
- test.assert_equals(p.gender, "None")
- @test.it("Age and n_legs convertible to int")
- def test_int_like_fields():
- p = Pet("X", "Y", age="10", n_legs="8")
- test.assert_equals(p.age, 10)
- test.assert_equals(p.n_legs, 8)
- p.age = 7.9 # int(7.9) == 7
- p.n_legs = True # int(True) == 1
- test.assert_equals(p.age, 7)
- test.assert_equals(p.n_legs, 1)
- # have_birthday conversions
- p.have_birthday("5")
- test.assert_equals(p.age, 12)
- p.have_birthday(2.3) # int(2.3) == 2
- test.assert_equals(p.age, 14)
- @test.it("Custom objects with __str__ and __int__")
- def test_custom_objects():
- class NameLike:
- def __str__(self):
- return "Fluffy"
- class IntLike:
- def __int__(self):
- return 42
- p = Pet(NameLike(), "Dog", age=IntLike(), n_legs=IntLike())
- test.assert_equals(p.name, "Fluffy")
- test.assert_equals(p.age, 42)
- test.assert_equals(p.n_legs, 42)
- @test.describe("Validation and error handling")
- def error_tests():
- @test.it("Invalid age and n_legs should raise ValueError")
- def test_invalid_int_conversion():
- def make_pet_bad_age():
- Pet("X", "Y", age="not-an-int")
- def make_pet_bad_legs():
- Pet("X", "Y", n_legs="four")
- p = defaultPet()
- def set_bad_age():
- p.age = "old"
- def set_bad_legs():
- p.n_legs = object() # int(object()) fails
- test.expect_error("age must be convertible to int", make_pet_bad_age)
- test.expect_error("n_legs must be convertible to int", make_pet_bad_legs)
- test.expect_error("setting age to non-int-like should fail", set_bad_age)
- test.expect_error("setting n_legs to non-int-like should fail", set_bad_legs)
- @test.it("Invalid birthday increment should raise ValueError")
- def test_invalid_birthday_increment():
- p = defaultPet()
- def bad_bday_nan():
- p.have_birthday("NaN")
- def bad_bday_obj():
- p.have_birthday(object())
- test.expect_error("birthday increment 'NaN' should fail", bad_bday_nan)
- test.expect_error("birthday increment object() should fail", bad_bday_obj)
- @test.it("Name/species/gender: extremely unlikely to fail, but still guarded")
- def test_invalid_str_conversion():
- class BadStr:
- def __str__(self):
- raise RuntimeError("boom")
- p = defaultPet()
- def set_bad_name():
- p.name = BadStr()
- def set_bad_species():
- p.species = BadStr()
- def set_bad_gender():
- p.gender = BadStr()
- test.expect_error("bad __str__ on name should fail", set_bad_name)
- test.expect_error("bad __str__ on species should fail", set_bad_species)
- test.expect_error("bad __str__ on gender should fail", set_bad_gender)
from operator import add, sub, mul, truediv OPS = dict(zip("+-*/", (add, sub, mul, truediv))) calculator = lambda a, b, op: OPS[op](a, b)- from operator import add, sub, mul, truediv
def calculator(a, b, operator):return {'+': add, '-': sub, '*': mul, '/': truediv}[operator](a, b)- OPS = dict(zip("+-*/", (add, sub, mul, truediv)))
- calculator = lambda a, b, op: OPS[op](a, b)
get Forked
export function findTheLongestWord(sentence?: string): string { if (typeof sentence !== "string") throw new Error("The sentence must end up being a string"); const words = sentence.trim().split(/\s+/); if (!words[0]) throw new Error("The sentence cannot be empty"); let longest = "", tie = false; for (const w of words) if (w.length > longest.length) { longest = w; tie = false; } else if (w.length === longest.length) tie = true; return tie ? "no longest word found" : `${longest}: ${longest.length} chars`; }- export function findTheLongestWord(sentence?: string): string {
if (typeof sentence !== "string") throw new Error("The sentence must be a string");- if (typeof sentence !== "string") throw new Error("The sentence must end up being a string");
- const words = sentence.trim().split(/\s+/);
if (!words[0]) throw new Error("The sentence can not be empty");- if (!words[0]) throw new Error("The sentence cannot be empty");
- let longest = "", tie = false;
- for (const w of words)
- if (w.length > longest.length) { longest = w; tie = false; }
- else if (w.length === longest.length) tie = true;
- return tie ? "no longest word found" : `${longest}: ${longest.length} chars`;
- }
Or even more cursed
def cursed_world(): return ( (ඞ := lambda ඞඞ: ඞඞ) ((སྐྱེས := [])or[(སྐྱེས := [*སྐྱེས, chr(c)])for c in (0x68,0x65,0x6c,0x6c,0x6f,0x20,0x77,0x6f,0x72,0x6c,0x64)]) and ඞ(''.join(སྐྱེས)) )- def cursed_world():
- return (
(ᐰ:=lambda ᐱ,ᐲ='':(ᐰ(ᐱ[1:],ᐲ+chr(ᐱ[0]))if ᐱ else ᐲ))([104,101,108,108,111,32,119,111,114,108,100])- (ඞ := lambda ඞඞ: ඞඞ)
- ((སྐྱེས := [])or[(སྐྱེས := [*སྐྱེས, chr(c)])for c in
- (0x68,0x65,0x6c,0x6c,0x6f,0x20,0x77,0x6f,0x72,0x6c,0x64)])
- and ඞ(''.join(སྐྱེས))
- )
A minimal, well-structured "Hello world" example with a public constant
and a basic unit test. Designed to be easy to extend (e.g., localization).
import std/unittest const text* = "Hello world!" proc main*() = echo text when isMainModule: main() suite "greeting": test "text is \"Hello world!\"": check text == "Hello world!"- import std/unittest
- const text* = "Hello world!"
echo text- proc main*() =
- echo text
- when isMainModule:
- main()
- suite "greeting":
- test "text is \"Hello world!\"":
- check text == "Hello world!"
import java.util.*; class WordChain { static boolean validate(String[] w, int n) { // Edge cases if (n <= 0 || w == null || w.length <= 1) return false; final int len = w.length; final int TABLE_SIZE = 65536; final int MASK = TABLE_SIZE - 1; // Pre-process: lowercase char arrays + hashes (single pass) char[][] chars = new char[len][]; int[] hashes = new int[len]; for (int i = 0; i < len; i++) { String s = w[i]; if (s == null || s.length() < n) return false; char[] c = new char[s.length()]; int h = 0; for (int j = 0; j < c.length; j++) { char ch = s.charAt(j); // Branchless lowercase for A-Z ch |= ((ch >= 'A' & ch <= 'Z') ? 0x20 : 0); c[j] = ch; h = 31 * h + ch; } chars[i] = c; hashes[i] = h; } // Hash table with chaining (faster than linear probing) int[] buckets = new int[TABLE_SIZE]; int[] next = new int[len]; Arrays.fill(buckets, -1); // Insert first word int idx = hashes[0] & MASK; next[0] = -1; buckets[idx] = 0; // Validate chain for (int i = 1; i < len; i++) { char[] prev = chars[i - 1]; char[] curr = chars[i]; // Suffix-prefix match (direct array access = no bounds check) int suffixStart = prev.length - n; for (int j = 0; j < n; j++) { if (prev[suffixStart + j] != curr[j]) return false; } // Duplicate detection with early hash rejection int hash = hashes[i]; idx = hash & MASK; for (int slot = buckets[idx]; slot != -1; slot = next[slot]) { if (hashes[slot] == hash && arraysEqual(chars[slot], curr)) { return false; } } // Insert into hash table next[i] = buckets[idx]; buckets[idx] = i; } return true; } private static boolean arraysEqual(char[] a, char[] b) { if (a.length != b.length) return false; for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; } }import java.util.*;class WordChain{static boolean validate(String[]w,int n){if(w==null||w.length<=1||n<=0)return false;Set<String>s=new HashSet<>();for(int i=0;i<w.length;i++)if(w[i]==null||w[i].length()<n||!s.add(w[i].toLowerCase())||(i>0&&!w[i-1].regionMatches(true,w[i-1].length()-n,w[i],0,n)))return false;return true;}}- import java.util.*;
- class WordChain {
- static boolean validate(String[] w, int n) {
- // Edge cases
- if (n <= 0 || w == null || w.length <= 1) return false;
- final int len = w.length;
- final int TABLE_SIZE = 65536;
- final int MASK = TABLE_SIZE - 1;
- // Pre-process: lowercase char arrays + hashes (single pass)
- char[][] chars = new char[len][];
- int[] hashes = new int[len];
- for (int i = 0; i < len; i++) {
- String s = w[i];
- if (s == null || s.length() < n) return false;
- char[] c = new char[s.length()];
- int h = 0;
- for (int j = 0; j < c.length; j++) {
- char ch = s.charAt(j);
- // Branchless lowercase for A-Z
- ch |= ((ch >= 'A' & ch <= 'Z') ? 0x20 : 0);
- c[j] = ch;
- h = 31 * h + ch;
- }
- chars[i] = c;
- hashes[i] = h;
- }
- // Hash table with chaining (faster than linear probing)
- int[] buckets = new int[TABLE_SIZE];
- int[] next = new int[len];
- Arrays.fill(buckets, -1);
- // Insert first word
- int idx = hashes[0] & MASK;
- next[0] = -1;
- buckets[idx] = 0;
- // Validate chain
- for (int i = 1; i < len; i++) {
- char[] prev = chars[i - 1];
- char[] curr = chars[i];
- // Suffix-prefix match (direct array access = no bounds check)
- int suffixStart = prev.length - n;
- for (int j = 0; j < n; j++) {
- if (prev[suffixStart + j] != curr[j]) return false;
- }
- // Duplicate detection with early hash rejection
- int hash = hashes[i];
- idx = hash & MASK;
- for (int slot = buckets[idx]; slot != -1; slot = next[slot]) {
- if (hashes[slot] == hash && arraysEqual(chars[slot], curr)) {
- return false;
- }
- }
- // Insert into hash table
- next[i] = buckets[idx];
- buckets[idx] = i;
- }
- return true;
- }
- private static boolean arraysEqual(char[] a, char[] b) {
- if (a.length != b.length) return false;
- for (int i = 0; i < a.length; i++) {
- if (a[i] != b[i]) return false;
- }
- return true;
- }
- }