WeixiangYan/CodeTransOcean huggingface dataset:
Task: Determinant and permanent




Go: package main

import (
    "fmt"
    "permute"
)

func determinant(m [][]float64) (d float64) {
    p := make([]int, len(m))
    for i := range p {
        p[i] = i
    }
    it := permute.Iter(p)
    for s := it(); s != 0; s = it() {
        pr := 1.
        for i, σ := range p {
            pr *= m[i][σ]
        }
        d += float64(s) * pr
    }
    return
}

func permanent(m [][]float64) (d float64) {
    p := make([]int, len(m))
    for i := range p {
        p[i] = i
    }
    it := permute.Iter(p)
    for s := it(); s != 0; s = it() {
        pr := 1.
        for i, σ := range p {
            pr *= m[i][σ]
        }
        d += pr
    }
    return
}

var m2 = [][]float64{
    {1, 2},
    {3, 4}}

var m3 = [][]float64{
    {2, 9, 4},
    {7, 5, 3},
    {6, 1, 8}}

func main() {
    fmt.Println(determinant(m2), permanent(m2))
    fmt.Println(determinant(m3), permanent(m3))
}




Python: from itertools import permutations
from operator import mul
from math import fsum
from spermutations import spermutations

def prod(lst):
    return reduce(mul, lst, 1)

def perm(a):
    n = len(a)
    r = range(n)
    s = permutations(r)
    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)

def det(a):
    n = len(a)
    r = range(n)
    s = spermutations(n)
    return fsum(sign * prod(a[i][sigma[i]] for i in r)
                for sigma, sign in s)

if __name__ == '__main__':
    from pprint import pprint as pp

    for a in ( 
            [
             [1, 2], 
             [3, 4]], 

            [
             [1, 2, 3, 4],
             [4, 5, 6, 7],
             [7, 8, 9, 10],
             [10, 11, 12, 13]],        

            [
             [ 0,  1,  2,  3,  4],
             [ 5,  6,  7,  8,  9],
             [10, 11, 12, 13, 14],
             [15, 16, 17, 18, 19],
             [20, 21, 22, 23, 24]],
        ):
        print('')
        pp(a)
        print('Perm: %s Det: %s' % (perm(a), det(a)))
Task: Partition function P




Go: package main

import (
    "fmt"
    "math/big"
    "time"
)

var p []*big.Int
var pd []int

func partDiffDiff(n int) int {
    if n&1 == 1 {
        return (n + 1) / 2
    }
    return n + 1
}

func partDiff(n int) int {
    if n < 2 {
        return 1
    }
    pd[n] = pd[n-1] + partDiffDiff(n-1)
    return pd[n]
}

func partitionsP(n int) {
    if n < 2 {
        return
    }
    psum := new(big.Int)
    for i := 1; i <= n; i++ {
        pdi := partDiff(i)
        if pdi > n {
            break
        }
        sign := int64(-1)
        if (i-1)%4 < 2 {
            sign = 1
        }
        t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))
        psum.Add(psum, t)
    }
    p[n] = psum
}

func main() {
    start := time.Now()
    const N = 6666
    p = make([]*big.Int, N+1)
    pd = make([]int, N+1)
    p[0], pd[0] = big.NewInt(1), 1
    p[1], pd[1] = big.NewInt(1), 1
    for n := 2; n <= N; n++ {
        partitionsP(n)
    }
    fmt.Printf("p[%d)] = %d\n", N, p[N])
    fmt.Printf("Took %s\n", time.Since(start))
}




Python: from itertools import islice

def posd():
    "diff between position numbers. 1, 2, 3... interleaved with  3, 5, 7..."
    count, odd = 1, 3
    while True:
        yield count
        yield odd
        count, odd = count + 1, odd + 2

def pos_gen():
    "position numbers. 1 3 2 5 7 4 9 ..."
    val = 1
    diff = posd()
    while True:
        yield val
        val += next(diff)
                
def plus_minus():
    "yield (list_offset, sign) or zero for Partition calc"
    n, sign = 0, [1, 1]
    p_gen = pos_gen()
    out_on = next(p_gen)
    while True:
        n += 1
        if n == out_on:
            next_sign = sign.pop(0)
            if not sign:
                sign = [-next_sign] * 2
            yield -n, next_sign
            out_on = next(p_gen)
        else:
            yield 0
            
def part(n):
    "Partition numbers"
    p = [1]
    p_m = plus_minus()
    mods = []
    for _ in range(n):
        next_plus_minus = next(p_m)
        if next_plus_minus:
            mods.append(next_plus_minus)
        p.append(sum(p[offset] * sign for offset, sign in mods))
    return p[-1]
        
print("(Intermediaries):")
print("    posd:", list(islice(posd(), 10)))
print("    pos_gen:", list(islice(pos_gen(), 10)))
print("    plus_minus:", list(islice(plus_minus(), 15)))
print("\nPartitions:", [part(x) for x in range(15)])
Task: Count occurrences of a substring




Go: package main
import (
        "fmt"
        "strings"
)

func main() {
        fmt.Println(strings.Count("the three truths", "th")) 
        fmt.Println(strings.Count("ababababab", "abab"))     
}




Python: >>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2
Task: Numbers with prime digits whose sum is 13




Go: package main

import (
    "fmt"
    "sort"
    "strconv"
)

func combrep(n int, lst []byte) [][]byte {
    if n == 0 {
        return [][]byte{nil}
    }
    if len(lst) == 0 {
        return nil
    }
    r := combrep(n, lst[1:])
    for _, x := range combrep(n-1, lst) {
        r = append(r, append(x, lst[0]))
    }
    return r
}

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 main() {
    primes := []byte{2, 3, 5, 7}
    var res []string
    for n := 3; n <= 6; n++ {
        reps := combrep(n, primes)
        for _, rep := range reps {
            sum := byte(0)
            for _, r := range rep {
                sum += r
            }
            if sum == 13 {
                var perms []string
                for i := 0; i < len(rep); i++ {
                    rep[i] += 48
                }
                findPerms(rep, 0, len(rep), &perms)
                res = append(res, perms...)
            }
        }
    }
    res2 := make([]int, len(res))
    for i, r := range res {
        res2[i], _ = strconv.Atoi(r)
    }
    sort.Ints(res2)
    fmt.Println("Those numbers whose digits are all prime and sum to 13 are:")
    fmt.Println(res2)
}




Python: from collections import deque

def prime_digits_sum(r):
    q = deque([(r, 0)])
    while q:
        r, n = q.popleft()
        for d in 2, 3, 5, 7:
            if d >= r:
                if d == r: yield n + d
                break
            q.append((r - d, (n + d) * 10))

print(*prime_digits_sum(13))
Task: String comparison




Go: package main

import (
    "fmt"
    "strings"
)

func main() {
    
    c := "cat"
    d := "dog"
    if c == d {
        fmt.Println(c, "is bytewise identical to", d)
    }
    if c != d {
        fmt.Println(c, "is bytewise different from", d)
    }
    if c > d {
        fmt.Println(c, "is lexically bytewise greater than", d)
    }
    if c < d {
        fmt.Println(c, "is lexically bytewise less than", d)
    }
    if c >= d {
        fmt.Println(c, "is lexically bytewise greater than or equal to", d)
    }
    if c <= d {
        fmt.Println(c, "is lexically bytewise less than or equal to", d)
    }
    
    

    
    
    eqf := `when interpreted as UTF-8 and compared under Unicode
simple case folding rules.`
    if strings.EqualFold(c, d) {
        fmt.Println(c, "equal to", d, eqf)
    } else {
        fmt.Println(c, "not equal to", d, eqf)
    }

    
    
    
    
    
    
    
}




Python: fun compare(a, b):
    print("\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}")
    if a < b: print("$a is strictly less than $b")
    if a <= b: print("$a is less than or equal to $b")
    if a >  b: print("$a is strictly greater than $b")
    if a >= b: print("$a is greater than or equal to $b")
    if a == b: print("$a is equal to $b")
    if a != b: print("$a is not equal to $b")
    if a is b: print("$a has object identity with $b")
    if a is not b: print("$a has negated object identity with $b")

compare("YUP", "YUP")
compare('a', 'z')
compare("24", "123")
compare(24, 123)
compare(5.0, 5)
Task: Take notes on the command line




Go: package main

import (
	"fmt"
	"io"
	"os"
	"strings"
	"time"
)

func addNote(fn string, note string) error {
	f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		return err
	}
	_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n")
	
	if cErr := f.Close(); err == nil {
		err = cErr
	}
	return err
}

func showNotes(w io.Writer, fn string) error {
	f, err := os.Open(fn)
	if err != nil {
		if os.IsNotExist(err) {
			return nil 
		}
		return err
	}
	_, err = io.Copy(w, f)
	f.Close()
	return err
}

func main() {
	const fn = "NOTES.TXT"
	var err error
	if len(os.Args) > 1 {
		err = addNote(fn, strings.Join(os.Args[1:], " "))
	} else {
		err = showNotes(os.Stdout, fn)
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}




Python: import sys, datetime, shutil

if len(sys.argv) == 1:
    try:
        with open('notes.txt', 'r') as f:
            shutil.copyfileobj(f, sys.stdout)
    except IOError:
        pass
else:
    with open('notes.txt', 'a') as f:
        f.write(datetime.datetime.now().isoformat() + '\n')
        f.write("\t%s\n" % ' '.join(sys.argv[1:]))
Task: Thiele's interpolation formula




Go: package main

import (
    "fmt"
    "math"
)

func main() {
    
    const nn = 32
    const step = .05
    xVal := make([]float64, nn)
    tSin := make([]float64, nn)
    tCos := make([]float64, nn)
    tTan := make([]float64, nn)
    for i := range xVal {
        xVal[i] = float64(i) * step
        tSin[i], tCos[i] = math.Sincos(xVal[i])
        tTan[i] = tSin[i] / tCos[i]
    }
    
    iSin := thieleInterpolator(tSin, xVal)
    iCos := thieleInterpolator(tCos, xVal)
    iTan := thieleInterpolator(tTan, xVal)
    
    fmt.Printf("%16.14f\n", 6*iSin(.5))
    fmt.Printf("%16.14f\n", 3*iCos(.5))
    fmt.Printf("%16.14f\n", 4*iTan(1))
}

func thieleInterpolator(x, y []float64) func(float64) float64 {
    n := len(x)
    ρ := make([][]float64, n)
    for i := range ρ {
        ρ[i] = make([]float64, n-i)
        ρ[i][0] = y[i]
    }
    for i := 0; i < n-1; i++ {
        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])
    }
    for i := 2; i < n; i++ {
        for j := 0; j < n-i; j++ {
            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]
        }
    }
    
    ρ0 := ρ[0]
    return func(xin float64) float64 {
        var a float64
        for i := n - 1; i > 1; i-- {
            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)
        }
        return y[0] + (xin-x[0])/(ρ0[1]+a)
    }
}




Python: 

import math

def thieleInterpolator(x, y):
    ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]
    for i in range(len(ρ)-1):
        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])
    for i in range(2, len(ρ)):
        for j in range(len(ρ)-i):
            ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]
    ρ0 = ρ[0]
    def t(xin):
        a = 0
        for i in range(len(ρ0)-1, 1, -1):
            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)
        return y[0] + (xin-x[0]) / (ρ0[1]+a)
    return t


xVal = [i*.05 for i in range(32)]
tSin = [math.sin(x) for x in xVal]
tCos = [math.cos(x) for x in xVal]
tTan = [math.tan(x) for x in xVal]

iSin = thieleInterpolator(tSin, xVal)
iCos = thieleInterpolator(tCos, xVal)
iTan = thieleInterpolator(tTan, xVal)

print('{:16.14f}'.format(6*iSin(.5)))
print('{:16.14f}'.format(3*iCos(.5)))
print('{:16.14f}'.format(4*iTan(1)))
Task: Fibonacci word




Go: package main

import (
	"fmt"
	"math"
)


func entropy(s string) float64 {
	m := map[rune]float64{}
	for _, r := range s {
		m[r]++
	}
	hm := 0.
	for _, c := range m {
		hm += c * math.Log2(c)
	}
	l := float64(len(s))
	return math.Log2(l) - hm/l
}

const F_Word1 = "1"
const F_Word2 = "0"

func FibonacciWord(n int) string {
	a, b := F_Word1, F_Word2
	for ; n > 1; n-- {
		a, b = b, b+a
	}
	return a
}

func FibonacciWordGen() <-chan string {
	ch := make(chan string)
	go func() {
		a, b := F_Word1, F_Word2
		for {
			ch <- a
			a, b = b, b+a
		}
	}()
	return ch
}

func main() {
	fibWords := FibonacciWordGen()
	fmt.Printf("%3s %9s  %-18s  %s\n", "N", "Length", "Entropy", "Word")
	n := 1
	for ; n < 10; n++ {
		s := <-fibWords
		
		if s2 := FibonacciWord(n); s != s2 {
			fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2)
		}
		fmt.Printf("%3d %9d  %.16f  %s\n", n, len(s), entropy(s), s)
	}
	for ; n <= 37; n++ {
		s := <-fibWords
		fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s))
	}
}




Python: >>> import math
>>> from collections import Counter
>>> 
>>> def entropy(s):
...     p, lns = Counter(s), float(len(s))
...     return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
... 
>>> 
>>> def fibword(nmax=37):
...     fwords = ['1', '0']
...     print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))
...     def pr(n, fwords):
...         while len(fwords) < n:
...             fwords += [''.join(fwords[-2:][::-1])]
...         v = fwords[n-1]
...         print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))
...     for n in range(1, nmax+1): pr(n, fwords)
... 
>>> fibword()
N       Length Entropy    Fibword
  1          1         -0 1
  2          1         -0 0
  3          2          1 01
  4          3  0.9182958 010
  5          5  0.9709506 01001
  6          8   0.954434 01001010
  7         13  0.9612366 0100101001001
  8         21  0.9587119 <too long>
  9         34  0.9596869 <too long>
 10         55   0.959316 <too long>
 11         89  0.9594579 <too long>
 12        144  0.9594038 <too long>
 13        233  0.9594244 <too long>
 14        377  0.9594165 <too long>
 15        610  0.9594196 <too long>
 16        987  0.9594184 <too long>
 17       1597  0.9594188 <too long>
 18       2584  0.9594187 <too long>
 19       4181  0.9594187 <too long>
 20       6765  0.9594187 <too long>
 21      10946  0.9594187 <too long>
 22      17711  0.9594187 <too long>
 23      28657  0.9594187 <too long>
 24      46368  0.9594187 <too long>
 25      75025  0.9594187 <too long>
 26     121393  0.9594187 <too long>
 27     196418  0.9594187 <too long>
 28     317811  0.9594187 <too long>
 29     514229  0.9594187 <too long>
 30     832040  0.9594187 <too long>
 31    1346269  0.9594187 <too long>
 32    2178309  0.9594187 <too long>
 33    3524578  0.9594187 <too long>
 34    5702887  0.9594187 <too long>
 35    9227465  0.9594187 <too long>
 36   14930352  0.9594187 <too long>
 37   24157817  0.9594187 <too long>
>>>
Task: Find common directory path




Go: package main

import (
	"fmt"
	"os"
	"path"
)

func CommonPrefix(sep byte, paths ...string) string {
	
	switch len(paths) {
	case 0:
		return ""
	case 1:
		return path.Clean(paths[0])
	}

	
	
	
	
	
	
	
	
	c := []byte(path.Clean(paths[0]))

	
	
	
	
	
	
	c = append(c, sep)

	
	for _, v := range paths[1:] {
		
		v = path.Clean(v) + string(sep)

		
		if len(v) < len(c) {
			c = c[:len(v)]
		}
		for i := 0; i < len(c); i++ {
			if v[i] != c[i] {
				c = c[:i]
				break
			}
		}
	}

	
	for i := len(c) - 1; i >= 0; i-- {
		if c[i] == sep {
			c = c[:i]
			break
		}
	}

	return string(c)
}

func main() {
	c := CommonPrefix(os.PathSeparator,
		
		"/home/user1/tmp/coverage/test",
		"/home/user1/tmp/covert/operator",
		"/home/user1/tmp/coven/members",
		"/home
		"/home/user1/././tmp/covertly/foo",
		"/home/bob/../user1/tmp/coved/bar",
	)
	if c == "" {
		fmt.Println("No common path")
	} else {
		fmt.Println("Common path:", c)
	}
}




Python: >>> import os
>>> os.path.commonpath(['/home/user1/tmp/coverage/test', 
                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'
Task: Verify distribution uniformity_Naive




Go: package main

import (
    "fmt"
    "math"
    "math/rand"
    "time"
)


func dice5() int {
    return rand.Intn(5) + 1
}


func dice7() (i int) {
    for {
        i = 5*dice5() + dice5()
        if i < 27 {
            break
        }
    }
    return (i / 3) - 1
}










func distCheck(f func() int, n int,
    repeats int, delta float64) (max float64, flatEnough bool) {
    count := make([]int, n)
    for i := 0; i < repeats; i++ {
        count[f()-1]++
    }
    expected := float64(repeats) / float64(n)
    for _, c := range count {
        max = math.Max(max, math.Abs(float64(c)-expected))
    }
    return max, max < delta
}


func main() {
    rand.Seed(time.Now().UnixNano())
    const calls = 1000000
    max, flatEnough := distCheck(dice7, 7, calls, 500)
    fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
    max, flatEnough = distCheck(dice7, 7, calls, 500)
    fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
}




Python: from collections import Counter
from pprint import pprint as pp

def distcheck(fn, repeats, delta):
    
    bin = Counter(fn() for i in range(repeats))
    target = repeats // len(bin)
    deltacount = int(delta / 100. * target)
    assert all( abs(target - count) < deltacount
                for count in bin.values() ), "Bin distribution skewed from %i +/- %i: %s" % (
                    target, deltacount, [ (key, target - count)
                                          for key, count in sorted(bin.items()) ]
                    )
    pp(dict(bin))
Task: Stirling numbers of the second kind




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    limit := 100
    last := 12
    s2 := make([][]*big.Int, limit+1)
    for n := 0; n <= limit; n++ {
        s2[n] = make([]*big.Int, limit+1)
        for k := 0; k <= limit; k++ {
            s2[n][k] = new(big.Int)
        }
        s2[n][n].SetInt64(int64(1))
    }
    var t big.Int
    for n := 1; n <= limit; n++ {
        for k := 1; k <= n; k++ {
            t.SetInt64(int64(k))
            t.Mul(&t, s2[n-1][k])
            s2[n][k].Add(&t, s2[n-1][k-1])
        }
    }
    fmt.Println("Stirling numbers of the second kind: S2(n, k):")
    fmt.Printf("n/k")
    for i := 0; i <= last; i++ {
        fmt.Printf("%9d ", i)
    }
    fmt.Printf("\n--")
    for i := 0; i <= last; i++ {
        fmt.Printf("----------")
    }
    fmt.Println()
    for n := 0; n <= last; n++ {
        fmt.Printf("%2d ", n)
        for k := 0; k <= n; k++ {
            fmt.Printf("%9d ", s2[n][k])
        }
        fmt.Println()
    }
    fmt.Println("\nMaximum value from the S2(100, *) row:")
    max := new(big.Int).Set(s2[limit][0])
    for k := 1; k <= limit; k++ {
        if s2[limit][k].Cmp(max) > 0 {
            max.Set(s2[limit][k])
        }
    }
    fmt.Println(max)
    fmt.Printf("which has %d digits.\n", len(max.String()))
}




Python: computed = {}

def sterling2(n, k):
	key = str(n) + "," + str(k)

	if key in computed.keys():
		return computed[key]
	if n == k == 0:
		return 1
	if (n > 0 and k == 0) or (n == 0 and k > 0):
		return 0
	if n == k:
		return 1
	if k > n:
		return 0
	result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
	computed[key] = result
	return result

print("Stirling numbers of the second kind:")
MAX = 12
print("n/k".ljust(10), end="")
for n in range(MAX + 1):
	print(str(n).rjust(10), end="")
print()
for n in range(MAX + 1):
	print(str(n).ljust(10), end="")
	for k in range(n + 1):
		print(str(sterling2(n, k)).rjust(10), end="")
	print()
print("The maximum value of S2(100, k) = ")
previous = 0
for k in range(1, 100 + 1):
	current = sterling2(100, k)
	if current > previous:
		previous = current
	else:
		print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1))
		break
Task: Recaman's sequence




Go: package main

import "fmt"

func main() {
    a := []int{0}
    used := make(map[int]bool, 1001)
    used[0] = true
    used1000 := make(map[int]bool, 1001)
    used1000[0] = true
    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
        next := a[n-1] - n
        if next < 1 || used[next] {
            next += 2 * n
        }
        alreadyUsed := used[next]
        a = append(a, next)

        if !alreadyUsed {
            used[next] = true
            if next >= 0 && next <= 1000 {
                used1000[next] = true
            }
        }

        if n == 14 {
            fmt.Println("The first 15 terms of the Recaman's sequence are:", a)
        }

        if !foundDup && alreadyUsed {
            fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next)
            foundDup = true
        }

        if len(used1000) == 1001 {
            fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n)
        }
    }
}




Python: from itertools import islice

class Recamans():
    "Recamán's sequence generator callable class"
    def __init__(self):
        self.a = None   
        self.n = None   
    
    def __call__(self):
        "Recamán's sequence  generator"
        nxt = 0
        a, n = {nxt}, 0
        self.a = a
        self.n = n
        yield nxt
        while True:
            an1, n = nxt, n + 1
            nxt = an1 - n
            if nxt < 0 or nxt in a:
                nxt = an1 + n
            a.add(nxt)
            self.n = n
            yield nxt

if __name__ == '__main__':
    recamans = Recamans()
    print("First fifteen members of Recamans sequence:", 
          list(islice(recamans(), 15)))

    so_far = set()
    for term in recamans():
        if term in so_far:
            print(f"First duplicate number in series is: a({recamans.n}) = {term}")
            break
        so_far.add(term)
    
    n = 1_000
    setn = set(range(n + 1))    
    for _ in recamans():
        if setn.issubset(recamans.a):
            print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
            break
Task: Memory allocation




Go: func inc(n int) {
    x := n + 1
    println(x)
}




Python: >>> from array import array
>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'),
	('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]
>>> for typecode, initializer in argslist:
	a = array(typecode, initializer)
	print a
	del a

	
array('l')
array('c', 'hello world')
array('u', u'hello \u2641')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.1400000000000001])
>>>
Task: Integer sequence




Go: package main

import "fmt"

func main() {
    for i := 1;; i++ {
        fmt.Println(i)
    }
}




Python: i=1
while i:
    print(i)
    i += 1
Task: Entropy_Narcissist




Go: package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "math"
    "os"
    "runtime"
)

func main() {
    _, src, _, _ := runtime.Caller(0)
    fmt.Println("Source file entropy:", entropy(src))
    fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}

func entropy(file string) float64 {
    d, err := ioutil.ReadFile(file)
    if err != nil {
        log.Fatal(err)
    }
    var f [256]float64
    for _, b := range d {
        f[b]++
    }
    hm := 0.
    for _, c := range f {
        if c > 0 {
            hm += c * math.Log2(c)
        }
    }
    l := float64(len(d))
    return math.Log2(l) - hm/l
}




Python: import math
from collections import Counter

def entropy(s):
    p, lns = Counter(s), float(len(s))
    return -sum( count/lns * math.log(count/lns, 2) for count in p.values())

with open(__file__) as f:
    b=f.read()
    
print(entropy(b))
Task: DNS query




Go: package main

import (
    "fmt"
    "net"
)

func main() {
    if addrs, err := net.LookupHost("www.kame.net"); err == nil {
        fmt.Println(addrs)
    } else {
        fmt.Println(err)
    }
}




Python: >>> import socket
>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))
>>> for ip in ips: print ip
...
2001:200:dff:fff1:216:3eff:feb1:44d7
203.178.141.194