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

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;
    • }
Code
Diff
  • 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()])
    
    
    
    • def count_valid_usernames(usernames):
    • count = 0
    • for u in usernames:
    • if (
    • 4 <= len(u) <= 12
    • and u[0].isalpha()
    • and u.isalnum()
    • and u.islower()
    • ):
    • count += 1
    • return count
    • return len([user for user in usernames if 4 <= len(user) <= 12 and user[0].isalpha() and user.isalnum() and user.islower()])
Code
Diff
  • export function findTheLongestWord(sentence?: string): string {
      if (!sentence || typeof sentence !== "string") throw new Error("The sentence must end up being a string");
      const words = sentence.trim().split(/\s+/);
      
      const max = Math.max(...words.map(w => w.length));
      const values = words.filter(w=>w.length === max)
      
      return values.length > 1 ? "no longest word found" : `${values[0]}: ${max} chars`;
    }
    • export function findTheLongestWord(sentence?: string): string {
    • if (typeof sentence !== "string") throw new Error("The sentence must end up being a string");
    • if (!sentence || 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;
    • const max = Math.max(...words.map(w => w.length));
    • const values = words.filter(w=>w.length === max)
    • return tie ? "no longest word found" : `${longest}: ${longest.length} chars`;
    • return values.length > 1 ? "no longest word found" : `${values[0]}: ${max} chars`;
    • }
Code
Diff
  • fn mean(x: &[f64]) -> f64 {
        x.iter().sum::<f64>() / x.len() as f64
    }
    • fn mean(x: &[f64]) -> f64 {
    • let x_len_float = x.len() as f64;
    • return x.iter().sum::<f64>() / x_len_float;
    • }
    • x.iter().sum::<f64>() / x.len() as f64
    • }

Very good job boys
well done
worlde
onb the way
pice of cake no probvlem

Code
Diff
  • import random
    general_words = [
        "about", "apple", "beach", "brain", "bread",  # Everyday nouns
        "clear", "cloud", "dance", "dream", "early",  # Verbs & adjectives
        "faith", "field", "glass", "heart", "house",  # Common concepts
        "light", "money", "night", "ocean", "party",  # Popular terms
        "quiet", "river", "smile", "table", "water"   # Daily objects   
    ]
    
    word_selected = ""
    wordarray = []
    wordcolour = []
    
    def choose_word(general_words):
        global word_selected
        length = len(general_words)
        word_selected = general_words[random.randint(0,length)]
        print(word_selected)
        
        
        
    
    
    def user_input(): #cancel it
        global word_selected, wordarray, wordcolour
        input_word = input("guess a word")
        input_word = input_word.lower()
        i_word_array = input_word.split()
        
        wordarray = word_selected.split()
        wordcolour = ["grey", "grey", "grey", "grey", "grey"]
        
        for i in range (0,4):
            for u in range (0,4):
                if i_word_array[i] == wordarray[u]:
                    if i != u:
                        wordcolour[u] = "yellow"
                    else:
                        wordcolour[u] = "green"
                        #burgulary 
                
            
            
            
        
    
    def parse():
        
        slots = [][] 
        
    def check():
        
        
    
    choose_word(general_words)
    
    for i in range (0,6):
        print(wordarray)
        print(wordcolour)
        print()
    • import random
    • general_words = [
    • "about", "apple", "beach", "brain", "bread", # Everyday nouns
    • "clear", "cloud", "dance", "dream", "early", # Verbs & adjectives
    • "faith", "field", "glass", "heart", "house", # Common concepts
    • "light", "money", "night", "ocean", "party", # Popular terms
    • "quiet", "river", "smile", "table", "water" # Daily objects
    • ]
    • word_selected = ""
    • wordarray = []
    • wordcolour = []
    • def choose_word(general_words):
    • global word_selected
    • length = len(general_words)
    • word_selected = general_words[random.randint(0,length)]
    • print(word_selected)
    • def user_input():
    • def user_input(): #cancel it
    • global word_selected, wordarray, wordcolour
    • input_word = input("guess a word")
    • input_word = input_word.lower()
    • i_word_array = input_word.split()
    • wordarray = word_selected.split()
    • wordcolour = ["grey", "grey", "grey", "grey", "grey"]
    • for i in range (0,4):
    • for u in range (0,4):
    • if i_word_array[i] == wordarray[u]:
    • if i != u:
    • wordcolour[u] = "yellow"
    • else:
    • wordcolour[u] = "green"
    • #burgulary
    • def parse():
    • slots = [][]
    • def check():
    • choose_word(general_words)
    • for i in range (0,6):
    • print(wordarray)
    • print(wordcolour)
    • print()