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.
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("________________________________________________________________________________________________________________")
The Itertools module offers a the generator permutations that gives a permutation as a tuple, each time. Nevertheless the result will not be printed because some outputs are huge.
from itertools import *
def permut(arr):
resL = []
for perm in permutations(arr):
resL.append(list(perm))
return resL
from itertools import *
def permut_check(arr):
resL = []
for perm in permutations(arr):
resL.append(list(perm))
return resL
test.describe("Basic Tests")
test.assert_equals(permut([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]])
test.describe("Random Tests")
from random import randint, choice, shuffle
for h in range(20):
l = randint(3, 9)
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 = permut_check(arr)
res = permut(arr)
test.assert_equals(res, result)
test.it(str(len(result)) + " permutations")
test.it("________________________________________________________________________________________________________________")
(ns quicksort.core)
(defn quick-sort [nums]
(if (< (count nums) 2) nums
(concat
(quick-sort (filter #(< % (first nums)) nums))
(filter #(= % (first nums)) nums)
(quick-sort (filter #(> % (first nums)) nums)))))
(ns quicksort.test
(:require [clojure.test :refer :all]
[quicksort.core :refer [quick-sort]]))
(deftest quick-sort-test
(is (= (quick-sort '(2 3 1)) '(1 2 3)))
(is (= (quick-sort '(9 -1 -2 10)) '(-2 -1 9 10)))
(is (= (quick-sort '(1 2 666 233 0 8 34 -1)) '(-1 0 1 2 8 34 233 666))))
Shows how to use bash kta and how to create simple tests
echo Hello Bash!
# TODO: replace with your own tests (TDD). An example to get you started is included below.
# run the solution and store its result
output = run_shell
describe "Solution" do
it "should return the argument passed in" do
expect(output).to include('Hello Bash!')
end
end
When we want to generate primes we may have problems of memory if we use cumulative data structures. The following code generates each prime lazely using a generator instead of a function. To generate the prime numbers we use a primality test as a helper function
function isPrime(n) {
if (n%1 || n<2) return false;
var upper = Math.round(Math.pow(n, 1/2.0));
for (var i = 2;i <= upper; i++) if (n % i == 0) return false;
return true;
}
function *primeGener() {
var i = 0;
while(true) {
if(isPrime(i)) yield i;
i += 1;
}
}
function countPrimes(limit) {
var count = 0, call = primeGener();
while(true) {
var prime = call.next().value;
if (prime > limit) break;
count++
}
return count
}
function isPrime(n) {
if (n%1 || n<2) return false;
var upper = Math.round(Math.pow(n, 1/2.0));
for (var i = 2;i <= upper; i++) if (n % i == 0) return false;
return true;
}
function *primeGener() {
var i = 0;
while(true) {
if(isPrime(i)) yield i;
i += 1;
}
}
function countPrimesSol(limit) {
var count = 0, call = primeGener();
while(true) {
var prime = call.next().value;
if (prime > limit) break;
count++
}
return count
}
function randint(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
describe("Basict tests", function(){
it("Low values for limit", function(){
Test.assertEquals(countPrimes(10), 4);
Test.assertEquals(countPrimes(20), 8);
Test.assertEquals(countPrimes(50), 15);
Test.assertEquals(countPrimes(100), 25)
});
});
describe("Random tests", function(){
it("100 <= limit <= 1000", function(){
for (var h = 1; h <= 20; h++) {
var limit = randint(100, 1000);
var result = countPrimesSol(limit), res = countPrimes(limit);
it("Testing for n = " + limit.toString(), function(){
Test.assertEquals(res, result);
})
}
})
it("1000 <= limit <= 5000", function(){
for (var h = 1; h <= 20; h++) {
var limit = randint(1000, 5000);
var result = countPrimesSol(limit), res = countPrimes(limit);
it("Testing for n = " + limit.toString(), function(){
Test.assertEquals(res, result);
})
}
})
it("5000 <= limit <= 10000", function(){
for (var h = 1; h <= 20; h++) {
var limit = randint(5000, 10000);
var result = countPrimesSol(limit), res = countPrimes(limit);
it("Testing for n = " + limit.toString(), function(){
Test.assertEquals(res, result);
})
}
})
it("10000 <= limit <= 50000", function(){
for (var h = 1; h <= 20; h++) {
var limit = randint(10000, 50000);
var result = countPrimesSol(limit), res = countPrimes(limit);
it("Testing for n = " + limit.toString(), function(){
Test.assertEquals(res, result);
})
}
})
it("50000 <= limit <= 100000", function(){
for (var h = 1; h <= 10; h++) {
var limit = randint(50000, 100000);
var result = countPrimesSol(limit), res = countPrimes(limit);
it("Testing for n = " + limit.toString(), function(){
Test.assertEquals(res, result);
})
}
})
it("100000 <= limit <= 500000", function(){
for (var h = 1; h <= 5; h++) {
var limit = randint(100000, 500000);
var result = countPrimesSol(limit), res = countPrimes(limit);
it("Testing for n = " + limit.toString(), function(){
Test.assertEquals(res, result);
})
}
})
it("500000 <= limit <= 1000000", function(){
for (var h = 1; h <= 3; h++) {
var limit = randint(500000, 1000000);
var result = countPrimesSol(limit), res = countPrimes(limit);
it("Testing for n = " + limit.toString(), function(){
Test.assertEquals(res, result);
})
}
})
it("1000000 <= limit <= 5000000", function(){
for (var h = 1; h <= 2; h++) {
var limit = randint(100000, 5000000);
var result = countPrimesSol(limit), res = countPrimes(limit);
it("Testing for n = " + limit.toString(), function(){
Test.assertEquals(res, result);
})
}
})
})