Recursion can do anything!
public class Program { public static int returnInputNumber(int num) { if (num == 0) { return 0; } else if (num < 0) { return -returnInputNumber(-num); } else { return returnInputNumber(num - 1) + 1; } } }
- public class Program
- {
- public static int returnInputNumber(int num)
- {
return num;- if (num == 0)
- {
- return 0;
- }
- else if (num < 0)
- {
- return -returnInputNumber(-num);
- }
- else
- {
- return returnInputNumber(num - 1) + 1;
- }
- }
- }
from pkgutil import iter_modules m = [p.name for p in iter_modules()]
import __future__import _weakrefsetimport grpimport reprlibimport _abcimport _xxsubinterpretersimport gzipimport requestsimport _astimport _xxtestfuzzimport hashlibimport resourceimport _asyncioimport abcimport heapq# import retryingimport _bisectimport aifcimport hmacimport rlcompleterimport _blake2import antigravityimport htmlimport runpy#import appdirs#import html5libimport schedimport _bz2import argparseimport httpimport secretsimport _codecsimport arrayimport idnaimport selectimport _codecs_cnimport astimport imaplibimport selectorsimport _codecs_hkimport asynchatimport imghdrimport setuptoolsimport _codecs_iso2022import asyncioimport impimport shelveimport _codecs_jpimport asyncoreimport importlibimport shleximport _codecs_krimport atexitimport inspectimport shutilimport _codecs_twimport audioopimport ioimport signalimport _collectionsimport base64import ipaddressimport siteimport _collections_abcimport bdbimport itertoolsimport siximport _compat_pickleimport binasciiimport jsonimport smtpdimport _compressionimport binheximport keywordimport smtplibimport _contextvarsimport bisectimport lib2to3import sndhdrimport _cryptimport builtinsimport linecacheimport socketimport _csvimport bz2import localeimport socketserverimport _ctypesimport cProfile#import lockfileimport spwdimport _ctypes_test#import cachecontrolimport loggingimport sqlite3import _cursesimport calendarimport lzmaimport sre_compileimport _curses_panelimport certifiimport mailboximport sre_constantsimport _datetimeimport cgiimport mailcapimport sre_parseimport _dbmimport cgitb#import mainimport sslimport _decimal#import chardetimport marshalimport stat#import _dummy_threadimport chunkimport mathimport statisticsimport _elementtreeimport cmathimport mimetypesimport stringimport _functoolsimport cmdimport mmapimport stringprepimport _gdbmimport codeimport modulefinderimport structimport _hashlibimport codecs#import msgpackimport subprocessimport _heapqimport codeopimport multiprocessingimport sunauimport _impimport collectionsimport netrc#import symbolimport _io#import coloramaimport nntplibimport symtableimport _jsonimport colorsysimport ntpathimport sysimport _localeimport compileallimport nturl2pathimport sysconfigimport _lsprofimport concurrentimport numbersimport syslogimport _lzmaimport configparserimport numpyimport tabnannyimport _markupbaseimport contextlibimport opcodeimport tarfileimport _md5#import contextlib2import operatorimport telnetlibimport _multibytecodecimport contextvarsimport optparseimport tempfileimport _multiprocessingimport copy#import ordered_setimport termiosimport _opcodeimport copyregimport osimport textwrapimport _operatorimport cryptimport ossaudiodev#import thisimport _osx_supportimport csvimport packagingimport threadingimport _pickleimport ctypesimport pandasimport timeimport _posixshmemimport curses#import parserimport timeitimport _posixsubprocessimport dataclassesimport pathlibimport tokenimport _py_abcimport datetimeimport pdbimport tokenizeimport _pydecimalimport dateutil#import pep517#import tomlimport _pyioimport dbmimport pickleimport traceimport _queueimport decimalimport pickletoolsimport tracebackimport _randomimport difflibimport pipimport tracemallocimport _sha1import disimport pipesimport ttyimport _sha256#import distlibimport pkg_resourcesimport turtleimport _sha3#import distroimport pkgutilimport turtledemoimport _sha512import platformimport typesimport _signalimport doctestimport plistlibimport typingimport _sitebuiltins#import dummy_threadingimport poplibimport unicodedataimport _socketimport posiximport unittestimport _sqlite3import emailimport posixpathimport urllibimport _sreimport encodingsimport pprintimport urllib3import _sslimport ensurepipimport profileimport uuimport _statimport enum#import progressimport uuidimport _statisticsimport errnoimport pstatsimport venvimport _stringimport faulthandlerimport ptyimport warningsimport _strptimeimport fcntlimport pwdimport waveimport _structimport filecmpimport py_compileimport weakrefimport _symtableimport fileinputimport pyclbrimport webbrowserimport fnmatchimport pydoc#import webencodingsimport _testbuffer#import formatterimport pydoc_dataimport wsgirefimport _testcapiimport fractionsimport pyexpatimport xdrlibimport _testimportmultipleimport ftplibimport pyparsingimport xmlimport _testinternalcapiimport functools#import pytomlimport xmlrpcimport _testmultiphaseimport gcimport pytzimport xxlimitedimport _threadimport genericpathimport queueimport xxsubtypeimport _threading_localimport getoptimport quopriimport zipappimport _tracemallocimport getpassimport randomimport zipfileimport _warningsimport gettextimport reimport zipimportimport _weakrefimport globimport readlineimport zlib- from pkgutil import iter_modules
- m = [p.name for p in iter_modules()]
import codewars_test as test # TODO Write tests import solution # or from solution import example for x in solution.m: print(f"------------------{x}------------------------\n") print(dir(__import__(x)),'\n') test.expect(True)
- import codewars_test as test
- # TODO Write tests
- import solution # or from solution import example
with open(r"/workspace/solution.txt") as file:imports = [x.replace('import ','') for x in file.read().splitlines() if not '#' in x]for x in imports:- for x in solution.m:
- print(f"------------------{x}------------------------\n")
print(dir(x),'')- print(dir(__import__(x)),'
- ')
- test.expect(True)
removeEverySecond=\ lambda s:s[::2]
function removeEverySecond(str) {return [...str].filter((_,i) => !(i%2)).join``;}- removeEverySecond=\
- lambda s:s[::2]
@test.describe("Solution") def fixed_tests(): @test.it('should test for something') def basic_test_cases(): test.assert_equals(removeEverySecond('hello world'), 'hlowrd') test.assert_equals(removeEverySecond('how you doing'), 'hwyudig') test.assert_equals(removeEverySecond('abc'), 'ac') test.assert_equals(removeEverySecond(''), '') test.assert_equals(removeEverySecond('1234 56789 10112314'), '13 68 0134')
const chai = require("chai");const assert = chai.assert;describe("Solution", function() {it("should test for something", function() {assert.strictEqual(removeEverySecond('hello world'), 'hlowrd');assert.strictEqual(removeEverySecond('how you doing'), 'hwyudig');assert.strictEqual(removeEverySecond('abc'), 'ac');assert.strictEqual(removeEverySecond(''), '');assert.strictEqual(removeEverySecond('1234 56789 10112314'), '13 68 0134');});});- @test.describe("Solution")
- def fixed_tests():
- @test.it('should test for something')
- def basic_test_cases():
- test.assert_equals(removeEverySecond('hello world'), 'hlowrd')
- test.assert_equals(removeEverySecond('how you doing'), 'hwyudig')
- test.assert_equals(removeEverySecond('abc'), 'ac')
- test.assert_equals(removeEverySecond(''), '')
- test.assert_equals(removeEverySecond('1234 56789 10112314'), '13 68 0134')
Functional programming solution. I've also added an optional radix argument.
def base_digits(num, base): if num < base: return [num] return base_digits(num//base, base) + [num%base] def fixed_point(func, start): l = [start] while (n:=func(l[-1])) not in l: l.append(n) return n is_happy=lambda n,b=10:fixed_point(lambda x:sum(map(lambda y:y*y,base_digits(x,b))),n)==1
def is_happy(h: int, *, _unhappy={0}, _happy={1}) -> bool:"""Returns `True` if `h` is happy, `False` otherwise."""seen = set()while True:if h in _unhappy or h in seen:_unhappy.update(seen)return Falseelif h in _happy:_happy.update(seen)return Trueseen.add(h)tot = 0while h > 0:tot += pow(h % 10, 2)h //= 10h = tot- def base_digits(num, base):
- if num < base:
- return [num]
- return base_digits(num//base, base) + [num%base]
- def fixed_point(func, start):
- l = [start]
- while (n:=func(l[-1])) not in l:
- l.append(n)
- return n
- is_happy=lambda n,b=10:fixed_point(lambda x:sum(map(lambda y:y*y,base_digits(x,b))),n)==1
from math import sqrt primes = [2] def prime_checker(n): global primes for p in primes: if n == p: return True if n % p == 0: return False for c in range((l := primes[-1]) + l % 2 + 1, int(sqrt(n)), 2): if prime_checker(c): primes.append(c) if n % c == 0: return False return True
- from math import sqrt
- primes = [2]
- def prime_checker(n):
if n == 2: return Trueif n < 2 or n % 2 == 0: return Falsefor i in range(3, n, 2):if n % i == 0: return False- global primes
- for p in primes:
- if n == p:
- return True
- if n % p == 0:
- return False
- for c in range((l := primes[-1]) + l % 2 + 1, int(sqrt(n)), 2):
- if prime_checker(c):
- primes.append(c)
- if n % c == 0:
- return False
- return True
No longer in Julia, and the valid range is severely reduced, but now supports hyperbolic trig functions. I'm sure there's some trig identities that could improve this but I'm happy I got to use getattr
so it's fine for now.
import cmath as c;f=lambda a,b=None:c.pi*a if b==None else getattr(c,"a"*(b<0)+["sin","cos","tan"][abs(b)%4-1]+"h"*(abs(b)>4))(a)
○(x)=π*x;○(t,x)=try(atan,acos,asin,0,sin,cos,tan)[t+4](x)catch;(asin,acos)[-t](Complex(round(x)))end- import cmath as c;f=lambda a,b=None:c.pi*a if b==None else getattr(c,"a"*(b<0)+["sin","cos","tan"][abs(b)%4-1]+"h"*(abs(b)>4))(a)
from cmath import * from random import randrange @test.it("Tests") def tests(): for _ in range(20): n = randrange(-710,710) test.assert_equals(f(n),n*pi) test.assert_equals(f(n,1),sin(n)) test.assert_equals(f(n,2),cos(n)) test.assert_equals(f(n,3),tan(n)) test.assert_equals(f(n,5),sinh(n)) test.assert_equals(f(n,6),cosh(n)) test.assert_equals(f(n,7),tanh(n)) test.assert_equals(f(n,-1),asin(n)) test.assert_equals(f(n,-2),acos(n)) test.assert_equals(f(n,-3),atan(n)) test.assert_equals(f(n,-5),asinh(n)) test.assert_equals(f(n,-6),acosh(n)) test.assert_equals(f(n,-7),atanh(n))
# FactCheck example:# TODO: replace with your own tests (TDD), these are just how-to examples.using FactCheckfacts("Testing basics") dofor _0 = 1:20_1 = rand(-1000000:1000000)@fact ○(_1) --> _1*π@fact ○(1, _1) --> sin(_1)@fact ○(2, _1) --> cos(_1)@fact ○(3, _1) --> tan(_1)if abs(_1) <= 1@fact ○(-1, _1) --> asin(_1)@fact ○(-2, _1) --> acos(_1)else@fact ○(-1, _1) --> asin(Complex(round(_1)))@fact ○(-2, _1) --> acos(Complex(round(_1)))end@fact ○(-3, _1) --> atan(_1)endend- from cmath import *
- from random import randrange
- @test.it("Tests")
- def tests():
- for _ in range(20):
- n = randrange(-710,710)
- test.assert_equals(f(n),n*pi)
- test.assert_equals(f(n,1),sin(n))
- test.assert_equals(f(n,2),cos(n))
- test.assert_equals(f(n,3),tan(n))
- test.assert_equals(f(n,5),sinh(n))
- test.assert_equals(f(n,6),cosh(n))
- test.assert_equals(f(n,7),tanh(n))
- test.assert_equals(f(n,-1),asin(n))
- test.assert_equals(f(n,-2),acos(n))
- test.assert_equals(f(n,-3),atan(n))
- test.assert_equals(f(n,-5),asinh(n))
- test.assert_equals(f(n,-6),acosh(n))
- test.assert_equals(f(n,-7),atanh(n))
Small improvement to avoid redundant string concatenations.
def factorial(n: int) -> int: """Returns factorial of a non-negative integer.""" return eval("*".join(str(i) for i in range(2, n + 1)) or "1")
- def factorial(n: int) -> int:
- """Returns factorial of a non-negative integer."""
return eval("1" + "".join("*" + str(i) for i in range(2, n + 1)))- return eval("*".join(str(i) for i in range(2, n + 1)) or "1")
Probably not very well golfed but screw it one-liners are fun.
print((i:=__import__)("collections").Counter(k.select("i")[0]["class"][0][10:]for p in range(1,11)for k in i("bs4").BeautifulSoup(i("requests").get("http://codewars.com/kumite?page=%i"%p).content,"html.parser").select(".code-snippet-list-item")))
require "net/http"require "nokogiri"langs = {}langs.default = 0(1..10).each { |page|Nokogiri::XML(Net::HTTP.get(URI("https://www.codewars.com/kumite?page=#{page}"))).xpath("//div[contains(@class, 'flex flex-row items-center mb-4')]").each { |node|lang = node.xpath("string(./div[contains(@class, "\"'icon-container mb-0 bg-gray-200 dark:bg-k-20')]"\"/i/@class)")langs[lang[10...lang.length - 1]] += 1}}puts langs- print((i:=__import__)("collections").Counter(k.select("i")[0]["class"][0][10:]for p in range(1,11)for k in i("bs4").BeautifulSoup(i("requests").get("http://codewars.com/kumite?page=%i"%p).content,"html.parser").select(".code-snippet-list-item")))
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)
# From Ruby 3.0, RSpec is used under the hood.# See https://rspec.info/# Defaults to the global `describe` for backwards compatibility, but `RSpec.desribe` works as well.describe "Example" doit "should return the sum" doexpect(1 + 1).to eq(2)# The following is still supported, but new tests should now use them.# Test.assert_equals(add(1, 1), 2)endend- 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)
A (nearly) literal translation of the previous implementation. I'm convinced there's another way to go about this but I can't quite see it yet.
def intersec(a, b, threshold = 0.001): p = a.start - b.start q = b.end - b.start r = a.end - a.start t1 = p * q * (q * r) - p * r * (q * q) t2 = q * q * (r * r) - q * r * (r * q) t = t1 / t2 u1 = p * q + t * (r * q) u2 = q * q u = u1 / u2 e = a.start + r * t s = b.start + q * u c = e - s i = (e + s) / 2 if (i - a.start) * r < 0 or (i - a.end) * (a.start - a.end) < 0: raise Exception("point outside first segment bound") if (i - b.start) * q < 0 or (i - b.end) * (b.start - b.end) < 0: raise Exception("point outside second segment bound") if c * c - threshold > 0: raise Exception("no intersection point") return i
float scalar_product(Vector3D a, Vector3D b){return (a.get_x()*b.get_x() + a.get_y()*b.get_y() + a.get_z()*b.get_z());}Vector3D intersec(Segment a, Segment b){Segment seg;float t1 = 0, t2 = 0, t = 0;t1+= scalar_product(a.start-b.start, b.end-b.start)*scalar_product(b.end-b.start, a.end-a.start);t1-= scalar_product(a.start-b.start, a.end-a.start)*scalar_product(b.end-b.start, b.end-b.start);t2+= scalar_product(a.end-a.start, a.end-a.start)*scalar_product(b.end-b.start, b.end-b.start);t2-= scalar_product(a.end-a.start, b.end-b.start)*scalar_product(b.end-b.start, a.end-a.start);t = t1/t2;float u1 = 0, u2 = 0;u1+= (scalar_product(a.start-b.start, b.end-b.start));u1+= t*scalar_product(a.end-a.start, b.end-b.start);u2 = scalar_product(b.end-b.start, b.end-b.start);seg.end = a.start + (a.end - a.start)*t;seg.start = b.start + (b.end - b.start)*u1/u2;Vector3D tmp = seg.end - seg.start;Vector3D close_point = (seg.end + seg.start) / 2;try{if (scalar_product(close_point - a.start, a.end - a.start) < 0 ||scalar_product(close_point - a.end, a.start - a.end) < 0)throw std::string("point outside first segment bound");if (scalar_product(close_point - b.start, b.end - b.start) < 0 ||scalar_product(close_point - b.end, b.start - b.end) < 0)throw std::string("point outside second segment boundaries");if ((scalar_product(tmp, tmp) - 0.001) > 0)throw std::string("no intersection point");}catch(const std::string& ex){std::cerr << ex << '\n';exit(1);}return close_point;}- def intersec(a, b, threshold = 0.001):
- p = a.start - b.start
- q = b.end - b.start
- r = a.end - a.start
- t1 = p * q * (q * r) - p * r * (q * q)
- t2 = q * q * (r * r) - q * r * (r * q)
- t = t1 / t2
- u1 = p * q + t * (r * q)
- u2 = q * q
- u = u1 / u2
- e = a.start + r * t
- s = b.start + q * u
- c = e - s
- i = (e + s) / 2
- if (i - a.start) * r < 0 or (i - a.end) * (a.start - a.end) < 0:
- raise Exception("point outside first segment bound")
- if (i - b.start) * q < 0 or (i - b.end) * (b.start - b.end) < 0:
- raise Exception("point outside second segment bound")
- if c * c - threshold > 0:
- raise Exception("no intersection point")
- return i
@test.it("Tests") def tests(): test.assert_equals(intersec(Segment(Vector3D(1, 0, 0), Vector3D(-1, 0, 0)), Segment(Vector3D(0, 1, 1), Vector3D(0, -1, -1))), Vector3D(0, 0, 0))
Vector3D::Vector3D(){}Vector3D::Vector3D(float x, float y, float z):x(x), y(y), z(z){}Vector3D::Vector3D(const Vector3D &v): x(v.x), y(v.y), z(v.z){}const float Vector3D::get_x(){return x;}const float Vector3D::get_y(){return y;}const float Vector3D::get_z(){return z;}void Vector3D::set_x(float x){this->x = x;}void Vector3D::set_y(float y){this->y = y;}void Vector3D::set_z(float z){this->z = z;}Vector3D& Vector3D::operator=(const Vector3D &v){x = v.x;y = v.y;z = v.z;return *this;}Vector3D Vector3D::operator+(const Vector3D &v){return Vector3D(x+v.x, y+v.y, z+v.z);}Vector3D Vector3D::operator-(const Vector3D &v){return Vector3D(x-v.x, y-v.y, z-v.z);}Vector3D Vector3D::operator*(const float &value){return Vector3D(x*value, y*value, z*value);}Vector3D Vector3D::operator/(const float &value){return Vector3D(x/value, y/value, z/value);}Segment::Segment(){};Segment::Segment(Vector3D start, Vector3D end): start(start), end(end){}Describe(any_group_name_you_want){It(should_do_something){Assert::That("some value", Equals("another value"));}};- @test.it("Tests")
- def tests():
- test.assert_equals(intersec(Segment(Vector3D(1, 0, 0), Vector3D(-1, 0, 0)), Segment(Vector3D(0, 1, 1), Vector3D(0, -1, -1))), Vector3D(0, 0, 0))
Slight performance boost.
import math def prime_checker(n): if n == 1: return False max_divisor = math.floor(math.sqrt(n)) if n % 2 == 0: return False for d in range(3, 1 + max_divisor, 2): if n % d == 0: return False return True
- import math
- def prime_checker(n):
- if n == 1:
- return False
- max_divisor = math.floor(math.sqrt(n))
for d in range(2, 1 + max_divisor):- if n % 2 == 0:
- return False
- for d in range(3, 1 + max_divisor, 2):
- if n % d == 0:
- return False
- return True
class Dislexifier{ public static String theDislexifier(String str){ char[] a = str.toCharArray(); for(int i=0; i<a.length; i++){ int x = Character.toUpperCase(a[i]); if(x == 65 || x == 69 || x == 73 || x == 79) a[i] = (char)((x*(x*(31*x-6627)+468737)-10632765)/6720); } return new String(a); } }
class Dislexifier {private static final int l00kup = '1' | '0' << 8 | '4' << 16 | '3' << 24;private static final int v3r1fy = 'i' | 'o' << 8 | 'a' << 16 | 'e' << 24;public static String theDislexifier(String str) {char[] s0lut10n = str.toCharArray();for (int p0s = 0; p0s < s0lut10n.length; ++p0s) {int t3mp = s0lut10n[p0s] | 0x20;int h4sh = ((t3mp >> 4 ^ t3mp >> 2) & 3) << 3;if ((v3r1fy >> h4sh & 0xff) == t3mp) {s0lut10n[p0s] = (char) (l00kup >> h4sh & 0xff);}- class Dislexifier{
- public static String theDislexifier(String str){
- char[] a = str.toCharArray();
- for(int i=0; i<a.length; i++){
- int x = Character.toUpperCase(a[i]);
- if(x == 65 || x == 69 || x == 73 || x == 79)
- a[i] = (char)((x*(x*(31*x-6627)+468737)-10632765)/6720);
- }
- return new String(a);
- }
return new String(s0lut10n);}}- }
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest{ @Test public void testDislixifier(){ assertEquals("1'm s0 hungry 1 c0uld 34t 4 b34r rn",Dislexifier.theDislexifier("I'm so hungry I could eat a bear rn")); assertEquals("Wh4t 4r3 th000000s3???",Dislexifier.theDislexifier("What are thoooooose???")); assertEquals("",Dislexifier.theDislexifier("")); assertEquals("üüüü 1s just 4 f4ncy u, 4lth0ugh n0t 4s f4ncy 4s y0u",Dislexifier.theDislexifier("üüüü is just a fancy u, although not as fancy as you")); assertEquals("щф, l1t3r4lly just g00gl3d \"russ14n l3tt3rs\", th4t sh1dd's w31rd\"",Dislexifier.theDislexifier("щф, literally just googled \"russian letters\", that shidd's weird\"")); assertEquals("Try gypsy hymns rhythm !",Dislexifier.theDislexifier("Try gypsy hymns rhythm !")); } }
- import org.junit.Test;
- import static org.junit.Assert.assertEquals;
- import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD by writing your own testspublic class SolutionTest {- public class SolutionTest{
- @Test
public void testDislixifier() {assertEquals("1'm s0 hungry 1 c0uld 34t 4 b34r rn",Dislexifier.theDislexifier("I'm so hungry I could eat a bear rn"));assertEquals("Wh4t 4r3 th000000s3???",Dislexifier.theDislexifier("What are thoooooose???"));assertEquals("",Dislexifier.theDislexifier(""));assertEquals("üüüü 1s just 4 f4ncy u, 4lth0ugh n0t 4s f4ncy 4s y0u",Dislexifier.theDislexifier("üüüü is just a fancy u, although not as fancy as you"));assertEquals("щф, l1t3r4lly just g00gl3d \"russ14n l3tt3rs\", th4t sh1dd's w31rd\"",Dislexifier.theDislexifier("щф, literally just googled \"russian letters\", that shidd's weird\""));assertEquals("Try gypsy hymns rhythm !",Dislexifier.theDislexifier("Try gypsy hymns rhythm !"));- public void testDislixifier(){
- assertEquals("1'm s0 hungry 1 c0uld 34t 4 b34r rn",Dislexifier.theDislexifier("I'm so hungry I could eat a bear rn"));
- assertEquals("Wh4t 4r3 th000000s3???",Dislexifier.theDislexifier("What are thoooooose???"));
- assertEquals("",Dislexifier.theDislexifier(""));
- assertEquals("üüüü 1s just 4 f4ncy u, 4lth0ugh n0t 4s f4ncy 4s y0u",Dislexifier.theDislexifier("üüüü is just a fancy u, although not as fancy as you"));
- assertEquals("щф, l1t3r4lly just g00gl3d \"russ14n l3tt3rs\", th4t sh1dd's w31rd\"",Dislexifier.theDislexifier("щф, literally just googled \"russian letters\", that shidd's weird\""));
- assertEquals("Try gypsy hymns rhythm !",Dislexifier.theDislexifier("Try gypsy hymns rhythm !"));
- }
- }
Your base_to_dec
algorithm seemed to be largely unrelated to your convert_to_base
algorithm, had several other problems, and honestly seemed a bit overcomplicated. I've replaced both of these functions with a simple recursive approach, but if you can explain why your functions had the peculuarities they did, we can work to create a more tailored solution.
def dict_sort(dictionary): return sorted(dictionary, key=dictionary.__getitem__) def convert_to_base(decimal_number, base, digits): if decimal_number == 0: return '' return digits[decimal_number % base] + convert_to_base(decimal_number // base, base, digits) def base_to_dec(string, base, digits): if string == '': return 0 return digits.index(string[0]) + base_to_dec(string[1:], base, digits) * base class converter: def __init__(self, codec=None): if codec == None: self.codec = '' else: self.codec = codec def fit(self, strings): chars = {} if type(strings) == list: string = '\n'.join(strings) else: string = strings for x in string: if x not in chars: chars[x] = string.count(x) self.codec = ''.join(dict_sort(chars)) def stoi(self, string): return base_to_dec(string, len(self.codec), self.codec) def itos(self, number): return convert_to_base(number, len(self.codec), self.codec)
- def dict_sort(dictionary):
- return sorted(dictionary, key=dictionary.__getitem__)
- def convert_to_base(decimal_number, base, digits):
remainder_stack = []while decimal_number > 0:remainder = decimal_number % baseremainder_stack.append(remainder)decimal_number = decimal_number // basenew_digits = []while remainder_stack:new_digits.append(digits[remainder_stack.pop()])return ''.join(new_digits)- if decimal_number == 0:
- return ''
- return digits[decimal_number % base] + convert_to_base(decimal_number // base, base, digits)
- def base_to_dec(string, base, digits):
num_str = string[::-1]num = 0for k in range(len(num_str)):dig = num_str[k]if dig.isdigit():dig = int(dig)else:dig = digits.index(dig.lower())-digits.index('a')+10num += dig*(base**k)return int(num)- if string == '':
- return 0
- return digits.index(string[0]) + base_to_dec(string[1:], base, digits) * base
- class converter:
- def __init__(self, codec=None):
- if codec == None:
- self.codec = ''
- else:
- self.codec = codec
- def fit(self, strings):
- chars = {}
- if type(strings) == list:
- string = '\n'.join(strings)
- else:
- string = strings
- for x in string:
- if x not in chars:
- chars[x] = string.count(x)
- self.codec = ''.join(dict_sort(chars))
- def stoi(self, string):
- return base_to_dec(string, len(self.codec), self.codec)
- def itos(self, number):
- return convert_to_base(number, len(self.codec), self.codec)
import codewars_test as test # TODO Write tests import solution # or from solution import example # test.assert_equals(actual, expected, [optional] message) @test.describe("Basic tests") def test_group(): converter_var = converter() converter_var.fit('Hello World! I am a program!') test.assert_equals(converter_var.itos(converter_var.stoi('I am a program!')), 'I am a program!')
- import codewars_test as test
- # TODO Write tests
- import solution # or from solution import example
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Basic tests")
- def test_group():
- converter_var = converter()
- converter_var.fit('Hello World! I am a program!')
test.assert_equals(converter_var.itos(converter_var.stoi('I am a program!')))- test.assert_equals(converter_var.itos(converter_var.stoi('I am a program!')), 'I am a program!')
This implementation makes it fairly clear that this is an O(n log(n)) operation.
from math import log
def lsd(l,b):
s = l
for n in range(int(log(max(l),b))+1):
r = [[] for n in range(b)]
for x in s:
r[x//b**n%b].append(x)
s = [e for i in r for e in i]
return s
@test.describe("Tests")
def tests():
test.assert_equals(lsd([170, 45, 75, 90, 2, 802, 2, 66], 10), [2, 2, 45, 66, 75, 90, 170, 802])
Significantly simpler solution, assuming the passed lists are allowed to be altered.
def merge_lists(a, b): for i in range(len(a)+len(b)): if len(a) > i and len(b) > 0 and a[i] > b[0]: a.insert(i, b.pop(0)) return a + b
- def merge_lists(a, b):
"""takes two sorted lists, and merges them"""sorted_list = []# grab inital valuesa_i = 0b_i = 0# while lists are not emptywhile len(a) != a_i and len(b) != b_i:if a[a_i] < b[b_i]:sorted_list.append(a[a_i])a_i += 1else:sorted_list.append(b[b_i])b_i += 1# append whatever is remaining[sorted_list.append(i) for i in a[a_i:]][sorted_list.append(i) for i in b[b_i:]]return sorted_list- for i in range(len(a)+len(b)):
- if len(a) > i and len(b) > 0 and a[i] > b[0]:
- a.insert(i, b.pop(0))
- return a + b