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.
Sprawdza czy wyraz jest palindromem.
Palindrom to wyraz który czytany od przodu i od tyłu daje to samo słowo.
function isPalindrom(word) {
if (!word || word.indexOf(' ') > -1) {
return false;
}
return word.toLowerCase() === word.toLowerCase().split('').reverse().join('');
}
// 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("isPalindrom", function() {
it("zwraca false kiedy word jest pustym ciągiem znaków", function() {
assert.strictEqual(isPalindrom(''), false);
});
it("zwraca false kiedy word zawiera spację", function() {
assert.strictEqual(isPalindrom('work krow'), false);
});
it("zwraca true kiedy word jest palindromem", function() {
assert.strictEqual(isPalindrom('kajak'), true);
});
it("zwraca true kiedy word jest palindromem z literami o różnej wielkości", function() {
assert.strictEqual(isPalindrom('Kajak'), true);
});
});
(This is a draft for a potential Kata series, left as a Kumite for now)
Regex engine from scratch
Throughout this series you'll be gradually piecing together a regex engine, with each successive Kata adding an additional piece of syntax into the mix.
You may wish to copy code you've developed in earlier parts of the series for later parts so that you can gradually build up the engine as you go, or you can cater each solution to the specific syntax proposed. The latter might be better for the first few steps as they're very simple.
It all begins with a dot.
For the first step we're going to implement regex's .
syntax.
To keep things simple, every other symbol except for a period should be treated as if it was inside a character set, even if the symbol would be treated as syntax by a real regex engine.
For example, the input [.]
, even though it looks like a character class, should be handled as if it was \[.\]
because we're only implementing the dot metacharacter for now. This also means you can't cheat and just import re!
Your function will be provided a pattern as a string. This pattern should be handled somehow to produce a function that can then be used to match on a string. You should expect this prepared function to be called multiple times with different inputs, it can't match just once.
The produced match function should behave as if it had anchors on either end, so it should match the entire string.
Examples
match('c.t')("cat") => True
match('c.t')("cbt") => True
match('c.t')("catastrophic") => False (must match entire string)
match('c.t')("abc") => False (not a match)
match('[.]')('[a]') => True (we don't support character classes, treat them like letters)
match('[a]')('a') => False (we've not implemented character classes yet)
def match(pattern):
def matcher(string):
return len(pattern) == len(string) and all(a == b if a != '.' else True for a, b in zip(pattern, string))
return matcher
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():
cat = match('c.t')
test.assert_equals(cat('cat'), True)
test.assert_equals(cat('cbt'), True)
test.assert_equals(cat('catastrophic'), False)
test.assert_equals(match('c.t')('abc'), False)
test.assert_equals(match('[.]')('[a]'), True)
test.assert_equals(match('[a]')('a'), False)
(This is a draft for a potential Kata series, left as a Kumite for now)
Regex engine from scratch
Throughout this series you'll be gradually piecing together a regex engine, with each successive Kata adding an additional piece of syntax into the mix.
You may wish to copy code you've developed in earlier parts of the series for later parts so that you can gradually build up the engine as you go, or you can cater each solution to the specific syntax proposed. The latter might be better for the first few steps as they're very simple.
More or less the same
Following on from the previous part, we'll now be adding support for the simple quantifiers: *
, +
, ?
. Support for braced quantifiers such as {3}
will not be added, so braces should be treated like letters.
In part 1 you implemented the dot syntax, so you must implement that in this part too.
All other syntax should be treated as letters (and just matched on), even if they would be valid regex syntax in a real regex parser.
For example, even though [a]
would typically be a character class containing the letter a, we haven't implemented character classes yet, so it should be treated as \[a\]
. This also means you can't just import re
, it won't work!
Your function will be provided with a pattern as a string. This pattern should be handled somehow to produce a function that can be used to match on a string. You should expect this prepared function to be called multiple times with different inputs, it can't match just once.
The produced match function should behave as if it had anchors on either end, so it should match the entire string.
Examples
match('.*')('cat') => True # .* should match anything
match('c.?t')('ct') => True # the dot is made optional by the ?
match('c.?t')('cat') => True
match('c[a]t')('cat') => False # We haven't implemented character classes
match('c[a]t')('c[a]t') => True
match('c{2}t')('cct') => False # We also won't be implementing braced quantifiers
match('c{2}t')('c{2}t') => True
# This is a k=1 solution and I'm not too happy with it.
# I was hoping to try and find an okay balance for something
# that could be written and understood in a Kata solution without being a full
# blown automata, but it's kind of unwieldy.
class PeekableIterator(object):
def __init__(self, iterator):
self.iterator = iterator
self.ahead = None
def peek(self):
if self.ahead:
return self.ahead
self.ahead = self.read()
return self.ahead
def read(self):
if (result := self.ahead):
self.ahead = None
return result
try:
return next(self.iterator)
except StopIteration:
return ''
def match(pattern):
ops = []
for part in pattern:
if part == '?':
op = ops.pop()
ops.append(('optional', op))
elif part == '*':
op = ops.pop()
ops.append(('many_or_none', op))
elif part == '+':
op = ops.pop()
ops.append(('many', op))
else:
ops.append(('match', part))
def do_op(stream, op, component):
if op == 'match':
return (component == '.' and stream.peek()) or stream.peek() == component
elif op == 'optional':
op, component = component
if do_op(stream, op, component) and op == 'match':
stream.read()
return True
elif op == 'many_or_none' or op == 'many':
original_op = op
op, component = component
i = 0
while do_op(stream, op, component):
if op == 'match':
stream.read()
i += 1
return original_op == 'many_or_none' or i > 0
raise "Huh?"
def matcher(string):
stream = PeekableIterator(iter(string))
for op, component in ops:
if not do_op(stream, op, component):
return False
if op == 'match':
stream.read()
return stream.read() == ''
return matcher
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():
# Part 1
cat = match('c.t')
test.assert_equals(cat('cat'), True)
test.assert_equals(cat('cbt'), True)
test.assert_equals(cat('catastrophic'), False)
test.assert_equals(match('c.t')('abc'), False)
test.assert_equals(match('[.]')('[a]'), True)
test.assert_equals(match('[a]')('a'), False)
# Part 2 (could do with more tests)
test.assert_equals(match('.*')('cat'), True)
test.assert_equals(match('.*')(''), True)
test.assert_equals(match('a*')(''), True)
test.assert_equals(match('a*')('a'), True)
test.assert_equals(match('a*')('aa'), True)
test.assert_equals(match('ab?c')('ac'), True)
test.assert_equals(match('ab?c')('abc'), True)
test.assert_equals(match('a+')(''), False)
test.assert_equals(match('a+')('a'), True)
test.assert_equals(match('a+')('aa'), True)
Trying something different...
The task is to check for strings in A that exist (as substrings) in B, sorted.
% check for Xs in As that exist in B, in sorted order
in_array(A, B, X) :-
msort(A, Sorted),
member(X, Sorted),
in_b(X, B).
in_b(A, B) :-
member(X, B),
sub_string(X, _, _, _, A), !.
:- begin_tests(example).
:- include(example).
test(example_test) :-
A = ["live", "arp", "strong"],
B = ["lively", "alive", "harp", "sharp", "armstrong"],
findall(R, in_array(A, B, R), Actual), % setof?
assertion(Actual == ["arp", "live", "strong"]).
:- end_tests(example).
main.cpp:10:10: error: always_inline function '_mm256_add_pd' requires target feature 'avx', but would be inlined into function 'add' that is compiled without support for 'avx'
return _mm256_add_pd(xs, ys);
#include <immintrin.h>
using v4d = double __attribute__((__vector_size__(32)));
v4d add(v4d xs, v4d ys) {
return _mm256_add_pd(xs, ys);
}
Describe(add_function) {
It(should_add_vectors_of_doubles) {
auto xs = v4d{1, 2, 3, 4}, ys = v4d{10, 20, 30, 40};
auto e = xs + ys, a = add(xs, ys);
Assert::That(a[0], Equals(e[0]));
}
};
solution.c:6:10: error: always_inline function '_mm256_add_pd' requires target feature 'avx', but would be inlined into function 'add' that is compiled without support for 'avx'
return _mm256_add_pd(xs, ys);
#include <immintrin.h>
typedef double v4d __attribute__((__vector_size__(32)));
v4d add(v4d xs, v4d ys) {
return _mm256_add_pd(xs, ys);
}
#include <criterion/criterion.h>
typedef double v4d __attribute__((__vector_size__(32)));
v4d add(v4d xs, v4d ys);
Test(add_function, should_add_vectors_of_doubles) {
v4d xs = (v4d){1, 2, 3, 4}, ys = (v4d){10, 20, 30, 40};
v4d e = xs + ys, a = add(xs, ys);
cr_assert_eq(a[0], e[0]);
}
Given a string S of length N, the task is to find the length of the longest palindromic substring from a given string.
Examples:
Input: S = “abcbab”
Output: 5
Explanation:
string “abcba” is the longest substring that is a palindrome which is of length 5.
Input: S = “abcdaa”
Output: 2
Explanation:
string “aa” is the longest substring that is a palindrome which is of length 2.
Note: If the string is empty or None or null then just return 0.do not try to convert the string to lowercase
def length_longest_palindrome(string):
n = len(string)
if n == 0:
return 0
maxlen = 1
table = [[False for i in range(n)]for j in range(n)]
for i in range(n):
table[i][i] = True
start = 0
for i in range(n-1):
if string[i] == string[i+1]:
table[i][i+1] = True
start = i
maxlen = 2
for k in range(3,n+1):
for i in range(n-k+1):
j = i + k - 1
if table[i+1][j-1] and string[i] == string[j]:
table[i][j] = True
if k > maxlen:
start = i
maxlen = k
return maxlen
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(length_longest_palindrome(''),0)
test.assert_equals(length_longest_palindrome('a'),1)
test.assert_equals(length_longest_palindrome('aaabbaa'),6)
test.assert_equals(length_longest_palindrome('Hannah'),4)
test.assert_equals(length_longest_palindrome('geeks'),2)
test.assert_equals(length_longest_palindrome('forgeeksskeegfor'),10)
test.assert_equals(length_longest_palindrome('aab'),2)
test.assert_equals(length_longest_palindrome('Abbas'),2)
Given an array of positive integers representing coin denominations and a single non-negative integer n.
representing a target amount of money, write a function that returns the smallest number of coins needed to
make change for (to sum up to) that target amount using the given coin denominations.
Example:
sample Input
n = 7
denoms = [1,5,10]
output = 3//2x1+1x5
time = O(nd),space = O(n).
where n is target amount and d is number of coin denominations
Note: you have access to an unlimited amount of coins.In other words,if denominations are [1,5,10],you have access to unlimited amount of 1s,5s and 10s
If it's impossible to make change for target amount return -1
def minNumberOfCoinsForChange(n, denoms):
numOfCoins = [float('inf') for amount in range(n+1)]
numOfCoins[0] = 0
for denom in denoms:
for amount in range(len(numOfCoins)):
if denom <= amount:
numOfCoins[amount] = min(numOfCoins[amount],1+numOfCoins[amount - denom])
return numOfCoins[n] if numOfCoins[n] != float('inf') else -1
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(minNumberOfCoinsForChange(7,[1,5,10]),3)
test.assert_equals(minNumberOfCoinsForChange(7,[1,10,5]),3)
test.assert_equals(minNumberOfCoinsForChange(7,[5,1,10]),3)
test.assert_equals(minNumberOfCoinsForChange(0,[1,2,3]),0)
test.assert_equals(minNumberOfCoinsForChange(3,[2,1]),2)
test.assert_equals(minNumberOfCoinsForChange(4,[1,5,10]),4)
test.assert_equals(minNumberOfCoinsForChange(10,[1,5,10]),1)
test.assert_equals(minNumberOfCoinsForChange(24,[1,5,10]),6)
test.assert_equals(minNumberOfCoinsForChange(9,[3,5]),3)
test.assert_equals(minNumberOfCoinsForChange(10,[1,3,4]),3)
test.it("good testcases")
test.assert_equals(minNumberOfCoinsForChange(135,[39, 45, 130, 40, 4, 1, 60, 75]),2)
test.assert_equals(minNumberOfCoinsForChange(135, [39, 45, 130, 40, 4, 1]),3)
given that you have:
stringObject = `{
\"a\":\"false\",
\"b\":\"33\",
\"c\":\"hi i'm C!\",
\"d\":\"{
\\\"d1\\\":\\\"4.5\\\",
\\\"d2\\\":\\\"Yo D2 here\\\"
}\"
}`
make it deeply primitive as such:
resultObject = {
a: false,
b: 33,
c: "hi i'm C!",
d:{
d1:4.5,
d2:"Yo D2 here"
}
}
function toPrimitiveDeep(stringObject){
let result
try{
result = JSON.parse(stringObject);
}catch (e){
return stringObject
}
if(typeof result !== 'object') return result
let keys = Object.keys(result)
keys.forEach((key)=>{
result[key] = toPrimitiveDeep(result[key])
})
return result
}
// Since Node 10, we"re using Mocha.
// You can use `chai` for assertions.
// 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 chai = require('chai')
const assert = chai.assert
const stgfy= JSON.stringify
describe('Solution', function () {
it('should test for something', function () {
const obj1 = `{"a":"false","b":"33","c":"hi i\'m C!","d":"{\\"d1\\":\\"4.5\\",\\"d2\\":\\"Yo D2 here\\"}"}`
assert.strictEqual(
stgfy(toPrimitiveDeep(obj1)),
stgfy({
a: false,
b: 33,
c: "hi i'm C!",
d: {
d1: 4.5,
d2: 'Yo D2 here',
},
}),
)
}),
it('should return the string when string is passed',()=>{
let aString = 'a string'
assert.strictEqual(toPrimitiveDeep(aString),aString)
}),
it('should return boolean when get string as "true" or "false"',()=>{
let thaBoolean = Math.random()<0.45
assert.strictEqual(toPrimitiveDeep(thaBoolean), thaBoolean)
}),
it('should return a deep object with a value diferent of a string when it can be interpreted as number or boolean', ()=>{
let thaBoolean = Math.random()<0.45
let thaNumba = Math.random() *100 %10
let answer = {
a:thaBoolean,
b:{
ba:thaNumba,
bb:{
bba:thaBoolean,
bbb:thaNumba
}
}
}
let question = stgfy({
a:thaBoolean.toString(),
b:stgfy({
ba:thaNumba.toString(),
bb:stgfy({
bba:thaBoolean.toString(),
bbb:thaNumba.toString()
})
})
})
console.log(question, answer)
assert.strictEqual(stgfy(toPrimitiveDeep(question)), stgfy(answer))
})
})
denis
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(1 + 1, 2)