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.
Returning zero on edge cases is incorrect, fixed it.
def Calculator(*args): operators = { '+': lambda a, b: a + b, '-': lambda a, b: a - b, '*': lambda a, b: a * b, '/': lambda a, b: a / b if b != 0 else float('inf') } if len(args) != 3 or str(args[0]) not in operators: return float('nan') operator, operand1, operand2 = args return operators[operator](operand1, operand2)
- def Calculator(*args):
- operators = {
- '+': lambda a, b: a + b,
- '-': lambda a, b: a - b,
- '*': lambda a, b: a * b,
'/': lambda a, b: a / b if b != 0 else 0- '/': lambda a, b: a / b if b != 0 else float('inf')
- }
- if len(args) != 3 or str(args[0]) not in operators:
return 0- return float('nan')
- operator, operand1, operand2 = args
- return operators[operator](operand1, operand2)
import codewars_test as test import random from math import isnan inf = float('inf') nan = float('nan') @test.describe("Sample tests") def sample_tests(): test.assert_equals(Calculator("/", 1, 0), inf) test.assert_equals(Calculator("+", 42, 11), 53) test.assert_equals(Calculator("-", 6, 50), -44) test.assert_equals(Calculator("/", 32, 2), 16) test.assert_equals(Calculator("*", 25, 5), 125) test.assert_equals(isnan(Calculator(123, 2)), True) operators = ['+', '-', '*', '/'] @test.describe("Random tests") def random_tests(): for _ in range(2000): operator = random.choice(operators) num1 = random.uniform(0, 1000) num2 = random.uniform(1, 1000) description = f"Operator: {operator}, Num1: {num1}, Num2: {num2}" expected = float(eval(f"{num1}{operator}{num2}")) test.assert_equals(Calculator(operator, num1, num2), expected, description)
- import codewars_test as test
- import random
- from math import isnan
- inf = float('inf')
- nan = float('nan')
- @test.describe("Sample tests")
- def sample_tests():
test.assert_equals(Calculator("/", 1, 0), 0)- test.assert_equals(Calculator("/", 1, 0), inf)
- test.assert_equals(Calculator("+", 42, 11), 53)
- test.assert_equals(Calculator("-", 6, 50), -44)
- test.assert_equals(Calculator("/", 32, 2), 16)
- test.assert_equals(Calculator("*", 25, 5), 125)
test.assert_equals(Calculator(123, 2), 0)- test.assert_equals(isnan(Calculator(123, 2)), True)
- operators = ['+', '-', '*', '/']
- @test.describe("Random tests")
- def random_tests():
- for _ in range(2000):
- operator = random.choice(operators)
- num1 = random.uniform(0, 1000)
- num2 = random.uniform(1, 1000)
- description = f"Operator: {operator}, Num1: {num1}, Num2: {num2}"
- expected = float(eval(f"{num1}{operator}{num2}"))
- test.assert_equals(Calculator(operator, num1, num2), expected, description)
Through experience I found that hardcoding in file names/ destinations/ quantities, etc. always lead to unknown bugs later on.
So I would really prefer having the folder source and destination as a variable/parameter.
import os, shutil class MoveFiles: def __init__(self): self.imageFolder = "folderA" self.images = [img for img in os.listdir(self.imageFolder) if img.endswith(('.png', '.jpg', '.jpeg'))] def move_image_files(self, source = "folderA", destination = "folderB"): for img in self.images: shutil.move(os.path.join(source, img), os.path.join(destination, img))
- import os, shutil
- class MoveFiles:
def __init__(self):self.images = [img for img in os.listdir('folderA') if img.endswith(('.png', '.jpg', '.jpeg'))]- def __init__(self):
- self.imageFolder = "folderA"
- self.images = [img for img in os.listdir(self.imageFolder) if img.endswith(('.png', '.jpg', '.jpeg'))]
def move_image_files(self):- def move_image_files(self, source = "folderA", destination = "folderB"):
- for img in self.images:
shutil.move(os.path.join('folderA', img), os.path.join('folderB', img))- shutil.move(os.path.join(source, img), os.path.join(destination, img))
fn math(s: &str) -> Result<i32, &'static str> { let math_str: String = s.chars().filter(|ch| !ch.is_whitespace()).collect(); let (num1, num2) = math_str .split_once(|ch: char| matches!(ch, '+' | '-' | '*' | '/' | '=')) .unwrap_or_else(|| panic!("missing operator, expected `+`, `-`, `*`, `/` or `=`")); let operator = &math_str[num1.len()..=num1.len()]; let num1: i32 = num1.parse().unwrap_or_else(|_| panic!("invalid first operand")); let num2: i32 = num2.parse().unwrap_or_else(|_| panic!("invalid second operand")); match operator { "+" => Ok(num1 + num2), "-" => Ok(num1 - num2), "*" => Ok(num1 * num2), "/" => { if num2 != 0 { Ok(num1 / num2) } else { Err("Cannot divide by zero") } }, "=" => Ok(i32::from(num1 == num2)), _ => Err("Invalid operator"), } }
fn math(s: &str) -> i32 {// remove whitespace characters so all we have left are digits and the operator- fn math(s: &str) -> Result<i32, &'static str> {
- let math_str: String = s.chars().filter(|ch| !ch.is_whitespace()).collect();
// split the string by the operator character- let (num1, num2) = math_str
- .split_once(|ch: char| matches!(ch, '+' | '-' | '*' | '/' | '='))
.expect("missing operator, expected `+`, `-`, `*`, `/` or `=`");// slice out the operator character we just splitted by- .unwrap_or_else(|| panic!("missing operator, expected `+`, `-`, `*`, `/` or `=`"));
- let operator = &math_str[num1.len()..=num1.len()];
- let num1: i32 = num1.parse().unwrap_or_else(|_| panic!("invalid first operand"));
- let num2: i32 = num2.parse().unwrap_or_else(|_| panic!("invalid second operand"));
// parse both operands as i32slet num1: i32 = num1.parse().expect("invalid first operand");let num2: i32 = num2.parse().expect("invalid second operand");// pattern-match the operator character- match operator {
"+" => num1 + num2,"-" => num1 - num2,"*" => num1 * num2,"/" => num1 / num2,"=" => i32::from(num1 == num2),_ => unreachable!(),- "+" => Ok(num1 + num2),
- "-" => Ok(num1 - num2),
- "*" => Ok(num1 * num2),
- "/" => {
- if num2 != 0 {
- Ok(num1 / num2)
- } else {
- Err("Cannot divide by zero")
- }
- },
- "=" => Ok(i32::from(num1 == num2)),
- _ => Err("Invalid operator"),
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test_math() { assert_eq!(math("1 + 2").unwrap(), 3); assert_eq!(math("12+ 3456789").unwrap(), 3456801); assert_eq!(math("50 + 10 0").unwrap(), 150); assert_eq!(math("1-3").unwrap(), -2); assert_eq!(math(" 500 - 150 ").unwrap(), 350); assert_eq!(math("0-2").unwrap(), -2); assert_eq!(math("1* 30").unwrap(), 30); assert_eq!(math("20 *5").unwrap(), 100); assert_eq!(math("10/5").unwrap(), 2); assert_eq!(math("500 / 2 ").unwrap(), 250); assert_eq!(math("10 = 10").unwrap(), 1); assert_eq!(math(" 2 =50").unwrap(), 0); assert_eq!(math("0=0").unwrap(), 1); } }
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
fn test_add() {assert_eq!(math("1 + 2"), 3);assert_eq!(math("12+ 3456789"), 3456801);assert_eq!(math("50 + 10 0"), 150);}#[test]fn test_sub() {assert_eq!(math("1-3"), -2);assert_eq!(math(" 500 - 150 "), 350);assert_eq!(math("0-2"), -2);}#[test]fn test_multiply() {assert_eq!(math("1* 30"), 30);assert_eq!(math("20 *5"), 100);}#[test]fn test_divide() {assert_eq!(math("10/5"), 2);assert_eq!(math("500 / 2 "), 250);}#[test]fn test_equal() {assert_eq!(math("10 = 10"), 1);assert_eq!(math(" 2 =50"), 0);assert_eq!(math("0=0"), 1);- fn test_math() {
- assert_eq!(math("1 + 2").unwrap(), 3);
- assert_eq!(math("12+ 3456789").unwrap(), 3456801);
- assert_eq!(math("50 + 10 0").unwrap(), 150);
- assert_eq!(math("1-3").unwrap(), -2);
- assert_eq!(math(" 500 - 150 ").unwrap(), 350);
- assert_eq!(math("0-2").unwrap(), -2);
- assert_eq!(math("1* 30").unwrap(), 30);
- assert_eq!(math("20 *5").unwrap(), 100);
- assert_eq!(math("10/5").unwrap(), 2);
- assert_eq!(math("500 / 2 ").unwrap(), 250);
- assert_eq!(math("10 = 10").unwrap(), 1);
- assert_eq!(math(" 2 =50").unwrap(), 0);
- assert_eq!(math("0=0").unwrap(), 1);
- }
- }