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 numpy
def primes(n):
sieve = numpy.ones(n/3 + (n%6==2), dtype=numpy.bool)
for j in xrange(1,int(n**0.5)/3+1):
if sieve[j]:
k=3*j+1|1
sieve[k*k/3::2*k] = False
sieve[k*(k-2*(j&1)+4)/3::2*k] = False
return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]
def primes_less_than(n):
#n should be higher or equal 6. If n is a prime will not be part of the result """
return primes(n).tolist()
import numpy
def primes(n):
sieve = numpy.ones(n/3 + (n%6==2), dtype=numpy.bool)
for j in xrange(1,int(n**0.5)/3+1):
if sieve[j]:
k=3*j+1|1
sieve[k*k/3::2*k] = False
sieve[k*(k-2*(j&1)+4)/3::2*k] = False
return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]
def primes_less_than_sol(n):
#n should be higher or equal 6. If n is a prime will not be part of the result """
return primes(n).tolist()
test.describe("Basic Tests")
test.assert_equals(primes_less_than(20), [2, 3, 5, 7, 11, 13, 17, 19])
test.assert_equals(primes_less_than(997),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491,
499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821,
823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929,
937, 941, 947, 953, 967, 971, 977, 983, 991])
test.describe("Random Tests")
from random import randint
for i in range(100):
n = randint(100, 10000)
result = primes_less_than_sol(n)
res = primes_less_than(n)
test.it("Testing for n = " + str(n))
test.assert_equals(res, result)
test.it(str(len(result)) + " primes. Primes generated List: " + str(result))
test.it("______________________________________________________________")
require 'prime'
def primes_less_than(n)
Prime.take_while {|p| p < n }
end
require 'prime'
def primes_less_than_sol(n)
Prime.take_while {|p| p < n }
end
describe "Basic Tests" do
it "Basic Cases" do
Test.assert_equals(primes_less_than(20), [2, 3, 5, 7, 11, 13, 17, 19])
Test.assert_equals(primes_less_than(997),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491,
499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821,
823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929,
937, 941, 947, 953, 967, 971, 977, 983, 991])
end
end
describe "Random Tests" do
it "Challenging Cases" do
for i in 1..100
n = rand(100..10000)
result = primes_less_than_sol(n)
res = primes_less_than(n)
it "Testing for n = " + n.to_s do
Test.assert_equals(res, result)
end
end
end
end
function primesLessThan(limit) {
var primes = [];
if (limit >= 2) {
var sqrtlmt = Math.sqrt(limit) - 2;
var nums = new Array(); // start with an empty Array...
for (var i = 2; i <= limit; i++) // and
nums.push(i); // only initialize the Array once...
for (var i = 0; i <= sqrtlmt; i++) {
var p = nums[i]
if (p)
for (var j = p * p - 2; j < nums.length; j += p)
nums[j] = 0;
}
for (var i = 0; i < nums.length - 1; i++) {
var p = nums[i];
if (p) primes.push(p);
}
}
return primes;
}
function primesLessThanRandTests(limit) {
var primes = [];
if (limit >= 2) {
var sqrtlmt = Math.sqrt(limit) - 2;
var nums = new Array(); // start with an empty Array...
for (var i = 2; i <= limit; i++) // and
nums.push(i); // only initialize the Array once...
for (var i = 0; i <= sqrtlmt; i++) {
var p = nums[i]
if (p)
for (var j = p * p - 2; j < nums.length; j += p)
nums[j] = 0;
}
for (var i = 0; i < nums.length - 1; i++) {
var p = nums[i];
if (p) primes.push(p);
}
}
return primes;
}
describe("Basic Tests", function(){
it("Some Cases", function(){
Test.assertSimilar(primesLessThan(20), [2, 3, 5, 7, 11, 13, 17, 19]);
Test.assertSimilar(primesLessThan(997),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491,
499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821,
823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929,
937, 941, 947, 953, 967, 971, 977, 983, 991]);
});
});
function randint(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
describe("Random Tests" , function() {
it("Challenging Cases", function() {
for (var i = 1; i <= 100; i++) {
var n = randint(100, 10000);
var result = primesLessThanRandTests(n);
var res = primesLessThan(n);
it("Testing for n = " + n.toString(), function(){
Test.assertSimilar(res, result);
})
}
})
})
Kotlin Hello World modified to show some language features
/**
* Created by Javatlacati on 26/10/2016.
*/
object LambdaKotlin {
@JvmStatic
fun main(args: Array<String>) {
val arr=arrayOf("hola","mundo","cruel")
arr.forEach {
println(it)
}
}
}
The following code will output a 2Darray with all the elements present in the array as keys and their corresponding occurrences sorted by the value of the element.
from collections import Counter
def count_occur_each_element(arr):
if arr == []: return []
return sorted(map(list, Counter(arr).items()))
from collections import Counter
def count_occur_each_element_check(arr):
if arr == []: return []
return sorted(map(list, Counter(arr).items()))
test.describe("Example Tests")
arr = [1, -2, 7, 2, 1, 3, 7, 1, 0, 2, 3]
test.assert_equals(count_occur_each_element(arr), [[-2, 1], [0, 1], [1, 3], [2, 2], [3, 2], [7, 2]])
arr= [2, -1, 1, 1, 1, 1, 2, 3, 3, 7, 7, 0]
test.assert_equals(count_occur_each_element(arr), [[-1, 1], [0, 1], [1, 4], [2, 2], [3, 2], [7, 2]])
from random import randint
def build_rand_arr(l):
arr = []
max_ = l/20
while True:
elem = randint(max_*(-1), max_)
arr.append(elem)
if len(arr) == l:break
return arr
test.describe("Random Tests")
for h in range(50):
length = randint(1000, 10000)
arr = build_rand_arr(length)
result = count_occur_each_element_check(arr)
res = count_occur_each_element(arr)
test.assert_equals(res, result)
test.it("Result = " + str(result))
test.it("_______________________________________")
def counter(arr)
counts = Hash.new 0
arr.each do |n|
counts[n] += 1
end
return counts
end
def count_occur_each_element(arr)
if arr == []
return []
end
count_pairs = []
counts = counter(arr)
counts.each do |k, v|
count_pairs << [k, v]
end
count_pairs.sort!
return count_pairs
end
def counter(arr)
counts = Hash.new 0
arr.each do |n|
counts[n] += 1
end
return counts
end
def count_occur_each_element_check(arr)
if arr == []
return []
end
count_pairs = []
counts = counter(arr)
counts.each do |k, v|
count_pairs << [k, v]
end
count_pairs.sort!
return count_pairs
end
describe "Example Tests" do
it "Very Simple Ones" do
arr = [1, -2, 7, 2, 1, 3, 7, 1, 0, 2, 3]
Test.assert_equals(count_occur_each_element(arr), [[-2, 1], [0, 1], [1, 3], [2, 2], [3, 2], [7, 2]])
arr = [2, -1, 1, 1, 1, 1, 2, 3, 3, 7, 7, 0]
Test.assert_equals(count_occur_each_element(arr), [[-1, 1], [0, 1], [1, 4], [2, 2], [3, 2], [7, 2]])
end
end
def build_rand_arr(l)
arr = []; max_ = l/20
max__ = -1 *max_
while true
elem = rand(max__..max_)
arr << elem
break if arr.length == l
end
return arr
end
describe "Random Tests" do
it "Challenging Cases" do
for h in 0..50
len = rand(1000..10000)
arr = build_rand_arr(len)
result = count_occur_each_element_check(arr)
res = count_occur_each_element(arr)
it "Testing for an array of length " + arr.length.to_s do
Test.assert_equals(res, result)
end
end
end
end
Try to upgrade codewars haskell-runner ghc to new version but fail one test.
Code extract from test/runner/haskell_spec.js
This code run fine here but failed on stackage lts-1.0 w/ ghc7.6.3
test.hs:38:12: error:
• Couldn't match type ‘IO ()’ with ‘() -> IO ()’
Expected type: ActionWith ()
Actual type: IO ()
• Possible cause: ‘deleteIfExists’ is applied to too many arguments
In the first argument of ‘after’, namely
‘(deleteIfExists moviesDBFileName)’
In the expression: after (deleteIfExists moviesDBFileName)
In the second argument of ‘($)’, namely
‘after (deleteIfExists moviesDBFileName)
$ do { it "contains the movies we expect"
$ do { mkMoviesDB;
movies <- getMovies;
.... } }’
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-}
{-# LANGUAGE OverloadedStrings, GADTs, FlexibleContexts, MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction, GeneralizedNewtypeDeriving #-}
module Movies where
import Database.Persist (insertMany)
import Database.Persist.Sqlite (runSqlite, runMigration)
import Database.Persist.TH (mkPersist, mkMigrate, persistUpperCase, share, sqlSettings)
share [mkPersist sqlSettings, mkMigrate "migrateTables"] [persistUpperCase|
Movies
title String
year Int
rating Int
deriving Eq Show
|]
mkMoviesDB :: IO ()
mkMoviesDB = runSqlite "/tmp/movies.db" $ do
runMigration migrateTables
insertMany
[ Movies "Rise of the Planet of the Apes" 2011 77
, Movies "Dawn of the Planet of the Apes" 2014 91
, Movies "Alien" 1979 97
, Movies "Aliens" 1986 98
, Movies "Mad Max" 1979 95
, Movies "Mad Max 2: The Road Warrior" 1981 100
]
return ()
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-}
{-# LANGUAGE OverloadedStrings, GADTs, FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
import Test.Hspec
import Database.Persist
import Control.Monad.IO.Class (MonadIO(liftIO))
import Database.Persist.Sqlite (runSqlite)
import Database.Persist.Sql (rawQuery)
import Data.Conduit (($$), (=$))
import Data.Conduit.List as CL
import Data.Text (pack, unpack)
import Movies (mkMoviesDB)
import Control.Monad (when)
import System.Posix.Files (fileExist)
import System.Directory (removeFile)
data Movie = Movie String Integer Integer deriving (Eq, Show)
moviesDBFileName :: String
moviesDBFileName = "/tmp/movies.db"
getMovies :: IO [Movie]
getMovies = runSqlite (pack moviesDBFileName) $ do
rawQuery "select Title, Year, Rating from Movies" [] $$ CL.map toMovie =$ consume
where
toMovie [PersistText title, PersistInt64 year, PersistInt64 rating] =
Movie (unpack title) (toInteger year) (toInteger rating)
deleteIfExists :: String -> IO ()
deleteIfExists fileName = do
exists <- fileExist fileName
when exists $ removeFile fileName
main :: IO ()
main = hspec $ do
describe "/tmp/movies.db"
$ before (deleteIfExists moviesDBFileName)
$ after (deleteIfExists moviesDBFileName)
$ do
it "contains the movies we expect" $ do
mkMoviesDB
movies <- getMovies
liftIO $ movies `shouldBe` [ Movie "Rise of the Planet of the Apes" 2011 77
, Movie "Dawn of the Planet of the Apes" 2014 91
, Movie "Alien" 1979 97,Movie "Aliens" 1986 98
, Movie "Mad Max" 1979 95
, Movie "Mad Max 2: The Road Warrior" 1981 100]
Given a certain integer n, the following code gives a 2D array with all the possible and different partitions of n.
The array is sorted by the length of each partition that is the number od addens of each partition. Each partition has the addens sorted.
function fillArray(value, len) {
if (len === 0) return [];
var a = [value];
while (a.length * 2 <= len) a = a.concat(a);
if (a.length < len) a = a.concat(a.slice(0, len - a.length));
return a;
}
function partitions(n){
var resL = [];
var a = fillArray(1, n), y = -1, v = n;
while (v > 0) {
v -= 1;
x = a[v] + 1;
while (y >= 2 * x) {
a[v] = x;
y -= x;
v += 1;
}
var w = v + 1;
while (x <= y) {
a[v] = x;
a[w] = y;
resL.push(a.slice(0,w + 1));
x += 1;
y -= 1;
}
a[v] = x + y;
y = a[v] - 1;
resL.push(a.slice(0,w));
}
return resL;
}
function fillArray(value, len) {
if (len === 0) return [];
var a = [value];
while (a.length * 2 <= len) a = a.concat(a);
if (a.length < len) a = a.concat(a.slice(0, len - a.length));
return a;
}
function partitionsCheck(n){
var resL = [];
var a = fillArray(1, n), y = -1, v = n;
while (v > 0) {
v -= 1;
x = a[v] + 1;
while (y >= 2 * x) {
a[v] = x;
y -= x;
v += 1;
}
var w = v + 1;
while (x <= y) {
a[v] = x;
a[w] = y;
resL.push(a.slice(0,w + 1));
x += 1;
y -= 1;
}
a[v] = x + y;
y = a[v] - 1;
resL.push(a.slice(0,w));
}
return resL;
}
describe("Basic tests", function(){
it("Simple cases", function(){
Test.assertSimilar(partitions(3),[ [ 1, 1, 1 ], [ 1, 2 ], [ 3 ] ]);
Test.assertSimilar(partitions(4),[ [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 1, 3 ], [ 2, 2 ], [ 4 ] ]);
Test.assertSimilar(partitions(5),[[1, 1, 1, 1, 1],[1, 1, 1, 2],[1, 1, 3],[1, 2, 2],[1, 4],[2, 3],[5]]);
});
});
function randint(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
describe("Random Tests", function(){
it("Higher values of n", function(){
for (var h = 0; h <= 50; h++) {
var n = randint(10, 20);
var result = partitionsCheck(n);
var res = partitions(n);
it("Testing for n = " + n.toString(), function(){
Test.assertSimilar(res, result);
})
}
})
})
Given a certain integer n, the following code gives a 2D array with all the possible and different partitions of n.
The array is sorted by the length of each partition that is the number od addens of each partition. Each partition has the addens sorted.
def partitions_(n):
ind = 1
sub = n - 1
list_ = [0 for i in range(n + 1)]
while True:
if ind == 0: break
elem = list_[ind - 1] + 1
ind -= 1
while True:
if 2 * elem > sub: break
list_[ind] = elem
sub -= elem
ind += 1
l = ind + 1
while True:
if elem > sub: break
list_[ind] = elem
list_[l] = sub
yield list_[:ind + 2]
elem += 1
sub -= 1
list_[ind] = elem + sub
sub = elem + sub - 1
yield list_[:ind + 1]
def partitions(n):
resL = []
for part in partitions_(n):
resL.append(part)
return resL
def partitions_(n):
ind = 1
sub = n - 1
list_ = [0 for i in range(n + 1)]
while True:
if ind == 0: break
elem = list_[ind - 1] + 1
ind -= 1
while True:
if 2 * elem > sub: break
list_[ind] = elem
sub -= elem
ind += 1
l = ind + 1
while True:
if elem > sub: break
list_[ind] = elem
list_[l] = sub
yield list_[:ind + 2]
elem += 1
sub -= 1
list_[ind] = elem + sub
sub = elem + sub - 1
yield list_[:ind + 1]
def partitions_check(n):
resL = []
for part in partitions_(n):
resL.append(part)
return resL
test.describe("Basic tests")
test.assert_equals(partitions(3), [[1, 1, 1], [1, 2], [3]])
test.assert_equals(partitions(4),[[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2], [4]])
test.assert_equals(partitions(5),[[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 4], [2, 3], [5]])
test.describe("Random tests")
from random import randint
for h in range(30):
n = randint(10, 20)
result = partitions_check(n)
res = partitions(n)
test.it("Testing for n = " + str(n))
test.assert_equals(res, result)
test.it("Result = " + str(result))
We will obtain a tuple of length 2:
the first element is a 2D array with all the permutations that the same length of the array. If all the elements are unique in the array the the output will have a length equals to (length_array)!. As we will use arrays of elements that occurs once the function will ouput a boolean showing that the number of permutations is equal to the length of the given array, this will be the second element of the tuple
from math import factorial
def permutations_(arr, r=None): # see at https://docs.python.org/2/library/itertools.html
pool = tuple(arr) # it generates a permutation at once (lazely)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
def permutations(arr):
resL = []
for perm in permutations_(arr):
resL.append(list(perm))
return resL, len(resL) == factorial(len(arr))
from math import factorial
def permutations_(arr, r=None): # see at https://docs.python.org/2/library/itertools.html
pool = tuple(arr) # it generates a permutation at once (lazely)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
def permutations_check(arr):
resL = []
for perm in permutations_(arr):
resL.append(list(perm))
return resL, len(resL) == factorial(len(arr))
test.describe("Basic Tests")
test.assert_equals(permutations([1,2,3,4]), ([[1, 2, 3, 4], [1, 2, 4, 3],
[1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4],
[2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1],
[3, 1, 2, 4], [3, 1, 4, 2], [3, 2, 1, 4], [3, 2, 4, 1], [3, 4, 1, 2],
[3, 4, 2, 1], [4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 2, 3, 1],
[4, 3, 1, 2], [4, 3, 2, 1]], True))
test.describe("Random Tests")
from random import randint, choice, shuffle
for h in range(20):
l = randint(3, 8)
range_ = range(100, 200)
shuffle(range_)
arr = []
while True:
elem = range_.pop()
arr.append(elem)
if len(arr) == l: break
test.it("Testing for the array: " + str(arr))
result = permutations_check(arr)
res = permutations(arr)
test.assert_equals(res, result)
test.it(str(len(result[0])) + " permutations")
test.it("________________________________________________________________________________________________________________")