WeixiangYan/CodeTransOcean huggingface dataset:
Task: Words from neighbour ones




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "sort"
    "strings"
    "unicode/utf8"
)

func main() {
    wordList := "unixdict.txt"
    b, err := ioutil.ReadFile(wordList)
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    var words []string
    for _, bword := range bwords {
        s := string(bword)
        if utf8.RuneCountInString(s) >= 9 {
            words = append(words, s)
        }
    }
    count := 0
    var alreadyFound []string
    le := len(words)
    var sb strings.Builder
    for i := 0; i < le-9; i++ {
        sb.Reset()
        for j := i; j < i+9; j++ {
            sb.WriteByte(words[j][j-i])
        }
        word := sb.String()
        ix := sort.SearchStrings(words, word)
        if ix < le && word == words[ix] {
            ix2 := sort.SearchStrings(alreadyFound, word)
            if ix2 == len(alreadyFound) {
                count++
                fmt.Printf("%2d: %s\n", count, word)
                alreadyFound = append(alreadyFound, word)
            }
        }
    }
}




Python: 

import urllib.request
from collections import Counter
 
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
 
dictionary = open("unixdict.txt","r")
 
wordList = dictionary.read().split('\n')
 
dictionary.close()
 
filteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]

for word in filteredWords[:-9]:
  position = filteredWords.index(word)
  newWord = "".join([filteredWords[position+i][i] for i in range(0,9)])
  if newWord in filteredWords:
   print(newWord)
Task: Numbers divisible by their individual digits, but not by the product of their digits.




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    var res []int
    for n := 1; n < 1000; n++ {
        digits := rcu.Digits(n, 10)
        var all = true
        for _, d := range digits {
            if d == 0 || n%d != 0 {
                all = false
                break
            }
        }
        if all {
            prod := 1
            for _, d := range digits {
                prod *= d
            }
            if prod > 0 && n%prod != 0 {
                res = append(res, n)
            }
        }
    }
    fmt.Println("Numbers < 1000 divisible by their digits, but not by the product thereof:")
    for i, n := range res {
        fmt.Printf("%4d", n)
        if (i+1)%9 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n%d such numbers found\n", len(res))
}




Python: 

from functools import reduce
from operator import mul



def p(n):
    
    digits = [int(c) for c in str(n)]
    return not 0 in digits and (
        0 != (n % reduce(mul, digits, 1))
    ) and all(0 == n % d for d in digits)




def main():
    
    xs = [
        str(n) for n in range(1, 1000)
        if p(n)
    ]
    w = len(xs[-1])
    print(f'{len(xs)} matching numbers:\n')
    print('\n'.join(
        ' '.join(cell.rjust(w, ' ') for cell in row)
        for row in chunksOf(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



if __name__ == '__main__':
    main()
Task: Generate Chess960 starting position




Go: package main

import (
    "fmt"
    "math/rand"
)

type symbols struct{ k, q, r, b, n rune }

var A = symbols{'K', 'Q', 'R', 'B', 'N'}
var W = symbols{'♔', '♕', '♖', '♗', '♘'}
var B = symbols{'♚', '♛', '♜', '♝', '♞'}

var krn = []string{
    "nnrkr", "nrnkr", "nrknr", "nrkrn",
    "rnnkr", "rnknr", "rnkrn",
    "rknnr", "rknrn",
    "rkrnn"}

func (sym symbols) chess960(id int) string {
    var pos [8]rune
    q, r := id/4, id%4
    pos[r*2+1] = sym.b
    q, r = q/4, q%4
    pos[r*2] = sym.b
    q, r = q/6, q%6
    for i := 0; ; i++ {
        if pos[i] != 0 {
            continue
        }
        if r == 0 {
            pos[i] = sym.q
            break
        }
        r--
    }
    i := 0
    for _, f := range krn[q] {
        for pos[i] != 0 {
            i++
        }
        switch f {
        case 'k':
            pos[i] = sym.k
        case 'r':
            pos[i] = sym.r
        case 'n':
            pos[i] = sym.n
        }
    }
    return string(pos[:])
}

func main() {
    fmt.Println(" ID  Start position")
    for _, id := range []int{0, 518, 959} {
        fmt.Printf("%3d  %s\n", id, A.chess960(id))
    }
    fmt.Println("\nRandom")
    for i := 0; i < 5; i++ {
        fmt.Println(W.chess960(rand.Intn(960)))
    }
}




Python: >>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
                     if p.index('B') % 2 != p.index('b') % 2 		
                     and ( p.index('r') < p.index('K') < p.index('R')	
                           or p.index('R') < p.index('K') < p.index('r') ) }
>>> len(starts)
960
>>> starts.pop()
'QNBRNKRB'
>>>
Task: Modulinos




Go: 
package main

import "fmt"

func MeaningOfLife() int {
    return 42
}

func libMain() {
    fmt.Println("The meaning of life is", MeaningOfLife())
}




Python: 



def meaning_of_life():
  return 42

if __name__ == "__main__":
  print("Main: The meaning of life is %s" % meaning_of_life())
Task: File size distribution




Go: package main

import (
    "fmt"
    "log"
    "math"
    "os"
    "path/filepath"
)

func commatize(n int64) 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 fileSizeDistribution(root string) {
    var sizes [12]int
    files := 0
    directories := 0
    totalSize := int64(0)
    walkFunc := func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        files++
        if info.IsDir() {
            directories++
        }
        size := info.Size()
        if size == 0 {
            sizes[0]++
            return nil
        }
        totalSize += size
        logSize := math.Log10(float64(size))
        index := int(math.Floor(logSize))
        sizes[index+1]++
        return nil
    }
    err := filepath.Walk(root, walkFunc)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("File size distribution for '%s' :-\n\n", root)
    for i := 0; i < len(sizes); i++ {
        if i == 0 {
            fmt.Print("  ")
        } else {
            fmt.Print("+ ")
        }
        fmt.Printf("Files less than 10 ^ %-2d bytes : %5d\n", i, sizes[i])
    }
    fmt.Println("                                  -----")
    fmt.Printf("= Total number of files         : %5d\n", files)
    fmt.Printf("  including directories         : %5d\n", directories)
    c := commatize(totalSize)
    fmt.Println("\n  Total size of files           :", c, "bytes")
}

func main() {
    fileSizeDistribution("./")
}




Python: import sys, os
from collections import Counter

def dodir(path):
    global h

    for name in os.listdir(path):
        p = os.path.join(path, name)

        if os.path.islink(p):
            pass
        elif os.path.isfile(p):
            h[os.stat(p).st_size] += 1
        elif os.path.isdir(p):
            dodir(p)
        else:
            pass

def main(arg):
    global h
    h = Counter()
    for dir in arg:
        dodir(dir)

    s = n = 0
    for k, v in sorted(h.items()):
        print("Size %d -> %d file(s)" % (k, v))
        n += v
        s += k * v
    print("Total %d bytes for %d files" % (s, n))

main(sys.argv[1:])
Task: Unix_ls




Go: package main

import (
	"fmt"
	"log"
	"os"
	"sort"
)

func main() {
	f, err := os.Open(".")
	if err != nil {
		log.Fatal(err)
	}
	files, err := f.Readdirnames(0)
	f.Close()
	if err != nil {
		log.Fatal(err)
	}
	sort.Strings(files)
	for _, n := range files {
		fmt.Println(n)
	}
}




Python: >>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
Task: First class environments




Go: package main

import "fmt"

const jobs = 12

type environment struct{ seq, cnt int }

var (
    env      [jobs]environment
    seq, cnt *int
)

func hail() {
    fmt.Printf("% 4d", *seq)
    if *seq == 1 {
        return
    }
    (*cnt)++
    if *seq&1 != 0 {
        *seq = 3*(*seq) + 1
    } else {
        *seq /= 2
    }
}

func switchTo(id int) {
    seq = &env[id].seq
    cnt = &env[id].cnt
}

func main() {
    for i := 0; i < jobs; i++ {
        switchTo(i)
        env[i].seq = i + 1
    }

again:
    for i := 0; i < jobs; i++ {
        switchTo(i)
        hail()
    }
    fmt.Println()

    for j := 0; j < jobs; j++ {
        switchTo(j)
        if *seq != 1 {
            goto again
        }
    }
    fmt.Println()

    fmt.Println("COUNTS:")
    for i := 0; i < jobs; i++ {
        switchTo(i)
        fmt.Printf("% 4d", *cnt)
    }
    fmt.Println()
}




Python: environments = [{'cnt':0, 'seq':i+1} for i in range(12)]

code = 

while any(env['seq'] > 1 for env in environments):
    for env in environments:
        exec(code, globals(), env)
    print()

print('Counts')
for env in environments:
    print('% 4d' % env['cnt'], end='')
print()
Task: UTF-8 encode and decode




Go: package main

import (
    "bytes"
    "encoding/hex"
    "fmt"
    "log"
    "strings"
)

var testCases = []struct {
    rune
    string
}{
    {'A', "41"},
    {'ö', "C3 B6"},
    {'Ж', "D0 96"},
    {'€', "E2 82 AC"},
    {'𝄞', "F0 9D 84 9E"},
}

func main() {
    for _, tc := range testCases {
        
        u := fmt.Sprintf("U+%04X", tc.rune)
        b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1))
        if err != nil {
            log.Fatal("bad test data")
        }
        
        e := encodeUTF8(tc.rune)
        d := decodeUTF8(b)
        
        fmt.Printf("%c  %-7s  %X\n", d, u, e)
        
        if !bytes.Equal(e, b) {
            log.Fatal("encodeUTF8 wrong")
        }
        if d != tc.rune {
            log.Fatal("decodeUTF8 wrong")
        }
    }
}

const (
    
    b2Lead = 0xC0 
    b2Mask = 0x1F 

    
    b3Lead = 0xE0 
    b3Mask = 0x0F 

    
    b4Lead = 0xF0 
    b4Mask = 0x07 

    
    mbLead = 0x80 
    mbMask = 0x3F 
)

func encodeUTF8(r rune) []byte {
    switch i := uint32(r); {
    case i <= 1<<7-1: 
        return []byte{byte(r)}
    case i <= 1<<11-1: 
        return []byte{
            b2Lead | byte(r>>6),
            mbLead | byte(r)&mbMask}
    case i <= 1<<16-1: 
        return []byte{
            b3Lead | byte(r>>12),
            mbLead | byte(r>>6)&mbMask,
            mbLead | byte(r)&mbMask}
    default:
        return []byte{
            b4Lead | byte(r>>18),
            mbLead | byte(r>>12)&mbMask,
            mbLead | byte(r>>6)&mbMask,
            mbLead | byte(r)&mbMask}
    }
}

func decodeUTF8(b []byte) rune {
    switch b0 := b[0]; {
    case b0 < 0x80:
        return rune(b0)
    case b0 < 0xE0:
        return rune(b0&b2Mask)<<6 |
            rune(b[1]&mbMask)
    case b0 < 0xF0:
        return rune(b0&b3Mask)<<12 |
            rune(b[1]&mbMask)<<6 |
            rune(b[2]&mbMask)
    default:
        return rune(b0&b4Mask)<<18 |
            rune(b[1]&mbMask)<<12 |
            rune(b[2]&mbMask)<<6 |
            rune(b[3]&mbMask)
    }
}




Python: 
from unicodedata import name


def unicode_code(ch):
    return 'U+{:04x}'.format(ord(ch))


def utf8hex(ch):
    return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()


if __name__ == "__main__":
    print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))
    chars = ['A', 'ö', 'Ж', '€', '𝄞']
    for char in chars:
        print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
Task: Keyboard macros




Go: package main


import "C"
import "fmt"
import "unsafe"

func main() {
    d := C.XOpenDisplay(nil)
    f7, f6 := C.CString("F7"), C.CString("F6")
    defer C.free(unsafe.Pointer(f7))
    defer C.free(unsafe.Pointer(f6))

    if d != nil {
        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),
            C.Mod1Mask, 
            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)
        C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),
            C.Mod1Mask,
            C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)

        var event C.XEvent
        for {
            C.XNextEvent(d, &event)
            if C.getXEvent_type(event) == C.KeyPress {
                xkeyEvent := C.getXEvent_xkey(event)
                s := C.XLookupKeysym(&xkeyEvent, 0)
                if s == C.XK_F7 {
                    fmt.Println("something's happened")
                } else if s == C.XK_F6 {
                    break
                }
            }
        }

        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
        C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
    } else {
        fmt.Println("XOpenDisplay did not succeed")
    }
}




Python: 
import curses

def print_message():
    stdscr.addstr('This is the message.\n')

stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)

stdscr.addstr('CTRL+P for message or q to quit.\n')
while True:
    c = stdscr.getch()
    if c == 16: print_message()
    elif c == ord('q'): break

curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()
Task: McNuggets problem




Go: package main

import "fmt"

func mcnugget(limit int) {
    sv := make([]bool, limit+1) 
    for s := 0; s <= limit; s += 6 {
        for n := s; n <= limit; n += 9 {
            for t := n; t <= limit; t += 20 {
                sv[t] = true
            }
        }
    }
    for i := limit; i >= 0; i-- {
        if !sv[i] {
            fmt.Println("Maximum non-McNuggets number is", i)
            return
        }
    }
}

func main() {
    mcnugget(100)
}




Python: >>> from itertools import product
>>> nuggets = set(range(101))
>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):
	nuggets.discard(6*s + 9*n + 20*t)

	
>>> max(nuggets)
43
>>>
Task: Magic squares of doubly even order




Go: package main

import (
	"fmt"
	"log"
	"strings"
)

const dimensions int = 8

func setupMagicSquareData(d int) ([][]int, error) {
	var output [][]int
	if d < 4 || d%4 != 0 {
		return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4")
	}
	var bits uint = 0x9669 
	size := d * d
	mult := d / 4
	for i, r := 0, 0; r < d; r++ {
		output = append(output, []int{})
		for c := 0; c < d; i, c = i+1, c+1 {
			bitPos := c/mult + (r/mult)*4
			if (bits & (1 << uint(bitPos))) != 0 {
				output[r] = append(output[r], i+1)
			} else {
				output[r] = append(output[r], size-i)
			}
		}
	}
	return output, nil
}

func arrayItoa(input []int) []string {
	var output []string
	for _, i := range input {
		output = append(output, fmt.Sprintf("%4d", i))
	}
	return output
}

func main() {
	data, err := setupMagicSquareData(dimensions)
	if err != nil {
		log.Fatal(err)
	}
	magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2
	for _, row := range data {
		fmt.Println(strings.Join(arrayItoa(row), " "))
	}
	fmt.Printf("\nMagic Constant: %d\n", magicConstant)
}




Python: def MagicSquareDoublyEven(order):
    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
    n1 = order/4
    for r in range(n1):
        r1 = sq[r][n1:-n1]
        r2 = sq[order -r - 1][n1:-n1]
        r1.reverse()
        r2.reverse()
        sq[r][n1:-n1] = r2
        sq[order -r - 1][n1:-n1] = r1
    for r in range(n1, order-n1):
        r1 = sq[r][:n1]
        r2 = sq[order -r - 1][order-n1:]
        r1.reverse()
        r2.reverse()
        sq[r][:n1] = r2
        sq[order -r - 1][order-n1:] = r1
    return sq

def printsq(s):
    n = len(s)
    bl = len(str(n**2))+1
    for i in range(n):
        print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] )
    print "\nMagic constant = %d"%sum(s[0])

printsq(MagicSquareDoublyEven(8))
Task: Extreme floating point values




Go: package main

import (
    "fmt"
    "math"
)

func main() {
    
    var zero float64                         
    var negZero, posInf, negInf, nan float64 
    negZero = zero * -1
    posInf = 1 / zero
    negInf = -1 / zero
    nan = zero / zero

    
    fmt.Println(negZero, posInf, negInf, nan)

    
    fmt.Println(math.Float64frombits(1<<63),
        math.Inf(1), math.Inf(-1), math.NaN())

    
    fmt.Println()
    validateNaN(negInf+posInf, "-Inf + Inf")
    validateNaN(0*posInf, "0 * Inf")
    validateNaN(posInf/posInf, "Inf / Inf")
    
    
    validateNaN(math.Mod(posInf, 1), "Inf % 1")
    validateNaN(1+nan, "1 + NaN")
    validateZero(1/posInf, "1 / Inf")
    validateGT(posInf, math.MaxFloat64, "Inf > max value")
    validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value")
    validateNE(nan, nan, "NaN != NaN")
    validateEQ(negZero, 0, "-0 == 0")
}

func validateNaN(n float64, op string) {
    if math.IsNaN(n) {
        fmt.Println(op, "-> NaN")
    } else {
        fmt.Println("!!! Expected NaN from", op, "  Found", n)
    }
}

func validateZero(n float64, op string) {
    if n == 0 {
        fmt.Println(op, "-> 0")
    } else {
        fmt.Println("!!! Expected 0 from", op, "  Found", n)
    }
}

func validateGT(a, b float64, op string) {
    if a > b {
        fmt.Println(op)
    } else {
        fmt.Println("!!! Expected", op, "  Found not true.")
    }
}

func validateNE(a, b float64, op string) {
    if a == b {
        fmt.Println("!!! Expected", op, "  Found not true.")
    } else {
        fmt.Println(op)
    }
}

func validateEQ(a, b float64, op string) {
    if a == b {
        fmt.Println(op)
    } else {
        fmt.Println("!!! Expected", op, "  Found not true.")
    }
}




Python: >>> 
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>> 
>>> for value in (inf, _inf, _zero, nan): print (value)

inf
-inf
-0.0
nan
>>> 
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> -0.
-0.0
>>> 
>>> nan == nan
False
>>> nan is nan
True
>>> 0. == -0.
True
>>> 0. is -0.
False
>>> inf + _inf
nan
>>> 0.0 * nan
nan
>>> nan * 0.0
nan
>>> 0.0 * inf
nan
>>> inf * 0.0
nan
Task: Pseudo-random numbers_Xorshift star




Go: package main

import (
    "fmt"
    "math"
)

const CONST = 0x2545F4914F6CDD1D

type XorshiftStar struct{ state uint64 }

func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }

func (xor *XorshiftStar) seed(state uint64) { xor.state = state }

func (xor *XorshiftStar) nextInt() uint32 {
    x := xor.state
    x = x ^ (x >> 12)
    x = x ^ (x << 25)
    x = x ^ (x >> 27)
    xor.state = x
    return uint32((x * CONST) >> 32)
}

func (xor *XorshiftStar) nextFloat() float64 {
    return float64(xor.nextInt()) / (1 << 32)
}

func main() {
    randomGen := XorshiftStarNew(1234567)
    for i := 0; i < 5; i++ {
        fmt.Println(randomGen.nextInt())
    }

    var counts [5]int
    randomGen.seed(987654321)
    for i := 0; i < 1e5; i++ {
        j := int(math.Floor(randomGen.nextFloat() * 5))
        counts[j]++
    }
    fmt.Println("\nThe counts for 100,000 repetitions are:")
    for i := 0; i < 5; i++ {
        fmt.Printf("  %d : %d\n", i, counts[i])
    }
}




Python: mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
const = 0x2545F4914F6CDD1D



class Xorshift_star():
    
    def __init__(self, seed=0):
        self.state = seed & mask64

    def seed(self, num):
        self.state =  num & mask64
    
    def next_int(self):
        "return random int between 0 and 2**32"
        x = self.state
        x = (x ^ (x >> 12)) & mask64
        x = (x ^ (x << 25)) & mask64
        x = (x ^ (x >> 27)) & mask64
        self.state = x
        answer = (((x * const) & mask64) >> 32) & mask32 
        return answer
    
    def  next_float(self):
        "return random float between 0 and 1"
        return self.next_int() / (1 << 32)
    

if __name__ == '__main__':
    random_gen = Xorshift_star()
    random_gen.seed(1234567)
    for i in range(5):
        print(random_gen.next_int())
        
    random_gen.seed(987654321)
    hist = {i:0 for i in range(5)}
    for i in range(100_000):
        hist[int(random_gen.next_float() *5)] += 1
    print(hist)
Task: Levenshtein distance_Alignment




Go: package main

import (
    "fmt"

    "github.com/biogo/biogo/align"
    ab "github.com/biogo/biogo/alphabet"
    "github.com/biogo/biogo/feat"
    "github.com/biogo/biogo/seq/linear"
)

func main() {
    
    
    lc := ab.Must(ab.NewAlphabet("-abcdefghijklmnopqrstuvwxyz",
        feat.Undefined, '-', 0, true))
    
    
    
    
    nw := make(align.NW, lc.Len())
    for i := range nw {
        r := make([]int, lc.Len())
        nw[i] = r
        for j := range r {
            if j != i {
                r[j] = -1
            }
        }
    }
    
    a := &linear.Seq{Seq: ab.BytesToLetters([]byte("rosettacode"))}
    a.Alpha = lc
    b := &linear.Seq{Seq: ab.BytesToLetters([]byte("raisethysword"))}
    b.Alpha = lc
    
    aln, err := nw.Align(a, b)
    
    if err != nil {
        fmt.Println(err)
        return
    }
    fa := align.Format(a, b, aln, '-')
    fmt.Printf("%s\n%s\n", fa[0], fa[1])
    aa := fmt.Sprint(fa[0])
    ba := fmt.Sprint(fa[1])
    ma := make([]byte, len(aa))
    for i := range ma {
        if aa[i] == ba[i] {
            ma[i] = ' '
        } else {
            ma[i] = '|'
        }
    }
    fmt.Println(string(ma))
}




Python: from difflib import ndiff

def levenshtein(str1, str2):
    result = ""
    pos, removed = 0, 0
    for x in ndiff(str1, str2):
        if pos<len(str1) and str1[pos] == x[2]:
          pos += 1
          result += x[2]
          if x[0] == "-":
              removed += 1
          continue
        else:
          if removed > 0:
            removed -=1
          else:
            result += "-"
    print(result)

levenshtein("place","palace")
levenshtein("rosettacode","raisethysword")
Task: Same fringe




Go: package main

import "fmt"

type node struct {
    int
    left, right *node
}



func leaves(t *node) chan int {
    ch := make(chan int)
    
    var f func(*node)
    f = func(n *node) {
        if n == nil {
            return
        }
        
        if n.left == nil && n.right == nil {
            ch <- n.int
        } else {
            f(n.left)
            f(n.right)
        }
    }
    
    
    go func() {
        f(t)
        close(ch)
    }()
    return ch
}

func sameFringe(t1, t2 *node) bool {
    f1 := leaves(t1)
    f2 := leaves(t2)
    for l1 := range f1 {
        
        if l2, ok := <-f2; !ok || l1 != l2 {
            return false
        }
    }
    
    _, ok := <-f2
    return !ok
}

func main() {
    
    
    t1 := &node{3,
        &node{1,
            &node{int: 1},
            &node{int: 2}},
        &node{8,
            &node{int: 5},
            &node{int: 13}}}
    
    
    t2 := &node{-8,
        &node{-3,
            &node{-1,
                &node{int: 1},
                &node{int: 2}},
            &node{int: 5}},
        &node{int: 13}}
    fmt.Println(sameFringe(t1, t2)) 
}




Python: try:
    from itertools import zip_longest as izip_longest 
except:
    from itertools import izip_longest                

def fringe(tree):
    
    for node1 in tree:
        if isinstance(node1, tuple):
            for node2 in fringe(node1):
                yield node2
        else:
            yield node1

def same_fringe(tree1, tree2):
    return all(node1 == node2 for node1, node2 in
               izip_longest(fringe(tree1), fringe(tree2)))

if __name__ == '__main__':
    a = 1, 2, 3, 4, 5, 6, 7, 8
    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))
    c = (((1, 2), 3), 4), 5, 6, 7, 8

    x = 1, 2, 3, 4, 5, 6, 7, 8, 9
    y = 0, 2, 3, 4, 5, 6, 7, 8
    z = 1, 2, (4, 3), 5, 6, 7, 8

    assert same_fringe(a, a)
    assert same_fringe(a, b)
    assert same_fringe(a, c)

    assert not same_fringe(a, x)
    assert not same_fringe(a, y)
    assert not same_fringe(a, z)