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.
-40 chars
describeAge=a=>(x=>"You're a(n) "+(["kid","teenager","adult"].find((i,id)=>a<=x[id])||"elderly"))([12,17,64])
describeAge = a => {ageL=[12,17,64]return "You're a(n) "+(["kid","teenager","adult"].find((i,id)=>{if(a<=ageL[id]){return i}})||"elderly")}- describeAge=a=>(x=>"You're a(n) "+(["kid","teenager","adult"].find((i,id)=>a<=x[id])||"elderly"))([12,17,64])
// Since Node 10, we're using Mocha. // You can use `chai` for assertions. const chai = require("chai"); const assert = chai.assert; // Uncomment the following line to disable truncating failure messages for deep equals, do: // chai.config.truncateThreshold = 0; // Since Node 12, we no longer include assertions from our deprecated custom test framework by default. // Uncomment the following to use the old assertions: const Test = require("@codewars/test-compat"); describe("Solution", function() { it("tests", function() { Test.assertEquals(describeAge(9), "You're a(n) kid") Test.assertEquals(describeAge(13), "You're a(n) teenager") Test.assertEquals(describeAge(18), "You're a(n) adult") Test.assertEquals(describeAge(100), "You're a(n) elderly") }); });
- // Since Node 10, we're using Mocha.
- // You can use `chai` for assertions.
- const chai = require("chai");
- const assert = chai.assert;
- // Uncomment the following line to disable truncating failure messages for deep equals, do:
- // chai.config.truncateThreshold = 0;
- // Since Node 12, we no longer include assertions from our deprecated custom test framework by default.
- // Uncomment the following to use the old assertions:
// const Test = require("@codewars/test-compat");- const Test = require("@codewars/test-compat");
- describe("Solution", function() {
it("should test for something", function() {// Test.assertEquals(1 + 1, 2);// assert.strictEqual(1 + 1, 2);- it("tests", function() {
- Test.assertEquals(describeAge(9), "You're a(n) kid")
- Test.assertEquals(describeAge(13), "You're a(n) teenager")
- Test.assertEquals(describeAge(18), "You're a(n) adult")
- Test.assertEquals(describeAge(100), "You're a(n) elderly")
- });
- });
fn round_half_up(n: f64, m: i32) -> f64 { (n * 10f64.powi(m) + 10f64.powi(-10)).round() / 10f64.powi(m) }
from decimal import Decimal, ROUND_HALF_UPdef roundHalfUp( n, m ):return float( Decimal( str( n ) ).quantize( Decimal( "1." + "0" * m ), rounding = ROUND_HALF_UP ) )- fn round_half_up(n: f64, m: i32) -> f64 {
- (n * 10f64.powi(m) + 10f64.powi(-10)).round() / 10f64.powi(m)
- }
#[test] fn test() { assert_eq!(round_half_up(2.5, 0), 3.0); assert_eq!(round_half_up(3.5, 0), 4.0); assert_eq!(round_half_up(2.535, 2), 2.54); assert_eq!(round_half_up(2.525, 2), 2.53); assert_eq!(round_half_up(2.5, 2), 2.5); assert_eq!(round_half_up(2.59999, 2), 2.6); assert_eq!(round_half_up(2.58499, 2), 2.58); assert_eq!(round_half_up(2.425, 2), 2.43); assert_eq!(round_half_up(2.435, 2), 2.44); assert_eq!(round_half_up(2.446, 2), 2.45); assert_eq!(round_half_up(2.444, 2), 2.44); assert_eq!(round_half_up(2.4445, 2), 2.44); assert_eq!(round_half_up(2.3435, 2), 2.34); assert_eq!(round_half_up(2.3415, 2), 2.34); }
test.assert_equals( roundHalfUp( 2.5, 0 ), 3 )test.assert_equals( roundHalfUp( 3.5, 0 ), 4 )test.assert_equals( roundHalfUp( 2.535, 2 ), 2.54 )test.assert_equals( roundHalfUp( 2.525, 2 ), 2.53 )test.assert_equals( roundHalfUp( 2.5, 2 ), 2.5 )test.assert_equals( roundHalfUp( 2.59999, 2 ), 2.6 )test.assert_equals( roundHalfUp( 2.58499, 2 ), 2.58 )test.assert_equals( roundHalfUp( 2.425, 2 ), 2.43 )test.assert_equals( roundHalfUp( 2.435, 2 ), 2.44 )test.assert_equals( roundHalfUp( 2.446, 2 ), 2.45 )test.assert_equals( roundHalfUp( 2.444, 2 ), 2.44 )test.assert_equals( roundHalfUp( 2.4445, 2 ), 2.44 )test.assert_equals( roundHalfUp( 2.3435, 2 ), 2.34 )test.assert_equals( roundHalfUp( 2.3415, 2 ), 2.34 )- #[test]
- fn test() {
- assert_eq!(round_half_up(2.5, 0), 3.0);
- assert_eq!(round_half_up(3.5, 0), 4.0);
- assert_eq!(round_half_up(2.535, 2), 2.54);
- assert_eq!(round_half_up(2.525, 2), 2.53);
- assert_eq!(round_half_up(2.5, 2), 2.5);
- assert_eq!(round_half_up(2.59999, 2), 2.6);
- assert_eq!(round_half_up(2.58499, 2), 2.58);
- assert_eq!(round_half_up(2.425, 2), 2.43);
- assert_eq!(round_half_up(2.435, 2), 2.44);
- assert_eq!(round_half_up(2.446, 2), 2.45);
- assert_eq!(round_half_up(2.444, 2), 2.44);
- assert_eq!(round_half_up(2.4445, 2), 2.44);
- assert_eq!(round_half_up(2.3435, 2), 2.34);
- assert_eq!(round_half_up(2.3415, 2), 2.34);
- }
use std::f64::consts::PI; pub struct Shape { color: String, thickness: u32, location: (i32, i32) } impl Shape { pub fn new(color: String, thickness: u32, location: (i32, i32)) -> Self { Self { color, thickness, location, } } pub fn change_color(&mut self, color: String) { self.color = color; } } pub struct Circle { radius: f64, color: String, thickness: u32, location: (i32, i32) } impl Circle { pub fn new(radius: f64, color: String, thickness: u32, location: (i32, i32)) -> Self { Self { radius, color, thickness, location } } pub fn change_color(&mut self, color: String) -> String { let message = format!("The color has changed from {} to {}", self.color, color); self.color = color; message } pub fn area(&self) -> f64 { PI * self.radius.powi(2) } }
import mathclass Shape:"""A Shape base class."""def __init__(self, color, thickness, location):self.color = colorself.thickness = thicknessself.location = locationdef __str__(self):return f'{self.__class__.__name__}(color={self.color}, thickness={self.thickness}, location={self.location})'def change_color(self, color):self.color = colorclass Circle(Shape):"""A Circle class that inherits from Shape class."""def __init__(self, radius, color, thickness, location):super().__init__(color, thickness, location)self.radius = radiusdef __str__(self):return f'{super().__str__()[:-1]}, radius={self.radius})'def change_color(self, color):"""Changes the color attribute of Shape. This is also an example of polymorphism"""old, self.color = self.color, colorreturn f'The color has changed from {old} to {self.color}!'def area(self):"""Returns the area of a Circle"""return math.pi * self.radius ** 2- use std::f64::consts::PI;
- pub struct Shape {
- color: String,
- thickness: u32,
- location: (i32, i32)
- }
- impl Shape {
- pub fn new(color: String, thickness: u32, location: (i32, i32)) -> Self {
- Self {
- color,
- thickness,
- location,
- }
- }
- pub fn change_color(&mut self, color: String) {
- self.color = color;
- }
- }
- pub struct Circle {
- radius: f64,
- color: String,
- thickness: u32,
- location: (i32, i32)
- }
- impl Circle {
- pub fn new(radius: f64, color: String, thickness: u32, location: (i32, i32)) -> Self {
- Self {
- radius,
- color,
- thickness,
- location
- }
- }
- pub fn change_color(&mut self, color: String) -> String {
- let message = format!("The color has changed from {} to {}", self.color, color);
- self.color = color;
- message
- }
- pub fn area(&self) -> f64 {
- PI * self.radius.powi(2)
- }
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test() { let mut c = Circle::new(113.776, "black".into(), 7, (7, 6)); assert_eq!(c.color, "black"); assert_eq!(c.thickness, 7); assert_eq!(c.location, (7, 6)); let mut s = Shape::new("white".into(), 1, (0, 0)); assert_eq!(s.change_color("red".into()), ()); assert_eq!(c.change_color("blue".into()), "The color has changed from black to blue"); } }
import codewars_test as testfrom solution import Shape, Circle@test.describe("Testing Circle class kumite:")def test_group():@test.it("test case 1: Testing for inheritence:")def test_case():c = Circle(113.776, 'black', 7, (7, 6))# (!) NOTE: Circle inheritences attributes of the Shape class:test.assert_equals(c.color, 'black')test.assert_equals(c.thickness, 7)test.assert_equals(c.location, (7, 6))- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test() {
- let mut c = Circle::new(113.776, "black".into(), 7, (7, 6));
- assert_eq!(c.color, "black");
- assert_eq!(c.thickness, 7);
- assert_eq!(c.location, (7, 6));
@test.it("test case 2: Testing for polymorphism:")def test_case():s = Shape('white', 1, (0, 0))c = Circle(113.776, 'black', 7, (7, 6))# (!) NOTE: The change_color() method is polymorphic between the Shape and Circle class:test.assert_equals(s.change_color('red'), None)test.assert_equals(c.change_color('blue'), f'The color has changed from black to blue!')- let mut s = Shape::new("white".into(), 1, (0, 0));
- assert_eq!(s.change_color("red".into()), ());
- assert_eq!(c.change_color("blue".into()), "The color has changed from black to blue");
- }
- }
fn filter_data(items: &[Item], search: &str) -> Vec<Item> { let conditions: Vec<Condition> = search .split(' ') .map(Into::into) .collect(); items .iter() .filter(|item| conditions.iter().all(|condition| condition.is_satisfied(item))) .cloned() .collect() } #[derive(Debug, PartialEq, Eq, Clone)] struct Item { pub name: String, pub code: String, } enum Condition { Positive(String), Negative(String), } impl Condition { fn is_satisfied(&self, item: &Item) -> bool { match self { Condition::Positive(s) => item.name.to_lowercase().contains(s) || item.code.to_lowercase().contains(s), Condition::Negative(s) => !item.name.to_lowercase().contains(s) && !item.code.to_lowercase().contains(s) } } } impl From<&str> for Condition { fn from(s: &str) -> Self { if s.starts_with("/-") { Condition::Negative(s[2..].to_lowercase()) } else { Condition::Positive(s.to_lowercase()) } } }
function filterData(items,search){if (!search || search?.length == 0) {return items;}let searchInput=search.replace(/\s\s+/g," ");let textNegate=searchInput.split(' ').filter(rs=>rs.startsWith('/-')).map(rs=>rs.replace('/-',''));searchInput=searchInput.replace(/[\s][/-]+.*/g, '');searchInput=searchInput.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&').toLowerCase();let seachArray=searchInput.split(' ');seachArray=seachArray.filter(rs=>!rs.startsWith('\-'));return items.filter(rs=>{let text=rs.name.toLowerCase();// test if contain only on word negatedif(textNegate.length==1 && textNegate[0].length>0){if(text.search(textNegate[0].toLowerCase())>=0){"negate one word"return false;}}if(text.search(search)>=0)return true;if(seachArray.length==1 && rs.code.search(search)>=0){return true;}let result=false;for(let i=0;i<seachArray.length;i++){if(!new RegExp(`${seachArray[i]}.*`).test(text)){result=false;break;}result=true;}return result;});}- fn filter_data(items: &[Item], search: &str) -> Vec<Item> {
- let conditions: Vec<Condition> = search
- .split(' ')
- .map(Into::into)
- .collect();
- items
- .iter()
- .filter(|item| conditions.iter().all(|condition| condition.is_satisfied(item)))
- .cloned()
- .collect()
- }
- #[derive(Debug, PartialEq, Eq, Clone)]
- struct Item {
- pub name: String,
- pub code: String,
- }
- enum Condition {
- Positive(String),
- Negative(String),
- }
- impl Condition {
- fn is_satisfied(&self, item: &Item) -> bool {
- match self {
- Condition::Positive(s) => item.name.to_lowercase().contains(s) || item.code.to_lowercase().contains(s),
- Condition::Negative(s) => !item.name.to_lowercase().contains(s) && !item.code.to_lowercase().contains(s)
- }
- }
- }
- impl From<&str> for Condition {
- fn from(s: &str) -> Self {
- if s.starts_with("/-") {
- Condition::Negative(s[2..].to_lowercase())
- } else {
- Condition::Positive(s.to_lowercase())
- }
- }
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test() { let array = [ Item { name: "MEMORY 3600 DIMM KINGSTON".to_string(), code:"445sdp".to_string() }, Item { name:"SSD KINGSTON".to_string(), code:"445sdA".to_string() }, Item { name:"MEMORY HP 3600".to_string(), code:"445sdD".to_string() } ]; assert_eq!( filter_data(&array, "king"), vec![ Item { name: "MEMORY 3600 DIMM KINGSTON".to_string(), code: "445sdp".to_string(), }, Item { name:"SSD KINGSTON".to_string(), code:"445sdA".to_string() } ] ); assert_eq!( filter_data(&array, "mem 3600"), vec![ Item { name: "MEMORY 3600 DIMM KINGSTON".to_string(), code: "445sdp".to_string(), }, Item { name:"MEMORY HP 3600".to_string(), code:"445sdD".to_string() } ] ); assert_eq!( filter_data(&array, "445sdA"), vec![ Item { name:"SSD KINGSTON".to_string(), code:"445sdA".to_string() } ] ); assert_eq!( filter_data(&array, "MEMO /-HP"), vec![ Item { name: "MEMORY 3600 DIMM KINGSTON".to_string(), code:"445sdp".to_string() } ] ); } } // describe("Solution", function() { // it(`ok try more than one word`, function() { // let result=JSON.stringify([{"name":"MEMORY 3600 DIMM KINGSTON","code":"445sdp"},{"name":"MEMORY HP 3600","code":"445sdD"}]); // assert.strictEqual(result, JSON.stringify(filterData(array,"mem 3600"))) // }); // it(`ok one word but code`, function() { // let result=JSON.stringify([{"name":"SSD KINGSTON","code":"445sdA"}]); // assert.strictEqual(result, JSON.stringify(filterData(array,"445sdA"))) // }); // it(`ok try DENIAL /-`, function() { // let result=JSON.stringify([{"name":"MEMORY 3600 DIMM KINGSTON","code":"445sdp"}]); // assert.strictEqual(result, JSON.stringify(filterData(array,"MEMO /-HP"))) // }); // it(`ok all if null or '' `, function() { // let result=JSON.stringify([{"name":"MEMORY 3600 DIMM KINGSTON","code":"445sdp"},{"name":"SSD KINGSTON","code":"445sdA"},{"name":"MEMORY HP 3600","code":"445sdD"}]); // assert.strictEqual(result, JSON.stringify(filterData(array,null))) // }); // });
const chai = require("chai");const assert = chai.assert;- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test() {
- let array = [
- Item {
- name: "MEMORY 3600 DIMM KINGSTON".to_string(),
- code:"445sdp".to_string()
- },
- Item {
- name:"SSD KINGSTON".to_string(),
- code:"445sdA".to_string()
- },
- Item {
- name:"MEMORY HP 3600".to_string(),
- code:"445sdD".to_string()
- }
- ];
- assert_eq!(
- filter_data(&array, "king"),
- vec![
- Item {
- name: "MEMORY 3600 DIMM KINGSTON".to_string(),
- code: "445sdp".to_string(),
- },
- Item {
- name:"SSD KINGSTON".to_string(),
- code:"445sdA".to_string()
- }
- ]
- );
- assert_eq!(
- filter_data(&array, "mem 3600"),
- vec![
- Item {
- name: "MEMORY 3600 DIMM KINGSTON".to_string(),
- code: "445sdp".to_string(),
- },
- Item {
- name:"MEMORY HP 3600".to_string(),
- code:"445sdD".to_string()
- }
- ]
- );
- assert_eq!(
- filter_data(&array, "445sdA"),
- vec![
- Item {
- name:"SSD KINGSTON".to_string(),
- code:"445sdA".to_string()
- }
- ]
- );
- assert_eq!(
- filter_data(&array, "MEMO /-HP"),
- vec![
- Item {
- name: "MEMORY 3600 DIMM KINGSTON".to_string(),
- code:"445sdp".to_string()
- }
- ]
- );
- }
- }
const array=[{"name":"MEMORY 3600 DIMM KINGSTON","code":"445sdp"},{"name":"SSD KINGSTON","code":"445sdA"},{"name":"MEMORY HP 3600","code":"445sdD"}];describe("Solution", function() {it(`Ok test only Word`, function() {let result=JSON.stringify([{"name":"MEMORY 3600 DIMM KINGSTON","code":"445sdp"},{"name":"SSD KINGSTON","code":"445sdA"}]);assert.strictEqual(result, JSON.stringify(filterData(array,"king")))});it(`ok try more than one word`, function() {let result=JSON.stringify([{"name":"MEMORY 3600 DIMM KINGSTON","code":"445sdp"},{"name":"MEMORY HP 3600","code":"445sdD"}]);assert.strictEqual(result, JSON.stringify(filterData(array,"mem 3600")))});it(`ok one word but code`, function() {let result=JSON.stringify([{"name":"SSD KINGSTON","code":"445sdA"}]);assert.strictEqual(result, JSON.stringify(filterData(array,"445sdA")))});it(`ok try DENIAL /-`, function() {let result=JSON.stringify([{"name":"MEMORY 3600 DIMM KINGSTON","code":"445sdp"}]);assert.strictEqual(result, JSON.stringify(filterData(array,"MEMO /-HP")))});it(`ok all if null or '' `, function() {let result=JSON.stringify([{"name":"MEMORY 3600 DIMM KINGSTON","code":"445sdp"},{"name":"SSD KINGSTON","code":"445sdA"},{"name":"MEMORY HP 3600","code":"445sdD"}]);assert.strictEqual(result, JSON.stringify(filterData(array,null)))});});- // describe("Solution", function() {
- // it(`ok try more than one word`, function() {
- // let result=JSON.stringify([{"name":"MEMORY 3600 DIMM KINGSTON","code":"445sdp"},{"name":"MEMORY HP 3600","code":"445sdD"}]);
- // assert.strictEqual(result, JSON.stringify(filterData(array,"mem 3600")))
- // });
- // it(`ok one word but code`, function() {
- // let result=JSON.stringify([{"name":"SSD KINGSTON","code":"445sdA"}]);
- // assert.strictEqual(result, JSON.stringify(filterData(array,"445sdA")))
- // });
- // it(`ok try DENIAL /-`, function() {
- // let result=JSON.stringify([{"name":"MEMORY 3600 DIMM KINGSTON","code":"445sdp"}]);
- // assert.strictEqual(result, JSON.stringify(filterData(array,"MEMO /-HP")))
- // });
- // it(`ok all if null or '' `, function() {
- // let result=JSON.stringify([{"name":"MEMORY 3600 DIMM KINGSTON","code":"445sdp"},{"name":"SSD KINGSTON","code":"445sdA"},{"name":"MEMORY HP 3600","code":"445sdD"}]);
- // assert.strictEqual(result, JSON.stringify(filterData(array,null)))
- // });
- // });
fn letter_frequency(s: &str) -> Vec<(char, usize)> { let s = s.to_lowercase(); let mut frequencies: Vec<(char, usize)> = ('a'..='z') .map(|l| (l, s.chars().filter(|&c| c == l).count())) .filter(|&(_, n)| n != 0) .collect(); frequencies.sort_by_key(|&(_, n)| usize::MAX - n); frequencies }
from collections import Counterdef letter_frequency(text):chars = Counter(c for c in text.lower() if c.isalpha())return sorted(chars.items(), key=lambda x: (-x[1], x[0]))- fn letter_frequency(s: &str) -> Vec<(char, usize)> {
- let s = s.to_lowercase();
- let mut frequencies: Vec<(char, usize)> = ('a'..='z')
- .map(|l| (l, s.chars().filter(|&c| c == l).count()))
- .filter(|&(_, n)| n != 0)
- .collect();
- frequencies.sort_by_key(|&(_, n)| usize::MAX - n);
- frequencies
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test() { assert_eq!( letter_frequency("wklv lv d vhfuhw phvvdjh"), [ ('v', 5), ('h', 4), ('d', 2), ('l', 2), ('w', 2), ('f', 1), ('j', 1), ('k', 1), ('p', 1), ('u', 1) ] ); assert_eq!( letter_frequency("As long as I\'m learning something, I figure I\'m OK - it\'s a decent day."), [ ('i', 7), ('a', 5), ('e', 5), ('n', 5), ('g', 4), ('s', 4), ('m', 3), ('o', 3), ('t', 3), ('d', 2), ('l', 2), ('r', 2), ('c', 1), ('f', 1), ('h', 1), ('k', 1), ('u', 1), ('y', 1) ] ); } }
test.assert_equals(letter_frequency('wklv lv d vhfuhw phvvdjh'), [('v', 5), ('h', 4), ('d', 2), ('l', 2), ('w', 2), ('f', 1), ('j', 1), ('k', 1), ('p', 1), ('u', 1)])test.assert_equals(letter_frequency('As long as I\'m learning something, I figure I\'m OK - it\'s a decent day.'), [('i', 7),('a', 5),('e', 5),('n', 5),('g', 4),('s', 4),('m', 3),('o', 3),('t', 3),('d', 2),('l', 2),('r', 2),('c', 1),('f', 1),('h', 1),('k', 1),('u', 1),('y', 1),])- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test() {
- assert_eq!(
- letter_frequency("wklv lv d vhfuhw phvvdjh"),
- [
- ('v', 5), ('h', 4), ('d', 2), ('l', 2), ('w', 2),
- ('f', 1), ('j', 1), ('k', 1), ('p', 1), ('u', 1)
- ]
- );
- assert_eq!(
- letter_frequency("As long as I\'m learning something, I figure I\'m OK - it\'s a decent day."),
- [
- ('i', 7), ('a', 5), ('e', 5), ('n', 5), ('g', 4),
- ('s', 4), ('m', 3), ('o', 3), ('t', 3), ('d', 2),
- ('l', 2), ('r', 2), ('c', 1), ('f', 1), ('h', 1),
- ('k', 1), ('u', 1), ('y', 1)
- ]
- );
- }
- }
fn remove_exclamation_marks(s: &str) -> String { s.replace('!', "") }
function removeExclamationMarks(s) {}- fn remove_exclamation_marks(s: &str) -> String {
- s.replace('!', "")
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test() { assert_eq!(remove_exclamation_marks("Hello World!"), "Hello World"); assert_eq!(remove_exclamation_marks("Hello World!!!"), "Hello World"); assert_eq!(remove_exclamation_marks("Hi! Hello!"), "Hi Hello"); assert_eq!(remove_exclamation_marks(""), ""); assert_eq!(remove_exclamation_marks("!"), ""); } }
// Since Node 10, we're using Mocha.// You can use `chai` for assertions.const chai = require("chai");const assert = chai.assert;// Uncomment the following line to disable truncating failure messages for deep equals, do:// chai.config.truncateThreshold = 0;// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.// Uncomment the following to use the old assertions:// const Test = require("@codewars/test-compat");describe("Solution", function() {it("should test for something", function() {// Test.assertEquals(removeExclamationMarks("Hello World!"), "Hello World");// Test.assertEquals(removeExclamationMarks("Hello World!!!"), "Hello World");// Test.assertEquals(removeExclamationMarks("Hi! Hello!"), "Hi Hello");// Test.assertEquals(removeExclamationMarks(""), "");// Test.assertEquals(removeExclamationMarks("!"), "");});});- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test() {
- assert_eq!(remove_exclamation_marks("Hello World!"), "Hello World");
- assert_eq!(remove_exclamation_marks("Hello World!!!"), "Hello World");
- assert_eq!(remove_exclamation_marks("Hi! Hello!"), "Hi Hello");
- assert_eq!(remove_exclamation_marks(""), "");
- assert_eq!(remove_exclamation_marks("!"), "");
- }
- }
fn prime_factors(number: u32) -> Vec<u32> { match (2..number).find(|divisor| number % divisor == 0) { Some(factor) => [vec![factor], prime_factors(number / factor)].concat(), None => vec![number], } }
def prime_factors(n):divider = lambda x: next((i for i in range(2, x) if x % i == 0), -1)return ([] if n == 1 else [n]) if divider(n) == -1 else ([divider(n)] + prime_factors(n // divider(n)))- fn prime_factors(number: u32) -> Vec<u32> {
- match (2..number).find(|divisor| number % divisor == 0) {
- Some(factor) => [vec![factor], prime_factors(number / factor)].concat(),
- None => vec![number],
- }
- }
#[cfg(test)] mod tests { use super::*; #[test] fn prime_factors_test() { assert_eq!(prime_factors(100), vec![2, 2, 5, 5]); assert_eq!(prime_factors(37), vec![37]); assert_eq!(prime_factors(18), vec![2, 3, 3]); } }
import codewars_test as testimport solution # or from solution import example@test.describe("Prime factors test")def test_case():test.assert_equals(prime_factors(100), [2, 2, 5, 5])test.assert_equals(prime_factors(37), [37])test.assert_equals(prime_factors(18), [2, 3, 3])- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn prime_factors_test() {
- assert_eq!(prime_factors(100), vec![2, 2, 5, 5]);
- assert_eq!(prime_factors(37), vec![37]);
- assert_eq!(prime_factors(18), vec![2, 3, 3]);
- }
- }
fn calculator(operator: char, num1: i32, num2: i32) -> i32 { match operator { '+' => num1 + num2, '-' => num1 - num2, '*' => num1 * num2, '/' => num1 / num2, _ => panic!("Invalid operator: '{operator}'.") } }
def calculator(operator, num1, num2):if operator == "+":result = num1 + num2elif operator == "-":result = num1 - num2elif operator == "*":result = num1 * num2elif operator == "/":result = num1 / num2else:raise ValueError("Invalid operator. Supported operators are +, -, *, /")return resultresult = calculator("+", 4, 8)print(result)result = calculator("-", 7, 4)print(result)result = calculator("*", 8, 7)print(result)result = calculator("/", 70, 7)print(result)- fn calculator(operator: char, num1: i32, num2: i32) -> i32 {
- match operator {
- '+' => num1 + num2,
- '-' => num1 - num2,
- '*' => num1 * num2,
- '/' => num1 / num2,
- _ => panic!("Invalid operator: '{operator}'.")
- }
- }
// 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 test() { assert_eq!(calculator('+', 4, 8), 12); assert_eq!(calculator('-', 7, 4), 3); assert_eq!(calculator('*', 8, 7), 56); assert_eq!(calculator('/', 70, 7), 10); } }
import codewars_test as test# TODO Write testsimport solution # or from solution import example- // Add your tests here.
- // See https://doc.rust-lang.org/stable/rust-by-example/testing/unit_testing.html
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")def test_group():@test.it("test case")def test_case():test.assert_equals(1 + 1, 2)- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test() {
- assert_eq!(calculator('+', 4, 8), 12);
- assert_eq!(calculator('-', 7, 4), 3);
- assert_eq!(calculator('*', 8, 7), 56);
- assert_eq!(calculator('/', 70, 7), 10);
- }
- }