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.
fn math(expression: &str) -> Result<i32, MathError> { // remove whitespace let expression: String = expression.chars().filter(|ch| !ch.is_whitespace()).collect(); let operator: char = expression.chars().find(|ch| ['+', '-', '*', '/', '='].contains(&ch)).ok_or(MathError::MissingOperator)?; let operands: Vec<i32> = expression.split(operator).filter_map(|n| n.parse().ok()).collect(); let num1 = *operands.get(0).ok_or(MathError::InvalidOperand)?; let num2 = *operands.get(1).ok_or(MathError::InvalidOperand)?; // check if they divide by zero if operator == '/' && num2 == 0 { return Err(MathError::DivideByZero); } match operator { '+' => num1.checked_add(num2).ok_or(MathError::Overflow), '-' => num1.checked_sub(num2).ok_or(MathError::Overflow), '*' => num1.checked_mul(num2).ok_or(MathError::Overflow), '/' => num1.checked_div(num2).ok_or(MathError::Overflow), '=' => Ok((num1 == num2).into()), _ => unreachable!() } } use MathError::*; #[derive(Debug, PartialEq, Eq)] enum MathError { MissingOperator, InvalidOperand, DivideByZero, Overflow, }
fn math(s: &str) -> Result<i32, MathError> {let s: String = s.chars().filter(|ch| !ch.is_whitespace()).collect();let Some((num1, num2)) =s.split_once(|c| ['+', '-', '*', '/', '='].contains(&c))else {return Err(MissingOperator);};- fn math(expression: &str) -> Result<i32, MathError> {
- // remove whitespace
- let expression: String = expression.chars().filter(|ch| !ch.is_whitespace()).collect();
- let operator: char = expression.chars().find(|ch| ['+', '-', '*', '/', '='].contains(&ch)).ok_or(MathError::MissingOperator)?;
- let operands: Vec<i32> = expression.split(operator).filter_map(|n| n.parse().ok()).collect();
- let num1 = *operands.get(0).ok_or(MathError::InvalidOperand)?;
- let num2 = *operands.get(1).ok_or(MathError::InvalidOperand)?;
- // check if they divide by zero
- if operator == '/' && num2 == 0 {
- return Err(MathError::DivideByZero);
- }
let operator = &s[num1.len()..=num1.len()];let (Ok(num1), Ok(num2)) = (num1.parse::<i32>(), num2.parse::<i32>()) else {return Err(InvalidOperand);};- match operator {
"+" => Ok(num1 + num2),"-" => Ok(num1 - num2),"*" => Ok(num1 * num2),"/" => {if num2 != 0 {Ok(num1 / num2)} else {Err(DivideByZero)}},"=" => Ok(i32::from(num1 == num2)),_ => unreachable!(),- '+' => num1.checked_add(num2).ok_or(MathError::Overflow),
- '-' => num1.checked_sub(num2).ok_or(MathError::Overflow),
- '*' => num1.checked_mul(num2).ok_or(MathError::Overflow),
- '/' => num1.checked_div(num2).ok_or(MathError::Overflow),
- '=' => Ok((num1 == num2).into()),
- _ => unreachable!()
- }
- }
- use MathError::*;
- #[derive(Debug, PartialEq, Eq)]
- enum MathError {
- MissingOperator,
- InvalidOperand,
DivideByZero- DivideByZero,
- Overflow,
- }
This solution avoids creating any objects or creating copies of the sequence or any temporary variables.
Using a class in the previous solutions was silly. >.<
from typing import Sequence, Optional def missing_integer(sequence: Sequence[int]) -> Optional[int]: for x, y in zip(sequence, range(sequence[0], sequence[-1])): if x != y: return y
class MissingInteger:def __init__(self, sequence):self.sequence = sequenceself.perfect_sequence = range(min(self.sequence), max(self.sequence) +1 )- from typing import Sequence, Optional
def solution(self):for number in self.perfect_sequence:if number not in self.sequence:return number- def missing_integer(sequence: Sequence[int]) -> Optional[int]:
- for x, y in zip(sequence, range(sequence[0], sequence[-1])):
- if x != y:
- return y
import codewars_test as test from solution import missing_integer @test.describe("Find the missing integer in a sorted sequence of natural numbers.") def test_group(): @test.it("Comparing to expected return values.") def test_case(): test.assert_equals(missing_integer([1, 2, 3, 4, 5, 7, 8, 9]), 6) test.assert_equals(missing_integer([1, 2, 4, 5, 6, 7, 8, 9]), 3) test.assert_equals(missing_integer([-2, 0, 1, 2, 3, 4, 5, 6]), -1) test.assert_equals(missing_integer([1, 2, 3, 4, 5, 6, 7, 8, 9]), None)
- import codewars_test as test
from solution import MissingInteger- from solution import missing_integer
@test.describe("Example")- @test.describe("Find the missing integer in a sorted sequence of natural numbers.")
- def test_group():
@test.it("test case")- @test.it("Comparing to expected return values.")
- def test_case():
test.assert_equals(MissingInteger([1, 2, 3, 4, 5, 7, 8, 9]).solution(), 6)test.assert_equals(MissingInteger([1, 2, 4, 5, 6, 7, 8, 9]).solution(), 3)test.assert_equals(MissingInteger([-2, 0, 1, 2, 3, 4, 5, 6]).solution(), -1)test.assert_equals(MissingInteger([1, 2, 3, 4, 5, 6, 7, 8, 9]).solution(), None)- test.assert_equals(missing_integer([1, 2, 3, 4, 5, 7, 8, 9]), 6)
- test.assert_equals(missing_integer([1, 2, 4, 5, 6, 7, 8, 9]), 3)
- test.assert_equals(missing_integer([-2, 0, 1, 2, 3, 4, 5, 6]), -1)
- test.assert_equals(missing_integer([1, 2, 3, 4, 5, 6, 7, 8, 9]), None)
fn capitalize(s: &str) -> String { s.split(' ') .flat_map(|w| Some(w.get(..1)?.to_uppercase() + &w.get(1..)?)) .collect::<Vec<String>>() .join(" ") }
fn capitalise(s: &str) -> String {return s.split(' ').map(capitalise_word)- fn capitalize(s: &str) -> String {
- s.split(' ')
- .flat_map(|w| Some(w.get(..1)?.to_uppercase() + &w.get(1..)?))
- .collect::<Vec<String>>()
.join(" ");}fn capitalise_word(s: &str) -> String {if s.len() == 0 {return s.to_uppercase();}return s.get(0..=0).unwrap().to_uppercase() + s.get(1..).unwrap();- .join(" ")
- }
// Add your tests here. // See https://doc.rust-lang.org/stable/rust-by-example/testing/unit_testing.html #[cfg(test)] mod tests { use super::*; #[test] fn lowercase_words() { assert_eq!(&capitalize("joe biden"), "Joe Biden"); } #[test] fn words_with_one_letter() { assert_eq!(&capitalize("a b c deez"), "A B C Deez"); } #[test] fn ignore_non_ascii() { assert_eq!(&capitalize("red green & blue *) purple"), "Red Green & Blue *) Purple"); } }
- // Add your tests here.
- // See https://doc.rust-lang.org/stable/rust-by-example/testing/unit_testing.html
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn lowercase_words() {
assert_eq!(&capitalise("joe biden"), "Joe Biden");- assert_eq!(&capitalize("joe biden"), "Joe Biden");
- }
- #[test]
- fn words_with_one_letter() {
assert_eq!(&capitalise("a b c deez"), "A B C Deez");- assert_eq!(&capitalize("a b c deez"), "A B C Deez");
- }
- #[test]
- fn ignore_non_ascii() {
assert_eq!(&capitalise("red green & blue *) purple"), "Red Green & Blue *) Purple");- assert_eq!(&capitalize("red green & blue *) purple"), "Red Green & Blue *) Purple");
- }
- }
Represents an ordinal numeral (i.e. 1st, 24th, etc.)
from __future__ import annotations class OrdinalNumeral: def __init__(self, n: int): """Represents an ordinal numeral (i.e. 1st, 24th, etc.) :param int n: The integer to represent :raises ValueError: Raised if n is below 0 :raises TypeError: Raised if a non-integer/OrdinalNumber value is added to the number """ if n < 0: raise ValueError("n must be positive or 0") self._n = n @property def n(self): return self._n @n.setter def n(self, n: int): if n < 0: raise ValueError("n must be positive or 0") self._n = n @property def numeral(self): if 11 <= (self.n % 100) <= 13: return str(self.n) + "th" return str(self.n) + ("th", "st", "nd", "rd", "th")[min(4, self.n % 10)] def __repr__(self): """Representation that can be used to recreate the object""" return f"OrdinalNumeral(n={self.n})" def __str__(self): """The 'nice' string version of the class""" return self.numeral def __int__(self): return self.n def __add__(self, other: int | OrdinalNumeral): """Can implement arithmetic operations if desired""" if isinstance(other, OrdinalNumeral): return OrdinalNumeral(self.n + other.n) elif isinstance(other, int): return OrdinalNumeral(self.n + other) else: raise TypeError(f"Unable to add {type(other)} with OrdinalNumeral")
- from __future__ import annotations
- class OrdinalNumeral:
- def __init__(self, n: int):
if n < 0: raise ValueError("n must be positive or 0")self.n = nself.numeral = self._numeral()- """Represents an ordinal numeral (i.e. 1st, 24th, etc.)
- :param int n: The integer to represent
- :raises ValueError: Raised if n is below 0
- :raises TypeError: Raised if a non-integer/OrdinalNumber value is added to the number
- """
- if n < 0:
- raise ValueError("n must be positive or 0")
- self._n = n
- @property
- def n(self):
- return self._n
- @n.setter
- def n(self, n: int):
- if n < 0:
- raise ValueError("n must be positive or 0")
- self._n = n
- @property
- def numeral(self):
- if 11 <= (self.n % 100) <= 13:
- return str(self.n) + "th"
- return str(self.n) + ("th", "st", "nd", "rd", "th")[min(4, self.n % 10)]
- def __repr__(self):
"""representation that can be used to recreate the object"""return f"OrdinalNumeral(self.n)"- """Representation that can be used to recreate the object"""
- return f"OrdinalNumeral(n={self.n})"
- def __str__(self):
"""the 'nice' string version of the class"""- """The 'nice' string version of the class"""
- return self.numeral
- def __int__(self):
- return self.n
def __add__(self, other):"""can implement arithmetic operations if desired"""if (isinstance(other, OrdinalNumeral)): return OrdinalNumeral(self.n + other.n)elif (isinstance(other, int)): return OrdinalNumeral(self.n + other)else: raise TypeError(f"Unable to add {type(other)} with OrdinalNumeral")def _numeral(self):"""define the ordinal numeral string"""if 11 <= (self.n % 100) <= 13: return str(self.n)+"th"return str(self.n)+("th", "st", "nd", "rd", "th")[min(4, self.n % 10)]- def __add__(self, other: int | OrdinalNumeral):
- """Can implement arithmetic operations if desired"""
- if isinstance(other, OrdinalNumeral):
- return OrdinalNumeral(self.n + other.n)
- elif isinstance(other, int):
- return OrdinalNumeral(self.n + other)
- else:
- raise TypeError(f"Unable to add {type(other)} with OrdinalNumeral")