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
  • def count_valid_usernames(usernames):
        count = 0
        for user in usernames:
            length = len(user)
            # 1. Check length first (fastest, constant time)
            if not (4 <= length <= 12):
                continue
                
            # 2. Check first character (fastest character check)
            if not user[0].isalpha():
                continue
                
            # 3. Single pass for Alphanumeric AND Lowercase
            # islower() + isalnum() requires two passes. 
            # For raw speed, a manual loop or a optimized regex is better.
            if user.islower() and user.isalnum():
                count += 1
                
        return count
    • def count_valid_usernames(usernames):
    • return len([user for user in usernames if 4 <= len(user) <= 12 and user[0].isalpha() and user.isalnum() and user.islower()])
    • count = 0
    • for user in usernames:
    • length = len(user)
    • # 1. Check length first (fastest, constant time)
    • if not (4 <= length <= 12):
    • continue
    • # 2. Check first character (fastest character check)
    • if not user[0].isalpha():
    • continue
    • # 3. Single pass for Alphanumeric AND Lowercase
    • # islower() + isalnum() requires two passes.
    • # For raw speed, a manual loop or a optimized regex is better.
    • if user.islower() and user.isalnum():
    • count += 1
    • return count
Mathematics
Code
Diff
  • square = lambda n: n*n
    • make_square = lambda a: a**2
    • square = lambda n: n*n
Code
Diff
  • int compare(int a, int b) {
    	return a % b == a ? b : a;
    }
    • int compare(int a, int b){return a>b?a:b;}
    • int compare(int a, int b) {
    • return a % b == a ? b : a;
    • }

pet could have said it had '1 legs' or '-1 legs', added if else to str method to account fot this so now it says '1 leg' or '-1 leg' if it only has 1 or -1

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} leg{'s' if abs(self.n_legs) != 1 else ''}!"
            )
    
    • 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!"
    • f"age {self.age} has {self.n_legs} leg{'s' if abs(self.n_legs) != 1 else ''}!"
    • )
Code
Diff
  • import random
    
    def calculate(ops: list[str]) -> tuple[int, str, int, float]:
    
        num2 = random.randint(0, 1000)
        num1 = random.randint(0, 1000)
    
        match random.choice(ops):
            case "+":
                return num1, "+", num2, num1 + num2
            case "-":
                return num1, "-", num2, num1 - num2
            case "*":
                return num1, "*", num2, num1 * num2
            case "/":
                if num2 == 0: # can't have division by 0
                    num2 = random.randint(1, 1000)
                return num1, "/", num2, num1 / num2
            case op:
                raise Exception(f"Unknown operation '{op}'") ## can always add more cases for '//' or '**' and others
                   
    operations = ["+", "-", "*", "/"]
           
    for _ in range(100):
        print("{} {} {} = {}".format(*calculate(operations))) # since the function now returns a tuple, you can unpack and format it nicely
    • import random
    • operations = ["+","-","*","/"]
    • def calculate(operations):
    • output = 0
    • num = random.randint(0,1000)
    • num2 = random.randint(0,1000)
    • operation = operations[random.randint(0,3)]
    • if num < num2:
    • return calculate(operations)
    • print(num, operation, num2, "=")
    • if operation == "+":
    • output = num + num2
    • elif operation == "-":
    • output = num * num2
    • elif operation == "*":
    • output = num + num2
    • elif operation == "/":
    • output = num / num2
    • return output
    • for i in range(0,10):
    • print(calculate(operations))
    • print()
    • def calculate(ops: list[str]) -> tuple[int, str, int, float]:
    • num2 = random.randint(0, 1000)
    • num1 = random.randint(0, 1000)
    • match random.choice(ops):
    • case "+":
    • return num1, "+", num2, num1 + num2
    • case "-":
    • return num1, "-", num2, num1 - num2
    • case "*":
    • return num1, "*", num2, num1 * num2
    • case "/":
    • if num2 == 0: # can't have division by 0
    • num2 = random.randint(1, 1000)
    • return num1, "/", num2, num1 / num2
    • case op:
    • raise Exception(f"Unknown operation '{op}'") ## can always add more cases for '//' or '**' and others
    • operations = ["+", "-", "*", "/"]
    • for _ in range(100):
    • print("{} {} {} = {}".format(*calculate(operations))) # since the function now returns a tuple, you can unpack and format it nicely
  • Less dependencies
Code
Diff
  • #include <stdlib.h>
    char *strdup_to_upper(const char *input) {
      if (!input) return NULL;
      char *result = strdup(input);
      if (!result) return NULL;
      char *cursor = result;
      while (*cursor) *(cursor++) = (*cursor >= 97  && *cursor <= 122)? *cursor-32:*cursor;
      return result;
    }
    • #include <string.h>
    • #include <stdlib.h>
    • char *strdup_to_upper(const char *input) {
    • if (!input) // prevent strdup UB
    • return NULL;
    • if (!input) return NULL;
    • char *result = strdup(input);
    • if (!result)
    • return NULL;
    • if (!result) return NULL;
    • char *cursor = result;
    • while (*cursor) {
    • *cursor = toupper(*cursor);
    • cursor++;
    • }
    • while (*cursor) *(cursor++) = (*cursor >= 97 && *cursor <= 122)? *cursor-32:*cursor;
    • return result;
    • }