WeixiangYan/CodeTransOcean huggingface dataset:
Task: Maximum triangle path sum




Go: package main

import (
    "fmt"
    "strconv"
    "strings"
)

const t = `               55
                        94 48
                       95 30 96
                     77 71 26 67
                    97 13 76 38 45
                  07 36 79 16 37 68
                 48 07 09 18 70 26 06
               18 72 79 46 59 79 29 90
              20 76 87 11 32 07 07 49 18
            27 83 58 35 71 11 25 57 29 85
           14 64 36 96 27 11 58 56 92 18 55
         02 90 03 60 48 49 41 46 33 36 47 23
        92 50 48 02 36 59 42 79 72 20 82 77 42
      56 78 38 80 39 75 02 71 66 66 01 03 55 72
     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`

func main() {
    lines := strings.Split(t, "\n")
    f := strings.Fields(lines[len(lines)-1])
    d := make([]int, len(f))
    var err error
    for i, s := range f {
        if d[i], err = strconv.Atoi(s); err != nil {
            panic(err)
        }
    }
    d1 := d[1:]
    var l, r, u int
    for row := len(lines) - 2; row >= 0; row-- {
        l = d[0]
        for i, s := range strings.Fields(lines[row]) {
            if u, err = strconv.Atoi(s); err != nil {
                panic(err)
            }
            if r = d1[i]; l > r {
                d[i] = u + l
            } else {
                d[i] = u + r
            }
            l = r
        }
    }
    fmt.Println(d[0])
}




Python: fun maxpathsum(t): 
    let a = val t
    for i in a.length-1..-1..1, c in linearindices a[r]:
        a[r, c] += max(a[r+1, c], a[r=1, c+1])
    return a[1, 1]

let test = [
    [55],
    [94, 48],
    [95, 30, 96],
    [77, 71, 26, 67],
    [97, 13, 76, 38, 45],
    [07, 36, 79, 16, 37, 68],
    [48, 07, 09, 18, 70, 26, 06],
    [18, 72, 79, 46, 59, 79, 29, 90],
    [20, 76, 87, 11, 32, 07, 07, 49, 18],
    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],
    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],
    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],
    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],
    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]

@print maxpathsum test
Task: Median filter




Go: package main







import (
    "fmt"
    "raster"
)

var g0, g1 *raster.Grmap
var ko [][]int
var kc []uint16
var mid int

func init() {
    
    ko = [][]int{
        {-1, -1}, {0, -1}, {1, -1},
        {-1,  0}, {0,  0}, {1,  0},
        {-1,  1}, {0,  1}, {1,  1}}
    kc = make([]uint16, len(ko))
    mid = len(ko) / 2
}

func main() {
    
    
    
    
    
    b, err := raster.ReadPpmFile("Lenna50.ppm")
    if err != nil {
        fmt.Println(err)
        return
    }
    g0 = b.Grmap()
    w, h := g0.Extent()
    g1 = raster.NewGrmap(w, h)
    for y := 0; y < h; y++ {
        for x := 0; x < w; x++ {
            g1.SetPx(x, y, median(x, y))
        }
    }
    
    
    err = g1.Bitmap().WritePpmFile("median.ppm")
    if err != nil {
        fmt.Println(err)
    }
}

func median(x, y int) uint16 {
    var n int
    
    
    
    for _, o := range ko {
        
        c, ok := g0.GetPx(x+o[0], y+o[1])
        if !ok {
            continue
        }
        
        var i int
        for ; i < n; i++ {
            if c < kc[i] {
                for j := n; j > i; j-- {
                    kc[j] = kc[j-1]
                }
                break
            }
        }
        kc[i] = c
        n++
    }
    
    switch {
    case n == len(kc): 
        return kc[mid]
    case n%2 == 1: 
        return kc[n/2]
    }
    
    m := n / 2
    return (kc[m-1] + kc[m]) / 2
}




Python: import Image, ImageFilter
im = Image.open('image.ppm')

median = im.filter(ImageFilter.MedianFilter(3))
median.save('image2.ppm')
Task: Run as a daemon or service




Go: package main

import (
    "fmt"
    "github.com/sevlyar/go-daemon"
    "log"
    "os"
    "time"
)

func work() {
    f, err := os.Create("daemon_output.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    ticker := time.NewTicker(time.Second)
    go func() {
        for t := range ticker.C {
            fmt.Fprintln(f, t) 
        }
    }()
    time.Sleep(60 * time.Second) 
    ticker.Stop()
    log.Print("ticker stopped")
}

func main() {
    cntxt := &daemon.Context{
        PidFileName: "pid",
        PidFilePerm: 0644,
        LogFileName: "log",
        LogFilePerm: 0640,
        WorkDir:     "./",
        Umask:       027,
        Args:        []string{"[Rosetta Code daemon example]"},
    }

    d, err := cntxt.Reborn()
    if err != nil {
        log.Fatal("Unable to run: ", err)
    }
    if d != nil {
        return
    }
    defer cntxt.Release()

    log.Print("- - - - - - - - - - - - - - -")
    log.Print("daemon started")

    work()
}




Python: 
import posix
import os
import sys

pid = posix.fork()
if pid != 0:
    print("Child process detached with pid %s" % pid)
    sys.exit(0)

old_stdin = sys.stdin
old_stdout = sys.stdout
old_stderr = sys.stderr

sys.stdin = open('/dev/null', 'rt')
sys.stdout = open('/tmp/dmn.log', 'wt')
sys.stderr = sys.stdout

old_stdin.close()
old_stdout.close()
old_stderr.close()

posix.setsid()

import time
t = time.time()
while time.time() < t + 10:
    print("timer running, %s seconds" % str(time.time() - t))
    time.sleep(1)
Task: Coprime triplets




Go: package main

import (
    "fmt"
    "rcu"
)

func contains(a []int, v int) bool {
    for _, e := range a {
        if e == v {
            return true
        }
    }
    return false
}

func main() {
    const limit = 50
    cpt := []int{1, 2}
    for {
        m := 1
        l := len(cpt)
        for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {
            m++
        }
        if m >= limit {
            break
        }
        cpt = append(cpt, m)
    }
    fmt.Printf("Coprime triplets under %d:\n", limit)
    for i, t := range cpt {
        fmt.Printf("%2d ", t)
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n\nFound %d such numbers\n", len(cpt))
}




Python: 












def Gcd(v1, v2):
    a, b = v1, v2
    if (a < b):
        a, b = v2, v1
    r = 1
    while (r != 0):
        r = a % b
        if (r != 0):
            a = b
            b = r
    return b


a = [1, 2]

n = 3

while (n < 50):
    gcd1 = Gcd(n, a[-1])
    gcd2 = Gcd(n, a[-2])
    
    
    if (gcd1 == 1 and gcd2 == 1 and not(n in a)):
        
        a.append(n)
        n = 3
    else:
        
        n += 1


for i in range(0, len(a)):
    if (i % 10 == 0):
        print('')
    print("%4d" % a[i], end = '');
    

print("\n\nNumber of elements in coprime triplets = " + str(len(a)), end = "\n")
Task: Variable declaration reset




Go: package main

import "fmt"

func main() {
    s := []int{1, 2, 2, 3, 4, 4, 5}

    
    
    for i := 0; i < len(s); i++ {
        curr := s[i]
        var prev int
        if i > 0 && curr == prev {
            fmt.Println(i)
        }
        prev = curr
    }

    
    
    var prev int
    for i := 0; i < len(s); i++ {
        curr := s[i]
        if i > 0 && curr == prev {
            fmt.Println(i)
        }
        prev = curr
    }
}




Python: s = [1, 2, 2, 3, 4, 4, 5]
 
for i in range(len(s)):
    curr = s[i]
    if i > 0 and curr == prev:
        print(i)
    prev = curr
Task: SOAP




Go: package main

import (
    "fmt"
    "github.com/tiaguinho/gosoap"
    "log"
)

type CheckVatResponse struct {
    CountryCode string `xml:"countryCode"`
    VatNumber   string `xml:"vatNumber"`
    RequestDate string `xml:"requestDate"`
    Valid       string `xml:"valid"`
    Name        string `xml:"name"`
    Address     string `xml:"address"`
}

var (
    rv CheckVatResponse
)

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    
    soap, err := gosoap.SoapClient("http:

    
    params := gosoap.Params{
        "vatNumber":   "6388047V",
        "countryCode": "IE",
    }

    
    err = soap.Call("checkVat", params)
    check(err)

    
    err = soap.Unmarshal(&rv)
    check(err)

    
    fmt.Println("Country Code  : ", rv.CountryCode)
    fmt.Println("Vat Number    : ", rv.VatNumber)
    fmt.Println("Request Date  : ", rv.RequestDate)
    fmt.Println("Valid         : ", rv.Valid)
    fmt.Println("Name          : ", rv.Name)
    fmt.Println("Address       : ", rv.Address)
}




Python: from SOAPpy import WSDL 
proxy = WSDL.Proxy("http://example.com/soap/wsdl")
result = proxy.soapFunc("hello")
result = proxy.anotherSoapFunc(34234)
Task: Pragmatic directives







Python: Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import __future__
>>> __future__.all_feature_names
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL']
>>>
Task: Find first and last set bit of a long integer




Go: package main

import (
    "fmt"
    "math/big"
)

const (
    mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota
    mask1, bit1
    mask2, bit2
    mask3, bit3
    mask4, bit4
    mask5, bit5
)

func rupb(x uint64) (out int) {
    if x == 0 {
        return -1
    }
    if x&^mask5 != 0 {
        x >>= bit5
        out |= bit5
    }
    if x&^mask4 != 0 {
        x >>= bit4
        out |= bit4
    }
    if x&^mask3 != 0 {
        x >>= bit3
        out |= bit3
    }
    if x&^mask2 != 0 {
        x >>= bit2
        out |= bit2
    }
    if x&^mask1 != 0 {
        x >>= bit1
        out |= bit1
    }
    if x&^mask0 != 0 {
        out |= bit0
    }
    return
}

func rlwb(x uint64) (out int) {
    if x == 0 {
        return 0
    }
    if x&mask5 == 0 {
        x >>= bit5
        out |= bit5
    }
    if x&mask4 == 0 {
        x >>= bit4
        out |= bit4
    }
    if x&mask3 == 0 {
        x >>= bit3
        out |= bit3
    }
    if x&mask2 == 0 {
        x >>= bit2
        out |= bit2
    }
    if x&mask1 == 0 {
        x >>= bit1
        out |= bit1
    }
    if x&mask0 == 0 {
        out |= bit0
    }
    return
}





func rupbBig(x *big.Int) int {
    return x.BitLen() - 1
}




func rlwbBig(x *big.Int) int {
    if x.BitLen() < 2 {
        return 0
    }
    bit := uint(1)
    mask := big.NewInt(1)
    var ms []*big.Int
    var y, z big.Int
    for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {
        ms = append(ms, mask)
        mask = new(big.Int).Or(mask, &z)
        bit <<= 1
    }
    out := bit
    for i := len(ms) - 1; i >= 0; i-- {
        bit >>= 1
        if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {
            out |= bit
        }
    }
    return int(out)
}

func main() {
    show()
    showBig()
}

func show() {
    fmt.Println("uint64:")
    fmt.Println("power              number  rupb  rlwb")
    const base = 42
    n := uint64(1)
    for i := 0; i < 12; i++ {
        fmt.Printf("%d^%02d %19d %5d %5d\n", base, i, n, rupb(n), rlwb(n))
        n *= base
    }
}

func showBig() {
    fmt.Println("\nbig numbers:")
    fmt.Println("  power                               number  rupb  rlwb")
    base := big.NewInt(1302)
    n := big.NewInt(1)
    for i := 0; i < 12; i++ {
        fmt.Printf("%d^%02d %36d %5d %5d\n", base, i, n, rupbBig(n), rlwbBig(n))
        n.Mul(n, base)
    }
}




Python: def msb(x):
    return x.bit_length() - 1

def lsb(x):
    return msb(x & -x)

for i in range(6):
    x = 42 ** i
    print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))

for i in range(6):
    x = 1302 ** i
    print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
Task: Numbers with equal rises and falls




Go: package main

import "fmt"

func risesEqualsFalls(n int) bool {
    if n < 10 {
        return true
    }
    rises := 0
    falls := 0
    prev := -1
    for n > 0 {
        d := n % 10
        if prev >= 0 {
            if d < prev {
                rises = rises + 1
            } else if d > prev {
                falls = falls + 1
            }
        }
        prev = d
        n /= 10   
    }
    return rises == falls
}

func main() {
    fmt.Println("The first 200 numbers in the sequence are:")
    count := 0
    n := 1
    for {
        if risesEqualsFalls(n) {
            count++
            if count <= 200 {
                fmt.Printf("%3d ", n)
                if count%20 == 0 {
                    fmt.Println()
                }
            }
            if count == 1e7 {
                fmt.Println("\nThe 10 millionth number in the sequence is ", n)
                break
            }
        }
        n++
    }
}




Python: import itertools

def riseEqFall(num):
    
    height = 0
    d1 = num % 10
    num //= 10
    while num:
        d2 = num % 10
        height += (d1<d2) - (d1>d2)
        d1 = d2
        num //= 10
    return height == 0
    
def sequence(start, fn):
    
    num=start-1
    while True:
        num += 1
        while not fn(num): num += 1
        yield num

a296712 = sequence(1, riseEqFall)


print("The first 200 numbers are:")
print(*itertools.islice(a296712, 200))


print("The 10,000,000th number is:")
print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))
Task: Terminal control_Cursor movement




Go: package main

import (
    "fmt"
    "time"
    "os"
    "os/exec"
    "strconv"
)

func main() {
    tput("clear") 
    tput("cup", "6", "3") 
    time.Sleep(1 * time.Second)
    tput("cub1") 
    time.Sleep(1 * time.Second)
    tput("cuf1") 
    time.Sleep(1 * time.Second)
    tput("cuu1") 
    time.Sleep(1 * time.Second)
    
    tput("cud", "1") 
    time.Sleep(1 * time.Second)
    tput("cr") 
    time.Sleep(1 * time.Second)
    
    var h, w int
    cmd := exec.Command("stty", "size")
    cmd.Stdin = os.Stdin
    d, _ := cmd.Output()
    fmt.Sscan(string(d), &h, &w)
    
    tput("hpa", strconv.Itoa(w-1))
    time.Sleep(2 * time.Second)
    
    tput("home")
    time.Sleep(2 * time.Second)
    
    tput("cup", strconv.Itoa(h-1), strconv.Itoa(w-1))
    time.Sleep(3 * time.Second)
}

func tput(args ...string) error {
    cmd := exec.Command("tput", args...)
    cmd.Stdout = os.Stdout
    return cmd.Run()
}




Python: import curses

scr = curses.initscr()

def move_left():
	y,x = curses.getyx()
	curses.move(y,x-1)
	

def move_right():
	y,x = curses.getyx()
	curses.move(y,x+1)
	

def move_up():
	y,x = curses.getyx()
	curses.move(y-1,x)
	

def move_down():
	y,x = curses.getyx()
	curses.move(y+1,x)


def move_line_home()	
	y,x = curses.getyx()
	curses.move(y,0)


def move_line_end()	
	y,x = curses.getyx()
	maxy,maxx = scr.getmaxyx()
	curses.move(y,maxx)


def move_page_home():
	curses.move(0,0)
	

def move_page_end():
	y,x = scr.getmaxyx()
	curses.move(y,x)
Task: Summation of primes




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    sum := 0
    for _, p := range rcu.Primes(2e6 - 1) {
        sum += p
    }
    fmt.Printf("The sum of all primes below 2 million is %s.\n", rcu.Commatize(sum))
}




Python: 

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

if __name__ == '__main__':
    suma = 2
    n = 1
    for i in range(3, 2000000, 2):
        if isPrime(i):
            suma += i
            n+=1 
    print(suma)
Task: Koch curve




Go: package main

import (
    "github.com/fogleman/gg"
    "math"
)

var dc = gg.NewContext(512, 512)

func koch(x1, y1, x2, y2 float64, iter int) {
    angle := math.Pi / 3 
    x3 := (x1*2 + x2) / 3
    y3 := (y1*2 + y2) / 3
    x4 := (x1 + x2*2) / 3
    y4 := (y1 + y2*2) / 3
    x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)
    y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)
    if iter > 0 {
        iter--
        koch(x1, y1, x3, y3, iter)
        koch(x3, y3, x5, y5, iter)
        koch(x5, y5, x4, y4, iter)
        koch(x4, y4, x2, y2, iter)
    } else {
        dc.LineTo(x1, y1)
        dc.LineTo(x3, y3)
        dc.LineTo(x5, y5)
        dc.LineTo(x4, y4)
        dc.LineTo(x2, y2)
    }
}

func main() {
    dc.SetRGB(1, 1, 1) 
    dc.Clear()
    koch(100, 100, 400, 400, 4)
    dc.SetRGB(0, 0, 1) 
    dc.SetLineWidth(2)
    dc.Stroke()
    dc.SavePNG("koch.png")
}




Python: l = 300

def setup():
    size(400, 400)
    background(0, 0, 255)
    stroke(255)
    
    translate(width / 2.0, height / 2.0)
    
    translate(-l / 2.0, l * sqrt(3) / 6.0)
    for i in range(4):
        kcurve(0, l)
        rotate(radians(120))
        translate(-l, 0)


def kcurve(x1, x2):
    s = (x2 - x1) / 3.0
    if s < 5:
        pushMatrix()
        translate(x1, 0)
        line(0, 0, s, 0)
        line(2 * s, 0, 3 * s, 0)
        translate(s, 0)
        rotate(radians(60))
        line(0, 0, s, 0)
        translate(s, 0)
        rotate(radians(-120))
        line(0, 0, s, 0)
        popMatrix()
        return

    pushMatrix()
    translate(x1, 0)
    kcurve(0, s)
    kcurve(2 * s, 3 * s)
    translate(s, 0)
    rotate(radians(60))
    kcurve(0, s)
    translate(s, 0)
    rotate(radians(-120))
    kcurve(0, s)
    popMatrix()
Task: Draw pixel 2




Go: package main

import (
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "math/rand"
    "time"
)

func main() {
    rect := image.Rect(0, 0, 640, 480)
    img := image.NewRGBA(rect)

    
    blue := color.RGBA{0, 0, 255, 255}
    draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src)

    
    yellow := color.RGBA{255, 255, 0, 255}
    width := img.Bounds().Dx()
    height := img.Bounds().Dy()
    rand.Seed(time.Now().UnixNano())
    x := rand.Intn(width)
    y := rand.Intn(height)
    img.Set(x, y, yellow)

    
    cmap := map[color.Color]string{blue: "blue", yellow: "yellow"}
    for i := 0; i < width; i++ {
        for j := 0; j < height; j++ {
            c := img.At(i, j)
            if cmap[c] == "yellow" {
                fmt.Printf("The color of the pixel at (%d, %d) is yellow\n", i, j)
            }
        }
    }
}




Python: import Tkinter,random
def draw_pixel_2 ( sizex=640,sizey=480 ):
    pos  = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )
    root = Tkinter.Tk()
    can  = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )
    can.create_rectangle( pos*2,outline='yellow' )
    can.pack()
    root.title('press ESCAPE to quit')
    root.bind('<Escape>',lambda e : root.quit())
    root.mainloop()

draw_pixel_2()
Task: Count how many vowels and consonants occur in a string




Go: package main

import (
    "fmt"
    "strings"
)

func main() {
    const (
        vowels     = "aeiou"
        consonants = "bcdfghjklmnpqrstvwxyz"
    )
    strs := []string{
        "Forever Go programming language",
        "Now is the time for all good men to come to the aid of their country.",
    }
    for _, str := range strs {
        fmt.Println(str)
        str = strings.ToLower(str)
        vc, cc := 0, 0
        vmap := make(map[rune]bool)
        cmap := make(map[rune]bool)
        for _, c := range str {
            if strings.ContainsRune(vowels, c) {
                vc++
                vmap[c] = true
            } else if strings.ContainsRune(consonants, c) {
                cc++
                cmap[c] = true
            }
        }
        fmt.Printf("contains (total) %d vowels and %d consonants.\n", vc, cc)
        fmt.Printf("contains (distinct %d vowels and %d consonants.\n\n", len(vmap), len(cmap))
    }
}




Python: def isvowel(c):
    
    return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', "I", 'O', 'U']

def isletter(c):
    
    return 'a' <= c <= 'z' or 'A' <= c <= 'Z'

def isconsonant(c):
    
    return  not isvowel(c) and isletter(c)

def vccounts(s):
    
    a = list(s.lower())
    au = set(a)
    return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \
        sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])

def testvccount():
    teststrings = [
        "Forever Python programming language",
        "Now is the time for all good men to come to the aid of their country."]
    for s in teststrings:
        vcnt, ccnt, vu, cu = vccounts(s)
        print(f"String: {s}\n    Vowels: {vcnt} (distinct {vu})\n    Consonants: {ccnt} (distinct {cu})\n")

testvccount()
Task: Draw a pixel




Go: package main

import (
    "fmt"
    "image"
    "image/color"
    "image/draw"
)

func main() {
    rect := image.Rect(0, 0, 320, 240)
    img := image.NewRGBA(rect)

    
    green := color.RGBA{0, 255, 0, 255}
    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)

    
    red := color.RGBA{255, 0, 0, 255}
    img.Set(100, 100, red)

    
    cmap := map[color.Color]string{green: "green", red: "red"}
    c1 := img.At(0, 0)
    c2 := img.At(100, 100)
    fmt.Println("The color of the pixel at (  0,   0) is", cmap[c1], "\b.")
    fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.")
}




Python: from PIL import Image

img = Image.new('RGB', (320, 240))
pixels = img.load()
pixels[100,100] = (255,0,0)
img.show()
Task: Numbers whose binary and ternary digit sums are prime




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    var numbers []int
    for i := 2; i < 200; i++ {
        bds := rcu.DigitSum(i, 2)
        if rcu.IsPrime(bds) {
            tds := rcu.DigitSum(i, 3)
            if rcu.IsPrime(tds) {
                numbers = append(numbers, i)
            }
        }
    }
    fmt.Println("Numbers < 200 whose binary and ternary digit sums are prime:")
    for i, n := range numbers {
        fmt.Printf("%4d", n)
        if (i+1)%14 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n\n%d such numbers found\n", len(numbers))
}




Python: 



def digitSumsPrime(n):
    
    def go(bases):
        return all(
            isPrime(digitSum(b)(n))
            for b in bases
        )
    return go



def digitSum(base):
    
    def go(n):
        q, r = divmod(n, base)
        return go(q) + r if n else 0
    return go




def main():
    
    xs = [
        str(n) for n in range(1, 200)
        if digitSumsPrime(n)([2, 3])
    ]
    print(f'{len(xs)} matches in [1..199]\n')
    print(table(10)(xs))





def chunksOf(n):
    
    def go(xs):
        return (
            xs[i:n + i] for i in range(0, len(xs), n)
        ) if 0 < n else None
    return go



def isPrime(n):
    
    if n in (2, 3):
        return True
    if 2 > n or 0 == n % 2:
        return False
    if 9 > n:
        return True
    if 0 == n % 3:
        return False

    def p(x):
        return 0 == n % x or 0 == n % (2 + x)

    return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))



def table(n):
    
    def go(xs):
        w = len(xs[-1])
        return '\n'.join(
            ' '.join(row) for row in chunksOf(n)([
                s.rjust(w, ' ') for s in xs
            ])
        )
    return go



if __name__ == '__main__':
    main()