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

repairs your list cur (current) with the knowledge from the list pre (previous).

print(repair(['line 1', '???? 2', 'line 3'], ['line 1', 'line 2']))
# ['line 1', 'line 2', 'line 3']

i didn't really understand the description, but i think this is a better solution.

how it works

  • it finds which index in the list cur is broken
  • it finds the part of the broken part that is not broken
  • it finds which index of the list pre is matching the known part with the broken part
  • replaces and returns the broken part with the fixed part from the list pre
Code
Diff
  • def repair(cur: list, pre: list):
        broken_index = [i.count("?") > 0 for i in cur].index(True)
        known_part = list(filter(lambda x: x[1] != '', enumerate(map(lambda x: x if x != "?" else "", [*cur[broken_index]]))))
        matching_pre_index = [pre.index(i) for i in pre if [(o, i) for o, i in enumerate([*i]) if (o, i) in known_part] == known_part and len(i) == len(cur[broken_index])][0]
        cur[broken_index] = pre[matching_pre_index]
        return cur
    • # This solution not vork correctly. Try improvement this code.
    • CONST_UNDEFINED = -999999 # or None
    • CONST_MAX_VALUE = 999999
    • class RepairEngine:
    • searchWindow1 = 70 # when diff < DIFF_TRESHOLD
    • searchWindow2 = 14 # when diff < 3
    • DIFF_TRESHOLD_1=68
    • DIFF_TRESHOLD_2=3
    • def __str__(self):
    • return f"RepairEngine(searchWindow1={str(self.searchWindow1)}, searchWindow2={str(self.searchWindow2)}, DIFF_TRESHOLD_1={str(self.DIFF_TRESHOLD_1)})"
    • def indexing(self, historySeq):
    • if len(historySeq)<2 : raise BaseException("History sequence should have 2 or more files. historySeq="+str(historySeq))
    • for text in historySeq: #markBrokenLines
    • for l in text:
    • l['hasBroken'] = self.checkBrokenLine(l['line'])
    • for i in range(1,len(historySeq)):
    • self.linkFiles(historySeq[i-1], historySeq[i])
    • #end of indexing
    • def linkFiles(self, lines1, lines2):
    • p2=0
    • seqenceLost=0
    • for i in range(0, len(lines1)):
    • #print(f"Progress {str(i+1)}/{len(lines1)} history items")
    • myLine=lines1[i]
    • p,thisK =self.searchLine(myLine['line'], lines2, p2, i);
    • #print('p=',p,' thisK=',thisK,' i=',i,' text:', myLine['line'])
    • if ((p!=CONST_UNDEFINED) and (p>=0)):
    • if (p2!=p):
    • #print(" new offset {str(i)} > {str(p)}")
    • p2=p
    • myLine['nextPos']=p
    • applyPatch = True
    • if (lines2[p]['prePos']!=CONST_UNDEFINED) and (lines2[p]['prePos']!=i):
    • if lines2[p]['preK'] > thisK:
    • None
    • elif (lines2[p]['preK'] < thisK):
    • applyPatch = False
    • else:
    • None
    • if applyPatch:
    • lines2[p]['prePos'] = i
    • lines2[p]['preK'] = thisK
    • if i != myLine['pos']:
    • print(f"WARN: i={str(i)} and pos={str(myLine['pos'])} not match! At line \"{str(myLine['line'])}\"");
    • if seqenceLost>self.searchWindow1*3:
    • print(f"i={str(i)}, found p={str(p)} after lost search window");
    • seqenceLost=0
    • else:
    • #print("i={str(i)} pos={str(p)} not found position")
    • seqenceLost +=1
    • if seqenceLost==self.searchWindow1*3:
    • print(f"i={str(i)}, p={str(p)} lost search window, next position search may be not correct");
    • p2 +=1
    • # end of linkFiles
    • # TODO hard method. Need more unit test!
    • def searchLine(self, text, inLines, nearPos1:int, nearPos2:int):
    • result=CONST_UNDEFINED
    • resultD=CONST_MAX_VALUE
    • for fromPos in [nearPos1,nearPos2] :
    • if (fromPos==CONST_UNDEFINED): continue
    • if (result!=CONST_UNDEFINED and nearPos1==nearPos2): break
    • for d in range(0,self.searchWindow1):
    • # todo mark previous interval and do not check against lines.
    • p=fromPos+d
    • if (0<= p) and (p <len(inLines)):
    • k = self.stringDiff(text, inLines[p]['line']);
    • if (k<=self.DIFF_TRESHOLD_1*3):
    • k+=min(20,d/40)
    • k+=min(16,min(abs(p-nearPos1),abs(p-nearPos2))/50)
    • #print('k=',k,' resultD=',resultD,'; t1="',text,'" t2="',inLines[p]['line'],'" ')
    • if (resultD>k):
    • result, resultD = p, k
    • if (d!=0):
    • p=fromPos-d
    • if (0<= p) and (p <len(inLines)):
    • k = self.stringDiff(text, inLines[p]['line'])
    • if (k<=self.DIFF_TRESHOLD_1*3):
    • k+=min(20,d/40)
    • k+=min(16,min(abs(p-nearPos1),abs(p-nearPos2))/50)
    • if resultD>k :
    • result, resultD = p, k
    • if (resultD==0 or resultD<self.DIFF_TRESHOLD_2 and d>3 and d < self.searchWindow2):
    • break # stop search - it is best.
    • if (resultD>self.DIFF_TRESHOLD_1):
    • return -1, None # not found
    • return result, resultD
    • # end of searchLine
    • not_allowed="?*"
    • def checkBrokenLine(self, line):
    • wrongChar=0
    • questionChar=0
    • for c in line:
    • if c in self.not_allowed: wrongChar+=1
    • #if not c in self.allowed: wrongChar+=1
    • if c=='?':
    • questionChar+=1
    • #if c in self.not_allowed: wrongChar-=1
    • return wrongChar>0 or (len(line)>5 and questionChar>5)
    • # end of checkBrokenLine
    • # Soft comparsion of 2 string
    • # return 0 - equals, 2 equals ignore case and whitespace, 15 high diff but maybe same, Integer.MAX_VALUE absolutly different
    • def stringDiff(self, l1, l2):
    • if (l1==l2):
    • #print('compare ',l1,l2," EQ=0")
    • return 0
    • if (l1.lower()==l2.lower()):
    • #print('compare ',l1,l2," EQ=1")
    • return 1
    • l1=l1.replace(" ", " ").strip()
    • l2=l2.replace(" ", " ").strip()
    • #todo optimization: l1,l2 = l1.upper(),l2.upper()
    • l1,l2=l1.upper(),l2.upper()
    • if (len(l1)==len(l2)):
    • eq=True
    • for i in range(len(l1)):
    • eq=eq and (l1[i]==l2[i]) or (l1[i] in self.not_allowed) or (l1[i] in self.not_allowed)
    • if eq:
    • #print('compare ',l1,l2," EQ=1,2")
    • return 1
    • #Damerau–Levenshtein distance / Расстояние Дамерау — Левенштейна (https://ru.wikipedia.org/w/index.php?#title=%D0%A0%D0%B0%D1%81%D1%81%D1%82%D0%BE%D1%8F%D0%BD%D0%B8%D0%B5_%D0%94%D0%B0%D0%BC%D0%B5%D1%80%D0%B0%D1%83_%E2%80%94_%D0%9B%D0%B5%D0%B2%D0%B5%D0%BD%D1%88%D1%82%D0%B5%D0%B9%D0%BD%D0%B0&oldid=100038662 Creative commons CC-BY-SA )
    • def damerau_levenshtein_distance(s1, s2):
    • d = {}
    • lenstr1 = len(s1)
    • lenstr2 = len(s2)
    • for i in range(-1,lenstr1+1):
    • d[(i,-1)] = i+1
    • for j in range(-1,lenstr2+1):
    • d[(-1,j)] = j+1
    • for i in range(lenstr1):
    • for j in range(lenstr2):
    • if s1[i] == s2[j]:
    • cost = 0
    • elif (s1[i] in self.not_allowed) or (s2[j] in self.not_allowed): # modification weight
    • cost = 0
    • else:
    • cost = 3
    • d[(i,j)] = min(
    • d[(i-1,j)] + 1, # deletion
    • d[(i,j-1)] + 1, # insertion
    • d[(i-1,j-1)] + cost, # substitution
    • )
    • if i and j and s1[i] == s2[j-1] and s1[i-1] == s2[j]:
    • d[(i,j)] = min(d[(i,j)], d[i-2,j-2] + 1) # transposition
    • return d[lenstr1-1,lenstr2-1]
    • xDiff=abs(len(l1)-len(l2)) + damerau_levenshtein_distance(l1,l2)
    • if (len(l1)<3 or len(l2)<3 or abs(len(l1)-len(l2))>30):
    • #print('compare ',l1,l2," EQ=",CONST_MAX_VALUE)
    • return CONST_MAX_VALUE
    • xDiff = xDiff *300 / len(l1)
    • if (xDiff>CONST_MAX_VALUE-1000):
    • #print('compare ',l1,l2," EQ=",CONST_MAX_VALUE-100)
    • return CONST_MAX_VALUE-100
    • #print('compare ',l1,l2," EQ=",xDiff)
    • return round(xDiff)
    • # end of stringDiff
    • def repair(self, historySeq, itm:int=-1):
    • if (itm==0): raise BaseException("Can not repair first item[0] from future!")
    • if (itm<0): itm=len(historySeq)-1
    • #log.debug("Start repair history[{}] \"{}\"", itm, historySeq.get(itm).name);
    • lines=historySeq[itm]
    • out=[]
    • statRepair, statHistoryUsedDepth, statHistoryWatchDepth, statNotFound = 0,0,0,0
    • print(" repair lines:"+str(len(lines)))
    • for line in lines:
    • print(" repair line>"+repr(line)+" pos="+str(line['pos'])+" test="+str(line))
    • if (line['hasBroken']):
    • oldP=line['prePos']
    • depth=0
    • i=itm-1
    • while (oldP!=CONST_UNDEFINED and i>=0):
    • depth+=1
    • statHistoryWatchDepth=max(statHistoryWatchDepth, depth)
    • oldL=historySeq[i][oldP]
    • if (not oldL['hasBroken']):
    • print(" repair line<use old source")
    • out.append(oldL['line'])
    • #log.trace(" [{}][{}] line {}({})> repair from \"{}\" to \"{}\"",
    • # itm, i, line.pos, oldP, line.line, oldL.line);
    • statRepair+=1
    • statHistoryUsedDepth=max(statHistoryUsedDepth, depth)
    • break
    • #else:
    • # log.trace(" [{}][{}] line {}({})> go deep", itm, i, line.pos, oldP);
    • oldP=oldL['prePos']
    • i-=1
    • if (oldP==CONST_UNDEFINED) :
    • print(" repair line<not found. ", line['line'])
    • out.append(line['line']) #no modify
    • statNotFound+=1
    • else:
    • print(" repair line<no need")
    • out.append(line['line'])
    • print(f"Repair complete: repair {statRepair} lines, max history depth = {statHistoryUsedDepth}, max history watch depth = {statHistoryWatchDepth}, not found {statNotFound} lines.")
    • print(" repair out lines:"+str(len(out)))
    • return out
    • # end of repair
    • def process(self, historySeq, i_to_repair:int=-1):
    • hSeq=[]
    • for histText in historySeq:
    • lines=[]
    • i=0
    • for l in histText:
    • tl={'pos':i, 'line':l, 'hasBroken':False,
    • 'prePos':CONST_UNDEFINED, 'preK':-1.0, 'nextPos':CONST_UNDEFINED}
    • lines.append(tl)
    • i+=1
    • hSeq.append(lines)
    • print("indexing...")
    • idx=self.indexing(hSeq)
    • print("pepair n="+str(i_to_repair))
    • repair=self.repair(hSeq, i_to_repair)
    • print("done")
    • return repair
    • def repair_text_by_history(history_of_text):
    • repairer=RepairEngine()
    • text=repairer.process(history_of_text, len(history_of_text)-1)
    • return text
    • def repair(cur: list, pre: list):
    • broken_index = [i.count("?") > 0 for i in cur].index(True)
    • known_part = list(filter(lambda x: x[1] != '', enumerate(map(lambda x: x if x != "?" else "", [*cur[broken_index]]))))
    • matching_pre_index = [pre.index(i) for i in pre if [(o, i) for o, i in enumerate([*i]) if (o, i) in known_part] == known_part and len(i) == len(cur[broken_index])][0]
    • cur[broken_index] = pre[matching_pre_index]
    • return cur
Code
Diff
  • fn find_the_longest_word(sentence: &str) -> Option<&str> {
        let max_len = sentence.split_whitespace().map(str::len).max()?;
        let mut max_words = sentence.split_whitespace().filter(|word| word.len() == max_len);
        let first_max = max_words.next();
        let second_max = max_words.next();
        if second_max.is_some() {
            return None;
        }
        first_max
    }
    
    
    • use std::cmp::Ordering;
    • fn find_the_longest_word(sentence: &str) -> Option<&str> {
    • let mut longest_word = None;
    • let mut max_length = 0;
    • for word in sentence.split_whitespace() {
    • match word.len().cmp(&max_length) {
    • Ordering::Less => {},
    • Ordering::Equal => {
    • if longest_word.is_none() {
    • longest_word = Some(word);
    • } else {
    • max_length += 1;
    • longest_word = None;
    • }
    • },
    • Ordering::Greater => {
    • max_length = word.len();
    • longest_word = Some(word);
    • }
    • }
    • let max_len = sentence.split_whitespace().map(str::len).max()?;
    • let mut max_words = sentence.split_whitespace().filter(|word| word.len() == max_len);
    • let first_max = max_words.next();
    • let second_max = max_words.next();
    • if second_max.is_some() {
    • return None;
    • }
    • longest_word
    • first_max
    • }
Code
Diff
  • function closestToZero(array $ints) {
        return 0;
    }
    ?>
    • function closestToZero(array $ints) {
    • // ici vous pouvez mettre votre code
    • return 0;
    • }
    • ?>
Code
Diff
  • using System.Linq;
    public class Program
    {
      public static int FindSquaresInArray(int[] arr) => arr.Sum(x => x*x);
    }
    • using System.Linq;
    • public class Program
    • {
    • public static int FindSquaresInArray(int[] arr)
    • {
    • int sum = 0;
    • foreach(int n in arr)
    • {
    • sum += n * n;
    • }
    • return sum;
    • }
    • public static int FindSquaresInArray(int[] arr) => arr.Sum(x => x*x);
    • }
Code
Diff
  • # let's compare :P
    
    from time import time
    from random import choice
    
    letters = [chr(i) for i in range(ord('a'), ord('z') + 1)] + [chr(i) for i in range(ord('A'), ord('Z') + 1)]
    
    function_one = lambda s:  ''.join(filter(lambda x: x.lower() not in "aeiou", s))
    function_two = lambda x : ''.join(l * (l.lower() not in 'aeiou') for l in x)
    
    for function, name in ((function_one, 'filter '), (function_two, 'boolean')):
        
        before = time()
        
        # run 100k tests
        for _ in range(80_000):
            length = 70
            word = "".join(choice(letters) for _ in range(length))
            function(word)
        
        after = time()
        print(f'Function with {name} took {round(after - before, 5)} seconds')
        
    # not really a difference, I guess? :D
    
    disemvowel = lambda x : ''.join(l * (l.lower() not in 'aeiou') for l in x) # let this here, so that tests won't fail
    • # Avoids use of filter() function
    • disemvowel = lambda x : ''.join(l * (l.lower() not in 'aeiou') for l in x)
    • # let's compare :P
    • from time import time
    • from random import choice
    • letters = [chr(i) for i in range(ord('a'), ord('z') + 1)] + [chr(i) for i in range(ord('A'), ord('Z') + 1)]
    • function_one = lambda s: ''.join(filter(lambda x: x.lower() not in "aeiou", s))
    • function_two = lambda x : ''.join(l * (l.lower() not in 'aeiou') for l in x)
    • for function, name in ((function_one, 'filter '), (function_two, 'boolean')):
    • before = time()
    • # run 100k tests
    • for _ in range(80_000):
    • length = 70
    • word = "".join(choice(letters) for _ in range(length))
    • function(word)
    • after = time()
    • print(f'Function with {name} took {round(after - before, 5)} seconds')
    • # not really a difference, I guess? :D
    • disemvowel = lambda x : ''.join(l * (l.lower() not in 'aeiou') for l in x) # let this here, so that tests won't fail
Code
Diff
  • mod preloaded;
    use preloaded::nand;
    
    fn not(a: bool) -> bool {
        nand(a, a)
    }
    
    fn and(a: bool, b: bool) -> bool {
        nand(nand(a, b), nand(a, b))
    }
    
    fn or(a: bool, b: bool) -> bool {
        nand(not(a), not(b))
    }
    
    fn nand_nand_or(a: bool, b: bool) -> bool {
        nand(nand(a, b), or(a, b))
    }
    
    fn xor(a: bool, b: bool) -> bool {
        nand(nand_nand_or(a, b), nand_nand_or(a, b))
    }
    
    fn nor(a: bool, b: bool) -> bool {
        nand(or(a, b), or(a, b))
    }
    
    fn xnor(a: bool, b: bool) -> bool {
        nand(nand(a, b), nand(nand(a, a), not(b)))
    }
    
    • mod preloaded;
    • use preloaded::nand;
    • fn not(a: bool) -> bool {
    • nand(a, a)
    • }
    • fn and(a: bool, b: bool) -> bool {
    • nand(nand(a, b), nand(a, b))
    • }
    • fn or(a: bool, b: bool) -> bool {
    • nand(nand(a, a), nand(b, b))
    • nand(not(a), not(b))
    • }
    • fn nand_nand_or(a: bool, b: bool) -> bool {
    • nand(nand(a, b), or(a, b))
    • }
    • fn xor(a: bool, b: bool) -> bool {
    • nand(nand(nand(a, b), nand(nand(a, a), nand(b, b))), nand(nand(a, b), nand(nand(a, a), nand(b, b))))
    • nand(nand_nand_or(a, b), nand_nand_or(a, b))
    • }
    • fn nor(a: bool, b: bool) -> bool {
    • nand(nand(nand(a, a), nand(b, b)), nand(nand(a, a), nand(b, b)))
    • nand(or(a, b), or(a, b))
    • }
    • fn xnor(a: bool, b: bool) -> bool {
    • nand(nand(a, b), nand(nand(a, a), nand(b, b)))
    • nand(nand(a, b), nand(nand(a, a), not(b)))
    • }