WeixiangYan/CodeTransOcean huggingface dataset:
Task: Pythagorean triples




Go: package main

import "fmt"

var total, prim, maxPeri int64

func newTri(s0, s1, s2 int64) {
    if p := s0 + s1 + s2; p <= maxPeri {
        prim++
        total += maxPeri / p
        newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)
        newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)
        newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)
    }
}

func main() {
    for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {
        prim = 0
        total = 0
        newTri(3, 4, 5)
        fmt.Printf("Up to %d:  %d triples, %d primitives\n",
            maxPeri, total, prim)
    }
}




Python: from fractions import gcd


def pt1(maxperimeter=100):
    
    trips = []
    for a in range(1, maxperimeter):
        aa = a*a
        for b in range(a, maxperimeter-a+1):
            bb = b*b
            for c in range(b, maxperimeter-b-a+1):
                cc = c*c
                if a+b+c > maxperimeter or cc > aa + bb: break
                if aa + bb == cc:
                    trips.append((a,b,c, gcd(a, b) == 1))
    return trips

def pytrip(trip=(3,4,5),perim=100, prim=1):
    a0, b0, c0 = a, b, c = sorted(trip)
    t, firstprim = set(), prim>0
    while a + b + c <= perim:
        t.add((a, b, c, firstprim>0))
        a, b, c, firstprim = a+a0, b+b0, c+c0, False
    
    t2 = set()
    for a, b, c, firstprim in t:
        a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
        if  a5 - b5 + c7 <= perim:
            t2 |= pytrip(( a - b2 + c2,  a2 - b + c2,  a2 - b2 + c3), perim, firstprim)
        if  a5 + b5 + c7 <= perim:
            t2 |= pytrip(( a + b2 + c2,  a2 + b + c2,  a2 + b2 + c3), perim, firstprim)
        if -a5 + b5 + c7 <= perim:
            t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
    return t | t2

def pt2(maxperimeter=100):
    
    trips = pytrip((3,4,5), maxperimeter, 1)
    return trips

def printit(maxperimeter=100, pt=pt1):
    trips = pt(maxperimeter)
    print("  Up to a perimeter of %i there are %i triples, of which %i are primitive"
          % (maxperimeter,
             len(trips),
             len([prim for a,b,c,prim in trips if prim])))
  
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
    print(algo.__doc__)
    for maxperimeter in range(mn, mx+1, mn):
        printit(maxperimeter, algo)
Task: Remove duplicate elements




Go: package main

import "fmt"

func uniq(list []int) []int {
	unique_set := make(map[int]bool, len(list))
	for _, x := range list {
		unique_set[x] = true
	}
	result := make([]int, 0, len(unique_set))
	for x := range unique_set {
		result = append(result, x)
	}
	return result
}

func main() {
	fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) 
}




Python: items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
Task: Look-and-say sequence




Go: package main

import (
    "fmt"
    "strconv"
)

func lss(s string) (r string) {
    c := s[0]
    nc := 1
    for i := 1; i < len(s); i++ {
        d := s[i]
        if d == c {
            nc++
            continue
        }
        r += strconv.Itoa(nc) + string(c)
        c = d
        nc = 1
    }
    return r + strconv.Itoa(nc) + string(c)
}

func main() {
    s := "1"
    fmt.Println(s)
    for i := 0; i < 8; i++ {
        s = lss(s)
        fmt.Println(s)
    }
}




Python: def lookandsay(number):
    result = ""

    repeat = number[0]
    number = number[1:]+" "
    times = 1

    for actual in number:
        if actual != repeat:
            result += str(times)+repeat
            times = 1
            repeat = actual
        else:
            times += 1

    return result

num = "1"

for i in range(10):
    print num
    num = lookandsay(num)
Task: Totient function




Go: package main

import "fmt"

func gcd(n, k int) int {
    if n < k || k < 1 {
        panic("Need n >= k and k >= 1")
    }

    s := 1
    for n&1 == 0 && k&1 == 0 {
        n >>= 1
        k >>= 1
        s <<= 1
    }

    t := n
    if n&1 != 0 {
        t = -k
    }
    for t != 0 {
        for t&1 == 0 {
            t >>= 1
        }
        if t > 0 {
            n = t
        } else {
            k = -t
        }
        t = n - k
    }
    return n * s
}

func totient(n int) int {
    tot := 0
    for k := 1; k <= n; k++ {
        if gcd(n, k) == 1 {
            tot++
        }
    }
    return tot
}

func main() {
    fmt.Println(" n  phi   prime")
    fmt.Println("---------------")
    count := 0
    for n := 1; n <= 25; n++ {
        tot := totient(n)
        isPrime := n-1 == tot
        if isPrime {
            count++
        }
        fmt.Printf("%2d   %2d   %t\n", n, tot, isPrime)
    }
    fmt.Println("\nNumber of primes up to 25     =", count)
    for n := 26; n <= 100000; n++ {
        tot := totient(n)
        if tot == n-1 {
            count++
        }
        if n == 100 || n == 1000 || n%10000 == 0 {
            fmt.Printf("\nNumber of primes up to %-6d = %d\n", n, count)
        }
    }
}




Python: from math import gcd

def  φ(n):
    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)

if __name__ == '__main__':
    def is_prime(n):
        return φ(n) == n - 1
    
    for n in range(1, 26):
        print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n)  else ''}")
    count = 0
    for n in range(1, 10_000 + 1):
        count += is_prime(n)
        if n in {100, 1000, 10_000}:
            print(f"Primes up to {n}: {count}")
Task: Conditional structures




Go: if booleanExpression {
    statements
}




Python: if x == 0:
    foo()
elif x == 1:
    bar()
elif x == 2:
    baz()
else:
    qux()

match x:
    0 => foo()
    1 => bar()
    2 => baz()
    _ => qux()

(a) ? b : c
Task: Fractran




Go: package main

import (
    "fmt"
    "log"
    "math/big"
    "os"
    "strconv"
    "strings"
)

func compile(src string) ([]big.Rat, bool) {
    s := strings.Fields(src)
    r := make([]big.Rat, len(s))
    for i, s1 := range s {
        if _, ok := r[i].SetString(s1); !ok {
            return nil, false
        }
    }
    return r, true
}

func exec(p []big.Rat, n *big.Int, limit int) {
    var q, r big.Int
rule:
    for i := 0; i < limit; i++ {
        fmt.Printf("%d ", n)
        for j := range p {
            q.QuoRem(n, p[j].Denom(), &r)
            if r.BitLen() == 0 {
                n.Mul(&q, p[j].Num())
                continue rule
            }
        }
        break
    }
    fmt.Println()
}

func usage() {
    log.Fatal("usage: ft <limit> <n> <prog>")
}

func main() {
    if len(os.Args) != 4 {
        usage()
    }
    limit, err := strconv.Atoi(os.Args[1])
    if err != nil {
        usage()
    }
    var n big.Int
    _, ok := n.SetString(os.Args[2], 10)
    if !ok {
        usage()
    }
    p, ok := compile(os.Args[3])
    if !ok {
        usage()
    }
    exec(p, &n, limit)
}




Python: from fractions import Fraction

def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
                        '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'
                        '13 / 11, 15 / 14, 15 / 2, 55 / 1'):
    flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]

    n = Fraction(n)
    while True:
        yield n.numerator
        for f in flist:
            if (n * f).denominator == 1:
                break
        else:
            break
        n *= f
    
if __name__ == '__main__':
    n, m = 2, 15
    print('First %i members of fractran(%i):\n  ' % (m, n) +
          ', '.join(str(f) for f,i in zip(fractran(n), range(m))))
Task: Sorting algorithms_Stooge sort




Go: package main

import "fmt"

var a = []int{170, 45, 75, -90, -802, 24, 2, 66}

func main() {
    fmt.Println("before:", a)
    stoogesort(a)
    fmt.Println("after: ", a)
    fmt.Println("nyuk nyuk nyuk")
}

func stoogesort(a []int) {
    last := len(a) - 1
    if a[last] < a[0] {
        a[0], a[last] = a[last], a[0]
    }
    if last > 1 {
        t := len(a) / 3
        stoogesort(a[:len(a)-t])
        stoogesort(a[t:])
        stoogesort(a[:len(a)-t])
    }
}




Python: >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
	if j is None:
		j = len(L) - 1
	if L[j] < L[i]:
		L[i], L[j] = L[j], L[i]
	if j - i > 1:
		t = (j - i + 1) // 3
		stoogesort(L, i  , j-t)
		stoogesort(L, i+t, j  )
		stoogesort(L, i  , j-t)
	return L

>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
Task: Sorting Algorithms_Circle Sort




Go: package main

import "fmt"

func circleSort(a []int, lo, hi, swaps int) int {
    if lo == hi {
        return swaps
    }
    high, low := hi, lo
    mid := (hi - lo) / 2
    for lo < hi {
        if a[lo] > a[hi] {
            a[lo], a[hi] = a[hi], a[lo]
            swaps++
        }
        lo++
        hi--
    }
    if lo == hi {
        if a[lo] > a[hi+1] {
            a[lo], a[hi+1] = a[hi+1], a[lo]
            swaps++
        }
    }
    swaps = circleSort(a, low, low+mid, swaps)
    swaps = circleSort(a, low+mid+1, high, swaps)
    return swaps
}

func main() {
    aa := [][]int{
        {6, 7, 8, 9, 2, 5, 3, 4, 1},
        {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1},
    }
    for _, a := range aa {
        fmt.Printf("Original: %v\n", a)
        for circleSort(a, 0, len(a)-1, 0) != 0 {
            
        }
        fmt.Printf("Sorted  : %v\n\n", a)
    }
}




Python: 




def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':
    
    n = R-L
    if n < 2:
        return 0
    swaps = 0
    m = n//2
    for i in range(m):
        if A[R-(i+1)] < A[L+i]:
            (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)
            swaps += 1
    if (n & 1) and (A[L+m] < A[L+m-1]):
        (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)
        swaps += 1
    return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)

def circle_sort(L:list)->'sort A in place, returning the number of swaps':
    swaps = 0
    s = 1
    while s:
        s = circle_sort_backend(L, 0, len(L))
        swaps += s
    return swaps


if __name__ == '__main__':
    from random import shuffle
    for i in range(309):
        L = list(range(i))
        M = L[:]
        shuffle(L)
        N = L[:]
        circle_sort(L)
        if L != M:
            print(len(L))
            print(N)
            print(L)
Task: Kronecker product based fractals




Go: package main

import "fmt"

type matrix [][]int

func (m1 matrix) kroneckerProduct(m2 matrix) matrix {
    m := len(m1)
    n := len(m1[0])
    p := len(m2)
    q := len(m2[0])
    rtn := m * p
    ctn := n * q
    r := make(matrix, rtn)
    for i := range r {
        r[i] = make([]int, ctn) 
    }
    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            for k := 0; k < p; k++ {
                for l := 0; l < q; l++ {
                    r[p*i+k][q*j+l] = m1[i][j] * m2[k][l]
                }
            }
        }
    }
    return r
}

func (m matrix) kroneckerPower(n int) matrix {
    pow := m
    for i := 1; i < n; i++ {
        pow = pow.kroneckerProduct(m)
    }
    return pow
}

func (m matrix) print(text string) {
    fmt.Println(text, "fractal :\n")
    for i := range m {
        for j := range m[0] {
            if m[i][j] == 1 {
                fmt.Print("*")
            } else {
                fmt.Print(" ")
            }
        }
        fmt.Println()
    }
    fmt.Println()
}

func main() {
    m1 := matrix{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}
    m1.kroneckerPower(4).print("Vivsek")

    m2 := matrix{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}
    m2.kroneckerPower(4).print("Sierpinski carpet")
}




Python: import os
from PIL import Image


def imgsave(path, arr):
    w, h = len(arr), len(arr[0])
    img = Image.new('1', (w, h))
    for x in range(w):
        for y in range(h):
            img.putpixel((x, y), arr[x][y])
    img.save(path)


def get_shape(mat):
    return len(mat), len(mat[0])


def kron(matrix1, matrix2):
    
    final_list = []

    count = len(matrix2)

    for elem1 in matrix1:
        for i in range(count):
            sub_list = []
            for num1 in elem1:
                for num2 in matrix2[i]:
                    sub_list.append(num1 * num2)
            final_list.append(sub_list)

    return final_list


def kronpow(mat):
    
    matrix = mat
    while True:
        yield matrix
        matrix = kron(mat, matrix)


def fractal(name, mat, order=6):
    
    path = os.path.join('fractals', name)
    os.makedirs(path, exist_ok=True)

    fgen = kronpow(mat)
    print(name)
    for i in range(order):
        p = os.path.join(path, f'{i}.jpg')
        print('Calculating n =', i, end='\t', flush=True)

        mat = next(fgen)
        imgsave(p, mat)

        x, y = get_shape(mat)
        print('Saved as', x, 'x', y, 'image', p)


test1 = [
    [0, 1, 0],
    [1, 1, 1],
    [0, 1, 0]
]

test2 = [
    [1, 1, 1],
    [1, 0, 1],
    [1, 1, 1]
]

test3 = [
    [1, 0, 1],
    [0, 1, 0],
    [1, 0, 1]
]

fractal('test1', test1)
fractal('test2', test2)
fractal('test3', test3)
Task: Sort using a custom comparator




Go: package main

import (
    "fmt"
    "sort"
    "strings"
)

type sortable []string

func (s sortable) Len() int      { return len(s) }
func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sortable) Less(i, j int) bool {
    a, b := s[i], s[j]
    if len(a) != len(b) {
        return len(a) > len(b)
    }
    return strings.ToLower(a) < strings.ToLower(b)
}

func main() {
    var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog")
    fmt.Println(s, "(original)")

    sort.Sort(s)
    fmt.Println(s, "(sorted)")
}




Python: strings = "here are Some sample strings to be sorted".split()

def mykey(x):
    return -len(x), x.upper()

print sorted(strings, key=mykey)
Task: Animation




Go: package main

import (
    "log"
    "time"

    "github.com/gdamore/tcell"
)

const (
    msg             = "Hello World! "
    x0, y0          = 8, 3
    shiftsPerSecond = 4
    clicksToExit    = 5
)

func main() {
    s, err := tcell.NewScreen()
    if err != nil {
        log.Fatal(err)
    }
    if err = s.Init(); err != nil {
        log.Fatal(err)
    }
    s.Clear()
    s.EnableMouse()
    tick := time.Tick(time.Second / shiftsPerSecond)
    click := make(chan bool)
    go func() {
        for {
            em, ok := s.PollEvent().(*tcell.EventMouse)
            if !ok || em.Buttons()&0xFF == tcell.ButtonNone {
                continue
            }
            mx, my := em.Position()
            if my == y0 && mx >= x0 && mx < x0+len(msg) {
                click <- true
            }
        }
    }()
    for inc, shift, clicks := 1, 0, 0; ; {
        select {
        case <-tick:
            shift = (shift + inc) % len(msg)
            for i, r := range msg {
                s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)
            }
            s.Show()
        case <-click:
            clicks++
            if clicks == clicksToExit {
                s.Fini()
                return
            }
            inc = len(msg) - inc
        }
    }
}




Python: txt = "Hello, world! "
left = True

def draw():
    global txt
    background(128)
    text(txt, 10, height / 2)
    if frameCount % 10 == 0:
        if (left):
            txt = rotate(txt, 1)
        else:
            txt = rotate(txt, -1)
        println(txt)

def mouseReleased():
    global left
    left = not left

def rotate(text, startIdx):
    rotated = text[startIdx:] + text[:startIdx]
    return rotated
Task: Sorting algorithms_Radix sort




Go: package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
)


type word int32
const wordLen = 4
const highBit = -1 << 31

var data = []word{170, 45, 75, -90, -802, 24, 2, 66}

func main() {
    buf := bytes.NewBuffer(nil)
    ds := make([][]byte, len(data))
    for i, x := range data {
        binary.Write(buf, binary.LittleEndian, x^highBit)
        b := make([]byte, wordLen)
        buf.Read(b)
        ds[i] = b
    }
    bins := make([][][]byte, 256)
    for i := 0; i < wordLen; i++ {
        for _, b := range ds {
            bins[b[i]] = append(bins[b[i]], b)
        }
        j := 0
        for k, bs := range bins {
            copy(ds[j:], bs)
            j += len(bs)
            bins[k] = bs[:0]
        }
    }
    fmt.Println("original:", data)
    var w word
    for i, b := range ds {
        buf.Write(b)
        binary.Read(buf, binary.LittleEndian, &w)
        data[i] = w^highBit
    }
    fmt.Println("sorted:  ", data)
}




Python: 
from math import log
 
def getDigit(num, base, digit_num):
    
    return (num // base ** digit_num) % base  
 
def makeBlanks(size):
    
    return [ [] for i in range(size) ]  
 
def split(a_list, base, digit_num):
    buckets = makeBlanks(base)
    for num in a_list:
        
        buckets[getDigit(num, base, digit_num)].append(num)  
    return buckets
 

def merge(a_list):
    new_list = []
    for sublist in a_list:
       new_list.extend(sublist)
    return new_list
 
def maxAbs(a_list):
    
    return max(abs(num) for num in a_list)

def split_by_sign(a_list):
    
    
    buckets = [[], []]
    for num in a_list:
        if num < 0:
            buckets[0].append(num)
        else:
            buckets[1].append(num)
    return buckets
 
def radixSort(a_list, base):
    
    passes = int(round(log(maxAbs(a_list), base)) + 1) 
    new_list = list(a_list)
    for digit_num in range(passes):
        new_list = merge(split(new_list, base, digit_num))
    return merge(split_by_sign(new_list))
Task: List comprehensions




Go: package main

import "fmt"

type (
    seq  []int
    sofs []seq
)

func newSeq(start, end int) seq {
    if end < start {
        end = start
    }
    s := make(seq, end-start+1)
    for i := 0; i < len(s); i++ {
        s[i] = start + i
    }
    return s
}

func newSofs() sofs {
    return sofs{seq{}}
}

func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
    var s2 sofs
    for _, t := range expr(s, in) {
        if pred(t) {
            s2 = append(s2, t)
        }
    }
    return s2
}

func (s sofs) build(t seq) sofs {
    var u sofs
    for _, ss := range s {
        for _, tt := range t {
            uu := make(seq, len(ss))
            copy(uu, ss)
            uu = append(uu, tt)
            u = append(u, uu)
        }
    }
    return u
}

func main() {
    pt := newSofs()
    in := newSeq(1, 20)
    expr := func(s sofs, t seq) sofs {
        return s.build(t).build(t).build(t)
    }
    pred := func(t seq) bool {
        if len(t) != 3 {
            return false
        }
        return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
    }
    pt = pt.listComp(in, expr, pred)
    fmt.Println(pt)
}




Python: [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
Task: Sorting algorithms_Selection sort




Go: package main

import "fmt"

var a = []int{170, 45, 75, -90, -802, 24, 2, 66}

func main() {
    fmt.Println("before:", a)
    selectionSort(a)
    fmt.Println("after: ", a)
}

func selectionSort(a []int) {
    last := len(a) - 1
    for i := 0; i < last; i++ {
        aMin := a[i]
        iMin := i
        for j := i + 1; j < len(a); j++ {
            if a[j] < aMin {
                aMin = a[j]
                iMin = j
            }
        }
        a[i], a[iMin] = aMin, a[i]
    }
}




Python: def selection_sort(lst):
    for i, e in enumerate(lst):
        mn = min(range(i,len(lst)), key=lst.__getitem__)
        lst[i], lst[mn] = lst[mn], e
    return lst
Task: Jacobi symbol




Go: package main

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

func jacobi(a, n uint64) int {
    if n%2 == 0 {
        log.Fatal("'n' must be a positive odd integer")
    }
    a %= n
    result := 1
    for a != 0 {
        for a%2 == 0 {
            a /= 2
            nn := n % 8
            if nn == 3 || nn == 5 {
                result = -result
            }
        }
        a, n = n, a
        if a%4 == 3 && n%4 == 3 {
            result = -result
        }
        a %= n
    }
    if n == 1 {
        return result
    }
    return 0
}

func main() {
    fmt.Println("Using hand-coded version:")
    fmt.Println("n/a  0  1  2  3  4  5  6  7  8  9")
    fmt.Println("---------------------------------")
    for n := uint64(1); n <= 17; n += 2 {
        fmt.Printf("%2d ", n)
        for a := uint64(0); a <= 9; a++ {
            fmt.Printf(" % d", jacobi(a, n))
        }
        fmt.Println()
    }

    ba, bn := new(big.Int), new(big.Int)
    fmt.Println("\nUsing standard library function:")
    fmt.Println("n/a  0  1  2  3  4  5  6  7  8  9")
    fmt.Println("---------------------------------")
    for n := uint64(1); n <= 17; n += 2 {
        fmt.Printf("%2d ", n)
        for a := uint64(0); a <= 9; a++ {
            ba.SetUint64(a)
            bn.SetUint64(n)
            fmt.Printf(" % d", big.Jacobi(ba, bn))            
        }
        fmt.Println()
    }
}




Python: def jacobi(a, n):
    if n <= 0:
        raise ValueError("'n' must be a positive integer.")
    if n % 2 == 0:
        raise ValueError("'n' must be odd.")
    a %= n
    result = 1
    while a != 0:
        while a % 2 == 0:
            a /= 2
            n_mod_8 = n % 8
            if n_mod_8 in (3, 5):
                result = -result
        a, n = n, a
        if a % 4 == 3 and n % 4 == 3:
            result = -result
        a %= n
    if n == 1:
        return result
    else:
        return 0
Task: Apply a callback to an array




Go: package main

import "fmt"

func main() {
    for _, i := range []int{1, 2, 3, 4, 5} {
        fmt.Println(i * i)
    }
}




Python: def square(n):
    return n * n
  
numbers = [1, 3, 5, 7]

squares1 = [square(n) for n in numbers]     

squares2a = map(square, numbers)            

squares2b = map(lambda x: x*x, numbers)     

squares3 = [n * n for n in numbers]         
                                            

isquares1 = (n * n for n in numbers)        

import itertools
isquares2 = itertools.imap(square, numbers)
Task: Singleton




Go: package main

import (
    "log"
    "math/rand"
    "sync"
    "time"
)

var (
    instance string
    once     sync.Once 
)

func claim(color string, w *sync.WaitGroup) {
    time.Sleep(time.Duration(rand.Intn(1e8))) 
    log.Println("trying to claim", color)
    once.Do(func() { instance = color })
    log.Printf("tried %s. instance: %s", color, instance)
    w.Done()
}

func main() {
    rand.Seed(time.Now().Unix())
    var w sync.WaitGroup
    w.Add(2)
    go claim("red", &w) 
    go claim("blue", &w)
    w.Wait()
    log.Println("after trying both, instance =", instance)
}




Python: >>> class Borg(object):
	__state = {}
	def __init__(self):
		self.__dict__ = self.__state
	

	
>>> b1 = Borg()
>>> b2 = Borg()
>>> b1 is b2
False
>>> b1.datum = range(5)
>>> b1.datum
[0, 1, 2, 3, 4]
>>> b2.datum
[0, 1, 2, 3, 4]
>>> b1.datum is b2.datum
True
>>>
Task: Safe addition




Go: package main

import (
    "fmt"
    "math"
)


type interval struct {
    lower, upper float64
}


func stepAway(x float64) interval {
    return interval {
        math.Nextafter(x, math.Inf(-1)),
        math.Nextafter(x, math.Inf(1))}
}


func safeAdd(a, b float64) interval {
    return stepAway(a + b)
    
}


func main() {
    a, b := 1.2, .03
    fmt.Println(a, b, safeAdd(a, b))
}




Python: >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> from math import fsum
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
Task: Case-sensitivity of identifiers




Go: package dogs

import "fmt"



var dog = "Salt"
var Dog = "Pepper"
var DOG = "Mustard"

func PackageSees() map[*string]int {
    
    fmt.Println("Package sees:", dog, Dog, DOG)
    
    
    
    
    return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}
}




Python: >>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'
>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)
The three dogs are named  Benjamin ,  Samba , and  Bernie
>>>
Task: Loops_Downward for




Go: for i := 10; i >= 0; i-- {
  fmt.Println(i)
}




Python: for i in xrange(10, -1, -1):
    print i
Task: Write entire file




Go: import "io/ioutil"

func main() {
    ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
}




Python: with open(filename, 'w') as f:
    f.write(data)