WeixiangYan/CodeTransOcean huggingface dataset:
Task: Numerical integration_Adaptive Simpson's method




Go: package main

import (
    "fmt"
    "math"
)

type F = func(float64) float64


func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
    
    m = (a + b) / 2
    fm = f(m)
    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
    return
}

func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
    
    
    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
    delta := left + right - whole
    if math.Abs(delta) <= eps*15 {
        return left + right + delta/15
    }
    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}

func quadAsr(f F, a, b, eps float64) float64 {
    
    fa, fb := f(a), f(b)
    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}

func main() {
    a, b := 0.0, 1.0
    sinx := quadAsr(math.Sin, a, b, 1e-09)
    fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)   
}




Python: 



import math

import collections
triple = collections.namedtuple('triple', 'm fm simp')

def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:
    
    m = a + (b - a) / 2
    fm = f(m)
    simp = abs(b - a) / 6 * (fa + 4*fm + fb)
    return triple(m, fm, simp,)
 
def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:
    
    lt = _quad_simpsons_mem(f, a, fa, m, fm)
    rt = _quad_simpsons_mem(f, m, fm, b, fb)
    delta = lt.simp + rt.simp - whole
    return (lt.simp + rt.simp + delta/15
        if (abs(delta) <= eps * 15) else
            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)
    )

def quad_asr(f: callable, a: float, b: float, eps: float)->float:
    
    fa = f(a)
    fb = f(b)
    t = _quad_simpsons_mem(f, a, fa, b, fb)
    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)

def main():
    (a, b,) = (0.0, 1.0,)
    sinx = quad_asr(math.sin, a, b, 1e-09);
    print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx))

main()
Task: FASTA format




Go: package main

import (
        "bufio"
        "fmt"
        "os"
)

func main() {
        f, err := os.Open("rc.fasta")
        if err != nil {
                fmt.Println(err)
                return
        }
        defer f.Close()
        s := bufio.NewScanner(f)
        headerFound := false
        for s.Scan() {
                line := s.Text()
                switch {
                case line == "":
                        continue
                case line[0] != '>':
                        if !headerFound {
                                fmt.Println("missing header")
                                return
                        }
                        fmt.Print(line)
                case headerFound:
                        fmt.Println()
                        fallthrough
                default:
                        fmt.Printf("%s: ", line[1:])
                        headerFound = true
                }
        }
        if headerFound {
                fmt.Println()
        }
        if err := s.Err(); err != nil {
                fmt.Println(err)
        }
}




Python: import io

FASTA=

infile = io.StringIO(FASTA)

def fasta_parse(infile):
    key = ''
    for line in infile:
        if line.startswith('>'):
            if key:
                yield key, val
            key, val = line[1:].rstrip().split()[0], ''
        elif key:
            val += line.rstrip()
    if key:
        yield key, val

print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
Task: Cousin primes




Go: package main

import "fmt"

func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        d := 5
        for d*d <= n {
            if n%d == 0 {
                return false
            }
            d += 2
            if n%d == 0 {
                return false
            }
            d += 4
        }
        return true
    }
}

func main() {
    count := 0
    fmt.Println("Cousin prime pairs whose elements are less than 1,000:")
    for i := 3; i <= 995; i += 2 {
        if isPrime(i) && isPrime(i+4) {
            fmt.Printf("%3d:%3d  ", i, i+4)
            count++
            if count%7 == 0 {
                fmt.Println()
            }
            if i != 3 {
                i += 4
            } else {
                i += 2
            }
        }
    }
    fmt.Printf("\n\n%d pairs found\n", count)
}




Python: 

from itertools import chain, takewhile



def cousinPrimes():
    
    def go(x):
        n = 4 + x
        return [(x, n)] if isPrime(n) else []

    return chain.from_iterable(
        map(go, primes())
    )




def main():
    

    pairs = list(
        takewhile(
            lambda ab: 1000 > ab[1],
            cousinPrimes()
        )
    )

    print(f'{len(pairs)} cousin pairs below 1000:\n')
    print(
        spacedTable(list(
            chunksOf(4)([
                repr(x) for x in pairs
            ])
        ))
    )





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 primes():
    
    n = 2
    dct = {}
    while True:
        if n in dct:
            for p in dct[n]:
                dct.setdefault(n + p, []).append(p)
            del dct[n]
        else:
            yield n
            dct[n * n] = [n]
        n = 1 + n



def listTranspose(xss):
    
    def go(xss):
        if xss:
            h, *t = xss
            return (
                [[h[0]] + [xs[0] for xs in t if xs]] + (
                    go([h[1:]] + [xs[1:] for xs in t])
                )
            ) if h and isinstance(h, list) else go(t)
        else:
            return []
    return go(xss)



def spacedTable(rows):
    
    columnWidths = [
        len(str(row[-1])) for row in listTranspose(rows)
    ]
    return '\n'.join([
        ' '.join(
            map(
                lambda w, s: s.rjust(w, ' '),
                columnWidths, row
            )
        ) for row in rows
    ])



if __name__ == '__main__':
    main()
Task: Find palindromic numbers in both binary and ternary bases




Go: package main

import (
    "fmt"
    "strconv"
    "time"
)

func isPalindrome2(n uint64) bool {
    x := uint64(0)
    if (n & 1) == 0 {
        return n == 0
    }
    for x < n {
        x = (x << 1) | (n & 1)
        n >>= 1
    }
    return n == x || n == (x>>1)
}

func reverse3(n uint64) uint64 {
    x := uint64(0)
    for n != 0 {
        x = x*3 + (n % 3)
        n /= 3
    }
    return x
}

func show(n uint64) {
    fmt.Println("Decimal :", n)
    fmt.Println("Binary  :", strconv.FormatUint(n, 2))
    fmt.Println("Ternary :", strconv.FormatUint(n, 3))
    fmt.Println("Time    :", time.Since(start))
    fmt.Println()
}

func min(a, b uint64) uint64 {
    if a < b {
        return a
    }
    return b
}

func max(a, b uint64) uint64 {
    if a > b {
        return a
    }
    return b
}

var start time.Time

func main() {
    start = time.Now()
    fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
    show(0)
    cnt := 1
    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
    for {
        i := lo
        for ; i < hi; i++ {
            n := (i*3+1)*pow3 + reverse3(i)
            if !isPalindrome2(n) {
                continue
            }
            show(n)
            cnt++
            if cnt >= 7 {
                return
            }
        }

        if i == pow3 {
            pow3 *= 3
        } else {
            pow2 *= 4
        }

        for {
            for pow2 <= pow3 {
                pow2 *= 4
            }

            lo2 := (pow2/pow3 - 1) / 3
            hi2 := (pow2*2/pow3-1)/3 + 1
            lo3 := pow3 / 3
            hi3 := pow3

            if lo2 >= hi3 {
                pow3 *= 3
            } else if lo3 >= hi2 {
                pow2 *= 4
            } else {
                lo = max(lo2, lo3)
                hi = min(hi2, hi3)
                break
            }
        }
    }
}




Python: from itertools import islice

digits = "0123456789abcdefghijklmnopqrstuvwxyz"

def baseN(num,b):
  if num == 0: return "0"
  result = ""
  while num != 0:
    num, d = divmod(num, b)
    result += digits[d]
  return result[::-1] 

def pal2(num):
    if num == 0 or num == 1: return True
    based = bin(num)[2:]
    return based == based[::-1]

def pal_23():
    yield 0
    yield 1
    n = 1
    while True:
        n += 1
        b = baseN(n, 3)
        revb = b[::-1]
        
        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
            t = int(trial, 3)
            if pal2(t):
                yield t

for pal23 in islice(pal_23(), 6):
    print(pal23, baseN(pal23, 3), baseN(pal23, 2))
Task: Check input device is a terminal




Go: package main

import (
    "golang.org/x/crypto/ssh/terminal"
    "fmt"
    "os"
)

func main() {
    if terminal.IsTerminal(int(os.Stdin.Fd())) {
        fmt.Println("Hello terminal")
    } else {
        fmt.Println("Who are you?  You're not a terminal.")
    }
}




Python: from sys import stdin
if stdin.isatty():
    print("Input comes from tty.")
else:
    print("Input doesn't come from tty.")
Task: Elementary cellular automaton_Random number generator




Go: package main

import "fmt"

const n = 64

func pow2(x uint) uint64 {
    return uint64(1) << x
}

func evolve(state uint64, rule int) {
    for p := 0; p < 10; p++ {
        b := uint64(0)
        for q := 7; q >= 0; q-- {
            st := state
            b |= (st & 1) << uint(q)
            state = 0
            for i := uint(0); i < n; i++ {
                var t1, t2, t3 uint64
                if i > 0 {
                    t1 = st >> (i - 1)
                } else {
                    t1 = st >> 63
                }
                if i == 0 {
                    t2 = st << 1
                } else if i == 1 {
                    t2 = st << 63

                } else {
                    t2 = st << (n + 1 - i)
                }
                t3 = 7 & (t1 | t2)
                if (uint64(rule) & pow2(uint(t3))) != 0 {
                    state |= pow2(i)
                }
            }
        }
        fmt.Printf("%d ", b)
    }
    fmt.Println()
}

func main() {
    evolve(1, 30)
}




Python: from elementary_cellular_automaton import eca, eca_wrap

def rule30bytes(lencells=100):
    cells = '1' + '0' * (lencells - 1)
    gen = eca(cells, 30)
    while True:
        yield int(''.join(next(gen)[0] for i in range(8)), 2)

if __name__ == '__main__':
    print([b for i,b in zip(range(10), rule30bytes())])
Task: Terminal control_Dimensions




Go: package main

import (
    "fmt"
    "os"

    "golang.org/x/crypto/ssh/terminal"
)

func main() {
    w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(h, w)
}




Python: import os

def get_windows_terminal():
    from ctypes import windll, create_string_buffer
    h = windll.kernel32.GetStdHandle(-12)
    csbi = create_string_buffer(22)
    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)

    
    if not res: return 80, 25 

    import struct
    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
    = struct.unpack("hhhhHhhhhhh", csbi.raw)
    width = right - left + 1
    height = bottom - top + 1

    return width, height

def get_linux_terminal():
    width = os.popen('tput cols', 'r').readline()
    height = os.popen('tput lines', 'r').readline()

    return int(width), int(height)

print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
Task: Vibrating rectangles




Go: package main

import (
    "image"
    "image/color"
    "image/gif"
    "log"
    "os"
)

var (
    black   = color.RGBA{0, 0, 0, 255}
    red     = color.RGBA{255, 0, 0, 255}
    green   = color.RGBA{0, 255, 0, 255}
    blue    = color.RGBA{0, 0, 255, 255}
    magenta = color.RGBA{255, 0, 255, 255}
    cyan    = color.RGBA{0, 255, 255, 255}
    yellow  = color.RGBA{255, 255, 0, 255}
    white   = color.RGBA{255, 255, 255, 255}
)

var palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}

func hline(img *image.Paletted, x1, y, x2 int, ci uint8) {
    for ; x1 <= x2; x1++ {
        img.SetColorIndex(x1, y, ci)
    }
}

func vline(img *image.Paletted, x, y1, y2 int, ci uint8) {
    for ; y1 <= y2; y1++ {
        img.SetColorIndex(x, y1, ci)
    }
}

func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {
    for x := 0; x < w; x++ {
        for y := 0; y < h; y++ {
            img.SetColorIndex(x, y, ci)
        }
    }
}

func drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {
    hline(img, x1, y1, x2, ci)
    hline(img, x1, y2, x2, ci)
    vline(img, x1, y1, y2, ci)
    vline(img, x2, y1, y2, ci)
}

func main() {
    const nframes = 140
    const delay = 10 
    width, height := 500, 500
    anim := gif.GIF{LoopCount: nframes}
    rect := image.Rect(0, 0, width, height)
    for c := uint8(0); c < 7; c++ {
        for f := 0; f < 20; f++ {
            img := image.NewPaletted(rect, palette)
            setBackgroundColor(img, width, height, 7) 
            for r := 0; r < 20; r++ {
                ix := c
                if r < f {
                    ix = (ix + 1) % 7
                }
                x := width * (r + 1) / 50
                y := height * (r + 1) / 50
                w := width - x
                h := height - y
                drawRectangle(img, x, y, w, h, ix)
            }
            anim.Delay = append(anim.Delay, delay)
            anim.Image = append(anim.Image, img)
        }
    }
    file, err := os.Create("vibrating.gif")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close() 
    if err2 := gif.EncodeAll(file, &anim); err != nil {
        log.Fatal(err2)
    }   
}




Python: import turtle
from itertools import cycle
from time import sleep

def rect(t, x, y):
    x2, y2 = x/2, y/2
    t.setpos(-x2, -y2)
    t.pendown()
    for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: 
        t.goto(pos)
    t.penup()

def rects(t, colour, wait_between_rect=0.1):
    for x in range(550, 0, -25):
        t.color(colour)
        rect(t, x, x*.75)
        sleep(wait_between_rect)

tl=turtle.Turtle()
screen=turtle.Screen()
screen.setup(620,620)
screen.bgcolor('black')
screen.title('Rosetta Code Vibrating Rectangles')
tl.pensize(3)
tl.speed(0)
tl.penup()
tl.ht() 
colours = 'red green blue orange white yellow'.split()
for colour in cycle(colours):
    rects(tl, colour)
    sleep(0.5)
Task: Last list item




Go: package main

import (
    "fmt"
    "sort"
)

func main() {
    a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11}
    for len(a) > 1 {
        sort.Ints(a)
        fmt.Println("Sorted list:", a)
        sum := a[0] + a[1]
        fmt.Printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum)
        a = append(a, sum)
        a = a[2:]
    }
    fmt.Println("Last item is", a[0], "\b.")
}




Python: 

def add_least_reduce(lis):
    
    while len(lis) > 1:
        lis.append(lis.pop(lis.index(min(lis))) + lis.pop(lis.index(min(lis))))
        print('Interim list:', lis)
    return lis

LIST = [6, 81, 243, 14, 25, 49, 123, 69, 11]

print(LIST, ' ==> ', add_least_reduce(LIST.copy()))
Task: Minimum numbers of three lists




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    numbers1 := [5]int{5, 45, 23, 21, 67}
    numbers2 := [5]int{43, 22, 78, 46, 38}
    numbers3 := [5]int{9, 98, 12, 98, 53}
    numbers := [5]int{}
    for n := 0; n < 5; n++ {
        numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n])
    }
    fmt.Println(numbers)
}




Python: numbers1 = [5,45,23,21,67]
numbers2 = [43,22,78,46,38]
numbers3 = [9,98,12,98,53]

numbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]

print(numbers)
Task: Cipolla's algorithm




Go: package main

import "fmt"

func c(n, p int) (R1, R2 int, ok bool) {
    
    powModP := func(a, e int) int {
        s := 1
        for ; e > 0; e-- {
            s = s * a % p
        }
        return s
    }
    
    ls := func(a int) int {
        return powModP(a, (p-1)/2)
    }
    
    if ls(n) != 1 {
        return
    }
    
    var a, ω2 int
    for a = 0; ; a++ {
        
        ω2 = (a*a + p - n) % p
        if ls(ω2) == p-1 {
            break
        }
    }
    
    type point struct{ x, y int }
    mul := func(a, b point) point {
        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}
    }
    
    r := point{1, 0}
    s := point{a, 1}
    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
        if n&1 == 1 {
            r = mul(r, s)
        }
        s = mul(s, s)
    }
    
    if r.y != 0 {
        return
    }
    
    if r.x*r.x%p != n {
        return
    }
    
    return r.x, p - r.x, true
}

func main() {
    fmt.Println(c(10, 13))
    fmt.Println(c(56, 101))
    fmt.Println(c(8218, 10007))
    fmt.Println(c(8219, 10007))
    fmt.Println(c(331575, 1000003))
}




Python: 

def convertToBase(n, b):
	if(n < 2):
		return [n];
	temp = n;
	ans = [];
	while(temp != 0):
		ans = [temp % b]+ ans;
		temp /= b;
	return ans;




def cipolla(n,p):
	n %= p
	if(n == 0 or n == 1):
		return (n,-n%p)
	phi = p - 1
	if(pow(n, phi/2, p) != 1):
		return ()
	if(p%4 == 3):
		ans = pow(n,(p+1)/4,p)
		return (ans,-ans%p)
	aa = 0
	for i in xrange(1,p):
		temp = pow((i*i-n)%p,phi/2,p)
		if(temp == phi):
			aa = i
			break;
	exponent = convertToBase((p+1)/2,2)
	def cipollaMult((a,b),(c,d),w,p):
		return ((a*c+b*d*w)%p,(a*d+b*c)%p)
	x1 = (aa,1)
	x2 = cipollaMult(x1,x1,aa*aa-n,p)
	for i in xrange(1,len(exponent)):
		if(exponent[i] == 0):
			x2 = cipollaMult(x2,x1,aa*aa-n,p)
			x1 = cipollaMult(x1,x1,aa*aa-n,p)
		else:
			x1 = cipollaMult(x1,x2,aa*aa-n,p)
			x2 = cipollaMult(x2,x2,aa*aa-n,p)
	return (x1[0],-x1[0]%p)

print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
Task: Pseudo-random numbers_PCG32




Go: package main

import (
    "fmt"
    "math"
)

const CONST = 6364136223846793005

type Pcg32 struct{ state, inc uint64 }

func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }

func (pcg *Pcg32) seed(seedState, seedSequence uint64) {
    pcg.state = 0
    pcg.inc = (seedSequence << 1) | 1
    pcg.nextInt()
    pcg.state = pcg.state + seedState
    pcg.nextInt()
}

func (pcg *Pcg32) nextInt() uint32 {
    old := pcg.state
    pcg.state = old*CONST + pcg.inc
    pcgshifted := uint32(((old >> 18) ^ old) >> 27)
    rot := uint32(old >> 59)
    return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))
}

func (pcg *Pcg32) nextFloat() float64 {
    return float64(pcg.nextInt()) / (1 << 32)
}

func main() {
    randomGen := Pcg32New()
    randomGen.seed(42, 54)
    for i := 0; i < 5; i++ {
        fmt.Println(randomGen.nextInt())
    }

    var counts [5]int
    randomGen.seed(987654321, 1)
    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 = 6364136223846793005


class PCG32():
    
    def __init__(self, seed_state=None, seed_sequence=None):
        if all(type(x) == int for x in (seed_state, seed_sequence)):
            self.seed(seed_state, seed_sequence)
        else:
            self.state = self.inc = 0
    
    def seed(self, seed_state, seed_sequence):
        self.state = 0
        self.inc = ((seed_sequence << 1) | 1) & mask64
        self.next_int()
        self.state = (self.state + seed_state)
        self.next_int()
        
    def next_int(self):
        "return random 32 bit unsigned int"
        old = self.state
        self.state = ((old * CONST) + self.inc) & mask64
        xorshifted = (((old >> 18) ^ old) >> 27) & mask32
        rot = (old >> 59) & mask32
        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))
        answer = answer &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 = PCG32()
    random_gen.seed(42, 54)
    for i in range(5):
        print(random_gen.next_int())
        
    random_gen.seed(987654321, 1)
    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: Deconvolution_1D




Go: package main

import "fmt"

func main() {
    h := []float64{-8, -9, -3, -1, -6, 7}
    f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}
    g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
        96, 31, 55, 36, 29, -43, -7}
    fmt.Println(h)
    fmt.Println(deconv(g, f))
    fmt.Println(f)
    fmt.Println(deconv(g, h))
}

func deconv(g, f []float64) []float64 {
    h := make([]float64, len(g)-len(f)+1)
    for n := range h {
        h[n] = g[n]
        var lower int
        if n >= len(f) {
            lower = n - len(f) + 1
        }
        for i := lower; i < n; i++ {
            h[n] -= h[i] * f[n-i]
        }
        h[n] /= f[0]
    }
    return h
}




Python: def ToReducedRowEchelonForm( M ):
    if not M: return
    lead = 0
    rowCount = len(M)
    columnCount = len(M[0])
    for r in range(rowCount):
        if lead >= columnCount:
            return
        i = r
        while M[i][lead] == 0:
            i += 1
            if i == rowCount:
                i = r
                lead += 1
                if columnCount == lead:
                    return
        M[i],M[r] = M[r],M[i]
        lv = M[r][lead]
        M[r] = [ mrx / lv for mrx in M[r]]
        for i in range(rowCount):
            if i != r:
                lv = M[i][lead]
                M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
        lead += 1
    return M
 
def pmtx(mtx):
    print ('\n'.join(''.join(' %4s' % col for col in row) for row in mtx))
 
def convolve(f, h):
    g = [0] * (len(f) + len(h) - 1)
    for hindex, hval in enumerate(h):
        for findex, fval in enumerate(f):
            g[hindex + findex] += fval * hval
    return g

def deconvolve(g, f):
    lenh = len(g) - len(f) + 1
    mtx = [[0 for x in range(lenh+1)] for y in g]
    for hindex in range(lenh):
        for findex, fval in enumerate(f):
            gindex = hindex + findex
            mtx[gindex][hindex] = fval
    for gindex, gval in enumerate(g):        
        mtx[gindex][lenh] = gval
    ToReducedRowEchelonForm( mtx )
    return [mtx[i][lenh] for i in range(lenh)]  

if __name__ == '__main__':
    h = [-8,-9,-3,-1,-6,7]
    f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]
    g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
    assert convolve(f,h) == g
    assert deconvolve(g, f) == h