WeixiangYan/CodeTransOcean huggingface dataset:
Task: Practical numbers




Go: package main

import (
    "fmt"
    "rcu"
)

func powerset(set []int) [][]int {
    if len(set) == 0 {
        return [][]int{{}}
    }
    head := set[0]
    tail := set[1:]
    p1 := powerset(tail)
    var p2 [][]int
    for _, s := range powerset(tail) {
        h := []int{head}
        h = append(h, s...)
        p2 = append(p2, h)
    }
    return append(p1, p2...)
}

func isPractical(n int) bool {
    if n == 1 {
        return true
    }
    divs := rcu.ProperDivisors(n)
    subsets := powerset(divs)
    found := make([]bool, n) 
    count := 0
    for _, subset := range subsets {
        sum := rcu.SumInts(subset)
        if sum > 0 && sum < n && !found[sum] {
            found[sum] = true
            count++
            if count == n-1 {
                return true
            }
        }
    }
    return false
}

func main() {
    fmt.Println("In the range 1..333, there are:")
    var practical []int
    for i := 1; i <= 333; i++ {
        if isPractical(i) {
            practical = append(practical, i)
        }
    }
    fmt.Println(" ", len(practical), "practical numbers")
    fmt.Println("  The first ten are", practical[0:10])
    fmt.Println("  The final ten are", practical[len(practical)-10:])
    fmt.Println("\n666 is practical:", isPractical(666))
}




Python: from itertools import chain, cycle, accumulate, combinations
from typing import List, Tuple



def factors5(n: int) -> List[int]:
    
    def prime_powers(n):
        
        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):
            if c*c > n: break
            if n%c: continue
            d,p = (), c
            while not n%c:
                n,p,d = n//c, p*c, d + (p,)
            yield(d)
        if n > 1: yield((n,))

    r = [1]
    for e in prime_powers(n):
        r += [a*b for a in r for b in e]
    return r[:-1]



def powerset(s: List[int]) -> List[Tuple[int, ...]]:
    
    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))



def is_practical(x: int) -> bool:
    
    if x == 1:
        return True
    if x %2:
        return False  
    f = factors5(x)
    ps = powerset(f)
    found = {y for y in {sum(i) for i in ps}
             if 1 <= y < x}
    return len(found) == x - 1


if __name__ == '__main__':
    n = 333
    p = [x for x in range(1, n + 1) if is_practical(x)]
    print(f"There are {len(p)} Practical numbers from 1 to {n}:")
    print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])
    x = 666
    print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
Task: Consecutive primes with ascending or descending differences




Go: package main

import (
    "fmt"
    "rcu"
)

const LIMIT = 999999

var primes = rcu.Primes(LIMIT)

func longestSeq(dir string) {
    pd := 0
    longSeqs := [][]int{{2}}
    currSeq := []int{2}
    for i := 1; i < len(primes); i++ {
        d := primes[i] - primes[i-1]
        if (dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd) {
            if len(currSeq) > len(longSeqs[0]) {
                longSeqs = [][]int{currSeq}
            } else if len(currSeq) == len(longSeqs[0]) {
                longSeqs = append(longSeqs, currSeq)
            }
            currSeq = []int{primes[i-1], primes[i]}
        } else {
            currSeq = append(currSeq, primes[i])
        }
        pd = d
    }
    if len(currSeq) > len(longSeqs[0]) {
        longSeqs = [][]int{currSeq}
    } else if len(currSeq) == len(longSeqs[0]) {
        longSeqs = append(longSeqs, currSeq)
    }
    fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":")
    for _, ls := range longSeqs {
        var diffs []int
        for i := 1; i < len(ls); i++ {
            diffs = append(diffs, ls[i]-ls[i-1])
        }
        for i := 0; i < len(ls)-1; i++ {
            fmt.Print(ls[i], " (", diffs[i], ") ")
        }
        fmt.Println(ls[len(ls)-1])
    }
    fmt.Println()
}

func main() {
    fmt.Println("For primes < 1 million:\n")
    for _, dir := range []string{"ascending", "descending"} {
        longestSeq(dir)
    }
}




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: Church numerals




Go: package main

import "fmt"

type any = interface{}

type fn func(any) any

type church func(fn) fn

func zero(f fn) fn {
    return func(x any) any {
        return x
    }
}

func (c church) succ() church {
    return func(f fn) fn {
        return func(x any) any {
            return f(c(f)(x))
        }
    }
}

func (c church) add(d church) church {
    return func(f fn) fn {
        return func(x any) any {
            return c(f)(d(f)(x))
        }
    }
}

func (c church) mul(d church) church {
    return func(f fn) fn {
        return func(x any) any {
            return c(d(f))(x)
        }
    }
}

func (c church) pow(d church) church {
    di := d.toInt()
    prod := c
    for i := 1; i < di; i++ {
        prod = prod.mul(c)
    }
    return prod
}

func (c church) toInt() int {
    return c(incr)(0).(int)
}

func intToChurch(i int) church {
    if i == 0 {
        return zero
    } else {
        return intToChurch(i - 1).succ()
    }
}

func incr(i any) any {
    return i.(int) + 1
}

func main() {
    z := church(zero)
    three := z.succ().succ().succ()
    four := three.succ()

    fmt.Println("three        ->", three.toInt())
    fmt.Println("four         ->", four.toInt())
    fmt.Println("three + four ->", three.add(four).toInt())
    fmt.Println("three * four ->", three.mul(four).toInt())
    fmt.Println("three ^ four ->", three.pow(four).toInt())
    fmt.Println("four ^ three ->", four.pow(three).toInt())
    fmt.Println("5 -> five    ->", intToChurch(5).toInt())
}




Python: 

from itertools import repeat
from functools import reduce




def churchZero():
    
    return lambda f: identity


def churchSucc(cn):
    
    return lambda f: compose(f)(cn(f))


def churchAdd(m):
    
    return lambda n: lambda f: compose(m(f))(n(f))


def churchMult(m):
    
    return lambda n: compose(m)(n)


def churchExp(m):
    
    return lambda n: n(m)


def churchFromInt(n):
    
    return lambda f: (
        foldl
        (compose)
        (identity)
        (replicate(n)(f))
    )



def churchFromInt_(n):
    
    if 0 == n:
        return churchZero()
    else:
        return churchSucc(churchFromInt(n - 1))


def intFromChurch(cn):
    
    return cn(succ)(0)




def main():
    'Tests'

    cThree = churchFromInt(3)
    cFour = churchFromInt(4)

    print(list(map(intFromChurch, [
        churchAdd(cThree)(cFour),
        churchMult(cThree)(cFour),
        churchExp(cFour)(cThree),
        churchExp(cThree)(cFour),
    ])))





def compose(f):
    
    return lambda g: lambda x: g(f(x))



def foldl(f):
    
    def go(acc, xs):
        return reduce(lambda a, x: f(a)(x), xs, acc)
    return lambda acc: lambda xs: go(acc, xs)



def identity(x):
    
    return x



def replicate(n):
    
    return lambda x: repeat(x, n)



def succ(x):
    
    return 1 + x if isinstance(x, int) else (
        chr(1 + ord(x))
    )


if __name__ == '__main__':
    main()
Task: Break OO privacy




Go: package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"reflect"
	"unsafe"
)

type foobar struct {
	Exported   int 
	unexported int 
}

func main() {
	obj := foobar{12, 42}
	fmt.Println("obj:", obj)

	examineAndModify(&obj)
	fmt.Println("obj:", obj)

	anotherExample()
}





func examineAndModify(any interface{}) {
	v := reflect.ValueOf(any) 
	v = v.Elem()              
	fmt.Println(" v:", v, "=", v.Interface())
	t := v.Type()
	
	fmt.Printf("    %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
	for i := 0; i < v.NumField(); i++ {
		f := v.Field(i) 
		fmt.Printf("    %2d: %-10s %-4s %t\n", i,
			t.Field(i).Name, f.Type(), f.CanSet())
	}

	
	v.Field(0).SetInt(16)
	
	
	
	

	
	
	
	vp := v.Field(1).Addr()            
	up := unsafe.Pointer(vp.Pointer()) 
	p := (*int)(up)                    
	fmt.Printf("  vp has type %-14T = %v\n", vp, vp)
	fmt.Printf("  up has type %-14T = %#0x\n", up, up)
	fmt.Printf("   p has type %-14T = %v pointing at %v\n", p, p, *p)
	*p = 43 
	
	*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++

	
	
	
	
	
	
	
}






func anotherExample() {
	r := bufio.NewReader(os.Stdin)

	
	errp := (*error)(unsafe.Pointer(
		reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
	*errp = errors.New("unsafely injected error value into bufio inner workings")

	_, err := r.ReadByte()
	fmt.Println("bufio.ReadByte returned error:", err)
}




Python: >>> class MyClassName:
	__private = 123
	non_private = __private * 2

	
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
  File "<pyshell
    mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
Task: Long year




Go: package main

import (
    "fmt"
    "time"
)

func main() {
    centuries := []string{"20th", "21st", "22nd"}
    starts := []int{1900, 2000, 2100} 
    for i := 0; i < len(centuries); i++ {
        var longYears []int
        fmt.Printf("\nLong years in the %s century:\n", centuries[i])
        for j := starts[i]; j < starts[i] + 100; j++ {
            t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)
            if _, week := t.ISOWeek(); week == 53 {
                longYears = append(longYears, j)
            }
        }
        fmt.Println(longYears)
    }
}




Python: 

from datetime import date



def longYear(y):
    
    return 52 < date(y, 12, 28).isocalendar()[1]




def main():
    
    for year in [
            x for x in range(2000, 1 + 2100)
            if longYear(x)
    ]:
        print(year)



if __name__ == '__main__':
    main()
Task: Zumkeller numbers




Go: package main

import "fmt"

func getDivisors(n int) []int {
    divs := []int{1, n}
    for i := 2; i*i <= n; i++ {
        if n%i == 0 {
            j := n / i
            divs = append(divs, i)
            if i != j {
                divs = append(divs, j)
            }
        }
    }
    return divs
}

func sum(divs []int) int {
    sum := 0
    for _, div := range divs {
        sum += div
    }
    return sum
}

func isPartSum(divs []int, sum int) bool {
    if sum == 0 {
        return true
    }
    le := len(divs)
    if le == 0 {
        return false
    }
    last := divs[le-1]
    divs = divs[0 : le-1]
    if last > sum {
        return isPartSum(divs, sum)
    }
    return isPartSum(divs, sum) || isPartSum(divs, sum-last)
}

func isZumkeller(n int) bool {
    divs := getDivisors(n)
    sum := sum(divs)
    
    if sum%2 == 1 {
        return false
    }
    
    if n%2 == 1 {
        abundance := sum - 2*n
        return abundance > 0 && abundance%2 == 0
    }
    
    return isPartSum(divs, sum/2)
}

func main() {
    fmt.Println("The first 220 Zumkeller numbers are:")
    for i, count := 2, 0; count < 220; i++ {
        if isZumkeller(i) {
            fmt.Printf("%3d ", i)
            count++
            if count%20 == 0 {
                fmt.Println()
            }
        }
    }
    fmt.Println("\nThe first 40 odd Zumkeller numbers are:")
    for i, count := 3, 0; count < 40; i += 2 {
        if isZumkeller(i) {
            fmt.Printf("%5d ", i)
            count++
            if count%10 == 0 {
                fmt.Println()
            }
        }
    }
    fmt.Println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:")
    for i, count := 3, 0; count < 40; i += 2 {
        if (i % 10 != 5) && isZumkeller(i) {
            fmt.Printf("%7d ", i)
            count++
            if count%8 == 0 {
                fmt.Println()
            }
        }
    }
    fmt.Println()
}




Python: from sympy import divisors

from sympy.combinatorics.subsets import Subset

def isZumkeller(n):
    d = divisors(n)
    s = sum(d)
    if not s % 2 and max(d) <= s/2:
        for x in range(1, 2**len(d)):
            if sum(Subset.unrank_binary(x, d).subset) == s/2:
                return True

    return False



def printZumkellers(N, oddonly=False):
    nprinted = 0
    for n in range(1, 10**5):
        if (oddonly == False or n % 2) and isZumkeller(n):
            print(f'{n:>8}', end='')
            nprinted += 1
            if nprinted % 10 == 0:
                print()
            if nprinted >= N:
                return


print("220 Zumkeller numbers:")
printZumkellers(220)
print("\n\n40 odd Zumkeller numbers:")
printZumkellers(40, True)
Task: Associative array_Merging




Go: package main

import "fmt"

type assoc map[string]interface{}

func merge(base, update assoc) assoc {
    result := make(assoc)
    for k, v := range base {
        result[k] = v
    }
    for k, v := range update {
        result[k] = v
    }
    return result
}

func main() {
    base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
    update := assoc{"price": 15.25, "color": "red", "year": 1974}
    result := merge(base, update)
    fmt.Println(result)
}




Python: base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}

result = {**base, **update}

print(result)
Task: Metallic ratios




Go: package main

import (
    "fmt"
    "math/big"
)

var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
    "Nickel", "Aluminium", "Iron", "Tin", "Lead"}

func lucas(b int64) {
    fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
    fmt.Print("First 15 elements: ")
    var x0, x1 int64 = 1, 1
    fmt.Printf("%d, %d", x0, x1)
    for i := 1; i <= 13; i++ {
        x2 := b*x1 + x0
        fmt.Printf(", %d", x2)
        x0, x1 = x1, x2
    }
    fmt.Println()
}

func metallic(b int64, dp int) {
    x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
    ratio := big.NewRat(1, 1)
    iters := 0
    prev := ratio.FloatString(dp)
    for {
        iters++
        x2.Mul(bb, x1)
        x2.Add(x2, x0)
        this := ratio.SetFrac(x2, x1).FloatString(dp)
        if prev == this {
            plural := "s"
            if iters == 1 {
                plural = " "
            }
            fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this)
            return
        }
        prev = this
        x0.Set(x1)
        x1.Set(x2)
    }
}

func main() {
    for b := int64(0); b < 10; b++ {
        lucas(b)
        metallic(b, 32)
    }
    fmt.Println("Golden ratio, where b = 1:")
    metallic(1, 256)
}




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: Associative array_Iteration




Go: myMap := map[string]int {
	   "hello": 13,
	   "world": 31,
	   "!"    : 71 }


for key, value := range myMap {
    fmt.Printf("key = %s, value = %d\n", key, value)
}


for key := range myMap {
    fmt.Printf("key = %s\n", key)
}


for _, value := range myMap {
    fmt.Printf("value = %d\n", value)
}




Python: myDict = { "hello": 13,
	   "world": 31,
	   "!"    : 71 }


for key, value in myDict.items():
    print ("key = %s, value = %s" % (key, value))


for key in myDict:
    print ("key = %s" % key)

for key in myDict.keys():
    print ("key = %s" % key)


for value in myDict.values():
    print ("value = %s" % value)
Task: Define a primitive data type




Go: package main

import "fmt"

type TinyInt int

func NewTinyInt(i int) TinyInt {
    if i < 1 {
        i = 1
    } else if i > 10 {
        i = 10
    }
    return TinyInt(i)
}

func (t1 TinyInt) Add(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) + int(t2))
}

func (t1 TinyInt) Sub(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) - int(t2))
}

func (t1 TinyInt) Mul(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) * int(t2))
}

func (t1 TinyInt) Div(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) / int(t2))
}

func (t1 TinyInt) Rem(t2 TinyInt) TinyInt {
    return NewTinyInt(int(t1) % int(t2))
}

func (t TinyInt) Inc() TinyInt {
    return t.Add(TinyInt(1))
}

func (t TinyInt) Dec() TinyInt {
    return t.Sub(TinyInt(1))
}

func main() {
    t1 := NewTinyInt(6)
    t2 := NewTinyInt(3)
    fmt.Println("t1      =", t1)
    fmt.Println("t2      =", t2)
    fmt.Println("t1 + t2 =", t1.Add(t2))
    fmt.Println("t1 - t2 =", t1.Sub(t2))
    fmt.Println("t1 * t2 =", t1.Mul(t2))
    fmt.Println("t1 / t2 =", t1.Div(t2))
    fmt.Println("t1 % t2 =", t1.Rem(t2))
    fmt.Println("t1 + 1  =", t1.Inc())
    fmt.Println("t1 - 1  =", t1.Dec())
}




Python: >>> class num(int):
    def __init__(self, b):
        if 1 <= b <= 10:
            return int.__init__(self+0)
        else:
            raise ValueError,"Value %s should be >=0 and <= 10" % b

        
>>> x = num(3)
>>> x = num(11)

Traceback (most recent call last):
  File "<pyshell
    x = num(11)
  File "<pyshell
    raise ValueError,"Value %s should be >=0 and <= 10" % b
ValueError: Value 11 should be >=0 and <= 10
>>> x
3
>>> type(x)
<class '__main__.num'>
>>>
Task: Arithmetic derivative




Go: package main

import (
    "fmt"
    "rcu"
)

func D(n float64) float64 {
    if n < 0 {
        return -D(-n)
    }
    if n < 2 {
        return 0
    }
    var f []int
    if n < 1e19 {
        f = rcu.PrimeFactors(int(n))
    } else {
        g := int(n / 100)
        f = rcu.PrimeFactors(g)
        f = append(f, []int{2, 2, 5, 5}...)
    }
    c := len(f)
    if c == 1 {
        return 1
    }
    if c == 2 {
        return float64(f[0] + f[1])
    }
    d := n / float64(f[0])
    return D(d)*float64(f[0]) + d
}

func main() {
    ad := make([]int, 200)
    for n := -99; n < 101; n++ {
        ad[n+99] = int(D(float64(n)))
    }
    rcu.PrintTable(ad, 10, 4, false)
    fmt.Println()
    pow := 1.0
    for m := 1; m < 21; m++ {
        pow *= 10
        fmt.Printf("D(10^%-2d) / 7 = %.0f\n", m, D(pow)/7)
    }
}




Python: from sympy.ntheory import factorint

def D(n):
    if n < 0:
        return -D(-n)
    elif n < 2:
        return 0
    else:
        fdict = factorint(n)
        if len(fdict) == 1 and 1 in fdict: 
            return 1
        return sum([n * e // p for p, e in fdict.items()])

for n in range(-99, 101):
    print('{:5}'.format(D(n)), end='\n' if n % 10 == 0 else '')

print()
for m in range(1, 21):
    print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))
Task: Permutations with some identical elements




Go: package main

import "fmt"

func shouldSwap(s []byte, start, curr int) bool {
    for i := start; i < curr; i++ {
        if s[i] == s[curr] {
            return false
        }
    }
    return true
}

func findPerms(s []byte, index, n int, res *[]string) {
    if index >= n {
        *res = append(*res, string(s))
        return
    }
    for i := index; i < n; i++ {
        check := shouldSwap(s, index, i)
        if check {
            s[index], s[i] = s[i], s[index]
            findPerms(s, index+1, n, res)
            s[index], s[i] = s[i], s[index]
        }
    }
}

func createSlice(nums []int, charSet string) []byte {
    var chars []byte
    for i := 0; i < len(nums); i++ {
        for j := 0; j < nums[i]; j++ {
            chars = append(chars, charSet[i])
        }
    }
    return chars
}

func main() {
    var res, res2, res3 []string
    nums := []int{2, 1}
    s := createSlice(nums, "12")
    findPerms(s, 0, len(s), &res)
    fmt.Println(res)
    fmt.Println()

    nums = []int{2, 3, 1}
    s = createSlice(nums, "123")
    findPerms(s, 0, len(s), &res2)
    fmt.Println(res2)
    fmt.Println()

    s = createSlice(nums, "ABC")
    findPerms(s, 0, len(s), &res3)
    fmt.Println(res3)
}




Python: 

from itertools import permutations

numList = [2,3,1]

baseList = []

for i in numList:
    for j in range(0,i):
        baseList.append(i)

stringDict = {'A':2,'B':3,'C':1}

baseString=""

for i in stringDict:
    for j in range(0,stringDict[i]):
        baseString+=i

print("Permutations for " + str(baseList) + " : ")
[print(i) for i in set(permutations(baseList))]

print("Permutations for " + baseString + " : ")
[print(i) for i in set(permutations(baseString))]