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

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

Code
Diff
  • 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 isinstance
    • class SupportsInt(Protocol):
    • def __int__(self) -> int: ...
    • @runtime_checkable
    • class 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 = name
    • self.__species = species
    • self.__gender = gender
    • self.__age = age
    • self.__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!"
    • )
Code
Diff
  • 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

Code
Diff
  • 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

Code
Diff
  • 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).

Code
Diff
  • 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!"
Games
Arrays
Code
Diff
  • 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;
    • }
    • }