Ad

Recursion can do anything!

Code
Diff
  • 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;
    • }
    • }
    • }
Fundamentals
Code
Diff
  • from pkgutil import iter_modules
    
    m = [p.name for p in iter_modules()]
    • import __future__
    • import _weakrefset
    • import grp
    • import reprlib
    • import _abc
    • import _xxsubinterpreters
    • import gzip
    • import requests
    • import _ast
    • import _xxtestfuzz
    • import hashlib
    • import resource
    • import _asyncio
    • import abc
    • import heapq
    • # import retrying
    • import _bisect
    • import aifc
    • import hmac
    • import rlcompleter
    • import _blake2
    • import antigravity
    • import html
    • import runpy
    • #import appdirs
    • #import html5lib
    • import sched
    • import _bz2
    • import argparse
    • import http
    • import secrets
    • import _codecs
    • import array
    • import idna
    • import select
    • import _codecs_cn
    • import ast
    • import imaplib
    • import selectors
    • import _codecs_hk
    • import asynchat
    • import imghdr
    • import setuptools
    • import _codecs_iso2022
    • import asyncio
    • import imp
    • import shelve
    • import _codecs_jp
    • import asyncore
    • import importlib
    • import shlex
    • import _codecs_kr
    • import atexit
    • import inspect
    • import shutil
    • import _codecs_tw
    • import audioop
    • import io
    • import signal
    • import _collections
    • import base64
    • import ipaddress
    • import site
    • import _collections_abc
    • import bdb
    • import itertools
    • import six
    • import _compat_pickle
    • import binascii
    • import json
    • import smtpd
    • import _compression
    • import binhex
    • import keyword
    • import smtplib
    • import _contextvars
    • import bisect
    • import lib2to3
    • import sndhdr
    • import _crypt
    • import builtins
    • import linecache
    • import socket
    • import _csv
    • import bz2
    • import locale
    • import socketserver
    • import _ctypes
    • import cProfile
    • #import lockfile
    • import spwd
    • import _ctypes_test
    • #import cachecontrol
    • import logging
    • import sqlite3
    • import _curses
    • import calendar
    • import lzma
    • import sre_compile
    • import _curses_panel
    • import certifi
    • import mailbox
    • import sre_constants
    • import _datetime
    • import cgi
    • import mailcap
    • import sre_parse
    • import _dbm
    • import cgitb
    • #import main
    • import ssl
    • import _decimal
    • #import chardet
    • import marshal
    • import stat
    • #import _dummy_thread
    • import chunk
    • import math
    • import statistics
    • import _elementtree
    • import cmath
    • import mimetypes
    • import string
    • import _functools
    • import cmd
    • import mmap
    • import stringprep
    • import _gdbm
    • import code
    • import modulefinder
    • import struct
    • import _hashlib
    • import codecs
    • #import msgpack
    • import subprocess
    • import _heapq
    • import codeop
    • import multiprocessing
    • import sunau
    • import _imp
    • import collections
    • import netrc
    • #import symbol
    • import _io
    • #import colorama
    • import nntplib
    • import symtable
    • import _json
    • import colorsys
    • import ntpath
    • import sys
    • import _locale
    • import compileall
    • import nturl2path
    • import sysconfig
    • import _lsprof
    • import concurrent
    • import numbers
    • import syslog
    • import _lzma
    • import configparser
    • import numpy
    • import tabnanny
    • import _markupbase
    • import contextlib
    • import opcode
    • import tarfile
    • import _md5
    • #import contextlib2
    • import operator
    • import telnetlib
    • import _multibytecodec
    • import contextvars
    • import optparse
    • import tempfile
    • import _multiprocessing
    • import copy
    • #import ordered_set
    • import termios
    • import _opcode
    • import copyreg
    • import os
    • import textwrap
    • import _operator
    • import crypt
    • import ossaudiodev
    • #import this
    • import _osx_support
    • import csv
    • import packaging
    • import threading
    • import _pickle
    • import ctypes
    • import pandas
    • import time
    • import _posixshmem
    • import curses
    • #import parser
    • import timeit
    • import _posixsubprocess
    • import dataclasses
    • import pathlib
    • import token
    • import _py_abc
    • import datetime
    • import pdb
    • import tokenize
    • import _pydecimal
    • import dateutil
    • #import pep517
    • #import toml
    • import _pyio
    • import dbm
    • import pickle
    • import trace
    • import _queue
    • import decimal
    • import pickletools
    • import traceback
    • import _random
    • import difflib
    • import pip
    • import tracemalloc
    • import _sha1
    • import dis
    • import pipes
    • import tty
    • import _sha256
    • #import distlib
    • import pkg_resources
    • import turtle
    • import _sha3
    • #import distro
    • import pkgutil
    • import turtledemo
    • import _sha512
    • import platform
    • import types
    • import _signal
    • import doctest
    • import plistlib
    • import typing
    • import _sitebuiltins
    • #import dummy_threading
    • import poplib
    • import unicodedata
    • import _socket
    • import posix
    • import unittest
    • import _sqlite3
    • import email
    • import posixpath
    • import urllib
    • import _sre
    • import encodings
    • import pprint
    • import urllib3
    • import _ssl
    • import ensurepip
    • import profile
    • import uu
    • import _stat
    • import enum
    • #import progress
    • import uuid
    • import _statistics
    • import errno
    • import pstats
    • import venv
    • import _string
    • import faulthandler
    • import pty
    • import warnings
    • import _strptime
    • import fcntl
    • import pwd
    • import wave
    • import _struct
    • import filecmp
    • import py_compile
    • import weakref
    • import _symtable
    • import fileinput
    • import pyclbr
    • import webbrowser
    • import fnmatch
    • import pydoc
    • #import webencodings
    • import _testbuffer
    • #import formatter
    • import pydoc_data
    • import wsgiref
    • import _testcapi
    • import fractions
    • import pyexpat
    • import xdrlib
    • import _testimportmultiple
    • import ftplib
    • import pyparsing
    • import xml
    • import _testinternalcapi
    • import functools
    • #import pytoml
    • import xmlrpc
    • import _testmultiphase
    • import gc
    • import pytz
    • import xxlimited
    • import _thread
    • import genericpath
    • import queue
    • import xxsubtype
    • import _threading_local
    • import getopt
    • import quopri
    • import zipapp
    • import _tracemalloc
    • import getpass
    • import random
    • import zipfile
    • import _warnings
    • import gettext
    • import re
    • import zipimport
    • import _weakref
    • import glob
    • import readline
    • import zlib
    • from pkgutil import iter_modules
    • m = [p.name for p in iter_modules()]
Code
Diff
  • RandomBool=lambda:id(object())&1==0
    • RandomBool=lambda:id(object())%2==0
    • RandomBool=lambda:id(object())&1==0
Strings
Data Types
Code
Diff
  • removeEverySecond=\
    lambda s:s[::2]
    • function removeEverySecond(str) {
    • return [...str].filter((_,i) => !(i%2)).join``;
    • }
    • removeEverySecond=\
    • lambda s:s[::2]
Mathematics
Algorithms
Logic
Numbers
Data Types

Functional programming solution. I've also added an optional radix argument.

Code
Diff
  • 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 False
    • elif h in _happy:
    • _happy.update(seen)
    • return True
    • seen.add(h)
    • tot = 0
    • while h > 0:
    • tot += pow(h % 10, 2)
    • h //= 10
    • h = 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
Mathematics
Algorithms
Logic
Numbers
Code
Diff
  • 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 True
    • if n < 2 or n % 2 == 0: return False
    • for 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.

Code
Diff
  • 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)

Small improvement to avoid redundant string concatenations.

Code
Diff
  • 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.

Code
Diff
  • 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")))

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.

Code
Diff
  • 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
Mathematics
Algorithms
Logic
Numbers

Slight performance boost.

Code
Diff
  • 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
Strings
Data Types
Code
Diff
  • 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);
    • }
    • }
    • }

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.

Code
Diff
  • 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 % base
    • remainder_stack.append(remainder)
    • decimal_number = decimal_number // base
    • new_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 = 0
    • for 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')+10
    • num += 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)

Read on Wikipedia.

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

Significantly simpler solution, assuming the passed lists are allowed to be altered.

Code
Diff
  • 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 values
    • a_i = 0
    • b_i = 0
    • # while lists are not empty
    • while len(a) != a_i and len(b) != b_i:
    • if a[a_i] < b[b_i]:
    • sorted_list.append(a[a_i])
    • a_i += 1
    • else:
    • 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
Loading more items...