WeixiangYan/CodeTransOcean huggingface dataset:
Task: Polynomial synthetic division







Python: from __future__ import print_function
from __future__ import division




def extended_synthetic_division(dividend, divisor):
    
    

    out = list(dividend) 
    normalizer = divisor[0]
    for i in xrange(len(dividend)-(len(divisor)-1)):
        out[i] /= normalizer 
                                 
        coef = out[i]
        if coef != 0: 
            for j in xrange(1, len(divisor)): 
                                              
                out[i + j] += -divisor[j] * coef

    
    
    
    separator = -(len(divisor)-1)
    return out[:separator], out[separator:] 

if __name__ == '__main__':
    print("POLYNOMIAL SYNTHETIC DIVISION")
    N = [1, -12, 0, -42]
    D = [1, -3]
    print("  %s / %s  =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
Task: Color wheel







Python: size(300, 300)
background(0)
radius = min(width, height) / 2.0
cx, cy = width / 2, width / 2
for x in range(width):
        for y in range(height):
            rx = x - cx
            ry = y - cy
            s = sqrt(rx ** 2 + ry ** 2) / radius
            if s <= 1.0:
                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0
                colorMode(HSB)
                c = color(int(h * 255), int(s * 255), 255)
                set(x, y, c)
Task: Retrieve and search chat history







Python: 
import datetime
import re
import urllib.request
import sys

def get(url):
    with urllib.request.urlopen(url) as response:
       html = response.read().decode('utf-8')
    if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html):
        return None
    return html

def main():
    template = 'http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl'
    today = datetime.datetime.utcnow()
    back = 10
    needle = sys.argv[1]
    
    
    
    for i in range(-back, 2):
        day = today + datetime.timedelta(days=i)
        url = day.strftime(template)
        haystack = get(url)
        if haystack:
            mentions = [x for x in haystack.split('\n') if needle in x]
            if mentions:
                print('{}\n------\n{}\n------\n'
                          .format(url, '\n'.join(mentions)))

main()
Task: Find duplicate files







Python: from __future__ import print_function
import os
import hashlib
import datetime

def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"):
    knownFiles = {}

    
    for root, dirs, files in os.walk(pth):
        for fina in files:
            fullFina = os.path.join(root, fina)
            isSymLink = os.path.islink(fullFina)
            if isSymLink:
                continue 
            si = os.path.getsize(fullFina)
            if si < minSize:
                continue
            if si not in knownFiles:
                knownFiles[si] = {}
            h = hashlib.new(hashName)
            h.update(open(fullFina, "rb").read())
            hashed = h.digest()
            if hashed in knownFiles[si]:
                fileRec = knownFiles[si][hashed]
                fileRec.append(fullFina)
            else:
                knownFiles[si][hashed] = [fullFina]

    
    sizeList = list(knownFiles.keys())
    sizeList.sort(reverse=True)
    for si in sizeList:
        filesAtThisSize = knownFiles[si]
        for hashVal in filesAtThisSize:
            if len(filesAtThisSize[hashVal]) < 2:
                continue
            fullFinaLi = filesAtThisSize[hashVal]
            print ("=======Duplicate=======")
            for fullFina in fullFinaLi:
                st = os.stat(fullFina)
                isHardLink = st.st_nlink > 1 
                infoStr = []
                if isHardLink:
                    infoStr.append("(Hard linked)")
                fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')
                print (fmtModTime, si, os.path.relpath(fullFina, pth), " ".join(infoStr))

if __name__=="__main__":

    FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)
Task: Legendre prime counting function







Python: from primesieve import primes
from math import isqrt
from functools import cache

p = primes(isqrt(1_000_000_000))

@cache
def phi(x, a):
    res = 0
    while True:
        if not a or not x:
            return x + res
    
        a -= 1
        res -= phi(x//p[a], a) 

def legpi(n):
    if n < 2: return 0

    a = legpi(isqrt(n))
    return phi(n, a) + a - 1

for e in range(10):
    print(f'10^{e}', legpi(10**e))
Task: Palindromic gapful numbers







Python: from itertools import count
from pprint import pformat
import re
import heapq


def pal_part_gen(odd=True):
    for i in count(1):
        fwd = str(i)
        rev = fwd[::-1][1:] if odd else fwd[::-1]
        yield int(fwd + rev)

def pal_ordered_gen():
    yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))

def is_gapful(x):
    return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)

if __name__ == '__main__':
    start = 100
    for mx, last in [(20, 20), (100, 15), (1_000, 10)]:
        print(f"\nLast {last} of the first {mx} binned-by-last digit " 
              f"gapful numbers >= {start}")
        bin = {i: [] for i in range(1, 10)}
        gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))
        while any(len(val) < mx for val in bin.values()):
            g = next(gen)
            val = bin[g % 10]
            if len(val) < mx:
                val.append(g)
        b = {k:v[-last:] for k, v in bin.items()}
        txt = pformat(b, width=220)
        print('', re.sub(r"[{},\[\]]", '', txt))
Task: Chernick's Carmichael numbers







Python: 



from sympy import isprime



def primality_pretest(k):
    if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):
        return (k <= 23)
        
    return True

def is_chernick(n, m):

    t = 9 * m
    
    if not primality_pretest(6 * m + 1):
        return False
        
    if not primality_pretest(12 * m + 1):
        return False
        
    for i in range(1,n-1):
        if not primality_pretest((t << i) + 1):
            return False
        
    if not isprime(6 * m + 1):
        return False
        
    if not isprime(12 * m + 1):
        return False
        
    for i in range(1,n - 1):
        if not isprime((t << i) + 1):
            return False
        
    return True
    
for n in range(3,10):

    if n > 4:
        multiplier = 1 << (n - 4)
    else:
        multiplier = 1
    
    if n > 5:
        multiplier *= 5
        
        
    k = 1
    
    while True:
        m = k * multiplier
        
        if is_chernick(n, m): 
            print("a("+str(n)+") has m = "+str(m))
            break
            
        k += 1
Task: The sieve of Sundaram







Python: from numpy import log

def sieve_of_Sundaram(nth, print_all=True):
    
    assert nth > 0, "nth must be a positive integer"
    k = int((2.4 * nth * log(nth)) // 2)  
    integers_list = [True] * k
    for i in range(1, k):
        j = i
        while i + j + 2 * i * j < k:
            integers_list[i + j + 2 * i * j] = False
            j += 1
    pcount = 0
    for i in range(1, k + 1):
        if integers_list[i]:
            pcount += 1
            if print_all:
                print(f"{2 * i + 1:4}", end=' ')
                if pcount % 10 == 0:
                    print()

            if pcount == nth:
                print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n")
                break



sieve_of_Sundaram(100, True)

sieve_of_Sundaram(1000000, False)
Task: Consecutive primes with ascending or descending differences







Python: from sympy import sieve

primelist = list(sieve.primerange(2,1000000))

listlen = len(primelist)



pindex = 1
old_diff = -1
curr_list=[primelist[0]]
longest_list=[]

while pindex < listlen:

    diff = primelist[pindex] - primelist[pindex-1]
    if diff > old_diff:
        curr_list.append(primelist[pindex])
        if len(curr_list) > len(longest_list):
            longest_list = curr_list
    else:
        curr_list = [primelist[pindex-1],primelist[pindex]]
        
    old_diff = diff
    pindex += 1
    
print(longest_list)



pindex = 1
old_diff = -1
curr_list=[primelist[0]]
longest_list=[]

while pindex < listlen:

    diff = primelist[pindex] - primelist[pindex-1]
    if diff < old_diff:
        curr_list.append(primelist[pindex])
        if len(curr_list) > len(longest_list):
            longest_list = curr_list
    else:
        curr_list = [primelist[pindex-1],primelist[pindex]]
        
    old_diff = diff
    pindex += 1
    
print(longest_list)
Task: Verhoeff algorithm







Python: MULTIPLICATION_TABLE = [
    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
    (1, 2, 3, 4, 0, 6, 7, 8, 9, 5),
    (2, 3, 4, 0, 1, 7, 8, 9, 5, 6),
    (3, 4, 0, 1, 2, 8, 9, 5, 6, 7),
    (4, 0, 1, 2, 3, 9, 5, 6, 7, 8),
    (5, 9, 8, 7, 6, 0, 4, 3, 2, 1),
    (6, 5, 9, 8, 7, 1, 0, 4, 3, 2),
    (7, 6, 5, 9, 8, 2, 1, 0, 4, 3),
    (8, 7, 6, 5, 9, 3, 2, 1, 0, 4),
    (9, 8, 7, 6, 5, 4, 3, 2, 1, 0),
]

INV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9)

PERMUTATION_TABLE = [
    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
    (1, 5, 7, 6, 2, 8, 3, 0, 9, 4),
    (5, 8, 0, 3, 7, 9, 6, 1, 4, 2),
    (8, 9, 1, 6, 0, 4, 3, 5, 2, 7),
    (9, 4, 5, 3, 1, 2, 6, 8, 7, 0),
    (4, 2, 8, 6, 5, 7, 3, 9, 0, 1),
    (2, 7, 9, 3, 8, 0, 6, 4, 1, 5),
    (7, 0, 4, 6, 9, 1, 3, 2, 5, 8),
]

def verhoeffchecksum(n, validate=True, terse=True, verbose=False):
    
    if verbose:
        print(f"\n{'Validation' if validate else 'Check digit'}",\
            f"calculations for {n}:\n\n i  nᵢ  p[i,nᵢ]   c\n------------------")
    
    c, dig = 0, list(str(n if validate else 10 * n))
    for i, ni in enumerate(dig[::-1]):
        p = PERMUTATION_TABLE[i % 8][int(ni)]
        c = MULTIPLICATION_TABLE[c][p]
        if verbose:
            print(f"{i:2}  {ni}      {p}    {c}")

    if verbose and not validate:
        print(f"\ninv({c}) = {INV[c]}")
    if not terse:
        print(f"\nThe validation for '{n}' is {'correct' if c == 0 else 'incorrect'}."\
              if validate else f"\nThe check digit for '{n}' is {INV[c]}.")
    return c == 0 if validate else INV[c]

if __name__ == '__main__':

    for n, va, t, ve in [
        (236, False, False, True), (2363, True, False, True), (2369, True, False, True),
        (12345, False, False, True), (123451, True, False, True), (123459, True, False, True),
        (123456789012, False, False, False), (1234567890120, True, False, False),
        (1234567890129, True, False, False)]:
        verhoeffchecksum(n, va, t, ve)
Task: Padovan n-step number sequences







Python: def pad_like(max_n=8, t=15):
    
    start = [[], [1, 1, 1]]     
    for n in range(2, max_n+1):
        this = start[n-1][:n+1]     
        while len(this) < t:
            this.append(sum(this[i] for i in range(-2, -n - 2, -1)))
        start.append(this)
    return start[2:]

def pr(p):
    print(.strip())
    for n, seq in enumerate(p, 2):
        print(f"| {n:2} || {str(seq)[1:-1].replace(' ', '')+', ...'}\n|-")
    print('|}')

if __name__ == '__main__':
    p = pad_like()
    pr(p)
Task: Prime triangle







Python: from numpy import array

def is_prime(n: int) -> bool:
    assert n < 64
    return ((1 << n) & 0x28208a20a08a28ac) != 0

def prime_triangle_row(a: array, start: int, length: int) -> bool:
    if length == 2:
        return is_prime(a[0] + a[1])
    for i in range(1, length - 1, 1):
        if is_prime(a[start] + a[start + i]):
            a[start + i], a[start + 1] = a[start + 1], a[start + i]
            if prime_triangle_row(a, start + 1, length - 1):
                return True
            a[start + i], a[start + 1] = a[start + 1], a[start + i]
    return False

def prime_triangle_count(a: array, start: int, length: int) -> int:
    count: int = 0
    if length == 2:
        if is_prime(a[start] + a[start + 1]):
            count += 1
    else:
        for i in range(1, length - 1, 1):
            if is_prime(a[start] + a[start + i]):
                a[start + i], a[start + 1] = a[start + 1], a[start + i]
                count += prime_triangle_count(a, start + 1, length - 1)
                a[start + i], a[start + 1] = a[start + 1], a[start + i]
    return count

def print_row(a: array):
    if a == []:
        return
    print("%2d"% a[0], end=" ")
    for x in a[1:]:
        print("%2d"% x, end=" ")
    print()

for n in range(2, 21):
    tr: array = [_ for _ in range(1, n + 1)]
    if prime_triangle_row(tr, 0, n):
        print_row(tr)
print()
for n in range(2, 21):
    tr: array = [_ for _ in range(1, n + 1)]
    if n > 2:
        print(" ", end="")
    print(prime_triangle_count(tr, 0, n), end="")
print()
Task: XML validation







Python: 
from __future__ import print_function
import lxml
from lxml import etree

if __name__=="__main__":

	parser = etree.XMLParser(dtd_validation=True)
	schema_root = etree.XML()
	schema = etree.XMLSchema(schema_root)

	
	parser = etree.XMLParser(schema = schema)
	try:
		root = etree.fromstring("<a>5</a>", parser)
		print ("Finished validating good xml")
	except lxml.etree.XMLSyntaxError as err:
		print (err)

	
	parser = etree.XMLParser(schema = schema)
	try:
		root = etree.fromstring("<a>5<b>foobar</b></a>", parser)
	except lxml.etree.XMLSyntaxError as err:
		print (err)
Task: Own digits power sum







Python: 

def isowndigitspowersum(integer):
    
    digits = [int(c) for c in str(integer)]
    exponent = len(digits)
    return sum(x ** exponent for x in digits) == integer

print("Own digits power sums for N = 3 to 9 inclusive:")
for i in range(100, 1000000000):
    if isowndigitspowersum(i):
        print(i)
Task: Metallic ratios







Python: from itertools import count, islice
from _pydecimal import getcontext, Decimal

def metallic_ratio(b):
    m, n = 1, 1
    while True:
        yield m, n
        m, n = m*b + n, m

def stable(b, prec):
    def to_decimal(b):
        for m,n in metallic_ratio(b):
            yield Decimal(m)/Decimal(n)

    getcontext().prec = prec
    last = 0
    for i,x in zip(count(), to_decimal(b)):
        if x == last:
            print(f'after {i} iterations:\n\t{x}')
            break
        last = x

for b in range(4):
    coefs = [n for _,n in islice(metallic_ratio(b), 15)]
    print(f'\nb = {b}: {coefs}')
    stable(b, 32)

print(f'\nb = 1 with 256 digits:')
stable(1, 256)
Task: Repunit primes







Python: from sympy import isprime
for b in range(2, 17):
    print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
Task: Earliest difference between prime gaps







Python: 

from primesieve import primes

LIMIT = 10**9
pri = primes(LIMIT * 5)
gapstarts = {}
for i in range(1, len(pri)):
    if pri[i] - pri[i - 1] not in gapstarts:
        gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]

PM, GAP1, = 10, 2
while True:
    while GAP1 not in gapstarts:
        GAP1 += 2
    start1 = gapstarts[GAP1]
    GAP2 = GAP1 + 2
    if GAP2 not in gapstarts:
        GAP1 = GAP2 + 2
        continue
    start2 = gapstarts[GAP2]
    diff = abs(start2 - start1)
    if diff > PM:
        print(f"Earliest difference >{PM: ,} between adjacent prime gap starting primes:")
        print(f"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\n")
        if PM == LIMIT:
            break
        PM *= 10
    else:
        GAP1 = GAP2
Task: Monads_Writer monad







Python: 
from __future__ import annotations

import functools
import math
import os

from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union


T = TypeVar("T")


class Writer(Generic[T]):
    def __init__(self, value: Union[T, Writer[T]], *msgs: str):
        if isinstance(value, Writer):
            self.value: T = value.value
            self.msgs: List[str] = value.msgs + list(msgs)
        else:
            self.value = value
            self.msgs = list(f"{msg}: {self.value}" for msg in msgs)

    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
        writer = func(self.value)
        return Writer(writer, *self.msgs)

    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
        return self.bind(func)

    def __str__(self):
        return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}"

    def __repr__(self):
        return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")"


def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:
    

    @functools.wraps(func)
    def wrapped(value):
        return Writer(func(value), msg)

    return wrapped


if __name__ == "__main__":
    square_root = lift(math.sqrt, "square root")
    add_one = lift(lambda x: x + 1, "add one")
    half = lift(lambda x: x / 2, "div two")

    print(Writer(5, "initial") >> square_root >> add_one >> half)
Task: Word ladder







Python: import os,sys,zlib,urllib.request

def h ( str,x=9 ):
    for c in str :
        x = ( x*33 + ord( c )) & 0xffffffffff
    return x  

def cache ( func,*param ):
    n = 'cache_%x.bin'%abs( h( repr( param )))
    try    : return eval( zlib.decompress( open( n,'rb' ).read()))
    except : pass
    s = func( *param )
    open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))
    return s

dico_url  = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'
read_url  = lambda url   : urllib.request.urlopen( url ).read()
load_dico = lambda url   : tuple( cache( read_url,url ).split( b'\n'))
isnext    = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1

def build_map ( words ):
    map = [(w.decode('ascii'),[]) for w in words]
    for i1,(w1,n1) in enumerate( map ):
        for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):
            if isnext( w1,w2 ):
                n1.append( i2 )
                n2.append( i1 )
    return map

def find_path ( words,w1,w2 ):
    i = [w[0] for w in words].index( w1 )
    front,done,res  = [i],{i:-1},[]
    while front :
        i = front.pop(0)
        word,next = words[i]
        for n in next :
            if n in done : continue
            done[n] = i
            if words[n][0] == w2 :
                while n >= 0 :
                    res = [words[n][0]] + res
                    n = done[n]
                return ' '.join( res )
            front.append( n )
    return '%s can not be turned into %s'%( w1,w2 )

for w in ('boy man','girl lady','john jane','alien drool','child adult'):
    print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))
Task: Non-transitive dice







Python: from itertools import combinations_with_replacement as cmbr
from time import time
 
def dice_gen(n, faces, m):
    dice = list(cmbr(faces, n))
 
    succ = [set(j for j, b in enumerate(dice)
                    if sum((x>y) - (x<y) for x in a for y in b) > 0)
                for a in dice]
 
    def loops(seq):
        s = succ[seq[-1]]

        if len(seq) == m:
            if seq[0] in s: yield seq
            return

        for d in (x for x in s if x > seq[0] and not x in seq):
            yield from loops(seq + (d,))
 
    yield from (tuple(''.join(dice[s]) for s in x)
                    for i, v in enumerate(succ)
                    for x in loops((i,)))
 
t = time()
for n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]:
    for i, x in enumerate(dice_gen(n, faces, loop_len)): pass
 
    print(f'{n}-sided, markings {faces}, loop length {loop_len}:')
    print(f'\t{i + 1}*{loop_len} solutions, e.g. {" > ".join(x)} > [loop]')
    t, t0 = time(), t
    print(f'\ttime: {t - t0:.4f} seconds\n')
Task: ADFGVX cipher







Python: 

from random import shuffle, choice
from itertools import product, accumulate
from numpy import floor, sqrt

class ADFGVX:
    
    def __init__(self, spoly, k, alph='ADFGVX'):
        self.polybius = list(spoly.upper())
        self.pdim = int(floor(sqrt(len(self.polybius))))
        self.key = list(k.upper())
        self.keylen = len(self.key)
        self.alphabet = list(alph)
        pairs = [p[0] + p[1] for p in product(self.alphabet, self.alphabet)]
        self.encode = dict(zip(self.polybius, pairs))
        self.decode = dict((v, k) for (k, v) in self.encode.items())

    def encrypt(self, msg):
        
        chars = list(''.join([self.encode[c] for c in msg.upper() if c in self.polybius]))
        colvecs = [(lett, chars[i:len(chars):self.keylen]) \
            for (i, lett) in enumerate(self.key)]
        colvecs.sort(key=lambda x: x[0])
        return ''.join([''.join(a[1]) for a in colvecs])

    def decrypt(self, cod):
        
        chars = [c for c in cod if c in self.alphabet]
        sortedkey = sorted(self.key)
        order = [self.key.index(ch) for ch in sortedkey]
        originalorder = [sortedkey.index(ch) for ch in self.key]
        base, extra = divmod(len(chars), self.keylen)
        strides = [base + (1 if extra > i else 0) for i in order]    
        starts = list(accumulate(strides[:-1], lambda x, y: x + y))  
        starts = [0] + starts                                        
        ends = [starts[i] + strides[i] for i in range(self.keylen)]  
        cols = [chars[starts[i]:ends[i]] for i in originalorder]     
        pairs = []                                                   
        for i in range((len(chars) - 1) // self.keylen + 1):
            for j in range(self.keylen):
                if i * self.keylen + j < len(chars):
                    pairs.append(cols[j][i])

        return ''.join([self.decode[pairs[i] + pairs[i + 1]] for i in range(0, len(pairs), 2)])


if __name__ == '__main__':
    PCHARS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
    shuffle(PCHARS)
    POLYBIUS = ''.join(PCHARS)
    with open('unixdict.txt') as fh:
        WORDS = [w for w in (fh.read()).split() \
            if len(w) == 9 and len(w) == len(set(list(w)))]
        KEY = choice(WORDS)

    SECRET, MESSAGE = ADFGVX(POLYBIUS, KEY), 'ATTACKAT1200AM'
    print(f'Polybius: {POLYBIUS}, key: {KEY}')
    print('Message: ', MESSAGE)
    ENCODED = SECRET.encrypt(MESSAGE)
    DECODED = SECRET.decrypt(ENCODED)
    print('Encoded: ', ENCODED)
    print('Decoded: ', DECODED)
Task: Geohash







Python: ch32 = "0123456789bcdefghjkmnpqrstuvwxyz"
bool2ch = {f"{i:05b}": ch for i, ch in enumerate(ch32)}
ch2bool = {v : k for k, v in bool2ch.items()}

def bisect(val, mn, mx, bits):
    mid = (mn + mx) / 2
    if val < mid:
        bits <<= 1                        
        mx = mid                          
    else:
        bits = bits << 1 | 1              
        mn = mid                          

    return mn, mx, bits

def encoder(lat, lng, pre):
    latmin, latmax = -90, 90
    lngmin, lngmax = -180, 180
    bits = 0
    for i in range(pre * 5):
        if i % 2:
            
            latmin, latmax, bits = bisect(lat, latmin, latmax, bits)
        else:
            
            lngmin, lngmax, bits = bisect(lng, lngmin, lngmax, bits)
    
    b = f"{bits:0{pre * 5}b}"
    geo = (bool2ch[b[i*5: (i+1)*5]] for i in range(pre))

    return ''.join(geo)

def decoder(geo):
    minmaxes, latlong = [[-90.0, 90.0], [-180.0, 180.0]], True
    for c in geo:
        for bit in ch2bool[c]:
            minmaxes[latlong][bit != '1'] = sum(minmaxes[latlong]) / 2
            latlong = not latlong

    return minmaxes

if __name__ == '__main__':
    for (lat, lng), pre in [([51.433718, -0.214126],  2),
                            ([51.433718, -0.214126],  9),
                            ([57.64911,  10.40744] , 11),
                            ([57.64911,  10.40744] , 22)]:
        print("encoder(lat=%f, lng=%f, pre=%i) = %r"
              % (lat, lng, pre, encoder(lat, lng, pre)))
Task: Smallest numbers







Python: 

import sys

if len(sys.argv)!=2:
    print("Usage : python " + sys.argv[0] + " <whole number>")
    exit()

numLimit = int(sys.argv[1])

resultSet = {}

base = 1

while len(resultSet)!=numLimit:
    result = base**base

    for i in range(0,numLimit):
        if str(i) in str(result) and i not in resultSet:
            resultSet[i] = base

    base+=1

[print(resultSet[i], end=' ') for i in sorted(resultSet)]