WeixiangYan/CodeTransOcean huggingface dataset:
Task: Spiral matrix




Go: package main

import (
    "fmt"
    "strconv"
)

var n = 5

func main() {
    if n < 1 {
        return
    }
    top, left, bottom, right := 0, 0, n-1, n-1
    sz := n * n
    a := make([]int, sz)
    i := 0
    for left < right {
        
        for c := left; c <= right; c++ {
            a[top*n+c] = i
            i++
        }
        top++
        
        for r := top; r <= bottom; r++ {
            a[r*n+right] = i
            i++
        }
        right--
        if top == bottom {
            break
        }
        
        for c := right; c >= left; c-- {
            a[bottom*n+c] = i
            i++
        }
        bottom--
        
        for r := bottom; r >= top; r-- {
            a[r*n+left] = i
            i++
        }
        left++
    }
    
    a[top*n+left] = i

    
    w := len(strconv.Itoa(n*n - 1))
    for i, e := range a {
        fmt.Printf("%*d ", w, e)
        if i%n == n-1 {
            fmt.Println("")
        }
    }
}




Python: def spiral(n):
    dx,dy = 1,0            
    x,y = 0,0              
    myarray = [[None]* n for j in range(n)]
    for i in xrange(n**2):
        myarray[x][y] = i
        nx,ny = x+dx, y+dy
        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:
            x,y = nx,ny
        else:
            dx,dy = -dy,dx
            x,y = x+dx, y+dy
    return myarray

def printspiral(myarray):
    n = range(len(myarray))
    for y in n:
        for x in n:
            print "%2i" % myarray[x][y],
        print

printspiral(spiral(5))
Task: Optional parameters




Go: type cell string

type spec struct {
    less     func(cell, cell) bool
    column   int
    reverse  bool
}

func newSpec() (s spec) {
    
    return
}


t.sort(newSpec())


s := newSpec
s.reverse = true
t.sort(s)




Python: >>> def printtable(data):
    for row in data:
        print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)

        
>>> import operator
>>> def sorttable(table, ordering=None, column=0, reverse=False):
    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)

>>> data = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]]
>>> printtable(data)
"a"   "b"   "c"  
""    "q"   "z"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data) )
""    "q"   "z"  
"a"   "b"   "c"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=2) )
"zap" "zip" "Zot"
"a"   "b"   "c"  
""    "q"   "z"  
>>> printtable( sorttable(data, column=1) )
"a"   "b"   "c"  
""    "q"   "z"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=1, reverse=True) )
"zap" "zip" "Zot"
""    "q"   "z"  
"a"   "b"   "c"  
>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )
"zap" "zip" "Zot"
"a"   "b"   "c"  
""    "q"   "z"  
>>>
Task: Voronoi diagram




Go: package main

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

const (
    imageWidth  = 300
    imageHeight = 200
    nSites      = 10
)

func main() {
    writePngFile(generateVoronoi(randomSites()))
}

func generateVoronoi(sx, sy []int) image.Image {
    
    sc := make([]color.NRGBA, nSites)
    for i := range sx {
        sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),
            uint8(rand.Intn(256)), 255}
    }

    
    img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))
    for x := 0; x < imageWidth; x++ {
        for y := 0; y < imageHeight; y++ {
            dMin := dot(imageWidth, imageHeight)
            var sMin int
            for s := 0; s < nSites; s++ {
                if d := dot(sx[s]-x, sy[s]-y); d < dMin {
                    sMin = s
                    dMin = d
                }
            }
            img.SetNRGBA(x, y, sc[sMin])
        }
    }
    
    black := image.NewUniform(color.Black)
    for s := 0; s < nSites; s++ {
        draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),
            black, image.ZP, draw.Src)
    }
    return img
}

func dot(x, y int) int {
    return x*x + y*y
}

func randomSites() (sx, sy []int) {
    rand.Seed(time.Now().Unix())
    sx = make([]int, nSites)
    sy = make([]int, nSites)
    for i := range sx {
        sx[i] = rand.Intn(imageWidth)
        sy[i] = rand.Intn(imageHeight)
    }
    return
}

func writePngFile(img image.Image) {
    f, err := os.Create("voronoi.png")
    if err != nil {
        fmt.Println(err)
        return
    }
    if err = png.Encode(f, img); err != nil {
        fmt.Println(err)
    }
    if err = f.Close(); err != nil {
        fmt.Println(err)
    }
}




Python: def setup():
    size(500, 500)
    generate_voronoi_diagram(width, height, 25)
    saveFrame("VoronoiDiagram.png")

def generate_voronoi_diagram(w, h, num_cells):
    nx, ny, nr, ng, nb = [], [], [], [], [] 
    for i in range(num_cells):
        nx.append(int(random(w)))
        ny.append(int(random(h)))
        nr.append(int(random(256)))
        ng.append(int(random(256)))
        nb.append(int(random(256)))
    for y in range(h):
        for x in range(w):
            dmin = dist(0, 0, w - 1, h - 1)
            j = -1
            for i in range(num_cells):
                d = dist(0, 0, nx[i] - x, ny[i] - y)
                if d < dmin:
                    dmin = d
                    j = i
            set(x, y, color(nr[j], ng[j], nb[j]))
Task: Call a foreign-language function




Go: package main



import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    
    go1 := "hello C"
    
    c1 := C.CString(go1)
    
    go1 = ""
    
    c2 := C.strdup(c1)
    
    C.free(unsafe.Pointer(c1))
    
    go2 := C.GoString(c2)
    
    C.free(unsafe.Pointer(c2))
    
    fmt.Println(go2)
}




Python: import ctypes
libc = ctypes.CDLL("/lib/libc.so.6")
libc.strcmp("abc", "def")     
libc.strcmp("hello", "hello")
Task: Knuth's algorithm S




Go: package main

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

func sOfNCreator(n int) func(byte) []byte {
    s := make([]byte, 0, n)
    m := n
    return func(item byte) []byte {
        if len(s) < n {
            s = append(s, item)
        } else {
            m++
            if rand.Intn(m) < n {
                s[rand.Intn(n)] = item
            }
        }
        return s
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    var freq [10]int
    for r := 0; r < 1e5; r++ {
        sOfN := sOfNCreator(3)
        for d := byte('0'); d < '9'; d++ {
            sOfN(d)
        }
        for _, d := range sOfN('9') {
            freq[d-'0']++
        }
    }
    fmt.Println(freq)
}




Python: from random import randrange

def s_of_n_creator(n):
    sample, i = [], 0
    def s_of_n(item):
        nonlocal i

        i += 1
        if i <= n:
            
            sample.append(item)
        elif randrange(i) < n:
            
            sample[randrange(n)] = item
        return sample
    return s_of_n

if __name__ == '__main__':
    bin = [0]* 10
    items = range(10)
    print("Single run samples for n = 3:")
    s_of_n = s_of_n_creator(3)
    for item in items:
        sample = s_of_n(item)
        print("  Item: %i -> sample: %s" % (item, sample))
    
    for trial in range(100000):
        s_of_n = s_of_n_creator(3)
        for item in items:
            sample = s_of_n(item)
        for s in sample:
            bin[s] += 1
    print("\nTest item frequencies for 100000 runs:\n ",
          '\n  '.join("%i:%i" % x for x in enumerate(bin)))
Task: Command-line arguments




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

func main() {
	for i, x := range os.Args[1:] {
		fmt.Printf("the argument #%d is %s\n", i, x)
	}
}




Python: import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
Task: Array concatenation




Go: package main

import "fmt"

func main() {
    
    
    a := []int{1, 2, 3}
    b := []int{7, 12, 60} 
    c := append(a, b...)
    fmt.Println(c)

    
    
    
    i := []interface{}{1, 2, 3}
    j := []interface{}{"Crosby", "Stills", "Nash", "Young"}
    k := append(i, j...) 
    fmt.Println(k)

    
    
    
    
    
    
    
    l := [...]int{1, 2, 3}
    m := [...]int{7, 12, 60} 
    var n [len(l) + len(m)]int
    copy(n[:], l[:]) 
    copy(n[len(l):], m[:])
    fmt.Println(n)

}




Python: arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2
assert arr4 == [1, 2, 3, 4, 5, 6]
arr4.extend(arr3)
assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
Task: User input_Text




Go: package main

import "fmt"

func main() {
    var s string
    var i int
    if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
        fmt.Println("good")
    } else {
        fmt.Println("wrong")
    }
}




Python:    string = raw_input("Input a string: ")
Task: Musical scale




Go: package main

import (
    "encoding/binary"
    "log"
    "math"
    "os"
    "strings"
)

func main() {
    const (
        sampleRate = 44100
        duration   = 8
        dataLength = sampleRate * duration
        hdrSize    = 44
        fileLen    = dataLength + hdrSize - 8
    )

    
    buf1 := make([]byte, 1)
    buf2 := make([]byte, 2)
    buf4 := make([]byte, 4)

    
    var sb strings.Builder
    sb.WriteString("RIFF")
    binary.LittleEndian.PutUint32(buf4, fileLen)
    sb.Write(buf4) 
    sb.WriteString("WAVE")
    sb.WriteString("fmt ")
    binary.LittleEndian.PutUint32(buf4, 16)
    sb.Write(buf4) 
    binary.LittleEndian.PutUint16(buf2, 1)
    sb.Write(buf2) 
    sb.Write(buf2) 
    binary.LittleEndian.PutUint32(buf4, sampleRate)
    sb.Write(buf4) 
    sb.Write(buf4) 
    sb.Write(buf2) 
    binary.LittleEndian.PutUint16(buf2, 8)
    sb.Write(buf2) 
    sb.WriteString("data")
    binary.LittleEndian.PutUint32(buf4, dataLength)
    sb.Write(buf4) 
    wavhdr := []byte(sb.String())

    
    f, err := os.Create("notes.wav")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    f.Write(wavhdr)

    
    freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
    for j := 0; j < duration; j++ {
        freq := freqs[j]
        omega := 2 * math.Pi * freq
        for i := 0; i < dataLength/duration; i++ {
            y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))
            buf1[0] = byte(math.Round(y))
            f.Write(buf1)
        }
    }
}




Python: >>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
	winsound.Beep(int(note+.5), 500)	
>>>
Task: Knapsack problem_0-1




Go: package main

import "fmt"

type item struct {
    string
    w, v int
}

var wants = []item{
    {"map", 9, 150},
    {"compass", 13, 35},
    {"water", 153, 200},
    {"sandwich", 50, 160},
    {"glucose", 15, 60},
    {"tin", 68, 45},
    {"banana", 27, 60},
    {"apple", 39, 40},
    {"cheese", 23, 30},
    {"beer", 52, 10},
    {"suntan cream", 11, 70},
    {"camera", 32, 30},
    {"T-shirt", 24, 15},
    {"trousers", 48, 10},
    {"umbrella", 73, 40},
    {"waterproof trousers", 42, 70},
    {"waterproof overclothes", 43, 75},
    {"note-case", 22, 80},
    {"sunglasses", 7, 20},
    {"towel", 18, 12},
    {"socks", 4, 50},
    {"book", 30, 10},
}

const maxWt = 400

func main() {
    items, w, v := m(len(wants)-1, maxWt)
    fmt.Println(items)
    fmt.Println("weight:", w)
    fmt.Println("value:", v)
}

func m(i, w int) ([]string, int, int) {
    if i < 0 || w == 0 {
        return nil, 0, 0
    } else if wants[i].w > w {
        return m(i-1, w)
    }
    i0, w0, v0 := m(i-1, w)
    i1, w1, v1 := m(i-1, w-wants[i].w)
    v1 += wants[i].v
    if v1 > v0 {
        return append(i1, wants[i].string), w1 + wants[i].w, v1
    }
    return i0, w0, v0
}




Python: from itertools import combinations

def anycomb(items):
    ' return combinations of any length from the items '
    return ( comb
             for r in range(1, len(items)+1)
             for comb in combinations(items, r)
             )

def totalvalue(comb):
    ' Totalise a particular combination of items'
    totwt = totval = 0
    for item, wt, val in comb:
        totwt  += wt
        totval += val
    return (totval, -totwt) if totwt <= 400 else (0, 0)

items = (
    ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160),
    ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40),
    ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30),
    ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40),
    ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75),
    ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12),
    ("socks", 4, 50), ("book", 30, 10),
    )
bagged = max( anycomb(items), key=totalvalue) 
print("Bagged the following items\n  " +
      '\n  '.join(sorted(item for item,_,_ in bagged)))
val, wt = totalvalue(bagged)
print("for a total value of %i and a total weight of %i" % (val, -wt))
Task: Cartesian product of two or more lists




Go: package main

import "fmt"

type pair [2]int

func cart2(a, b []int) []pair {
    p := make([]pair, len(a)*len(b))
    i := 0
    for _, a := range a {
        for _, b := range b {
            p[i] = pair{a, b}
            i++
        }
    }
    return p
}

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




Python: import itertools

def cp(lsts):
    return list(itertools.product(*lsts))

if __name__ == '__main__':
    from pprint import pprint as pp
    
    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],
                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),
                  ((1, 2, 3), (30,), (500, 100)),
                  ((1, 2, 3), (), (500, 100))]:
        print(lists, '=>')
        pp(cp(lists), indent=2)
Task: First-class functions




Go: package main

import "math"
import "fmt"


func cube(x float64) float64 { return math.Pow(x, 3) }


type ffType func(float64) float64

func compose(f, g ffType) ffType {
    return func(x float64) float64 {
        return f(g(x))
    }
}

func main() {
    
    funclist := []ffType{math.Sin, math.Cos, cube}
    
    funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
    for i := 0; i < 3; i++ {
        
        fmt.Println(compose(funclisti[i], funclist[i])(.5))
    }
}




Python: >>> 
>>> from math import sin, cos, acos, asin
>>> 
>>> cube = lambda x: x * x * x
>>> croot = lambda x: x ** (1/3.0)
>>> 
>>> 
>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )
>>> 
>>> funclist = [sin, cos, cube]
>>> funclisti = [asin, acos, croot]
>>> 
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>>
Task: Proper divisors




Go: package main

import (
    "fmt"
    "strconv"
)

func listProperDivisors(limit int) {
    if limit < 1 {
        return
    }
    width := len(strconv.Itoa(limit))
    for i := 1; i <= limit; i++ {
        fmt.Printf("%*d -> ", width, i)
        if i == 1 {
            fmt.Println("(None)")
            continue
        }
        for j := 1; j <= i/2; j++ {
            if i%j == 0 {
                fmt.Printf(" %d", j)
            }
        }
        fmt.Println()
    }
}

func countProperDivisors(n int) int {
    if n < 2 {
        return 0
    }
    count := 0
    for i := 1; i <= n/2; i++ {
        if n%i == 0 {
            count++
        }
    }
    return count
}

func main() {
    fmt.Println("The proper divisors of the following numbers are :\n")
    listProperDivisors(10)
    fmt.Println()
    maxCount := 0
    most := []int{1}
    for n := 2; n <= 20000; n++ {
        count := countProperDivisors(n)
        if count == maxCount {
            most = append(most, n)
        } else if count > maxCount {
            maxCount = count
            most = most[0:1]
            most[0] = n
        }
    }
    fmt.Print("The following number(s) <= 20000 have the most proper divisors, ")
    fmt.Println("namely", maxCount, "\b\n")
    for _, n := range most {
        fmt.Println(n)
    }
}




Python: >>> def proper_divs2(n):
...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}
... 
>>> [proper_divs2(n) for n in range(1, 11)]
[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]
>>> 
>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])
>>> n
15120
>>> length
79
>>>
Task: XML_Output




Go: package main

import (
    "encoding/xml"
    "fmt"
)


func xRemarks(r CharacterRemarks) (string, error) {
    b, err := xml.MarshalIndent(r, "", "    ")
    return string(b), err
}



type CharacterRemarks struct {
    Character []crm
}

type crm struct {
    Name   string `xml:"name,attr"`
    Remark string `xml:",chardata"`
}

func main() {
    x, err := xRemarks(CharacterRemarks{[]crm{
        {`April`, `Bubbly: I'm > Tam and <= Emily`},
        {`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`},
        {`Emily`, `Short & shrift`},
    }})
    if err != nil {
        x = err.Error()
    }
    fmt.Println(x)
}




Python: >>> from xml.etree import ElementTree as ET
>>> from itertools import izip
>>> def characterstoxml(names, remarks):
	root = ET.Element("CharacterRemarks")
	for name, remark in izip(names, remarks):
		c = ET.SubElement(root, "Character", {'name': name})
		c.text = remark
	return ET.tostring(root)

>>> print characterstoxml(
	names = ["April", "Tam O'Shanter", "Emily"],
	remarks = [ "Bubbly: I'm > Tam and <= Emily",
		    'Burns: "When chapman billies leave the street ..."',
		    'Short & shrift' ] ).replace('><','>\n<')
Task: Plot coordinate pairs




Go: package main

import (
  "fmt"
  "log"
  "os/exec"
)

var (
  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)

func main() {
  g := exec.Command("gnuplot", "-persist")
  w, err := g.StdinPipe()
  if err != nil {
    log.Fatal(err)
  }
  if err = g.Start(); err != nil {
    log.Fatal(err)
  }
  fmt.Fprintln(w, "unset key; plot '-'")
  for i, xi := range x {
    fmt.Fprintf(w, "%d %f\n", xi, y[i])
  }
  fmt.Fprintln(w, "e")
  w.Close()
  g.Wait()
}




Python: >>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]

>>> import pylab
>>> pylab.plot(x, y, 'bo')
>>> pylab.savefig('qsort-range-10-9.png')
Task: Regular expressions




Go: package main
import "fmt"
import "regexp"

func main() {
  str := "I am the original string"

  
  matched, _ := regexp.MatchString(".*string$", str)
  if matched { fmt.Println("ends with 'string'") }

  
  pattern := regexp.MustCompile("original")
  result := pattern.ReplaceAllString(str, "modified")
  fmt.Println(result)
}




Python: import re

string = "This is a string"

if re.search('string$', string):
    print("Ends with string.")

string = re.sub(" a ", " another ", string)
print(string)
Task: Guess the number_With feedback (player)




Go: package main

import (
    "fmt"
    "sort"
)

func main() {
    lower, upper := 0, 100
    fmt.Printf(`Instructions:
Think of integer number from %d (inclusive) to %d (exclusive) and
I will guess it. After each guess, I will ask you if it is less than
or equal to some number, and you will respond with "yes" or "no".
`, lower, upper)
    answer := sort.Search(upper-lower, func (i int) bool {
        fmt.Printf("Is your number less than or equal to %d? ", lower+i)
        s := ""
        fmt.Scanf("%s", &s)
        return s != "" && s[0] == 'y'
    })
    fmt.Printf("Your number is %d.\n", lower+answer)
}




Python: inclusive_range = mn, mx = (1, 10)

print( % inclusive_range)

i = 0
while True:
    i += 1
    guess = (mn+mx)//2
    txt = input("Guess %2i is: %2i. The score for which is (h,l,=): "
                % (i, guess)).strip().lower()[0]
    if txt not in 'hl=':
        print("  I don't understand your input of '%s' ?" % txt)
        continue
    if txt == 'h':
        mx = guess-1
    if txt == 'l':
        mn = guess+1
    if txt == '=':
        print("  Ye-Haw!!")
        break
    if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):
        print("Please check your scoring as I cannot find the value")
        break
        
print("\nThanks for keeping score.")
Task: Hash from two arrays




Go: package main

import "fmt"

func main() {
    keys := []string{"a", "b", "c"}
    vals := []int{1, 2, 3}
    hash := map[string]int{}
    for i, key := range keys {
        hash[key] = vals[i]
    }
    fmt.Println(hash)
}




Python: keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)}
Task: Fractal tree




Go: package main







import (
    "math"
    "raster"
)

const (
    width  = 400
    height = 300
    depth  = 8
    angle  = 12
    length = 50
    frac   = .8
)

func main() {
    g := raster.NewGrmap(width, height)
    ftree(g, width/2, height*9/10, length, 0, depth)
    g.Bitmap().WritePpmFile("ftree.ppm")
}

func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {
    x2 := x + distance*math.Sin(direction*math.Pi/180)
    y2 := y - distance*math.Cos(direction*math.Pi/180)
    g.AaLine(x, y, x2, y2)
    if depth > 0 {
        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)
        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)
    }
}




Python: def setup():
    size(600, 600)
    background(0)
    stroke(255)
    drawTree(300, 550, 9)
    
def drawTree(x, y, depth):
    fork_ang = radians(20)
    base_len = 10
    if depth > 0:
        pushMatrix()
        translate(x, y - baseLen * depth)
        line(0, baseLen * depth, 0, 0)  
        rotate(fork_ang)
        drawTree(0, 0, depth - 1)  
        rotate(2 * -fork_ang)
        drawTree(0, 0, depth - 1) 
        popMatrix()
Task: Colour pinstripe_Display




Go: package main

import "github.com/fogleman/gg"

var palette = [8]string{
    "000000", 
    "FF0000", 
    "00FF00", 
    "0000FF", 
    "FF00FF", 
    "00FFFF", 
    "FFFF00", 
    "FFFFFF", 
}

func pinstripe(dc *gg.Context) {
    w := dc.Width()
    h := dc.Height() / 4
    for b := 1; b <= 4; b++ {
        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
            dc.SetHexColor(palette[ci%8])
            y := h * (b - 1)
            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
            dc.Fill()
        }
    }
}

func main() {
    dc := gg.NewContext(900, 600)
    pinstripe(dc)
    dc.SavePNG("color_pinstripe.png")
}




Python: from turtle import *

colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"]



screen = getscreen()

left_edge = -screen.window_width()//2

right_edge = screen.window_width()//2

quarter_height = screen.window_height()//4

half_height = quarter_height * 2

speed("fastest")

for quarter in range(4):
    pensize(quarter+1)
    colornum = 0

    min_y = half_height - ((quarter + 1) * quarter_height)
    max_y = half_height - ((quarter) * quarter_height)
    
    for x in range(left_edge,right_edge,quarter+1):
        penup()
        pencolor(colors[colornum])
        colornum = (colornum + 1) % len(colors)
        setposition(x,min_y)
        pendown()
        setposition(x,max_y)
         
notused = input("Hit enter to continue: ")