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.
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
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 ''}!"
- )
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("Abnormal legs") def test_one_leg(): p = defaultPet() p.n_legs = 1 test.assert_equals( str(p), "Bob the Male Dog, age 5 has 1 leg!", ) p.n_legs = 0 test.assert_equals( str(p), "Bob the Male Dog, age 5 has 0 legs!", ) p.n_legs = -1 test.assert_equals( str(p), "Bob the Male Dog, age 5 has -1 leg!", ) p.n_legs = -2 test.assert_equals( str(p), "Bob the Male Dog, age 5 has -2 legs!", ) @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
- 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("Abnormal legs")
- def test_one_leg():
- p = defaultPet()
- p.n_legs = 1
- test.assert_equals(
- str(p),
- "Bob the Male Dog, age 5 has 1 leg!",
- )
- p.n_legs = 0
- test.assert_equals(
- str(p),
- "Bob the Male Dog, age 5 has 0 legs!",
- )
- p.n_legs = -1
- test.assert_equals(
- str(p),
- "Bob the Male Dog, age 5 has -1 leg!",
- )
- p.n_legs = -2
- test.assert_equals(
- str(p),
- "Bob the Male Dog, age 5 has -2 legs!",
- )
- @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 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 = 0num = 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 + num2elif operation == "-":output = num * num2elif operation == "*":output = num + num2elif operation == "/":output = num / num2return outputfor 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
#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 UBreturn 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;
- }
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 = 0for u in usernames:if (4 <= len(u) <= 12and u[0].isalpha()and u.isalnum()and u.islower()):count += 1return count- return len([user for user in usernames if 4 <= len(user) <= 12 and user[0].isalpha() and user.isalnum() and user.islower()])
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`;
- }
Very good job boys
well done
worlde
onb the way
pice of cake no probvlem
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()