WeixiangYan/CodeTransOcean huggingface dataset:
Task: Addition-chain exponentiation







Python: 

from math import sqrt
from numpy import array
from mpmath import mpf


class AdditionChains:
    

    def __init__(self):
        
        self.chains, self.idx, self.pos = [[1]], 0, 0
        self.pat, self.lvl = {1: 0}, [[1]]

    def add_chain(self):
        
        newchain = self.chains[self.idx].copy()
        newchain.append(self.chains[self.idx][-1] +
                        self.chains[self.idx][self.pos])
        self.chains.append(newchain)
        if self.pos == len(self.chains[self.idx])-1:
            self.idx += 1
            self.pos = 0
        else:
            self.pos += 1
        return newchain

    def find_chain(self, nexp):
        
        assert nexp > 0
        if nexp == 1:
            return [1]
        chn = next((a for a in self.chains if a[-1] == nexp), None)
        if chn is None:
            while True:
                chn = self.add_chain()
                if chn[-1] == nexp:
                    break

        return chn

    def knuth_path(self, ngoal):
        
        if ngoal < 1:
            return []
        while not ngoal in self.pat:
            new_lvl = []
            for i in self.lvl[0]:
                for j in self.knuth_path(i):
                    if not i + j in self.pat:
                        self.pat[i + j] = i
                        new_lvl.append(i + j)

            self.lvl[0] = new_lvl

        returnpath = self.knuth_path(self.pat[ngoal])
        returnpath.append(ngoal)
        return returnpath


def cpow(xbase, chain):
    
    pows, products = 0, {0: 1, 1: xbase}
    for i in chain:
        products[i] = products[pows] * products[i - pows]
        pows = i
    return products[chain[-1]]


if __name__ == '__main__':
    
    acs = AdditionChains()
    print('First one hundred addition chain lengths:')
    for k in range(1, 101):
        print(f'{len(acs.find_chain(k))-1:3}', end='\n'if k % 10 == 0 else '')

    print('\nKnuth chains for addition chains of 31415 and 27182:')
    chns = {m: acs.knuth_path(m) for m in [31415, 27182]}
    for (num, cha) in chns.items():
        print(f'Exponent: {num:10}\n  Addition Chain: {cha[:-1]}')
    print('\n1.00002206445416^31415 =', cpow(1.00002206445416, chns[31415]))
    print('1.00002550055251^27182 =', cpow(1.00002550055251, chns[27182]))
    print('1.000025 + 0.000058i)^27182 =',
          cpow(complex(1.000025, 0.000058), chns[27182]))
    print('1.000022 + 0.000050i)^31415 =',
          cpow(complex(1.000022, 0.000050), chns[31415]))
    sq05 = mpf(sqrt(0.5))
    mat = array([[sq05, 0, sq05, 0, 0, 0], [0, sq05, 0, sq05, 0, 0], [0, sq05, 0, -sq05, 0, 0],
                 [-sq05, 0, sq05, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0]])
    print('matrix A ^ 27182 =')
    print(cpow(mat, chns[27182]))
    print('matrix A ^ 31415 =')
    print(cpow(mat, chns[31415]))
    print('(matrix A ** 27182) ** 31415 =')
    print(cpow(cpow(mat, chns[27182]), chns[31415]))
Task: Execute SNUSP







Python: 

HW = r

def snusp(store, code):
    ds = bytearray(store)  
    dp = 0                 
    cs = code.splitlines() 
    ipr, ipc = 0, 0        
    for r, row in enumerate(cs):
        try:
            ipc = row.index('$')
            ipr = r
            break
        except ValueError:
            pass
    rt, dn, lt, up = range(4)
    id = rt  
    def step():
        nonlocal ipr, ipc
        if id&1:
            ipr += 1 - (id&2)
        else:
            ipc += 1 - (id&2)
    while ipr >= 0 and ipr < len(cs) and ipc >= 0 and ipc < len(cs[ipr]):
        op = cs[ipr][ipc]
        if op == '>':
            dp += 1
        elif op == '<':
            dp -= 1
        elif op == '+':
            ds[dp] += 1
        elif op == '-':
            ds[dp] -= 1
        elif op == '.':
            print(chr(ds[dp]), end='')
        elif op == ',':
            ds[dp] = input()
        elif op == '/':
            id = ~id
        elif op == '\\':
            id ^= 1
        elif op == '!':
            step()
        elif op == '?':
            if not ds[dp]:
                step()
        step()

if __name__ == '__main__':
    snusp(5, HW)
Task: O'Halloran numbers







Python: 

maxArea = 1000
halfMaxArea = 500
T = []                           
for i in range(halfMaxArea):
    T.append(True)               

for l in range(1,maxArea):
    for w in range(1, halfMaxArea):
        for h in range(1, halfMaxArea):
            suma = l*w + l*h + w*h
            if suma < halfMaxArea:
                T[suma] = False  

print("All known O'Halloran numbers:")
for l in range(3,halfMaxArea):
    if T[l]:
        print(l*2, end=" ");
Task: Calmo numbers







Python: 

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True

def isCalmo(n):
    limite = pow(n, 0.5)
    cont = 0
    SumD = 0
    SumQ = 0
    k = 0
    q = 0
    d = 2
    while d < limite:
        q = n/d
        if n % d == 0:
            cont += 1
            SumD += d
            SumQ += q
            if cont == 3:
                k += 3
                if not isPrime(SumD):
                    return False
                if not isPrime(SumQ):
                    return False
                cont = 0
                SumD = 0
                SumQ = 0
        d += 1
    if cont != 0 or k == 0:
        return False
    return True


if __name__ == "__main__":
    for n in range(1, 1000-1):
        if isCalmo(n):
            print(n, end=" ");
Task: Sieve of Pritchard







Python: 

from numpy import ndarray
from math import isqrt


def pritchard(limit):
    
    members = ndarray(limit + 1, dtype=bool)
    members.fill(False)
    members[1] = True
    steplength, prime, rtlim, nlimit = 1, 2, isqrt(limit), 2
    primes = []
    while prime <= rtlim:
        if steplength < limit:
            for w in range(1, len(members)):
                if members[w]:
                    n = w + steplength
                    while n <= nlimit:
                        members[n] = True
                        n += steplength
            steplength = nlimit

        np = 5
        mcpy = members.copy()
        for w in range(1, len(members)):
            if mcpy[w]:
                if np == 5 and w > prime:
                    np = w
                n = prime * w
                if n > nlimit:
                    break  
                members[n] = False  

        if np < prime:
            break
        primes.append(prime)
        prime = 3 if prime == 2 else np
        nlimit = min(steplength * prime, limit)  

    newprimes = [i for i in range(2, len(members)) if members[i]]
    return sorted(primes + newprimes)


print(pritchard(150))
print('Number of primes up to 1,000,000:', len(pritchard(1000000)))
Task: Even numbers which cannot be expressed as the sum of two twin primes







Python: 

from sympy import sieve


def nonpairsums(include1=False, limit=20_000):
    
    tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve)
            for i in range(limit+2)]
    if include1:
        tpri[1] = True
    twinsums = [False] * (limit * 2)
    for i in range(limit):
        for j in range(limit-i+1):
            if tpri[i] and tpri[j]:
                twinsums[i + j] = True

    return [i for i in range(2, limit+1, 2) if not twinsums[i]]


print('Non twin prime sums:')
for k, p in enumerate(nonpairsums()):
    print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')

print('\n\nNon twin prime sums (including 1):')
for k, p in enumerate(nonpairsums(include1=True)):
    print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')
Task: Zsigmondy numbers







Python: 

from math import gcd
from sympy import divisors


def zsig(num, aint, bint):
    
    assert aint > bint
    dexpms = [aint**i - bint**i for i in range(1, num)]
    dexpn = aint**num - bint**num
    return max([d for d in divisors(dexpn) if all(gcd(k, d) == 1 for k in dexpms)])


tests = [(2, 1), (3, 1), (4, 1), (5, 1), (6, 1),
         (7, 1), (3, 2), (5, 3), (7, 3), (7, 5)]
for (a, b) in tests:
    print(f'\nZsigmondy(n, {a}, {b}):', ', '.join(
        [str(zsig(n, a, b)) for n in range(1, 21)]))
Task: Meissel–Mertens constant







Python: 

from math import log

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True


if __name__ == '__main__':
    Euler = 0.57721566490153286
    m = 0
    for x in range(2, 10_000_000):
        if isPrime(x):
            m += log(1-(1/x)) + (1/x)

    print("MM =", Euler + m)
Task: Factor-perfect numbers







Python: 

from functools import cache
from sympy import divisors


def more_multiples(to_seq, from_seq):
    
    onemores = [to_seq + [i]
                for i in from_seq if i > to_seq[-1] and i % to_seq[-1] == 0]
    if len(onemores) == 0:
        return []
    for i in range(len(onemores)):
        for arr in more_multiples(onemores[i], from_seq):
            onemores.append(arr)
    return onemores


listing = [a + [48]
           for a in sorted(more_multiples([1], divisors(48)[1:-1]))] + [[1, 48]]
print('48 sequences using first definition:')
for j, seq in enumerate(listing):
    print(f'{str(seq):22}', end='\n' if (j + 1) % 4 == 0 else '')



print('\n48 sequences using second definition:')
for k, seq in enumerate(listing):
    seq2 = [seq[i] // seq[i - 1] for i in range(1, len(seq))]
    print(f'{str(seq2):20}', end='\n' if (k + 1) % 4 == 0 else '')


@cache
def erdos_factor_count(number):
    
    return sum(erdos_factor_count(number // d) for d in divisors(number)[1:-1]) + 1


print("\nOEIS A163272:  ", end='')
for num in range(2_400_000):
    if num == 0 or erdos_factor_count(num) == num:
        print(num, end=',  ')
Task: CalmoSoft primes







Python: from sympy import isprime, primerange

pri = list(primerange(1, 100))

lcal = sorted([pri[i:j] for j in range(len(pri), 0, -1)
          for i in range(len(pri)) if j > i and isprime(sum(pri[i:j]))], key=len)[-1]

print(f'Longest Calmo prime seq (length {len(lcal)}) of primes less than 100 is:\n{lcal}')
Task: Singular value decomposition







Python: from numpy import *
A = matrix([[3, 0], [4, 5]])
U, Sigma, VT = linalg.svd(A)
print(U)
print(Sigma)
print(VT)
Task: Selection bias in clinical sciences







Python: 


from random import randrange
from numpy.random import rand
from scipy.stats import kruskal

UNTREATED = 0
IRREGULAR = 1
REGULAR = 2
DOSE_FOR_REGULAR = 100


class Subject:
    

    def __init__(self):
        self.cum_dose = 0.0
        self.category = UNTREATED
        self.had_covid = False
        self.update_count = 0

    def update(self, p_covid=0.001, p_starting_treatment=0.005, p_redose=0.25, drange=(3, 10, 3)):
        
        if not self.had_covid:
            if rand() < p_covid:
                self.had_covid = True
            elif (self.cum_dose == 0 and rand() < p_starting_treatment) or\
                 (self.cum_dose > 0 and rand() < p_redose):
                self.cum_dose += randrange(*drange)
                self.categorize()
        self.update_count += 1

    def categorize(self):
        
        self.category = UNTREATED if self.cum_dose == 0 else REGULAR if\
            self.cum_dose >= DOSE_FOR_REGULAR else IRREGULAR
        return self.category


def run_study(num_subjects=1000, duration=180, interval=30):
    
    population = [Subject() for _ in range(num_subjects)]
    unt, unt_covid, irr, irr_covid, reg, reg_covid = 0, 0, 0, 0, 0, 0
    print(f'Total subjects: {num_subjects:,}')
    for day in range(duration):
        for subj in population:
            subj.update()

        if (day + 1) % interval == 0:
            print(f'\nDay {day + 1}:')
            unt = sum(s.category == UNTREATED for s in population)
            unt_covid = sum(s.category ==
                            UNTREATED and s.had_covid for s in population)
            print(f'Untreated: N = {unt}, with infection = {unt_covid}')
            irr = sum(s.category == IRREGULAR for s in population)
            irr_covid = sum(s.category ==
                            IRREGULAR and s.had_covid for s in population)
            print(f'Irregular Use: N = {irr}, with infection = {irr_covid}')
            reg = sum(s.category == REGULAR for s in population)
            reg_covid = sum(s.category ==
                            REGULAR and s.had_covid for s in population)
            print(f'Regular Use: N = {reg}, with infection = {reg_covid}')

        if day == duration // 2 - 1:
            print('\nAt midpoint, Infection case percentages are:')
            print('  Untreated : ', 100 * unt_covid / unt)
            print('  Irregulars: ', 100 * irr_covid / irr)
            print('  Regulars  : ', 100 * reg_covid / reg)

    print('\nAt study end, Infection case percentages are:')
    print(f'  Untreated : {100 * unt_covid / unt} of group size of {unt}')
    print(f'  Irregulars: {100 * irr_covid / irr} of group size of {irr}')
    print(f'  Regulars  : {100 * reg_covid / reg} of group size of {reg}')
    untreated = [
        s.had_covid for s in population if s.category == UNTREATED]
    irregular = [
        s.had_covid for s in population if s.category == IRREGULAR]
    regular = [s.had_covid for s in population if s.category == REGULAR]
    print('\nFinal statistics: ', kruskal(untreated, irregular, regular))


run_study()
Task: Visitor pattern







Python: 
from __future__ import annotations

from abc import ABC
from abc import abstractmethod


class CarElement(ABC):
    def accept(self, visitor: CarElementVisitor) -> None:
        visitor.visit(self)


class CarElementVisitor(ABC):
    @abstractmethod
    def visit(self, car_element: CarElement) -> None:
        


class Body(CarElement):
    


class Engine(CarElement):
    


class Wheel(CarElement):
    

    def __init__(self, name: str) -> None:
        self.name = name


class Car(CarElement):
    def __init__(self) -> None:
        self.elements: list[CarElement] = [
            Wheel("front left"),
            Wheel("front right"),
            Wheel("back left"),
            Wheel("back right"),
            Body(),
            Engine(),
        ]

    def accept(self, visitor: CarElementVisitor) -> None:
        for element in self.elements:
            visitor.visit(element)
        super().accept(visitor)


class CarElementDoVisitor(CarElementVisitor):
    def visit(self, car_element: CarElement) -> None:
        match car_element:
            case Body():
                print("Moving my body.")
            case Car():
                print("Starting my car.")
            case Wheel() as wheel:
                print(f"Kicking my {wheel.name} wheel.")
            case Engine():
                print("Starting my engine.")


class CarElementPrintVisitor(CarElementVisitor):
    def visit(self, car_element: CarElement) -> None:
        match car_element:
            case Body():
                print("Visiting body.")
            case Car():
                print("Visiting car.")
            case Wheel() as wheel:
                print(f"Visiting my {wheel.name} wheel.")
            case Engine():
                print("Visiting my engine.")


if __name__ == "__main__":
    car = Car()
    car.accept(CarElementPrintVisitor())
    car.accept(CarElementDoVisitor())
Task: Statistics_Chi-squared distribution







Python:  gamma function, accurate to about 12 decimal places  Chi-squared function, the probability distribution function (pdf) for chi-squared  lower incomplete gamma by series formula with gamma  Cumulative probability function (cdf) for chi-squared '''
    return gamma_cdf(k / 2, x / 2) if x > 0 and k > 0 else 0.0


print('x         χ2 k = 1           k = 2           k = 3           k = 4           k = 5')
print('-' * 93)
for x in range(11):
    print(f'{x:2}', end='')
    for k in range(1, 6):
        print(f'{χ2(x, k):16.8}', end='\n' if k % 5 == 0 else '')


print('\nχ2 x     P value (df=3)\n----------------------')
for p in [1, 2, 4, 8, 16, 32]:
    print(f'{p:2}', '    ', 1.0 - cdf_χ2(p, 3))


AIRPORT_DATA = [[77, 23], [88, 12], [79, 21], [81, 19]]

EXPECTED = [[81.25, 18.75],
            [81.25, 18.75],
            [81.25, 18.75],
            [81.25, 18.75]]

DTOTAL = sum((d[pos] - EXPECTED[i][pos])**2 / EXPECTED[i][pos]
             for i, d in enumerate(AIRPORT_DATA) for pos in [0, 1])

print(
    f'\nFor the airport data, diff total is {DTOTAL}, χ2 is {χ2(DTOTAL, 3)}, p value {cdf_χ2(DTOTAL, 3)}')
X = [x * 0.001 for x in range(10000)]
for k in range(5):
    plot(X, [χ2(p, k) for p in X])
legend([0, 1, 2, 3, 4])
ylim(-0.02, 0.5)
Task: Erdős–Woods numbers







Python: 

def erdős_woods(n):
    
    primes = []
    P = k = 1
    while k < n:
        if P % k:
            primes.append(k)
        P *= k * k
        k += 1
    divs = [
        int(''.join(str((a%p==0) + 0) for p in primes)[::-1], 2)
        for a in range(n)
    ]
    np = len(primes)
    partitions = [(0, 0, 2**np-1)]
    for i in sorted(
        range(1,n),
        key = lambda x: bin(divs[x] | divs[n-x])[::-1].find('1'),
        reverse=True
    ):
        new_partitions = []
        factors = divs[i]
        other_factors = divs[n-i]
        for p in partitions:
            set_a, set_b, r_primes = p
            if factors & set_a or other_factors & set_b:
                new_partitions += (p,)
                continue
            for ix, v in enumerate(bin(factors & r_primes)[2:][::-1]):
                if v=='1':
                    w = 1 << ix
                    new_partitions += ((set_a^w, set_b, r_primes^w),)
            for ix, v in enumerate(bin(other_factors & r_primes)[2:][::-1]):
                if v=='1':
                    w = 1 << ix
                    new_partitions += ((set_a, set_b^w, r_primes^w),)
        partitions = new_partitions
    result = float('inf')
    for px, py, _ in partitions:
        x = y = 1
        for p in primes:
            if px % 2:
                x *= p
            if py % 2:
                y *= p
            px //= 2
            py //= 2
        result = min(result, n*pow(x,-1,y)%y*x-n)
    return result


K = 3
COUNT = 0
print('The first 20 Erdős–Woods numbers and their minimum interval start values are:')
while COUNT < 20:
    a = erdős_woods(K)
    if a != float('inf'):
        print(f"{K: 3d} -> {a}")
        COUNT += 1
    K += 1
Task: Upside-down numbers







Python: 


def gen_upside_down_number():
    
    wrappings = [[1, 9], [2, 8], [3, 7], [4, 6],
                 [5, 5], [6, 4], [7, 3], [8, 2], [9, 1]]
    evens = [19, 28, 37, 46, 55, 64, 73, 82, 91]
    odds = [5]
    odd_index, even_index = 0, 0
    ndigits = 1
    while True:
        if ndigits % 2 == 1:
            if len(odds) > odd_index:
                yield odds[odd_index]
                odd_index += 1
            else:
                
                odds = [hi * 10**(ndigits + 1) + 10 *
                        i + lo for hi, lo in wrappings for i in odds]
                ndigits += 1
                odd_index = 0
        else:
            if len(evens) > even_index:
                yield evens[even_index]
                even_index += 1
            else:
                
                evens = [hi * 10**(ndigits + 1) + 10 *
                         i + lo for hi, lo in wrappings for i in evens]
                ndigits += 1
                even_index = 0     even_index = 0


print('First fifty upside-downs:')
for (udcount, udnumber) in enumerate(gen_upside_down_number()):
    if udcount < 50:
        print(f'{udnumber : 5}', end='\n' if (udcount + 1) % 10 == 0 else '')
    elif udcount == 499:
        print(f'\nFive hundredth: {udnumber: ,}')
    elif udcount == 4999:
        print(f'\nFive thousandth: {udnumber: ,}')
    elif udcount == 49_999:
        print(f'\nFifty thousandth: {udnumber: ,}')
    elif udcount == 499_999:
        print(f'\nFive hundred thousandth: {udnumber: ,}')
    elif udcount == 4_999_999:
        print(f'\nFive millionth: {udnumber: ,}')
        break
Task: LZW compression








VB: Option Explicit
Const numchars=127  

Function LZWCompress(si)
  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j
  Set oDict = CreateObject("Scripting.Dictionary")
  ReDim a(Len(si))
  
  intMaxCode = numchars
  For i = 0 To numchars
    oDict.Add Chr(i), i
  Next
  
  strCurrent = Left(si,1)
  j=0
  For ii=2 To Len(si)
    strNext = Mid(si,ii,1)
    ss=strCurrent & strNext
    If oDict.Exists(ss) Then
      strCurrent = ss
    Else
      a(j)=oDict.Item(strCurrent) :j=j+1
      intMaxCode = intMaxCode + 1
      oDict.Add ss, intMaxCode
      strCurrent = strNext
    End If
  Next
  a(j)=oDict.Item(strCurrent) 
  ReDim preserve a(j)
  LZWCompress=a
  Set oDict = Nothing
End Function

Function lzwUncompress(sc)
  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j
  s=""     
  reDim dict(1000)
  intMaxCode = numchars
  For i = 0 To numchars : dict(i)= Chr(i) :  Next
    intCurrent=sc(0)
    
    For j=1 To UBound(sc)
      ss=dict(intCurrent)
      s= s & ss
      intMaxCode = intMaxCode + 1
      intnext=sc(j)
      If intNext<intMaxCode Then
        dict(intMaxCode)=ss & Left(dict(intNext), 1)
      Else
        dict(intMaxCode)=ss & Left(ss, 1) 
      End If
      intCurrent = intNext
    Next
    s= s & dict(intCurrent)
    lzwUncompress=s
End function

Sub printvec(a)
  Dim s,i,x
  s="("
  For i=0 To UBound (a)
   s=s & x & a(i)
   x=", "
  Next 
  WScript.echo s &")"
End sub

Dim a,b
b="TOBEORNOTTOBEORTOBEORNOT"
WScript.Echo b
a=LZWCompress (b)
printvec(a)
WScript.echo lzwUncompress (a )
wscript.quit 1




Ada: package LZW is

   MAX_CODE : constant := 4095;

   type Codes is new Natural range 0 .. MAX_CODE;
   type Compressed_Data is array (Positive range <>) of Codes;

   function Compress (Cleartext : in String) return Compressed_Data;
   function Decompress (Data : in Compressed_Data) return String;

end LZW;