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.
import re
def remove_numbers(string):
return re.sub(r"[0-9]","",string)
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("Tests")
def test_case():
test.assert_equals(remove_numbers("Hello world!"), "Hello world!")
test.assert_equals(remove_numbers("2 times 2 is 4"), " times is ")
test.assert_equals(remove_numbers("this is the year 2021"), "this is the year ")
const input = ["a", 1, 2, false, "b"];
const output = input.reduce((acc, el) => {
const type = typeof el;
acc[type] = acc[type] || [];
acc[type].push(el);
return acc;
}, {});
console.log(output);
Test.sample(array)
Your job is to group the words in anagrams.
What is an anagram ?
star
and tsar
are anagram of each other because you can rearrange the letters for star to obtain tsar.
Example
A typical test could be :
// input
groupAnagrams(["tsar", "rat", "tar", "star", "tars", "cheese"]);
// output
[
["tsar", "star", "tars"],
["rat", "tar"],
["cheese"]
]
## Helpers
The method `assertSimilarUnsorted` has been preloaded for you **in the Solution Sandbox only** to compare to arrays without relying on the sorting of the elements.
`assertSimilarUnsorted([[1,2], [3]], [[3], [1,2]]); // returns true`
Hvae unf !
I'd advise you to find an efficient way for grouping the words in anagrams otherwise you'll probably won't pass the heavy superhero test cases
def group_anagrams(words):
def sort_word(word):
charlist = list(word)
charlist.sort()
return "".join(charlist)
anagrams = {}
for word in words:
sorted = sort_word(word)
if sorted in anagrams:
anagrams[sorted].append(word)
else:
anagrams[sorted] = [word]
return list(anagrams.values())
import random
import string
import codewars_test as test
def get_randword(length):
charlist = string.ascii_letters
return "".join([random.choice(charlist) for x in range(length)])
def generate_anagrams(word, amount):
charlist = list(word)
anagrams = []
for i in range(amount):
random.shuffle(charlist)
anagrams.append("".join(charlist))
return anagrams
def deep_sort(array):
for i in range(len(array)):
array[i].sort()
array.sort()
@test.describe("Fixed Tests")
def _():
@test.it("Tests")
def _():
test.assert_equals(group_anagrams(["rat", "tar", "star"]), [["rat", "tar"], ["star"]])
@test.describe("Random Tests")
def _():
@test.it("Test")
def _():
for i in range(100):
anagram_list = []
shuffled_list = []
# Rare chance solution would fail if the second loop iterates >= 500 times
# Medium chance solutiom would fail if the second loop iterates >= 1000 times
for i in range(1000):
randword = get_randword(random.randint(3, 10))
anagram = generate_anagrams(randword, random.randint(3, 10))
anagram_list.append(anagram)
shuffled_list.extend(anagram)
deep_sort(anagram_list)
random.shuffle(shuffled_list)
actual = group_anagrams(shuffled_list)
deep_sort(actual)
test.assert_equals(actual, anagram_list, "Testing for {0}\n\n".format(shuffled_list))
In Node v12, if you overwrite Math.pow
with a function that throws an error, it will automatically triggered despite there is no code in the Code
, Preloaded
, and Test Cases
section that calls them. Maybe used by the test framework?
This behavior does not appear in Node v8 or v10.
Note
Not tested locally (only tested it on Codewars).
// Switch to Node v12 to see the error
console.log("Hello, World!")
// 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(1 + 1, 2);
// assert.strictEqual(1 + 1, 2);
});
});
The evaluation order may be different from the left-to-right order if the pipe operator is present.
The generated code for this example is similar to the following code:
Caml_obj.caml_equal(Caml_array.caml_array_get(a.sort(), 0), Caml_array.caml_array_get($$Array.copy(a), 0));
let f = (a: array(int)): int => a[0]
open Jest;
open Expect;
open Solution;
describe("test", () => {
let refSol = (a: array(int)): int => Js.Array.sortInPlaceWith((-), a)[0];
test("[| 3, 1, 2 |]", () => {
let a = [| 3, 1, 2 |];
// let c = Array.copy(a);
expect(f(Array.copy(a))) |> toBe(refSol(a))
})
});
Royal Morse Code
The Royal British Kingdom has enforced a new decree in the society that all princes and princesses must use a new
form of Morse code for all communications.
We know that Morse Code uses dots (.) and dashes (;) to communicate meaning to the receiver. The following rules
are stated according to this decree:
Any message must begin with a dot (.)
Any message must end with a dash (-)
Every dot (.) must have a corresponding dash (-) after it to close it
If a message follows all the mentioned rules, then it is considered compliant with the Royal Decree and the messa
allowed to be sent. Otherwise, it is considered as defaulted.
The Great Prince of Britain has sent out a set of N messages of the new Morse code. You have to figure out the
number of messages which are compliant and ultimately sent forward.
Input Specification:
input1: N, the number of messages.
input2: Sequence of strings, each representing a new message in the set.
Output Specification:
The number of messages compliant to the new decree
Example 1:
input1: 1
input2: ("..---.-")
Output: 0
Explanation:
The given string starts with a dot(.) and ends with a dash (-), but it fails the third criteria as there are 5 dots but only 4
dashes. Thus, O messages are compliant.
Example 2:
input1: 2
input2: (".-.-.-.-","...---.-")
Output: 2
Explanation:
Both the given strings follow all 3 rules. Thus, both 2 messages are compliant.
import java.util.*;
class MorseCodeChecker{
public int decreeCompliant(int input1, String[] input2){
int result = 0;
for(int i = 0 ; i < input2.length; i++){
Deque<Character> stack = new ArrayDeque<>();
if(input2[i] == null || input2[i].length() == 0){
continue;
}
String cur = input2[i];
if(cur.charAt(0) != '.' && cur.charAt(cur.length()-1) != '-'){
break;
}
int j = 0;
while(j < cur.length()){
if((cur.charAt(j) == '.')){
while(j < cur.length() && cur.charAt(j) == '.'){
j++;
stack.push('.');
}
}
else{
if(stack.size() == 0){
break;
}
stack.pop();
j++;
}
}
if(j == cur.length() && stack.size() == 0){
result++;
}
}
return result;
}
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
// TODO: Replace examples and use TDD by writing your own tests
class SolutionTest {
MorseCodeChecker tests = new MorseCodeChecker();
@Test
void testValid() {
// assertEquals("expected", "actual");
String[] testcase = {".-.-.-","...---.-"};
String[] testcase2 = {".---.-"};
assertEquals(2,tests.decreeCompliant(2,testcase));
assertEquals(1,tests.decreeCompliant(1,testcase2));
}
@Test
void testInvalid() {
// assertEquals("expected", "actual");
String[] testcase = {".-..-.-"};
String[] testcase2 = {"-.-.-."};
String[] testcase3 = {".--..-.-"};
assertEquals(0,tests.decreeCompliant(1,testcase));
assertEquals(0,tests.decreeCompliant(1,testcase2));
assertEquals(0,tests.decreeCompliant(1,testcase3));
}
}
Roman numerals can be generated with the following letters I, V, X, L, C, D, M
, but the generated numbers must be entered in decimal. Let's see examples:
convert_decimal_roman('46') # 'XLVI'
convert_decimal_roman('999') # 'CMXCIX'
convert_decimal_roman('504') # 'DIV'
Requirements:
- The number per argument must be in string type
- No validation required for floating numbers
- Only numbers up to 999 can be entered
def convert_decimal_roman(numero):
num_romanos_dic = {
1: 'I',
5: 'V',
10: 'X',
50: 'L',
100: 'C',
500: 'D',
1000: 'M'
}
list_num_rom = [{'key': x, 'value': y} for x, y in num_romanos_dic.items()]
size_num = len(numero)
output = []
for i in range(size_num):
num = numero[i:]
num_unit = int(num)
numextre_izq = int(num[0])
pref = []
for i in range(1, len(list_num_rom), 2):
if num_unit >= list_num_rom[i-1]['key'] and num_unit < list_num_rom[i+1]['key']:
pref.append(list_num_rom[i-1]['value'])
pref.append(list_num_rom[i]['value'])
pref.append(list_num_rom[i+1]['value'])
if numextre_izq < 4 and numextre_izq > 0:
output.append(pref[0]*numextre_izq)
if numextre_izq == 4:
output.extend(pref[0:2])
if numextre_izq == 5:
output.append(pref[1])
if numextre_izq > 5 and numextre_izq < 9:
output.append(pref[1] + pref[0]*(numextre_izq-5))
if numextre_izq == 9:
output.extend(pref[::2])
output = ''.join(output)
return output
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(convert_decimal_roman('69'), 'LXIX')
test.assert_equals(convert_decimal_roman('874'), 'DCCCLXXIV')
test.assert_equals(convert_decimal_roman('938'), 'CMXXXVIII')
test.assert_equals(convert_decimal_roman('442'), 'CDXLII')
test.assert_equals(convert_decimal_roman('323'), 'CCCXXIII')
test.assert_equals(convert_decimal_roman('548'), 'DXLVIII')
test.assert_equals(convert_decimal_roman('386'), 'CCCLXXXVI')
test.assert_equals(convert_decimal_roman('962'), 'CMLXII')
test.assert_equals(convert_decimal_roman('217'), 'CCXVII')
test.assert_equals(convert_decimal_roman('771'), 'DCCLXXI')
test.assert_equals(convert_decimal_roman('997'), 'CMXCVII')
test.assert_equals(convert_decimal_roman('175'), 'CLXXV')
test.assert_equals(convert_decimal_roman('873'), 'DCCCLXXIII')
test.assert_equals(convert_decimal_roman('33'), 'XXXIII')
test.assert_equals(convert_decimal_roman('508'), 'DVIII')
test.assert_equals(convert_decimal_roman('743'), 'DCCXLIII')
test.assert_equals(convert_decimal_roman('326'), 'CCCXXVI')
test.assert_equals(convert_decimal_roman('858'), 'DCCCLVIII')
test.assert_equals(convert_decimal_roman('707'), 'DCCVII')
test.assert_equals(convert_decimal_roman('459'), 'CDLIX')
test.assert_equals(convert_decimal_roman('976'), 'CMLXXVI')
test.assert_equals(convert_decimal_roman('855'), 'DCCCLV')
test.assert_equals(convert_decimal_roman('840'), 'DCCCXL')
test.assert_equals(convert_decimal_roman('682'), 'DCLXXXII')
test.assert_equals(convert_decimal_roman('506'), 'DVI')
test.assert_equals(convert_decimal_roman('553'), 'DLIII')
test.assert_equals(convert_decimal_roman('1'), 'I')
test.assert_equals(convert_decimal_roman('48'), 'XLVIII')
test.assert_equals(convert_decimal_roman('125'), 'CXXV')
test.assert_equals(convert_decimal_roman('353'), 'CCCLIII')
test.assert_equals(convert_decimal_roman('137'), 'CXXXVII')
test.assert_equals(convert_decimal_roman('423'), 'CDXXIII')
test.assert_equals(convert_decimal_roman('26'), 'XXVI')
test.assert_equals(convert_decimal_roman('362'), 'CCCLXII')
test.assert_equals(convert_decimal_roman('587'), 'DLXXXVII')
test.assert_equals(convert_decimal_roman('599'), 'DXCIX')
test.assert_equals(convert_decimal_roman('589'), 'DLXXXIX')
test.assert_equals(convert_decimal_roman('619'), 'DCXIX')
test.assert_equals(convert_decimal_roman('261'), 'CCLXI')
test.assert_equals(convert_decimal_roman('480'), 'CDLXXX')
test.assert_equals(convert_decimal_roman('410'), 'CDX')
test.assert_equals(convert_decimal_roman('776'), 'DCCLXXVI')
test.assert_equals(convert_decimal_roman('625'), 'DCXXV')
test.assert_equals(convert_decimal_roman('116'), 'CXVI')
test.assert_equals(convert_decimal_roman('112'), 'CXII')
test.assert_equals(convert_decimal_roman('603'), 'DCIII')
test.assert_equals(convert_decimal_roman('549'), 'DXLIX')
test.assert_equals(convert_decimal_roman('838'), 'DCCCXXXVIII')
test.assert_equals(convert_decimal_roman('846'), 'DCCCXLVI')
test.assert_equals(convert_decimal_roman('756'), 'DCCLVI')
test.assert_equals(convert_decimal_roman('333'), 'CCCXXXIII')
test.assert_equals(convert_decimal_roman('325'), 'CCCXXV')
test.assert_equals(convert_decimal_roman('154'), 'CLIV')
test.assert_equals(convert_decimal_roman('104'), 'CIV')
test.assert_equals(convert_decimal_roman('669'), 'DCLXIX')
test.assert_equals(convert_decimal_roman('822'), 'DCCCXXII')
test.assert_equals(convert_decimal_roman('51'), 'LI')
test.assert_equals(convert_decimal_roman('372'), 'CCCLXXII')
test.assert_equals(convert_decimal_roman('824'), 'DCCCXXIV')
test.assert_equals(convert_decimal_roman('136'), 'CXXXVI')
test.assert_equals(convert_decimal_roman('89'), 'LXXXIX')
test.assert_equals(convert_decimal_roman('693'), 'DCXCIII')
test.assert_equals(convert_decimal_roman('81'), 'LXXXI')
test.assert_equals(convert_decimal_roman('681'), 'DCLXXXI')
test.assert_equals(convert_decimal_roman('306'), 'CCCVI')
test.assert_equals(convert_decimal_roman('398'), 'CCCXCVIII')
test.assert_equals(convert_decimal_roman('554'), 'DLIV')
test.assert_equals(convert_decimal_roman('651'), 'DCLI')
test.assert_equals(convert_decimal_roman('403'), 'CDIII')
test.assert_equals(convert_decimal_roman('485'), 'CDLXXXV')
test.assert_equals(convert_decimal_roman('815'), 'DCCCXV')
test.assert_equals(convert_decimal_roman('88'), 'LXXXVIII')
test.assert_equals(convert_decimal_roman('53'), 'LIII')
test.assert_equals(convert_decimal_roman('610'), 'DCX')
test.assert_equals(convert_decimal_roman('410'), 'CDX')
test.assert_equals(convert_decimal_roman('376'), 'CCCLXXVI')
test.assert_equals(convert_decimal_roman('791'), 'DCCXCI')
test.assert_equals(convert_decimal_roman('594'), 'DXCIV')
test.assert_equals(convert_decimal_roman('486'), 'CDLXXXVI')
test.assert_equals(convert_decimal_roman('165'), 'CLXV')
test.assert_equals(convert_decimal_roman('812'), 'DCCCXII')
test.assert_equals(convert_decimal_roman('224'), 'CCXXIV')
test.assert_equals(convert_decimal_roman('185'), 'CLXXXV')
test.assert_equals(convert_decimal_roman('833'), 'DCCCXXXIII')
test.assert_equals(convert_decimal_roman('994'), 'CMXCIV')
test.assert_equals(convert_decimal_roman('385'), 'CCCLXXXV')
test.assert_equals(convert_decimal_roman('821'), 'DCCCXXI')
test.assert_equals(convert_decimal_roman('572'), 'DLXXII')
test.assert_equals(convert_decimal_roman('428'), 'CDXXVIII')
test.assert_equals(convert_decimal_roman('918'), 'CMXVIII')
test.assert_equals(convert_decimal_roman('86'), 'LXXXVI')
test.assert_equals(convert_decimal_roman('238'), 'CCXXXVIII')
test.assert_equals(convert_decimal_roman('206'), 'CCVI')
test.assert_equals(convert_decimal_roman('56'), 'LVI')
test.assert_equals(convert_decimal_roman('279'), 'CCLXXIX')
test.assert_equals(convert_decimal_roman('72'), 'LXXII')
test.assert_equals(convert_decimal_roman('380'), 'CCCLXXX')
test.assert_equals(convert_decimal_roman('26'), 'XXVI')
test.assert_equals(convert_decimal_roman('715'), 'DCCXV')
test.assert_equals(convert_decimal_roman('168'), 'CLXVIII')
Programming challenge description:
The example sequence
011212201220200112 ... is constructed as
follows:
- The first element in the sequence is 0.
- For each iteration, repeat the following
action: take a copy of the entire current
sequence, replace O with 1, 1 with 2, and 2
with 0, and place it at the end of the
current sequence. E.g.
0 ≥ 01 > 0112 > 01121220 > ...
Create an algorithm which determines what
number is at the Nth position in the
sequence (using -based indexing).
Input:
Your program should read lines from
standard input. Each line contains an
integer N such that O <= N <=
3000000000.
Output:
Print out the number which is at the Nth
position in the sequence.
Test 1
Test Input: 5
Test Output: 2
Test 2
Test Input: 101
Test Output: 1
Test 3
Test Input: 25684
Test Output: 0
function solution(num){
if(num === 0) return 0
let count = 1;
while(num >1){
count++;
let tmp = Math.round(Math.log2(num))
num -= Math.pow(tmp,2)
}
if(Math.round(count % 3) === 1){
return 1
}
if(Math.round(count % 3) === 2){
return 2
}
if(Math.round(count % 3) === 0){
return 0
}
}
// let test1 = findNth(0)
// console.log(test1)//0
// let test2 = findNth(5)
// console.log(test2)//2
// let test3 = findNth(101)
// console.log(test3)//1
// let test4 = findNth(25684)
// console.log(test4)//0
const { assert } = require("chai")
function test(n, expected) {
let actual = solution(n)
it(`Expected ${expected}, got ${actual}`, () => {
assert.strictEqual(actual, expected)
})
}
describe("basic tests", function(){
test(0,0);
test(5,2);
test(101,1);
test(25684,0);
})
Consider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5…. The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on.
Find the number on the n-th position of the sequence.
Input: n = 3
Output: 2
Input: n = 55
Output:10
function solution(num){
let times = 1;
let count = 0;
while(num > 0){
count = num
num -= times;
times++;
}
return count;
}
const { assert } = require("chai")
function test(n, expected) {
let actual = solution(n)
it(`Expected ${expected}, got ${actual}`, () => {
assert.strictEqual(actual, expected)
})
}
describe("basic tests", function(){
test(3,2);
test(55,10);
test(4,1);
})
In Ruby MRI 2.5.0, If you add assertion messaage with a '\n
in it. The message after the newline character will be logged as a regular message instead of an error message.
puts "Uncomment the test cases to see the errors"
describe "Example" do
it "Will log error" do
Test.expect(true)
# Test.expect(false, "This is an error\nThis is a log")
# Test.assert_equals(false, true, "This is an error\nThis is a log")
# Test.assert_not_equals("error", "error", "This is an error\nThis is a log")
end
end