Start a new Kumite
AllAgda (Beta)BF (Beta)CCFML (Beta)ClojureCOBOL (Beta)CoffeeScriptCommonLisp (Beta)CoqC++CrystalC#D (Beta)DartElixirElm (Beta)Erlang (Beta)Factor (Beta)Forth (Beta)Fortran (Beta)F#GoGroovyHaskellHaxe (Beta)Idris (Beta)JavaJavaScriptJulia (Beta)Kotlinλ Calculus (Beta)LeanLuaNASMNim (Beta)Objective-C (Beta)OCaml (Beta)Pascal (Beta)Perl (Beta)PHPPowerShell (Beta)Prolog (Beta)PureScript (Beta)PythonR (Beta)RacketRaku (Beta)Reason (Beta)RISC-V (Beta)RubyRustScalaShellSolidity (Beta)SQLSwiftTypeScriptVB (Beta)
Show only mine

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.

Ad
Ad
def to_camel_case(text):
    k = text.split("-")
    p = case_loop(k)
    j = p.split("_")
    m = case_loop(j)
    return m

def case_loop(k):
    p = []

    for i,item in enumerate(k):
        if i == 0:
            p.append(item)
            continue
        # print(i,item)
        a = item[0].upper()
        b = item[1:]
        c = f"{a}{b}"
        p.append(c)
    d = "".join(p)
    return d

You have a nested list of items and need to find out how many layers of nesting there is.

For example

[1,2] = 1
[[1,2],[3,4]] = 2
[[[1,2],[3,4]],[[1,2],[3,4]]] = 3

def get_nesting_layers(lst):
    for item in lst:
        if type(item) == type([]):
            return 1+get_nesting_layers(item)
        
    return 1
def assert_equals(a,b):
    return a+b
#include <ctype.h>
#include <string.h>

void drop_caps(char *dest, const char *src) {
  unsigned in_word = 0;
	for (unsigned i = 0; i < strlen(src) + 1000; i++, src++, dest++) {
		if (*src == ' ' || (!in_word && strcspn(src, " ") <= 2)) in_word = 0, *dest = *src;
		else if (in_word) *dest = tolower(*src);
		else in_word = 1, *dest = toupper(*src);
	}
	*dest = '\0';
}
Functional Programming
Declarative Programming
Programming Paradigms
Monads
Data Structures

The State monad solution.

return = Pair
bind = C
#import combinators.lc
B  = \ f g x . f (g x)
BB = \ f g x y . f (g x y)
C  = \ f x y . f y x
I  = \ x . x
K  = \ x _ . x
KI = \ _ x . x
S  = \ f g x . f x (g x)
T  = \ x f . f x
V  = \ x y f . f x y
W  = \ f x . f x x
Y = \ f . f (Y f)

#import church-boolean.lc
True  = K
False = KI
not = C
and = W C

#import scott-pair.lc
Pair = V
fst = T K

#import church-number.lc
succ = S B
is-zero = V (K False) True
add = \ m n . \ f x . n f (m f x)
sub = #inline scott-stream.lc
      T  V           \ cons   .
      T (T K)        \ head   .
      T (T KI)       \ tail   .
      T (Y (S cons)) \ repeat .
      # factor out go
      T (S (C cons) (B succ head)) \ go .
      \ m n . head (n tail (m go (repeat 0)))
le = BB is-zero sub
eq = \ m n . and (le m n) (le n m)

#import scott-list.lc
nil = K
cons = BB K V
foldr = \ fn z xxs . xxs z \ x xs . fn x (foldr fn z xs)
foldl = \ fn z xxs . xxs z \ x xs . foldl fn (fn z x) xs
length = foldr (K succ) 0
reverse = foldl (C cons) nil
filter = \ p . foldr ( \ x z . p x (cons x z) z ) nil

#import scott-assoc-list.lc # TODO: replace with scott-map for performance
empty = nil
# index = lookup : assocList i x -> i -> x | ()
index = \ assocs j . assocs () \ assoc xs . assoc \ i x . eq i j x (index xs j)
insert-with = \ fn j y assocs . assocs (cons (Pair j y) nil) \ assoc xs . assoc \ i x . eq i j (cons (Pair i (fn x y)) xs) (cons assoc (insert-with fn j y xs))

# -- State --

#import scott-state-monad.lc

# State s a = State { runState :: s -> (,) a s }
# State = (,) a # forget the type parameters, the wrapper and the unwrapper

# return : a -> State s a
# return = \ a . \ s . Pair a s
return = Pair

# bind : State s a -> (a -> State s b) -> State s b
# bind = \ ma fn . \ s . let (a,s') = ma s in fn a s'
# bind = \ ma fn . \ s . ma s \ a s' . fn a s'
# bind = \ ma fn s . ma s fn
bind = C

# get :: State s s
# get = \ s . Pair s s
get = W Pair

# put :: s -> State s ()
# put s = \ _ . Pair () s
put = B K (Pair ())

# -- helpers --

# fmap :: (Monad m) => (a -> b) -> m a -> m b
# liftM fn ma = do a <- ma ; return (fn a)
fmap = \ fn ma .
  bind ma \ a .
       return (fn a)

# (<*>) :: (Monad m) => m (a -> b) -> m a -> m b
# ap mfn ma = do fn <- mfn ; a <- ma ; return (fn a)
ap = \ mfn ma .
  bind mfn \ fn .
  bind ma \ a .
       return (fn a)

# liftM2 fn x y = fn <$> x <*> y
lift2 = \ fn ma mb . ap (fmap fn ma) mb

# join :: (Monad m) => m (m a) -> m a
# join mma = mma >>= id
join = \ mma . bind mma I

# modify :: (s -> s) -> State s ()
# modify = put . fn =<< get
modify = \ fn . bind get (B put fn)

# gets :: (s -> t) -> State s t
# gets = return . fn =<< get
gets = \ fn . bind get (B return fn)

# runState : State s a -> s -> (a,s)
# runState = I # there are no wrappers

# evalState :: State s a -> s -> a
# evalState ma s = fst (ma s)
evalState = B fst

# filterM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a]
# filterM p = foldr (\ x -> liftA2 (\ flg -> if flg then (x:) else id) (p x)) (pure [])
filterM = \ p . foldr ( \ x . lift2 (V (cons x) I) (p x) ) (return nil)

# -- solution --

# deleteNth :: [Int] -> Int -> [Int]
# deleteNth xs n = evalState (filterM go xs) empty where
#   go :: Int -> State (IntMap Int) Bool
#   go x = do
#     modify $ insertWith (+) x 1
#     (<= n) <$> gets (! x)

delete-nth = \ xs n .
  T ( \ x .
        bind (modify (insert-with add x 1)) \ _ .
              fmap (C le n) (gets (C index x))
    ) \ go .
  evalState (filterM go xs) empty
module Example where

import Control.Monad.Free (Free(..),liftF)
import Data.Bifunctor (first)
import Control.Monad (filterM)
import Data.IntMap (IntMap,empty,insertWith,(!))

infixr 9 ...
(...) = (.).(.)

newtype StateF s a = StateF { runStateF :: s -> (,) a s }

instance Functor (StateF s) where
  fmap fn = StateF . first fn ... runStateF
  -- fmap fn fa = StateF $ first fn . runStateF fa

getF :: StateF s s
getF = StateF $ \ s -> (s,s)

putF :: s -> StateF s ()
putF s = StateF $ \ _ -> ((),s)

type State s = Free (StateF s)

get :: State s s
get = liftF getF

put :: s -> State s ()
put = liftF . putF

runState :: State s a -> s -> (a,s)
runState (Pure a) s = (a,s)
runState (Free fa) s = uncurry runState $ runStateF fa s
-- runState (Free fa) s = let (ma,s') = runStateF fa s
--                        in  runState ma s'

modify :: (s -> s) -> State s ()
modify fn = put . fn =<< get

gets :: (s -> t) -> State s t
gets fn = return . fn =<< get

evalState :: State s a -> s -> a
evalState = fst ... runState

deleteNth :: [Int] -> Int -> [Int]
deleteNth xs n = evalState (filterM go xs) empty where
  go :: Int -> State (IntMap Int) Bool
  go x = do
    modify $ insertWith (+) x 1
    (<= n) <$> gets (! x)

odd and even are mutually recursive; sub is actually only self-recursive, but the principle holds.

Yes, Y3 fixes plurivariadic functions.

#debug

#import combinators.lc
K  = \ x _ . x
KI = \ _ x . x
KK = \ x _ _ . x
T  = \ x f . f x
X  = \ x y z f . f x y z
Y  = \ f . ( \ x . f (x x) ) ( \ x . f (x x) )

#import scott-boolean.lc
False = K
True = KI

#import scott-triple.lc
Triple = X
fst = T KK
snd = T (K K)
thd = T (K KI)
map3 = \ fn . T \ x y z . Triple (fn x) (fn y) (fn z)

# polyvariadic Y-combinator
Y3 = \ triple . Y \ self . map3 (T self) triple

# odd-even-sub : Triple (Number -> Boolean) (Number -> Boolean) (Number -> Number -> Number)
odd-even-sub = Y3 (Triple ( \ odd-even-sub . \ n . n False (snd odd-even-sub) ) # odd, recursing to even
                          ( \ odd-even-sub . \ n . n True  (fst odd-even-sub) ) # even, recursing to odd
                          ( \ odd-even-sub . \ m n . m 0 \ m-1 . n m (thd odd-even-sub m-1) ) # sub, recursing to sub
                  )
# odd, even : Number -> Boolean
# sub : Number -> Number -> Number
odd  = fst odd-even-sub
even = snd odd-even-sub
sub  = thd odd-even-sub

Given 6 random numbers and a target number it can calculate how to get the target with a combination of numbers and operators + - * /.

Currently it is set to time out after 51 attempts or until it hits the target number. It may take a few retries before you hit the solution.

import random
import operator

ops = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv,
} 

def find_operation(operation):
    if operation == 1:
        return "+"
    if operation == 2:
        return "-"
    if operation == 3:
        return "*"
    if operation == 4:
        return "/"

def create_random_list():
    randomlist = []
    for i in range(0,5):
        n = random.randint(1,4)
        randomlist.append(n)
    return randomlist

j = 0
target_number = 503
list_of_integers = [100, 25, 75, 50, 3, 10]
number_1 = 0

while number_1 != target_number:
    if j == 50:
        print(f"Timed out after {j+1} attempts")
        break
    i = 0
    random.shuffle(list_of_integers)
    number_1 = list_of_integers[0]
    operation_list = create_random_list()
    for operation in operation_list:
        number_2 = list_of_integers[i+1]
        op = find_operation(operation)
        op_func = ops[op]
        answer = op_func(number_1, number_2)
        number_1 = answer
        i+=1
        if int(answer) == 0:
            break
        if answer < 0:
            break
        if answer == target_number:
            print(operation_list)
            print(list_of_integers)
            print(f"Success after {j+1} attempts")
            break
    j+=1

Test Kumite

#HELLO WORLD

Given an input of 6 numbers, a target and a combination of 5 operators +, -, * and /, you will be given a score based on how close your solution is to the target.

The solver will calculate all the possible combinations and then compare your given combination to all combinations and score you a 5 if within 10, a 7 if within 5 and a 10 if you reached the target.

import operator
from itertools import permutations, product

ops = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv,
} 

def find_operation(operation):
    if operation == 1:
        return "+"
    if operation == 2:
        return "-"
    if operation == 3:
        return "*"
    if operation == 4:
        return "/"

def find_solutions(list_of_integers):
    integer_permutations = permutations(list_of_integers)
    operation_perms = list(product([1, 2, 3, 4], repeat=5))
    all_solutions = []
    j = 0
    for combination in integer_permutations:
        for op_combo in operation_perms:
            i = 0
            solution = {}
            number_1 = combination[i]
            for op in op_combo:
                op_name = find_operation(op)
                op_func = ops[op_name]
                answer = op_func(number_1, combination[i+1])
                number_1 = answer
                i+=1
            solution["integer_combo"] = combination
            solution["operation_combo"] = op_combo
            solution["answer"] = answer
            all_solutions.append(solution)
            j+=1
#     print(len(all_solutions))
    return all_solutions


def find_my_solution(integer_combination, operation_combination):
    all_solutions = find_solutions(integer_combination)
    for solution in all_solutions:
        if solution["integer_combo"] == integer_combination and solution["operation_combo"] == operation_combination:
            answer = solution["answer"]
            return answer

def determine_points(number_answer, target_number):
    if number_answer == target_number:
        print(f"You get 10 points for: {number_answer}")
        return 10
    if target_number - 5 < number_answer < target_number + 5:
        print(f"You get 7 points for: {number_answer}")
        return 7
    if target_number - 10 < number_answer < target_number + 10:
        print(f"You get 5 points for: {number_answer}")
        return 5
    else:
        print(f"You get 0 points for: {number_answer}")
        return 0

target_number = 503
integer_combination = (100, 25, 75, 50, 10, 3)
operation_combination = (2, 4, 3, 3, 1)

final_answer = find_my_solution(integer_combination, operation_combination)
determine_points(final_answer, target_number)