WeixiangYan/CodeTransOcean huggingface dataset:
Task: Rosetta Code_Fix code tags




Go: package main

import "fmt"
import "io/ioutil"
import "log"
import "os"
import "regexp"
import "strings"

func main() {
	err := fix()
	if err != nil {
		log.Fatalln(err)
	}
}

func fix() (err error) {
	buf, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		return err
	}
	out, err := Lang(string(buf))
	if err != nil {
		return err
	}
	fmt.Println(out)
	return nil
}

func Lang(in string) (out string, err error) {
	reg := regexp.MustCompile("<[^>]+>")
	out = reg.ReplaceAllStringFunc(in, repl)
	return out, nil
}

func repl(in string) (out string) {
	if in == "</code>" {
		
		return "</"+"lang>"
	}

	
	mid := in[1 : len(in)-1]

	
	var langs = []string{
		"abap", "actionscript", "actionscript3", "ada", "apache", "applescript",
		"apt_sources", "asm", "asp", "autoit", "avisynth", "bash", "basic4gl",
		"bf", "blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg", "cfm",
		"cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css", "d", "delphi",
		"diff", "_div", "dos", "dot", "eiffel", "email", "fortran", "freebasic",
		"genero", "gettext", "glsl", "gml", "gnuplot", "go", "groovy", "haskell",
		"hq9plus", "html4strict", "idl", "ini", "inno", "intercal", "io", "java",
		"java5", "javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp",
		"lolcode", "lotusformulas", "lotusscript", "lscript", "lua", "m68k",
		"make", "matlab", "mirc", "modula3", "mpasm", "mxml", "mysql", "nsis",
		"objc", "ocaml", "ocaml-brief", "oobas", "oracle11", "oracle8", "pascal",
		"per", "perl", "php", "php-brief", "pic16", "pixelbender", "plsql",
		"povray", "powershell", "progress", "prolog", "providex", "python",
		"qbasic", "rails", "reg", "robots", "ruby", "sas", "scala", "scheme",
		"scilab", "sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm",
		"text", "thinbasic", "tsql", "typoscript", "vb", "vbnet", "verilog",
		"vhdl", "vim", "visualfoxpro", "visualprolog", "whitespace", "winbatch",
		"xml", "xorg_conf", "xpp", "z80",
	}
	for _, lang := range langs {
		if mid == lang {
			
			return fmt.Sprintf("<lang %s>", lang)
		}

		if strings.HasPrefix(mid, "/") {
			if mid[len("/"):] == lang {
				
				return "</"+"lang>"
			}
		}

		if strings.HasPrefix(mid, "code ") {
			if mid[len("code "):] == lang {
				
				return fmt.Sprintf("<lang %s>", lang)
			}
		}
	}

	return in
}




Python: 

from re import sub

testtexts = [
,
    ,
    ]

for txt in testtexts:
    text2 = sub(r'<lang\s+\"?([\w\d\s]+)\"?\s?>', r'<syntaxhighlight lang=\1>', txt)
    text2 = sub(r'<lang\s*>', r'<syntaxhighlight lang=text>', text2)
    text2 = sub(r'</lang\s*>', r'
Task: Permutations with repetitions




Go: package main

import "fmt"

var (
    n      = 3
    values = []string{"A", "B", "C", "D"}
    k      = len(values)
    decide = func(p []string) bool {
        return p[0] == "B" && p[1] == "C"
    }
)

func main() {
    pn := make([]int, n)
    p := make([]string, n)
    for {
        
        for i, x := range pn {
            p[i] = values[x]
        }
        
        fmt.Println(p)
        
        if decide(p) {
            return 
        }
        
        for i := 0; ; {
            pn[i]++
            if pn[i] < k {
                break
            }
            pn[i] = 0
            i++
            if i == n {
                return 
            }
        }
    }
}




Python: 

from itertools import product



def replicateM(n):
    
    def rep(m):
        def go(x):
            return [[]] if 1 > x else (
                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
            )
        return go(n)
    return lambda m: rep(m)




def main():
    
    print(
        fTable(main.__doc__ + ':\n')(repr)(showList)(

            replicateM(2)

        )([[1, 2, 3], 'abc'])
    )





def liftA2List(f):
    
    return lambda xs: lambda ys: [
        f(*xy) for xy in product(xs, ys)
    ]






def fTable(s):
    
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )



def showList(xs):
    
    return '[' + ','.join(
        showList(x) if isinstance(x, list) else repr(x) for x in xs
    ) + ']'



if __name__ == '__main__':
    main()
Task: Exponentiation with infix operators in (or operating on) the base




Go: package main

import (
    "fmt"
    "math"
)

type float float64

func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) }

func main() {
    ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"}
    for _, x := range []float{float(-5), float(5)} {
        for _, e := range []float{float(2), float(3)} {
            fmt.Printf("x = %2.0f e = %0.0f | ", x, e)
            fmt.Printf("%s = %4.0f | ", ops[0], -x.p(e))
            fmt.Printf("%s = %4.0f | ", ops[1], -(x).p(e))
            fmt.Printf("%s = %4.0f | ", ops[2], (-x).p(e))
            fmt.Printf("%s = %4.0f\n", ops[3], -(x.p(e)))
        }
    }
}




Python: from itertools import product

xx = '-5 +5'.split()
pp = '2 3'.split()
texts = '-x**p -(x)**p (-x)**p -(x**p)'.split()

print('Integer variable exponentiation')
for x, p in product(xx, pp):
    print(f'  x,p = {x:2},{p}; ', end=' ')
    x, p = int(x), int(p)
    print('; '.join(f"{t} =={eval(t):4}" for t in texts))

print('\nBonus integer literal exponentiation')
X, P = 'xp'
xx.insert(0, ' 5')
texts.insert(0, 'x**p')
for x, p in product(xx, pp):
    texts2 = [t.replace(X, x).replace(P, p) for t in texts]
    print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))
Task: Common list elements




Go: package main

import "fmt"

func indexOf(l []int, n int) int {
    for i := 0; i < len(l); i++ {
        if l[i] == n {
            return i
        }
    }
    return -1
}

func common2(l1, l2 []int) []int {
    
    c1, c2 := len(l1), len(l2)
    shortest, longest := l1, l2
    if c1 > c2 {
        shortest, longest = l2, l1
    }
    longest2 := make([]int, len(longest))
    copy(longest2, longest) 
    var res []int
    for _, e := range shortest {
        ix := indexOf(longest2, e)
        if ix >= 0 {
            res = append(res, e)
            longest2 = append(longest2[:ix], longest2[ix+1:]...)
        }
    }
    return res
}

func commonN(ll [][]int) []int {
    n := len(ll)
    if n == 0 {
        return []int{}
    }
    if n == 1 {
        return ll[0]
    }
    res := common2(ll[0], ll[1])
    if n == 2 {
        return res
    }
    for _, l := range ll[2:] {
        res = common2(res, l)
    }
    return res
}

func main() {
    lls := [][][]int{
        {{2, 5, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 9, 8, 4}, {1, 3, 7, 6, 9}},
        {{2, 2, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 2, 2, 4}, {2, 3, 7, 6, 2}},
    }
    for _, ll := range lls {
        fmt.Println("Intersection of", ll, "is:")
        fmt.Println(commonN(ll))
        fmt.Println()
    }
}




Python: 

def common_list_elements(*lists):
    return list(set.intersection(*(set(list_) for list_ in lists)))


if __name__ == "__main__":
    test_cases = [
        ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]),
        ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]),
    ]

    for case in test_cases:
        result = common_list_elements(*case)
        print(f"Intersection of {case} is {result}")
Task: Monads_Writer monad




Go: package main

import (
    "fmt"
    "math"
)

type mwriter struct {
    value float64
    log   string
}

func (m mwriter) bind(f func(v float64) mwriter) mwriter {
    n := f(m.value)
    n.log = m.log + n.log
    return n
}

func unit(v float64, s string) mwriter {
    return mwriter{v, fmt.Sprintf("  %-17s: %g\n", s, v)}
}

func root(v float64) mwriter {
    return unit(math.Sqrt(v), "Took square root")
}

func addOne(v float64) mwriter {
    return unit(v+1, "Added one")
}

func half(v float64) mwriter {
    return unit(v/2, "Divided by two")
}

func main() {
    mw1 := unit(5, "Initial value")
    mw2 := mw1.bind(root).bind(addOne).bind(half)
    fmt.Println("The Golden Ratio is", mw2.value)
    fmt.Println("\nThis was derived as follows:-")
    fmt.Println(mw2.log)
}




Python: 
from __future__ import annotations

import functools
import math
import os

from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union


T = TypeVar("T")


class Writer(Generic[T]):
    def __init__(self, value: Union[T, Writer[T]], *msgs: str):
        if isinstance(value, Writer):
            self.value: T = value.value
            self.msgs: List[str] = value.msgs + list(msgs)
        else:
            self.value = value
            self.msgs = list(f"{msg}: {self.value}" for msg in msgs)

    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
        writer = func(self.value)
        return Writer(writer, *self.msgs)

    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
        return self.bind(func)

    def __str__(self):
        return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}"

    def __repr__(self):
        return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")"


def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:
    

    @functools.wraps(func)
    def wrapped(value):
        return Writer(func(value), msg)

    return wrapped


if __name__ == "__main__":
    square_root = lift(math.sqrt, "square root")
    add_one = lift(lambda x: x + 1, "add one")
    half = lift(lambda x: x / 2, "div two")

    print(Writer(5, "initial") >> square_root >> add_one >> half)
Task: Neighbour primes




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    primes := rcu.Primes(504)
    var nprimes []int
    fmt.Println("Neighbour primes < 500:")
    for i := 0; i < len(primes)-1; i++ {
        p := primes[i]*primes[i+1] + 2
        if rcu.IsPrime(p) {
            nprimes = append(nprimes, primes[i])
        }
    }
    rcu.PrintTable(nprimes, 10, 3, false)
    fmt.Println("\nFound", len(nprimes), "such primes.")
}




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__':
    print("p        q       pq+2")
    print("-----------------------")
    for p in range(2, 499):
        if not isPrime(p):
            continue
        q = p + 1
        while not isPrime(q):
            q += 1
        if not isPrime(2 + p*q):
            continue 
        print(p, "\t", q, "\t", 2+p*q)
Task: Minkowski question-mark function




Go: package main

import (
    "fmt"
    "math"
)

const MAXITER = 151

func minkowski(x float64) float64 {
    if x > 1 || x < 0 {
        return math.Floor(x) + minkowski(x-math.Floor(x))
    }
    p := uint64(x)
    q := uint64(1)
    r := p + 1
    s := uint64(1)
    d := 1.0
    y := float64(p)
    for {
        d = d / 2
        if y+d == y {
            break
        }
        m := p + r
        if m < 0 || p < 0 {
            break
        }
        n := q + s
        if n < 0 {
            break
        }
        if x < float64(m)/float64(n) {
            r = m
            s = n
        } else {
            y = y + d
            p = m
            q = n
        }
    }
    return y + d
}

func minkowskiInv(x float64) float64 {
    if x > 1 || x < 0 {
        return math.Floor(x) + minkowskiInv(x-math.Floor(x))
    }
    if x == 1 || x == 0 {
        return x
    }
    contFrac := []uint32{0}
    curr := uint32(0)
    count := uint32(1)
    i := 0
    for {
        x *= 2
        if curr == 0 {
            if x < 1 {
                count++
            } else {
                i++
                t := contFrac
                contFrac = make([]uint32, i+1)
                copy(contFrac, t)
                contFrac[i-1] = count
                count = 1
                curr = 1
                x--
            }
        } else {
            if x > 1 {
                count++
                x--
            } else {
                i++
                t := contFrac
                contFrac = make([]uint32, i+1)
                copy(contFrac, t)
                contFrac[i-1] = count
                count = 1
                curr = 0
            }
        }
        if x == math.Floor(x) {
            contFrac[i] = count
            break
        }
        if i == MAXITER {
            break
        }
    }
    ret := 1.0 / float64(contFrac[i])
    for j := i - 1; j >= 0; j-- {
        ret = float64(contFrac[j]) + 1.0/ret
    }
    return 1.0 / ret
}

func main() {
    fmt.Printf("%19.16f %19.16f\n", minkowski(0.5*(1+math.Sqrt(5))), 5.0/3.0)
    fmt.Printf("%19.16f %19.16f\n", minkowskiInv(-5.0/9.0), (math.Sqrt(13)-7)/6)
    fmt.Printf("%19.16f %19.16f\n", minkowski(minkowskiInv(0.718281828)),
        minkowskiInv(minkowski(0.1213141516171819)))
}




Python:     print(
        "{:19.16f} {:19.16f}".format(
            minkowski(minkowski_inv(4.04145188432738056)),
            minkowski_inv(minkowski(4.04145188432738056)),
        )
    )
Task: Canny edge detector




Go: package main

import (
    ed "github.com/Ernyoke/Imger/edgedetection"
    "github.com/Ernyoke/Imger/imgio"
    "log"
)

func main() {
    img, err := imgio.ImreadRGBA("Valve_original_(1).png")
    if err != nil {
        log.Fatal("Could not read image", err)
    }

    cny, err := ed.CannyRGBA(img, 15, 45, 5)
    if err != nil {
        log.Fatal("Could not perform Canny Edge detection")
    }

    err = imgio.Imwrite(cny, "Valve_canny_(1).png")
    if err != nil {
        log.Fatal("Could not write Canny image to disk")
    }
}




Python: 
import numpy as np
from scipy.ndimage.filters import convolve, gaussian_filter
from scipy.misc import imread, imshow
	
def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):
	im = np.array(im, dtype=float) 
 
	
	im2 = gaussian_filter(im, blur)

	
	im3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) 
	im3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])

	
	grad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)
	theta = np.arctan2(im3v, im3h)
	thetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 

	
	gradSup = grad.copy()
	for r in range(im.shape[0]):
		for c in range(im.shape[1]):
			
			if r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:
				gradSup[r, c] = 0
				continue
			tq = thetaQ[r, c] % 4

			if tq == 0: 
				if grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:
					gradSup[r, c] = 0
			if tq == 1: 
				if grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:
					gradSup[r, c] = 0
			if tq == 2: 
				if grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:
					gradSup[r, c] = 0
			if tq == 3: 
				if grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:
					gradSup[r, c] = 0

	
	strongEdges = (gradSup > highThreshold)

	
	thresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)

	
	
	finalEdges = strongEdges.copy()
	currentPixels = []
	for r in range(1, im.shape[0]-1):
		for c in range(1, im.shape[1]-1):	
			if thresholdedEdges[r, c] != 1:
				continue 
			
			
			localPatch = thresholdedEdges[r-1:r+2,c-1:c+2]
			patchMax = localPatch.max()
			if patchMax == 2:
				currentPixels.append((r, c))
				finalEdges[r, c] = 1

	
	while len(currentPixels) > 0:
		newPix = []
		for r, c in currentPixels:
			for dr in range(-1, 2):
				for dc in range(-1, 2):
					if dr == 0 and dc == 0: continue
					r2 = r+dr
					c2 = c+dc
					if thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0:
						
						newPix.append((r2, c2))
						finalEdges[r2, c2] = 1
		currentPixels = newPix

	return finalEdges

if __name__=="__main__":
	im = imread("test.jpg", mode="L") 
	finalEdges = CannyEdgeDetector(im)
	imshow(finalEdges)
Task: Modified random distribution




Go: package main

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

func rng(modifier func(x float64) float64) float64 {
    for {
        r1 := rand.Float64()
        r2 := rand.Float64()
        if r2 < modifier(r1) {
            return r1
        }
    }
}

func commatize(n int) string {
    s := fmt.Sprintf("%d", n)
    if n < 0 {
        s = s[1:]
    }
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    if n >= 0 {
        return s
    }
    return "-" + s
}

func main() {
    rand.Seed(time.Now().UnixNano())
    modifier := func(x float64) float64 {
        if x < 0.5 {
            return 2 * (0.5 - x)
        }
        return 2 * (x - 0.5)
    }
    const (
        N              = 100000
        NUM_BINS       = 20
        HIST_CHAR      = "■"
        HIST_CHAR_SIZE = 125
    )
    bins := make([]int, NUM_BINS) 
    binSize := 1.0 / NUM_BINS
    for i := 0; i < N; i++ {
        rn := rng(modifier)
        bn := int(math.Floor(rn / binSize))
        bins[bn]++
    }

    fmt.Println("Modified random distribution with", commatize(N), "samples in range [0, 1):\n")
    fmt.Println("    Range           Number of samples within that range")
    for i := 0; i < NUM_BINS; i++ {
        hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE)))
        fi := float64(i)
        fmt.Printf("%4.2f ..< %4.2f  %s %s\n", binSize*fi, binSize*(fi+1), hist, commatize(bins[i]))
    }
}




Python: import random
from typing import List, Callable, Optional


def modifier(x: float) -> float:
    
    return 2*(.5 - x) if x < 0.5 else 2*(x - .5)


def modified_random_distribution(modifier: Callable[[float], float],
                                 n: int) -> List[float]:
    
    d: List[float] = []
    while len(d) < n:
        r1 = prob = random.random()
        if random.random() < modifier(prob):
            d.append(r1)
    return d


if __name__ == '__main__':
    from collections import Counter

    data = modified_random_distribution(modifier, 50_000)
    bins = 15
    counts = Counter(d // (1 / bins) for d in data)
    
    mx = max(counts.values())
    print("   BIN, COUNTS, DELTA: HISTOGRAM\n")
    last: Optional[float] = None
    for b, count in sorted(counts.items()):
        delta = 'N/A' if last is None else str(count - last)
        print(f"  {b / bins:5.2f},  {count:4},  {delta:>4}: "
              f"{'
        last = count
Task: Collect and sort square numbers in ascending order from three lists




Go: package main

import (
    "fmt"
    "math"
    "sort"
)

func isSquare(n int) bool {
    s := int(math.Sqrt(float64(n)))
    return s*s == n
}

func main() {
    lists := [][]int{
        {3, 4, 34, 25, 9, 12, 36, 56, 36},
        {2, 8, 81, 169, 34, 55, 76, 49, 7},
        {75, 121, 75, 144, 35, 16, 46, 35},
    }
    var squares []int
    for _, list := range lists {
        for _, e := range list {
            if isSquare(e) {
                squares = append(squares, e)
            }
        }
    }
    sort.Ints(squares)
    fmt.Println(squares)
}




Python: import math

print("working...")
list = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)]
Squares = []

def issquare(x):
	for p in range(x):
		if x == p*p:
			return 1
for n in range(3):
	for m in range(len(list[n])):
		if issquare(list[n][m]):
			Squares.append(list[n][m])

Squares.sort()
print(Squares)
print("done...")
Task: Reverse the order of lines in a text file while preserving the contents of each line




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "runtime"
)

func main() {
    fileName1 := "rodgers.txt"
    fileName2 := "rodgers_reversed.txt"
    lineBreak := "\n"
    if runtime.GOOS == "windows" {
        lineBreak = "\r\n"
    }
    
    b, err := ioutil.ReadFile(fileName1)
    if err != nil {
        log.Fatal(err)
    }
    lines := bytes.Split(b, []byte(lineBreak))
    
    if len(lines[len(lines)-1]) == 0 {
        lines = lines[:len(lines)-1]
    }

    
    for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 {
        lines[i], lines[j] = lines[j], lines[i]
    }
    b = bytes.Join(lines, []byte(lineBreak))
    if err = ioutil.WriteFile(fileName2, b, 0o666); err != nil {
        log.Fatal(err)
    }
    
    b, err = ioutil.ReadFile(fileName2)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(b))
}




Python: 

import sys

if len(sys.argv)!=2:
    print("Usage : python " + sys.argv[0] + " <filename>")
    exit()

dataFile = open(sys.argv[1],"r")

fileData = dataFile.read().split('\n')

dataFile.close()

[print(i) for i in fileData[::-1]]
Task: Hourglass puzzle




Go: package main

import (
    "fmt"
    "log"
)

func minimum(a []int) int {
    min := a[0]
    for i := 1; i < len(a); i++ {
        if a[i] < min {
            min = a[i]
        }
    }
    return min
}

func sum(a []int) int {
    s := 0
    for _, i := range a {
        s = s + i
    }
    return s
}

func hourglassFlipper(hourglasses []int, target int) (int, []int) {
    flippers := make([]int, len(hourglasses))
    copy(flippers, hourglasses)
    var series []int
    for iter := 0; iter < 10000; iter++ {
        n := minimum(flippers)
        series = append(series, n)
        for i := 0; i < len(flippers); i++ {
            flippers[i] -= n
        }
        for i, flipper := range flippers {
            if flipper == 0 {
                flippers[i] = hourglasses[i]
            }
        }
        for start := len(series) - 1; start >= 0; start-- {
            if sum(series[start:]) == target {
                return start, series
            }
        }
    }
    log.Fatal("Unable to find an answer within 10,000 iterations.")
    return 0, nil
}

func main() {
    fmt.Print("Flip an hourglass every time it runs out of grains, ")
    fmt.Println("and note the interval in time.")
    hgs := [][]int{{4, 7}, {5, 7, 31}}
    ts := []int{9, 36}
    for i := 0; i < len(hgs); i++ {
        start, series := hourglassFlipper(hgs[i], ts[i])
        end := len(series) - 1
        fmt.Println("\nSeries:", series)
        fmt.Printf("Use hourglasses from indices %d to %d (inclusive) to sum ", start, end)
        fmt.Println(ts[i], "using", hgs[i])
    }
}




Python: def hourglass_puzzle():
    t4 = 0
    while t4 < 10_000:
        t7_left = 7 - t4 % 7
        if t7_left == 9 - 4:
            break
        t4 += 4
    else:
        print('Not found')
        return 
    print(f)
 
hourglass_puzzle()
Task: Unique characters in each string




Go: package main

import (
    "fmt"
    "sort"
)

func main() {
    strings := []string{"1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"}
    u := make(map[rune]int)
    for _, s := range strings {
        m := make(map[rune]int)
        for _, c := range s {
            m[c]++
        }
        for k, v := range m {
            if v == 1 {
                u[k]++
            }
        }
    }
    var chars []rune
    for k, v := range u {
        if v == 3 {
            chars = append(chars, k)
        }
    }
    sort.Slice(chars, func(i, j int) bool { return chars[i] < chars[j] })
    fmt.Println(string(chars))
}




Python: LIST = ["1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"]

print(sorted([ch for ch in set([c for c in ''.join(LIST)]) if all(w.count(ch) == 1 for w in LIST)]))