this is a simple kumite
def is_more_then_2(n):
return n > 2
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(1 + 1, 2)
its a static amout of numbers, so it can be just a list, duh
get_fibs=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994, 190392490709135, 308061521170129, 498454011879264, 806515533049393, 1304969544928657, 2111485077978050, 3416454622906707, 5527939700884757, 8944394323791464, 14472334024676221, 23416728348467685, 37889062373143906, 61305790721611591, 99194853094755497, 160500643816367088, 259695496911122585, 420196140727489673, 679891637638612258, 1100087778366101931, 1779979416004714189, 2880067194370816120, 4660046610375530309, 7540113804746346429, 12200160415121876738, 19740274219868223167, 31940434634990099905, 51680708854858323072, 83621143489848422977, 135301852344706746049, 218922995834555169026, 354224848179261915075]
get_fibs=lambda a=1,b=1:[(t:=a,a:=b,b:=b+t)[0]for _ in range(100)]- get_fibs=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994, 190392490709135, 308061521170129, 498454011879264, 806515533049393, 1304969544928657, 2111485077978050, 3416454622906707, 5527939700884757, 8944394323791464, 14472334024676221, 23416728348467685, 37889062373143906, 61305790721611591, 99194853094755497, 160500643816367088, 259695496911122585, 420196140727489673, 679891637638612258, 1100087778366101931, 1779979416004714189, 2880067194370816120, 4660046610375530309, 7540113804746346429, 12200160415121876738, 19740274219868223167, 31940434634990099905, 51680708854858323072, 83621143489848422977, 135301852344706746049, 218922995834555169026, 354224848179261915075]
import codewars_test as test from solution import get_fibs @test.describe("Example") def test_group(): @test.it("test case") def test_case(): fibs = get_fibs test.assert_equals(fibs, [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994, 190392490709135, 308061521170129, 498454011879264, 806515533049393, 1304969544928657, 2111485077978050, 3416454622906707, 5527939700884757, 8944394323791464, 14472334024676221, 23416728348467685, 37889062373143906, 61305790721611591, 99194853094755497, 160500643816367088, 259695496911122585, 420196140727489673, 679891637638612258, 1100087778366101931, 1779979416004714189, 2880067194370816120, 4660046610375530309, 7540113804746346429, 12200160415121876738, 19740274219868223167, 31940434634990099905, 51680708854858323072, 83621143489848422977, 135301852344706746049, 218922995834555169026, 354224848179261915075]) test.assert_equals(len(fibs), 100)
- import codewars_test as test
- from solution import get_fibs
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
fibs = get_fibs()- fibs = get_fibs
- test.assert_equals(fibs, [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994, 190392490709135, 308061521170129, 498454011879264, 806515533049393, 1304969544928657, 2111485077978050, 3416454622906707, 5527939700884757, 8944394323791464, 14472334024676221, 23416728348467685, 37889062373143906, 61305790721611591, 99194853094755497, 160500643816367088, 259695496911122585, 420196140727489673, 679891637638612258, 1100087778366101931, 1779979416004714189, 2880067194370816120, 4660046610375530309, 7540113804746346429, 12200160415121876738, 19740274219868223167, 31940434634990099905, 51680708854858323072, 83621143489848422977, 135301852344706746049, 218922995834555169026, 354224848179261915075])
- test.assert_equals(len(fibs), 100)
rewritten in python
I am to lazy to write tests
def is_unique(text: str) -> bool: return len({*text}) == len(text)
function isUnique(string) {let knownChars = "";for (let char of string) {if (!knownChars.includes(char)) {knownChars += char;} else {return false;}}return true;}- def is_unique(text: str) -> bool:
- return len({*text}) == len(text)
import codewars_test as test # TODO Write tests import solution # or from solution import example # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test case") def test_case(): test.assert_equals(1 + 1, 2)
// Since Node 10, we're using Mocha.// You can use `chai` for assertions.const chai = require("chai");const assert = chai.assert;// Uncomment the following line to disable truncating failure messages for deep equals, do:// chai.config.truncateThreshold = 0;// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.// Uncomment the following to use the old assertions:const Test = require("@codewars/test-compat");- import codewars_test as test
- # TODO Write tests
- import solution # or from solution import example
describe("Solution", function() {it("should return true for strings without repetition", function() {Test.assertEquals(isUnique('gino'), true);Test.assertEquals(isUnique('glhf'), true);// assert.strictEqual(1 + 1, 2);});it("should return false for strings with repetition", function() {Test.assertEquals(isUnique('gg'), false);Test.assertEquals(isUnique('phillip'), false);// assert.strictEqual(1 + 1, 2);});});- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
- test.assert_equals(1 + 1, 2)
in one line
def repair(cur: list, pre: list):cur[[i.count("?") > 0 for i in cur].index(True)] = pre[[pre.index(i) for i in pre if [(o, i) for o, i in enumerate([*i]) if (o, i) in list(filter(lambda x: x[1] != '', enumerate(map(lambda x: x if x != "?" else "", [*cur[[i.count("?") > 0 for i in cur].index(True)]]))))] == list(filter(lambda x: x[1] != '', enumerate(map(lambda x: x if x != "?" else "", [*cur[[i.count("?") > 0 for i in cur].index(True)]])))) and len(i) == len(cur[[i.count("?") > 0 for i in cur].index(True)])][0]];return cur
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- def repair(cur: list, pre: list):cur[[i.count("?") > 0 for i in cur].index(True)] = pre[[pre.index(i) for i in pre if [(o, i) for o, i in enumerate([*i]) if (o, i) in list(filter(lambda x: x[1] != '', enumerate(map(lambda x: x if x != "?" else "", [*cur[[i.count("?") > 0 for i in cur].index(True)]]))))] == list(filter(lambda x: x[1] != '', enumerate(map(lambda x: x if x != "?" else "", [*cur[[i.count("?") > 0 for i in cur].index(True)]])))) and len(i) == len(cur[[i.count("?") > 0 for i in cur].index(True)])][0]];return cur
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
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 NoneCONST_MAX_VALUE = 999999class RepairEngine:searchWindow1 = 70 # when diff < DIFF_TRESHOLDsearchWindow2 = 14 # when diff < 3DIFF_TRESHOLD_1=68DIFF_TRESHOLD_2=3def __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: #markBrokenLinesfor 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 indexingdef linkFiles(self, lines1, lines2):p2=0seqenceLost=0for 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=pmyLine['nextPos']=papplyPatch = Trueif (lines2[p]['prePos']!=CONST_UNDEFINED) and (lines2[p]['prePos']!=i):if lines2[p]['preK'] > thisK:Noneelif (lines2[p]['preK'] < thisK):applyPatch = Falseelse:Noneif applyPatch:lines2[p]['prePos'] = ilines2[p]['preK'] = thisKif 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=0else:#print("i={str(i)} pos={str(p)} not found position")seqenceLost +=1if 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_UNDEFINEDresultD=CONST_MAX_VALUEfor fromPos in [nearPos1,nearPos2] :if (fromPos==CONST_UNDEFINED): continueif (result!=CONST_UNDEFINED and nearPos1==nearPos2): breakfor d in range(0,self.searchWindow1):# todo mark previous interval and do not check against lines.p=fromPos+dif (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, kif (d!=0):p=fromPos-dif (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, kif (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 foundreturn result, resultD# end of searchLinenot_allowed="?*"def checkBrokenLine(self, line):wrongChar=0questionChar=0for c in line:if c in self.not_allowed: wrongChar+=1#if not c in self.allowed: wrongChar+=1if c=='?':questionChar+=1#if c in self.not_allowed: wrongChar-=1return 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 differentdef stringDiff(self, l1, l2):if (l1==l2):#print('compare ',l1,l2," EQ=0")return 0if (l1.lower()==l2.lower()):#print('compare ',l1,l2," EQ=1")return 1l1=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=Truefor 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+1for j in range(-1,lenstr2+1):d[(-1,j)] = j+1for i in range(lenstr1):for j in range(lenstr2):if s1[i] == s2[j]:cost = 0elif (s1[i] in self.not_allowed) or (s2[j] in self.not_allowed): # modification weightcost = 0else:cost = 3d[(i,j)] = min(d[(i-1,j)] + 1, # deletiond[(i,j-1)] + 1, # insertiond[(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) # transpositionreturn 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_VALUExDiff = 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 stringDiffdef 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,0print(" 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=0i=itm-1while (oldP!=CONST_UNDEFINED and i>=0):depth+=1statHistoryWatchDepth=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+=1statHistoryUsedDepth=max(statHistoryUsedDepth, depth)break#else:# log.trace(" [{}][{}] line {}({})> go deep", itm, i, line.pos, oldP);oldP=oldL['prePos']i-=1if (oldP==CONST_UNDEFINED) :print(" repair line<not found. ", line['line'])out.append(line['line']) #no modifystatNotFound+=1else: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 repairdef process(self, historySeq, i_to_repair:int=-1):hSeq=[]for histText in historySeq:lines=[]i=0for l in histText:tl={'pos':i, 'line':l, 'hasBroken':False,'prePos':CONST_UNDEFINED, 'preK':-1.0, 'nextPos':CONST_UNDEFINED}lines.append(tl)i+=1hSeq.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 repairdef 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
import codewars_test as test import random, string # TODO Write tests from solution import repair def tru_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 # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("static tests") def _(): test.assert_equals(repair(['line 1', '???? 2', 'line 3'], ['line 1', 'line 2']),['line 1', 'line 2', 'line 3']) test.assert_equals(repair(['hi', 'my name is', '????????HRUM'], ['hi my name is', 'HRUMHRUMHRUM']), ['hi', 'my name is', 'HRUMHRUMHRUM']) test.assert_equals(repair(['what', 'was', 'pl?????1', 'thinking', 'when', 'writing this code'], ['what was', 'playerO1', "thinking when writing this code"]), ['what', 'was', 'playerO1', 'thinking', 'when', 'writing this code']) test.assert_equals(repair(['boy oh boy do I LOVE f?x?n? code'], ['boy oh boy do I LOVE fixing code']), ['boy oh boy do I LOVE fixing code']) @test.it("random tests") def _(): def break_str(st: str): return "".join(map(lambda x: x if random.getrandbits(1) else "?", [*st])) for i in range(1000): sts = ["".join(random.choices([*string.ascii_letters], k=random.randint(10, 30))) for _ in range(random.randint(10, 30))] broken_sts = list(map(lambda x: break_str(x), sts)) test.assert_equals(repair(broken_sts, sts), tru_repair(broken_sts, sts))
- import codewars_test as test
from solution import repair_text_by_historyimport numpy as np- import random, string
- # TODO Write tests
- from solution import repair
def text_generator(sample_sentence, depth=4, sentences_up_to=3,rand_seed=100):rand=np.random.RandomState(rand_seed)hist=[]hist_broken=[]prev=[]prev_broken=[]def f_make_line():l=''for i in range(rand.randint(1,sentences_up_to)):if len(l)>0:l+=' 'l+=rand.choice(sample_sentence)+rand.choice([c for c in '......???!!;'])#print('new:', l)return l;def f_break_line(l):o=''bk=rand.randint(8,20)for c in l:if rand.randint(16) <= bk :o+='?'else:o+=c#print('break:', l,' > ',o)return onew_break=False # first history was goodfor j in range(depth):text=[]text_broken=[]for i in range(len(prev)):if rand.randint(15) >= 13 : # corrosion linetext.append(prev[i])text_broken.append(f_break_line(prev_broken[i]))elif rand.randint(20) >= 18 :continue # deleteelse:text.append(prev[i])text_broken.append(prev_broken[i])if rand.randint(25) >= 20 :for i in range(1,rand.randint(10)):l=f_make_line()text.append(l)if new_break and (rand.randint(15) >= 13) :text_broken.append(f_break_line(l))else:text_broken.append(l)# append textif rand.randint(10) >= 7 :for i in range(1,rand.randint(20)):l=f_make_line()text.append(l)if new_break and (rand.randint(15) >= 13) :text_broken.append(f_break_line(l))else:text_broken.append(l)prev=texthist.append(text)prev_broken=text_brokenhist_broken.append(text_broken)new_broke=Truereturn hist_broken, hist- def tru_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
- # test.assert_equals(actual, expected, [optional] message)
@test.describe("Repair text test")- @test.describe("Example")
- def test_group():
@test.it("Fixed test case")def test_case():data1=[['Hello, world!','THIS is first version.'],['Hello, world.''This is first ???????.'],['Hello world','Line 2.','This is first ?????on.','There can be large document'],['Hello.','???? ??','???????????? ?????on.','There can be large document'],['Hello.','???? ??','???????????? ?????on.','There can be large document','','Simple alhorithm for repair:','','Step 1.','* mark broken symbols and lines','','Step 2.','* find line number in history','','Step 3.','* search good lines in history','','Step 4.','* replace broken line, if it is can be true',],['Hello.','???? ??','???????????? ?????on.','There can be large document','','Simple alhorithm for repair:','','???? ??','* mark broken symbols and lines','','Step 2.','? ???? line ?????? ?? ???????','','???? 3.','* search good lines in history','','Step 4.','* replace broken line, if it is can be true',],['Hello.','???? ??','???????????? ?????on.','There can be large document','','Simple alhorithm for repair:','','???? ??','* mark broken symbols and lines','','Step 2.','? ???? line ?????? ?? ???????','','???? 3.','* search good lines in history','','Step 4.','* replace broken line, if it is can be true','','You can make more better alhorighm, or try improvement it.','But do not repair string','In cases, when it can be ambigous.',''],['Hello.','???? ??','???????????? ?????on.','There can be large document','','Simple alhorithm for repair:','','???? ??','* mark broken symbols and lines','','Step 2.','? ???? line ?????? ?? ???????','','???? 3.','* search good lines in history','','???? ?.','','Step 4.','* replace broken line, if it is can be true','','You can make more better alhorighm, or try improvement it.','?? ?????? ???? ?? ??? ?? ?????????','??? ?? ??? ?????? ??????','']]expected_text=['Hello.','Line 2.','THIS is first version.' # TODO may be "This is first version."'There can be large document','','Simple alhorithm for repair:','','Step 1.','* mark broken symbols and lines','','Step 2.','* find line number in history','','Step 3.','* search good lines in history','','Step 4.','','Step 4.','* replace broken line, if it is can be true','','You can make more better alhorighm, or try improvement it.','?? ?????? ???? ?? ??? ?? ?????????','??? ?? ??? ?????? ??????','']r_text=repair_text_by_history(data1)test.assert_equals(r_text, expected_text)- @test.it("static tests")
- def _():
- test.assert_equals(repair(['line 1', '???? 2', 'line 3'], ['line 1', 'line 2']),['line 1', 'line 2', 'line 3'])
- test.assert_equals(repair(['hi', 'my name is', '????????HRUM'], ['hi my name is', 'HRUMHRUMHRUM']), ['hi', 'my name is', 'HRUMHRUMHRUM'])
- test.assert_equals(repair(['what', 'was', 'pl?????1', 'thinking', 'when', 'writing this code'], ['what was', 'playerO1', "thinking when writing this code"]), ['what', 'was', 'playerO1', 'thinking', 'when', 'writing this code'])
- test.assert_equals(repair(['boy oh boy do I LOVE f?x?n? code'], ['boy oh boy do I LOVE fixing code']), ['boy oh boy do I LOVE fixing code'])
@test.it("Random test case")def test_case_random():words=['','','Hello world','Line 2','This is first version','You can make more better alhorighm, or try improvement it','You got damaged paper with text','And got previous edition of this text','Each next edition has any good changes and break character change','In broken lines will be same character replaced to ''?''', 'Make solution for repair broken text by history']broken_t,original_t=text_generator(words, depth=3) # depth>4 need many timeexpected_text = original_t[-1]print("Random history with ",str(len(broken_t))," items, last with ",str(len(expected_text))," lines")r_text=repair_text_by_history(broken_t)test.assert_equals(r_text, expected_text)- @test.it("random tests")
- def _():
- def break_str(st: str):
- return "".join(map(lambda x: x if random.getrandbits(1) else "?", [*st]))
- for i in range(1000):
- sts = ["".join(random.choices([*string.ascii_letters], k=random.randint(10, 30))) for _ in range(random.randint(10, 30))]
- broken_sts = list(map(lambda x: break_str(x), sts))
- test.assert_equals(repair(broken_sts, sts), tru_repair(broken_sts, sts))
nevermind, i figured out how to do random tests
import codewars_test as test from solution import str_opt import random import string tru_str_opt = lambda s:s if len(s) == 1 else None if len({s.count(i) for i in {*s}}) <= 1 else sorted([*s], key=lambda x: s.count(x))[0] # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test cases") def test_case(): test.assert_equals(str_opt("abbcc"), "a", "returns the value that repeats the least") test.assert_equals(str_opt("bacc"), "b", "returns the value that repeats the least and goes first") test.assert_equals(str_opt("aabbcc"), None, " returns None if all characters repeat equally") test.assert_equals(str_opt("c"), "c", "returns the value if it is the only one") test.assert_equals(str_opt(""), None, "if it is empty, it returns None") test.assert_equals(str_opt(f"{'a'*10000}{'b'*10000}c"), "c", "shall work with large numbers") test.assert_equals(str_opt(f"{'a'*10000}{'b'*10000}{'c'*10000}"), None, "should handle very long strings with all characters repeating") @test.it("random cases") def _(): for i in range(500): testval = "".join([random.choice([*string.ascii_lowercase]) for _ in range(200)]) test.assert_equals(str_opt(testval), tru_str_opt(testval))
- import codewars_test as test
- from solution import str_opt
- import random
- import string
- tru_str_opt = lambda s:s if len(s) == 1 else None if len({s.count(i) for i in {*s}}) <= 1 else sorted([*s], key=lambda x: s.count(x))[0]
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test cases")
- def test_case():
- test.assert_equals(str_opt("abbcc"), "a", "returns the value that repeats the least")
- test.assert_equals(str_opt("bacc"), "b", "returns the value that repeats the least and goes first")
- test.assert_equals(str_opt("aabbcc"), None, " returns None if all characters repeat equally")
- test.assert_equals(str_opt("c"), "c", "returns the value if it is the only one")
- test.assert_equals(str_opt(""), None, "if it is empty, it returns None")
- test.assert_equals(str_opt(f"{'a'*10000}{'b'*10000}c"), "c", "shall work with large numbers")
- test.assert_equals(str_opt(f"{'a'*10000}{'b'*10000}{'c'*10000}"), None, "should handle very long strings with all characters repeating")
- @test.it("random cases")
- def _():
- for i in range(500):
- testval = "".join([random.choice([*string.ascii_lowercase]) for _ in range(200)])
- test.assert_equals(str_opt(testval), tru_str_opt(testval))
rewritten in the best programming language, Python
please add random tests, i am to dumb to build them.
str_opt = lambda s:s if len(s) == 1 else None if len({s.count(i) for i in {*s}}) <= 1 else sorted([*s], key=lambda x: s.count(x))[0]
const firstNonRepeatingCharacter = (str) => {let chars = [], counts = [];for(const char of str) {let index = chars.indexOf(char);if(index < 0) {index = counts.length;chars.push(char);counts.push(0);}counts[index]++;}for(let index = 0; index < chars.length; index++) {if(counts[index] === 1) {return chars[index];}}return null;};- str_opt = lambda s:s if len(s) == 1 else None if len({s.count(i) for i in {*s}}) <= 1 else sorted([*s], key=lambda x: s.count(x))[0]
import codewars_test as test from solution import str_opt import random # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test cases") def test_case(): test.assert_equals(str_opt("abbcc"), "a", "returns the value that repeats the least") test.assert_equals(str_opt("bacc"), "b", "returns the value that repeats the least and goes first") test.assert_equals(str_opt("aabbcc"), None, " returns None if all characters repeat equally") test.assert_equals(str_opt("c"), "c", "returns the value if it is the only one") test.assert_equals(str_opt(""), None, "if it is empty, it returns None") test.assert_equals(str_opt(f"{'a'*10000}{'b'*10000}c"), "c", "shall work with large numbers") test.assert_equals(str_opt(f"{'a'*10000}{'b'*10000}{'c'*10000}"), None, "should handle very long strings with all characters repeating")
// Since Node 10, we're using Mocha.// You can use `chai` for assertions.const chai = require("chai");const assert = chai.assert;// Uncomment the following line to disable truncating failure messages for deep equals, do:// chai.config.truncateThreshold = 0;// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.// Uncomment the following to use the old assertions:// const Test = require("@codewars/test-compat");describe("Solution", function() {it('should return the first non-repeating character', function() {assert.strictEqual(firstNonRepeatingCharacter('abcd'), 'a');assert.strictEqual(firstNonRepeatingCharacter('aabbcdc'), 'd');});it('should return the first non-repeating character when special characters are included', function() {assert.strictEqual(firstNonRepeatingCharacter('a@b@bc'), 'a');});it('should return null when all characters are repeating', function() {assert.strictEqual(firstNonRepeatingCharacter('aabbcc'), null);});it('should return the first character if it is the only one', function() {assert.strictEqual(firstNonRepeatingCharacter('z'), 'z');});it('should handle an empty string correctly', function() {assert.strictEqual(firstNonRepeatingCharacter(''), null);});it('should handle strings with numbers', function() {assert.strictEqual(firstNonRepeatingCharacter('1122a'), 'a');});it('should handle very long strings with the non-repeating character at the end', function() {const longString = 'a'.repeat(10000) + 'b'.repeat(10000) + 'c';assert.strictEqual(firstNonRepeatingCharacter(longString), 'c');});it('should handle very long strings with all characters repeating', function() {const longString = 'a'.repeat(20000) + 'b'.repeat(20000);assert.strictEqual(firstNonRepeatingCharacter(longString), null);});});- import codewars_test as test
- from solution import str_opt
- import random
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test cases")
- def test_case():
- test.assert_equals(str_opt("abbcc"), "a", "returns the value that repeats the least")
- test.assert_equals(str_opt("bacc"), "b", "returns the value that repeats the least and goes first")
- test.assert_equals(str_opt("aabbcc"), None, " returns None if all characters repeat equally")
- test.assert_equals(str_opt("c"), "c", "returns the value if it is the only one")
- test.assert_equals(str_opt(""), None, "if it is empty, it returns None")
- test.assert_equals(str_opt(f"{'a'*10000}{'b'*10000}c"), "c", "shall work with large numbers")
- test.assert_equals(str_opt(f"{'a'*10000}{'b'*10000}{'c'*10000}"), None, "should handle very long strings with all characters repeating")
randomized tests, decreased the amount of tests
import codewars_test as test from solution import maxnum import random @test.describe('Example Tests') def example_tests(): @test.it('Simple Tests') def example_test_case(): test.assert_equals(maxnum(4), 4) test.assert_equals(maxnum(21), 12) test.assert_equals(maxnum(110), 101) test.assert_equals(maxnum(4), 4) @test.it('random tests') def random_test_case(): for i in range(1, 607): i = random.randint(1, 10000) test.assert_equals(sorted([*str(maxnum(i))]), sorted([*str(i)]), str(i))
- import codewars_test as test
- from solution import maxnum
- import random
- @test.describe('Example Tests')
- def example_tests():
- @test.it('Simple Tests')
- def example_test_case():
- test.assert_equals(maxnum(4), 4)
- test.assert_equals(maxnum(21), 12)
- test.assert_equals(maxnum(110), 101)
- test.assert_equals(maxnum(4), 4)
- @test.it('random tests')
- def random_test_case():
for i in range(1, 1500):- for i in range(1, 607):
- i = random.randint(1, 10000)
- test.assert_equals(sorted([*str(maxnum(i))]), sorted([*str(i)]), str(i))
a harder, completly unreadable more stupid solution, but it is in Python and it works and thats all that matters
maxnum = lambda n: int(n) if len(str(n)) == 1 else int(n) if len({*str(n)}) == 1 else int(n) if len(str(n)) < str(n).count("0")*2 else n if n < 100 and n % 10 == 0 else int(sorted([i for i in range(int("".join(sorted([*str(n)])[::-1])) + 1) if sorted([*str(i)]) == sorted([*str(n)])])[::-1][1]) if sorted([i for i in range(int("".join(sorted([*str(n)])[::-1])) + 1) if sorted([*str(i)]) == sorted([*str(n)])])[::-1][0] == n else int(sorted([i for i in range(int("".join(sorted([*str(n)])[::-1])) + 1) if sorted([*str(i)]) == sorted([*str(n)])])[::-1][0])
import java.util.Arrays;import java.util.Scanner;public class MaxNumber {public static long print(long number) {String numeroString = Long.toString(number);char[] digitos = numeroString.toCharArray();Arrays.sort(digitos);StringBuilder numeroOrdenadoStr = new StringBuilder(new String(digitos));numeroOrdenadoStr.reverse();return Long.parseLong(numeroOrdenadoStr.toString());}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("Ingrese un numero: ");long number = scanner.nextLong();long maxNumber = print(number);System.out.println("El número más alto que se puede formar con estos dígitos es: " + maxNumber);}}- maxnum = lambda n: int(n) if len(str(n)) == 1 else int(n) if len({*str(n)}) == 1 else int(n) if len(str(n)) < str(n).count("0")*2 else n if n < 100 and n % 10 == 0 else int(sorted([i for i in range(int("".join(sorted([*str(n)])[::-1])) + 1) if sorted([*str(i)]) == sorted([*str(n)])])[::-1][1]) if sorted([i for i in range(int("".join(sorted([*str(n)])[::-1])) + 1) if sorted([*str(i)]) == sorted([*str(n)])])[::-1][0] == n else int(sorted([i for i in range(int("".join(sorted([*str(n)])[::-1])) + 1) if sorted([*str(i)]) == sorted([*str(n)])])[::-1][0])
import codewars_test as test from solution import maxnum @test.describe('Example Tests') def example_tests(): @test.it('Simple Tests') def example_test_case(): test.assert_equals(maxnum(4), 4) test.assert_equals(maxnum(21), 12) test.assert_equals(maxnum(110), 101) test.assert_equals(maxnum(4), 4) @test.it('random tests') def random_test_case(): for i in range(1, 1500): test.assert_equals(sorted([*str(maxnum(i))]), sorted([*str(i)]), str(i))
import static org.junit.Assert.assertEquals;import org.junit.Test;import java.util.Random;- import codewars_test as test
- from solution import maxnum
public class MaxNumberTest {@Testpublic void testFour() {assertEquals(4, MaxNumber.print(4));}@Testpublic void testTwelve() {assertEquals(21, MaxNumber.print(12));}@Testpublic void testOneHundred() {assertEquals(110, MaxNumber.print(101));}@Testpublic void testHuge1() {assertEquals(754000000000000000L, MaxNumber.print(400000005000007000L));}@Testpublic void testHuge2() {assertEquals(988777666444322200L, MaxNumber.print(307778062924466824L));}}- @test.describe('Example Tests')
- def example_tests():
- @test.it('Simple Tests')
- def example_test_case():
- test.assert_equals(maxnum(4), 4)
- test.assert_equals(maxnum(21), 12)
- test.assert_equals(maxnum(110), 101)
- test.assert_equals(maxnum(4), 4)
- @test.it('random tests')
- def random_test_case():
- for i in range(1, 1500):
- test.assert_equals(sorted([*str(maxnum(i))]), sorted([*str(i)]), str(i))
- added types
- added tests
mylist = [("yellow", 1), ("blue", 2), ("yellow", 3), ("blue", 4), ("red", 1)] def group(lst: list[tuple[str, int], ...], result: dict[str, int]={}) -> dict[str, list[int, ...]]: {result[c].append(n) if c in result else result.update({c: [n]}) for c, n in lst} return result # print(group(mylist))
- mylist = [("yellow", 1), ("blue", 2), ("yellow", 3), ("blue", 4), ("red", 1)]
def group(lst, result={}):- def group(lst: list[tuple[str, int], ...], result: dict[str, int]={}) -> dict[str, list[int, ...]]:
- {result[c].append(n) if c in result else result.update({c: [n]}) for c, n in lst}
- return result
print(group(mylist))- # print(group(mylist))
import codewars_test as test # TODO Write tests from solution import group # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test case") def test_case(): test.assert_equals(group([("yellow", 1), ("blue", 2), ("yellow", 3), ("blue", 4), ("red", 1)]), {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})
- import codewars_test as test
- # TODO Write tests
import solution # or from solution import example- from solution import group
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
test.assert_equals(1 + 1, 2)- test.assert_equals(group([("yellow", 1), ("blue", 2), ("yellow", 3), ("blue", 4), ("red", 1)]), {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})
changelog
- added tests
- added types
- added docs
docs
you have a function, average()
, that gets a tuple (t
) with tuples inside that have numbers. this code returns the average of all numbers from these tuples at index 0.
def average(t: tuple[tuple[int | float, ...], ...]) -> list[int | float]: return [sum(i) / len(i) for i in zip(*t)]
m_t = ((10, 10, 10, 12), (30, 45, 56, 45), (81, 80, 39, 32), (1, 2, 3, 4))def average(t):return [sum(i) / len(i) for i in zip(*t)]print(f"\nAverage value: {average(m_t)}")- def average(t: tuple[tuple[int | float, ...], ...]) -> list[int | float]:
- return [sum(i) / len(i) for i in zip(*t)]
import codewars_test as test # TODO Write tests from solution import average # or from solution import example tests = { ((10, 10, 10, 12), (30, 45, 56, 45), (81, 80, 39, 32), (1, 2, 3, 4)):[30.5, 34.25, 27.0, 23.25], ((12, 34, 143, 154), (34, 54, 565, 56), (6556, 675, 3554, 1209), (100, 12, 321, 0.12)):[1675.5, 193.75, 1145.75, 354.78], } # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test case") def test_case(): for i in tests: test.assert_equals(average(i), tests[i])
- import codewars_test as test
- # TODO Write tests
import solution # or from solution import example- from solution import average # or from solution import example
- tests = {
- ((10, 10, 10, 12), (30, 45, 56, 45), (81, 80, 39, 32), (1, 2, 3, 4)):[30.5, 34.25, 27.0, 23.25],
- ((12, 34, 143, 154), (34, 54, 565, 56), (6556, 675, 3554, 1209), (100, 12, 321, 0.12)):[1675.5, 193.75, 1145.75, 354.78],
- }
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
test.assert_equals(1 + 1, 2)- for i in tests:
- test.assert_equals(average(i), tests[i])