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.
Often times kata authors want to prevent certain code from being used within a kata, to increase the level of difficulty. This is an example of how you can read the solution.txt file into your code.
This example is in JavaScript, but the /home/codewarrior/solution.txt
file is available for all languages.
// write a add function that doesn't use the plus symbol
function add(a, b){
return a + b;
}
// Make sure to view the test cases to see how this test fails
const fs = require('fs');
const solution = fs.readFileSync('/home/codewarrior/solution.txt', 'utf8');
describe("Check Solution", function(){
it("should prevent the '+' symbol from being used anywhere in the code", function(){
Test.expect(solution.indexOf('+') == -1, "Your code isn't allowed to include the + symbol!");
});
});
This is a basic example of rendering a plot chart to the output window. It uses matplotlib and mpld3.
Some dummy tests were added at the end to demonstrate how you could have a challenge based on rendering data to a chart and then you could have tests that test the chart data after the fact - allowing you to have an interactive visualazation for the data that is being tested.
# Example taken from http://mpld3.github.io/examples/drag_points.html
import numpy as np
import matplotlib
matplotlib.use('Agg') # need to do this to set the display type
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots()
np.random.seed(0)
points = ax.plot(np.random.normal(size=20),
np.random.normal(size=20), 'or', alpha=0.5,
markersize=50, markeredgewidth=1)
ax.set_title("Click and Drag", fontsize=18)
# See Preloaded code for JS DragPlugin
plugins.connect(fig, DragPlugin(points[0]))
print(mpld3.fig_to_html(fig))
Test.describe("You can add tests after the plot is rendered")
Test.it("should do something that passes or fails")
test.expect(True)
Test.it("should do something else that passes or fails")
test.expect(True)
This is a very basic example of how you can start a redis server using async code and wrapping it so that you can enable the solution to run only after the server has started.
This example also demonstrates how you can support async code within it
tests. To enable async mode, you can pass true
or a number value as the 2nd argument to describe
. If true
is provided, 2000
is used as the default number value, which is used as the timeout for each it
run.
Notice how the it
function has a done
callback. You are required to call this when using async code so that the function knows when the it
test has finished and can move on to the next test.
const redis = require("redis");
const Promise = require("bluebird");
// promisfy redis client to make it much easier to work with.
Promise.promisifyAll(redis.RedisClient.prototype);
// solution is your entry point. The redis server will not be available until solution is called. Since
// we are using async code you must call done() once you have completed the requirements.
function solution(done){
let client = redis.createClient();
// use Promise.join to make sure the done callback is fired after all other async operations have fired.
Promise.join(
client.setAsync("foo", "bar"),
client.hsetAsync("h", "key", "value"),
done
)
}
startRedis().then(stop => {
let client = redis.createClient();
solution(_ => {
describe("redis challenge", true, _ => {
it ("should have set foo to == 'bar'", done => {
client.getAsync('foo').then(actual => {
Test.assertEquals(actual, "bar");
done();
});
});
it ("should set h.key to == 'value'", done => {
client.hgetAsync('h', 'key').then(actual => {
Test.assertEquals(actual, "value");
done();
});
});
})
.then(stop); // describe returns a promise so we can hook into that to shut down our spawned process.
});
});
Given a list of numbers, return the combination that is largest number.
As output can be large, return the result in String
format.
Example:
Input:
[5, 50, 56]
Output:
56550
import java.util.*;
class Solution {
public static String largestNumber(Integer[] nums) {
Arrays.sort( nums, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
String aStr = a.toString();
String bStr = b.toString();
return (aStr + bStr).compareTo(bStr + aStr) * -1;
}
} );
String result = "";
for(Integer num : nums) {
result += num.toString();
}
return result;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
@Test
public void test1() {
assertEquals( "56550", Solution.largestNumber(new Integer[] {5, 50, 56}) );
}
@Test
public void test2() {
assertEquals( "8765431", Solution.largestNumber(new Integer[] {1, 3, 5, 4, 7, 6, 8}) );
}
}
My first performance tester for functions, it was inspired because of the lack of this function in http://pythontutor.com/
from time import time
def helper(func,*arg):
start = time()
func(*arg)
total = round(time()-start,5)*100
return total
def testPerformance(arg,*funcs):
"""
First parameter is a tuple with all the arguments for each function
Each function should take the same amount of parameters in the
same order
The output is a dict with function:timeFromMinimum pair
"""
times = []
for func in funcs:
times.append(helper(func,*arg))
minimum = min(times)
sustractivetimes = [i - minimum for i in times]
result = {i:j for i,j in zip(funcs ,sustractivetimes)}
return result
def lambdaproach(x):
minimum = min(x)
return list(map(lambda x: x - minimum, x))
def listcomp1(x):
minimum = min(x)
return [i - minimum for i in x]
def listcomp2(x):
minimum = min(x)
return [sustract(i,minimum) for i in x]
def sustract(x,y):
return x - y
nums = ([i for i in range(5,10)],)
testPerformance(nums,lambdaproach,listcomp1,listcomp2)
test.expect(True)
I made a function that reverses the words in a string:
def shuffle(st):
st = st.split(' ')
for x in range(0, len(st)):
st[x] = list(st[x])
st[x].reverse()
st[x] = ''.join(st[x])
st = ' '.join(st)
return st
# TODO: Replace examples and use TDD development by writing your own tests
# These are some of the methods available:
# test.expect(boolean, [optional] message)
# test.assert_equals(actual, expected, [optional] message)
# test.assert_not_equals(actual, expected, [optional] message)
# You can use Test.describe and Test.it to write BDD style test groupings
test.assert_equals(shuffle('hi there'), 'ih ereht')
Here's the code that I'm using to list all files in a given directory. The question is, is there any other way to do this?
import glob
print(glob.glob('directorypath'))# Replace 'directorypath' with path to directory
# TODO: Replace examples and use TDD development by writing your own tests
# These are some of the methods available:
# test.expect(boolean, [optional] message)
# test.assert_equals(actual, expected, [optional] message)
# test.assert_not_equals(actual, expected, [optional] message)
# You can use Test.describe and Test.it to write BDD style test groupings
from the rowanblush solution
using Ordering monoid instance we can change the bias on EQ for all higher order accepting (a -> a -> Ordering)
module LeftBias where
import Data.Monoid
leftBias g = g . (fmap . fmap) (`mappend` GT)
import Data.List
import Data.Ord
import Test.Hspec
import LeftBias
main = hspec $ do
describe "leftBias with maximumBy" $ do
it "maximumBy is right biased" $
maximumBy (comparing length) ["ciao","wave"] `shouldBe` "wave"
it "leftBias maximumBy is left biased" $
leftBias maximumBy (comparing length) ["ciao","wave"] `shouldBe` "ciao"
Hello world in Kotlin.
fun main(args: Array<String>) {
println("Hello from Kotlin")
}
In Kotlin data classes is classes which do nothing but only hold data.
The compiler automatically derives the following members from all properties declared in the primary constructor:
- equals()/hashCode() pair,
- toString() of the form "User(name=John, age=42)",
- componentN() functions corresponding to the properties in their order of declaration,
- copy() function (see below).
data class User(val id: Long, var email: String, var name: String)
fun main(args: Array<String>) {
var user = User(1, "random@email.com", "randomName")
// toString
println(user)
// equals
println(user.equals(User(1, "random@email.com", "randomName")))
// ComponentN
println("user name is ${user.component3()}")
// copy
var newUser = user.copy(name="newName")
println(newUser)
}