Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Ensure the translated Go code behaves exactly like the original Python snippet.
import re as RegEx def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ): outString = "" strPos = 0 matches = RegEx.findall( "[0-9]*", _string ) for match in matches[:-1]: if not match: outString += _string[ strPos ] strPos += 1 else: if len(match) > _periodLen: leadIn = match[:_st...
package main import ( "fmt" "regexp" "strings" ) var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func commatiz...
Write the same algorithm in Go as shown in this Python implementation.
import re as RegEx def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ): outString = "" strPos = 0 matches = RegEx.findall( "[0-9]*", _string ) for match in matches[:-1]: if not match: outString += _string[ strPos ] strPos += 1 else: if len(match) > _periodLen: leadIn = match[:_st...
package main import ( "fmt" "regexp" "strings" ) var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func commatiz...
Produce a language-to-language conversion: from Python to Go, same semantics.
from collections import Counter def cumulative_freq(freq): cf = {} total = 0 for b in range(256): if b in freq: cf[b] = total total += freq[b] return cf def arithmethic_coding(bytes, radix): freq = Counter(bytes) cf = cumulative_freq(freq) ...
package main import ( "fmt" "math/big" ) func cumulative_freq(freq map[byte]int64) map[byte]int64 { total := int64(0) cf := make(map[byte]int64) for i := 0; i < 256; i++ { b := byte(i) if v, ok := freq[b]; ok { cf[b] = total total += v } } re...
Convert the following code from Python to Go, ensuring the logic remains intact.
from collections import Counter def cumulative_freq(freq): cf = {} total = 0 for b in range(256): if b in freq: cf[b] = total total += freq[b] return cf def arithmethic_coding(bytes, radix): freq = Counter(bytes) cf = cumulative_freq(freq) ...
package main import ( "fmt" "math/big" ) func cumulative_freq(freq map[byte]int64) map[byte]int64 { total := int64(0) cf := make(map[byte]int64) for i := 0; i < 256; i++ { b := byte(i) if v, ok := freq[b]; ok { cf[b] = total total += v } } re...
Generate a Go translation of this Python snippet without changing its computational steps.
def kosaraju(g): class nonlocal: pass size = len(g) vis = [False]*size l = [0]*size nonlocal.x = size t = [[]]*size def visit(u): if not vis[u]: vis[u] = True for v in g[u]: visit(v) t[v] = t[v] + [u] non...
package main import "fmt" var g = [][]int{ 0: {1}, 1: {2}, 2: {0}, 3: {1, 2, 4}, 4: {3, 5}, 5: {2, 6}, 6: {5}, 7: {4, 6, 7}, } func main() { fmt.Println(kosaraju(g)) } func kosaraju(g [][]int) []int { vis := make([]bool, len(g)) L := make([]int, len(g)) x := len(...
Port the provided Python code into Go while preserving the original functionality.
import inspect class Super(object): def __init__(self, name): self.name = name def __str__(self): return "Super(%s)" % (self.name,) def doSup(self): return 'did super stuff' @classmethod def cls(cls): return 'cls method (in sup)' @classmethod def supCls(cls): return 'Supe...
package main import ( "fmt" "image" "reflect" ) type t int func (r t) Twice() t { return r * 2 } func (r t) Half() t { return r / 2 } func (r t) Less(r2 t) bool { return r < r2 } func (r t) privateMethod() {} func main() { report(t(0)) report(image.Point{}) } func report(x interface{}) { v := ...
Change the programming language of this snippet from Python to Go without modifying what it does.
from itertools import product minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ...
package main import ( "fmt" "math/rand" "time" ) var F = [][]int{ {1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}, } var ...
Change the following Python code into Go without altering its purpose.
class Example(object): def foo(self, x): return 42 + x name = "foo" getattr(Example(), name)(5)
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func main() { var e example m := reflect.ValueOf(e).MethodByName("Foo") r := m.Call(nil) fmt.Println(r[0].Int()) }
Convert the following code from Python to Go, ensuring the logic remains intact.
example1 = 3 example2 = 3.0 example3 = True example4 = "hello" example1 = "goodbye"
x := 3
Generate a Go translation of this Python snippet without changing its computational steps.
import math import random INFINITY = 1 << 127 MAX_INT = 1 << 31 class Parameters: def __init__(self, omega, phip, phig): self.omega = omega self.phip = phip self.phig = phig class State: def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDi...
package main import ( "fmt" "math" "math/rand" "time" ) type ff = func([]float64) float64 type parameters struct{ omega, phip, phig float64 } type state struct { iter int gbpos []float64 gbval float64 min []float64 max []float64 params parame...
Transform the following Python implementation into Go, maintaining the same output and logic.
python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(string1, string2, separator): return separator.join([string1, '', string2]) >>> f('Rosetta', 'Code', ':') 'Rosetta::Code' >>>
package main import "fmt" func f(s1, s2, sep string) string { return s1 + sep + sep + s2 } func main() { fmt.Println(f("Rosetta", "Code", ":")) }
Convert this Python snippet to Go and keep its semantics consistent.
python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(string1, string2, separator): return separator.join([string1, '', string2]) >>> f('Rosetta', 'Code', ':') 'Rosetta::Code' >>>
package main import "fmt" func f(s1, s2, sep string) string { return s1 + sep + sep + s2 } func main() { fmt.Println(f("Rosetta", "Code", ":")) }
Change the following Python code into Go without altering its purpose.
def rank(x): return int('a'.join(map(str, [1] + x)), 11) def unrank(n): s = '' while n: s,n = "0123456789a"[n%11] + s, n//11 return map(int, s.split('a'))[1:] l = [1, 2, 3, 10, 100, 987654321] print l n = rank(l) print n l = unrank(n) print l
package main import ( "fmt" "math/big" ) func rank(l []uint) (r big.Int) { for _, n := range l { r.Lsh(&r, n+1) r.SetBit(&r, int(n), 1) } return } func unrank(n big.Int) (l []uint) { m := new(big.Int).Set(&n) for a := m.BitLen(); a > 0; { m.SetBit(m, a-1, 0) ...
Please provide an equivalent version of this Python code in Go.
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
package main import ( "fmt" "io/ioutil" "os" ) func main() { fn := "myth" bx := ".backup" var err error if tf, err := os.Readlink(fn); err == nil { fn = tf } var fi os.FileInfo if fi, err = os.Stat(fn); err != nil { fmt.Println(err) return ...
Port the provided Python code into Go while preserving the original functionality.
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
package main import ( "fmt" "io/ioutil" "os" ) func main() { fn := "myth" bx := ".backup" var err error if tf, err := os.Readlink(fn); err == nil { fn = tf } var fi os.FileInfo if fi, err = os.Stat(fn); err != nil { fmt.Println(err) return ...
Change the programming language of this snippet from Python to Go without modifying what it does.
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
package main import ( "fmt" "io/ioutil" "os" ) func main() { fn := "myth" bx := ".backup" var err error if tf, err := os.Readlink(fn); err == nil { fn = tf } var fi os.FileInfo if fi, err = os.Stat(fn); err != nil { fmt.Println(err) return ...
Change the following Python code into Go without altering its purpose.
import re male2female=u re_nl=re.compile(r",[ \n]*") m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ] switch={} words=[] re_plural=re.compile("E*S$") re_ES=re.compile("ES$") def gen_pluralize(m,f): yield re_plural.sub("",m),re_plural.sub("",f) yield re_ES.sub("es",m),re_ES.sub("es",f) yie...
package main import ( "fmt" "strings" ) func reverseGender(s string) string { if strings.Contains(s, "She") { return strings.Replace(s, "She", "He", -1) } else if strings.Contains(s, "He") { return strings.Replace(s, "He", "She", -1) } return s } func main() { s := "She wa...
Change the programming language of this snippet from Python to Go without modifying what it does.
import re male2female=u re_nl=re.compile(r",[ \n]*") m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ] switch={} words=[] re_plural=re.compile("E*S$") re_ES=re.compile("ES$") def gen_pluralize(m,f): yield re_plural.sub("",m),re_plural.sub("",f) yield re_ES.sub("es",m),re_ES.sub("es",f) yie...
package main import ( "fmt" "strings" ) func reverseGender(s string) string { if strings.Contains(s, "She") { return strings.Replace(s, "She", "He", -1) } else if strings.Contains(s, "He") { return strings.Replace(s, "He", "She", -1) } return s } func main() { s := "She wa...
Generate an equivalent Go version of this Python code.
import time import os seconds = input("Enter a number of seconds: ") sound = input("Enter an mp3 filename: ") time.sleep(float(seconds)) os.startfile(sound + ".mp3")
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" "time" ) func main() { scanner := bufio.NewScanner(os.Stdin) number := 0 for number < 1 { fmt.Print("Enter number of seconds delay > 0 : ") scanner.Scan() input := scanner.Text() ...
Convert this Python snippet to Go and keep its semantics consistent.
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char i...
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" ...
Transform the following Python implementation into Go, maintaining the same output and logic.
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char i...
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" ...
Please provide an equivalent version of this Python code in Go.
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char i...
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" ...
Generate an equivalent Go version of this Python code.
>>> def eval_with_x(code, a, b): return eval(code, {'x':b}) - eval(code, {'x':a}) >>> eval_with_x('2 ** x', 3, 5) 24
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w :=...
Ensure the translated Go code behaves exactly like the original Python snippet.
>>> def eval_with_x(code, a, b): return eval(code, {'x':b}) - eval(code, {'x':a}) >>> eval_with_x('2 ** x', 3, 5) 24
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w :=...
Produce a functionally identical Go code for the snippet given in Python.
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and ...
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, ...
Change the following Python code into Go without altering its purpose.
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and ...
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, ...
Port the provided Python code into Go while preserving the original functionality.
import math rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15,...
package main import ( "fmt" "math" "bytes" "encoding/binary" ) type testCase struct { hashCode string string } var testCases = []testCase{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b69...
Translate this program into Go but keep the logic exactly as in Python.
from math import pi, sin, cos from collections import namedtuple from random import random, choice from copy import copy try: import psyco psyco.full() except ImportError: pass FLOAT_MAX = 1e100 class Point: __slots__ = ["x", "y", "group"] def __init__(self, x=0.0, y=0.0, group=0): self...
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "math/rand" "os" "time" ) type r2 struct { x, y float64 } type r2c struct { r2 c int } func kmpp(k int, data []r2c) { kMeans(data, kmppSeeds(k, data)) } func kmppSeeds(k int, da...
Generate a Go translation of this Python snippet without changing its computational steps.
def Dijkstra(Graph, source): infinity = float('infinity') n = len(graph) dist = [infinity]*n previous = [infinity]*n dist[source] = 0 Q = list(range(n)) while Q: u = min(Q, key=lambda n:dist[n]) Q.remove(u) if dist[...
package main import ( "bytes" "fmt" "math/rand" "time" ) type maze struct { c2 [][]byte h2 [][]byte v2 [][]byte } func newMaze(rows, cols int) *maze { c := make([]byte, rows*cols) h := bytes.Repeat([]byte{'-'}, rows*cols) v := bytes.Repeat([]byte{'|'}, rows...
Write the same code in Go as shown below in Python.
import random print(random.sample(range(1, 21), 20))
package main import ( "fmt" "log" "math/rand" "time" ) func generate(from, to int64) { if to < from || from < 0 { log.Fatal("Invalid range.") } span := to - from + 1 generated := make([]bool, span) count := span for count > 0 { n := from + rand.Int63n(span) ...
Maintain the same structure and functionality when rewriting this code in Go.
def DrawBoard(board): peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for n in xrange(1,16): peg[n] = '.' if n in board: peg[n] = "%X" % n print " %s" % peg[1] print " %s %s" % (peg[2],peg[3]) print " %s %s %s" % (peg[4],peg[5],peg[6]) print " %s %s %s %s" % (peg[7],peg[8],peg[9],peg[10])...
package main import "fmt" type solution struct{ peg, over, land int } type move struct{ from, to int } var emptyStart = 1 var board [16]bool var jumpMoves = [16][]move{ {}, {{2, 4}, {3, 6}}, {{4, 7}, {5, 9}}, {{5, 8}, {6, 10}}, {{2, 1}, {5, 6}, {7, 11}, {8, 13}}, {{8, 12}, {9, 14}}, {{...
Convert this Python block to Go, preserving its control flow and logic.
from itertools import combinations_with_replacement as cmbr from time import time def dice_gen(n, faces, m): dice = list(cmbr(faces, n)) succ = [set(j for j, b in enumerate(dice) if sum((x>y) - (x<y) for x in a for y in b) > 0) for a in dice] def loops(seq): ...
package main import ( "fmt" "sort" ) func fourFaceCombs() (res [][4]int) { found := make([]bool, 256) for i := 1; i <= 4; i++ { for j := 1; j <= 4; j++ { for k := 1; k <= 4; k++ { for l := 1; l <= 4; l++ { c := [4]int{i, j, k, l} ...
Write the same code in Go as shown below in Python.
from itertools import combinations_with_replacement as cmbr from time import time def dice_gen(n, faces, m): dice = list(cmbr(faces, n)) succ = [set(j for j, b in enumerate(dice) if sum((x>y) - (x<y) for x in a for y in b) > 0) for a in dice] def loops(seq): ...
package main import ( "fmt" "sort" ) func fourFaceCombs() (res [][4]int) { found := make([]bool, 256) for i := 1; i <= 4; i++ { for j := 1; j <= 4; j++ { for k := 1; k <= 4; k++ { for l := 1; l <= 4; l++ { c := [4]int{i, j, k, l} ...
Ensure the translated Go code behaves exactly like the original Python snippet.
import sys HIST = {} def trace(frame, event, arg): for name,val in frame.f_locals.items(): if name not in HIST: HIST[name] = [] else: if HIST[name][-1] is val: continue HIST[name].append(val) return trace def undo(name): HIST[name].pop(-1) ...
package main import ( "fmt" "sort" "sync" "time" ) type history struct { timestamp tsFunc hs []hset } type tsFunc func() time.Time type hset struct { int t time.Time } func newHistory(ts tsFunc) history { return history{ts, []hset{{t: ts()}}} } ...
Keep all operations the same but rewrite the snippet in Go.
import random TRAINING_LENGTH = 2000 class Perceptron: def __init__(self,n): self.c = .01 self.weights = [random.uniform(-1.0, 1.0) for _ in range(n)] def feed_forward(self, inputs): vars = [] for i in range(len(inputs)): vars.append(inputs[i] * self.weights[i...
package main import ( "github.com/fogleman/gg" "math/rand" "time" ) const c = 0.00001 func linear(x float64) float64 { return x*0.7 + 40 } type trainer struct { inputs []float64 answer int } func newTrainer(x, y float64, a int) *trainer { return &trainer{[]float64{x, y, 1}, a} } type p...
Translate this program into Go but keep the logic exactly as in Python.
>>> exec 10
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time er...
Generate a Go translation of this Python snippet without changing its computational steps.
>>> exec 10
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time er...
Change the programming language of this snippet from Python to Go without modifying what it does.
from sympy import isprime, lcm, factorint, primerange from functools import reduce def pisano1(m): "Simple definition" if m < 2: return 1 lastn, n = 0, 1 for i in range(m ** 2): lastn, n = n, (lastn + n) % m if lastn == 0 and n == 1: return i + 1 return 1 def p...
package main import "fmt" func gcd(a, b uint) uint { if b == 0 { return a } return gcd(b, a%b) } func lcm(a, b uint) uint { return a / gcd(a, b) * b } func ipow(x, p uint) uint { prod := uint(1) for p > 0 { if p&1 != 0 { prod *= x } p >>= 1 ...
Write the same code in Go as shown below in Python.
from itertools import count, islice import numpy as np from numpy import sin, cos, pi ANGDIV = 12 ANG = 2*pi/ANGDIV def draw_all(sols): import matplotlib.pyplot as plt def draw_track(ax, s): turn, xend, yend = 0, [0], [0] for d in s: x0, y0 = xend[-1], yend[-1] a = t...
package main import "fmt" const ( right = 1 left = -1 straight = 0 ) func normalize(tracks []int) string { size := len(tracks) a := make([]byte, size) for i := 0; i < size; i++ { a[i] = "abc"[tracks[i]+1] } norm := string(a) for i := 0; i < size; i++ { ...
Ensure the translated Go code behaves exactly like the original Python snippet.
from itertools import imap, imap, groupby, chain, imap from operator import itemgetter from sys import argv from array import array def concat_map(func, it): return list(chain.from_iterable(imap(func, it))) def minima(poly): return (min(pt[0] for pt in poly), min(pt[1] for pt in poly)) def translate_to_...
package main import ( "fmt" "sort" ) type point struct{ x, y int } type polyomino []point type pointset map[point]bool func (p point) rotate90() point { return point{p.y, -p.x} } func (p point) rotate180() point { return point{-p.x, -p.y} } func (p point) rotate270() point { return point{-p.y, p.x} } func (...
Transform the following Python implementation into Go, maintaining the same output and logic.
import requests import json city = None topic = None def getEvent(url_path, key) : responseString = "" params = {'city':city, 'key':key,'topic':topic} r = requests.get(url_path, params = params) print(r.url) responseString = r.text return responseString def getApiKey(key_path):...
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "net/url" "os" "strings" "time" ) var key string func init() { const keyFile = "api_key.txt" f, err := os.Open(keyFile) if err != nil { log.Fatal(err) } keydata, err := ioutil.ReadAll(f) if err != nil { log.Fatal...
Produce a functionally identical Go code for the snippet given in Python.
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the eve...
package main import "fmt" var solution = make(chan int) var nearMiss = make(chan int) var done = make(chan bool) func main() { for i := 0; i < 4096; i++ { go checkPerm(i) } var ms []int for i := 0; i < 4096; { select { case <-done: i++ case s := ...
Maintain the same structure and functionality when rewriting this code in Go.
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the eve...
package main import "fmt" var solution = make(chan int) var nearMiss = make(chan int) var done = make(chan bool) func main() { for i := 0; i < 4096; i++ { go checkPerm(i) } var ms []int for i := 0; i < 4096; { select { case <-done: i++ case s := ...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
import math dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, ...
package main import ( "fmt" "math" ) type rule func(float64, float64) float64 var dxs = []float64{ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0...
Translate this program into Go but keep the logic exactly as in Python.
import math dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, ...
package main import ( "fmt" "math" ) type rule func(float64, float64) float64 var dxs = []float64{ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0...
Ensure the translated Go code behaves exactly like the original Python snippet.
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'
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 { ...
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
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__ ...
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 { ...
Rewrite the snippet below in Go so it works the same as the original Python code.
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__ ...
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 { ...
Transform the following Python implementation into Go, maintaining the same output and logic.
def ownCalcPass (password, nonce, test=False) : start = True num1 = 0 num2 = 0 password = int(password) if test: print("password: %08x" % (password)) for c in nonce : if c != "0": if start: num2 = password start = False if test:...
package main import ( "fmt" "strconv" ) func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd ...
Write a version of this Python function in Go with identical behavior.
from random import shuffle, choice from itertools import product, accumulate from numpy import floor, sqrt class ADFGVX: def __init__(self, spoly, k, alph='ADFGVX'): self.polybius = list(spoly.upper()) self.pdim = int(floor(sqrt(len(self.polybius)))) self.key = list(k.upper()) ...
package main import ( "bytes" "fmt" "io/ioutil" "log" "math/rand" "sort" "strings" "time" ) var adfgvx = "ADFGVX" var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func distinct(bs []byte) []byte { var u []byte for _, b := range bs { if !bytes.Contains(u, []byte{b}...
Translate the given Python code snippet into Go without altering its behavior.
from random import shuffle, choice from itertools import product, accumulate from numpy import floor, sqrt class ADFGVX: def __init__(self, spoly, k, alph='ADFGVX'): self.polybius = list(spoly.upper()) self.pdim = int(floor(sqrt(len(self.polybius)))) self.key = list(k.upper()) ...
package main import ( "bytes" "fmt" "io/ioutil" "log" "math/rand" "sort" "strings" "time" ) var adfgvx = "ADFGVX" var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func distinct(bs []byte) []byte { var u []byte for _, b := range bs { if !bytes.Contains(u, []byte{b}...
Keep all operations the same but rewrite the snippet in Go.
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)) pr...
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 []floa...
Translate this program into Go but keep the logic exactly as in 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)) pr...
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 []floa...
Convert this Python block to Go, preserving its control flow and logic.
Plataanstraat 5 split as (Plataanstraat, 5) Straat 12 split as (Straat, 12) Straat 12 II split as (Straat, 12 II) Dr. J. Straat 12 split as (Dr. J. Straat , 12) Dr. J. Straat 12 a split as (Dr. J. Straat, 12 a) Dr. J. Straat 12-14 split as (Dr. J. Straat, 12...
package main import ( "fmt" "strings" ) func isDigit(b byte) bool { return '0' <= b && b <= '9' } func separateHouseNumber(address string) (street string, house string) { length := len(address) fields := strings.Fields(address) size := len(fields) last := fields[size-1] penult := fiel...
Generate a Go translation of this Python snippet without changing its computational steps.
import itertools import re import sys from collections import deque from typing import NamedTuple RE_OUTLINE = re.compile(r"^((?: |\t)*)(.+)$", re.M) COLORS = itertools.cycle( [ " " " " " ] ) class Node: def __init__(self, indent, value, parent, children=None)...
package main import ( "fmt" "strings" ) type nNode struct { name string children []nNode } type iNode struct { level int name string } func toNest(iNodes []iNode, start, level int, n *nNode) { if level == 0 { n.name = iNodes[0].name } for i := start + 1; i < len(iNod...
Translate this program into Go but keep the logic exactly as in 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 c...
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 ...
Write a version of this Python function in Go with identical behavior.
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 c...
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 ...
Produce a language-to-language conversion: from Python to Go, same semantics.
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, Wri...
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", ...
Transform the following Python implementation into Go, maintaining the same output and logic.
from mip import Model, BINARY, xsum, minimize def n_queens_min(N): if N < 4: brd = [[0 for i in range(N)] for j in range(N)] brd[0 if N < 2 else 1][0 if N < 2 else 1] = 1 return 1, brd model = Model() board = [[model.add_var(var_type=BINARY) for j in range(N)] for i in range...
package main import ( "fmt" "math" "strings" "time" ) var board [][]bool var diag1, diag2 [][]int var diag1Lookup, diag2Lookup []bool var n, minCount int var layout string func isAttacked(piece string, row, col int) bool { if piece == "Q" { for i := 0; i < n; i++ { if board[i]...
Translate the given Python code snippet into Go without altering its behavior.
from functools import reduce from operator import add def wordleScore(target, guess): return mapAccumL(amber)( *first(charCounts)( mapAccumL(green)( [], zip(target, guess) ) ) )[1] def green(residue, tg): t, g = tg return (residue...
package main import ( "bytes" "fmt" "log" ) func wordle(answer, guess string) []int { n := len(guess) if n != len(answer) { log.Fatal("The words must be of the same length.") } answerBytes := []byte(answer) result := make([]int, n) for i := 0; i < n; i++ { if guess...
Preserve the algorithm and functionality while converting the code from Python to Go.
from math import prod def maxproduct(mat, length): nrow, ncol = len(mat), len(mat[0]) maxprod, maxrow, maxcol, arr = 0, [0, 0], [0, 0], [0] for row in range(nrow): for col in range(ncol): row2, col2 = row + length, col + length if row < nrow - length: ...
package main import ( "fmt" "rcu" "strings" ) var grid = [][]int { { 8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8}, {49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0}, {81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3...
Transform the following Python implementation into Go, maintaining the same output and logic.
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...
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]) ...
Rewrite the snippet below in Go so it works the same as the original Python code.
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...
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]) ...
Produce a functionally identical Go code for the snippet given in Python.
import strutils, strformat type Node = ref object kind: char resistance: float voltage: float a: Node b: Node proc res(node: Node): float = if node.kind == '+': return node.a.res + node.b.res if node.kind == '*': return 1 / (1 / node.a.res + 1 / node.b.res) node.resistance proc current(...
package main import "fmt" type Resistor struct { symbol rune resistance, voltage float64 a, b *Resistor } func (r *Resistor) res() float64 { switch r.symbol { case '+': return r.a.res() + r.b.res() case '*': return 1 / (1/r.a.res() + 1/r.b.res()) ...
Port the provided Python code into Go while preserving the original functionality.
def gen_upside_down_number(): wrappings = [[1, 9], [2, 8], [3, 7], [4, 6], [5, 5], [6, 4], [7, 3], [8, 2], [9, 1]] evens = [19, 28, 37, 46, 55, 64, 73, 82, 91] odds = [5] odd_index, even_index = 0, 0 ndigits = 1 while True: if ndigits % 2 == 1: if len...
package main import ( "fmt" "rcu" ) func genUpsideDown(limit int) chan int { ch := make(chan int) wrappings := [][2]int{ {1, 9}, {2, 8}, {3, 7}, {4, 6}, {5, 5}, {6, 4}, {7, 3}, {8, 2}, {9, 1}, } evens := []int{19, 28, 37, 46, 55, 64, 73, 82, 91} odds := []int{5} oddInde...
Please provide an equivalent version of this Python code in Go.
print( "{:19.16f} {:19.16f}".format( minkowski(minkowski_inv(4.04145188432738056)), minkowski_inv(minkowski(4.04145188432738056)), ) )
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...
Write the same algorithm in Go as shown in this Python implementation.
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]]) ...
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 ...
Maintain the same structure and functionality when rewriting this code in Go.
from numpy.random import shuffle SUITS = ['♣', '♦', '♥', '♠'] FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] DECK = [f + s for f in FACES for s in SUITS] CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK))) class WarCardGame: def __init__(self): deck =...
package main import ( "fmt" "math/rand" "time" ) var suits = []string{"♣", "♦", "♥", "♠"} var faces = []string{"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"} var cards = make([]string, 52) var ranks = make([]int, 52) func init() { for i := 0; i < 52; i++ { cards[i] = fmt.Spr...
Change the programming language of this snippet from Python to Go without modifying what it does.
from numpy.random import shuffle SUITS = ['♣', '♦', '♥', '♠'] FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] DECK = [f + s for f in FACES for s in SUITS] CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK))) class WarCardGame: def __init__(self): deck =...
package main import ( "fmt" "math/rand" "time" ) var suits = []string{"♣", "♦", "♥", "♠"} var faces = []string{"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"} var cards = make([]string, 52) var ranks = make([]int, 52) func init() { for i := 0; i < 52; i++ { cards[i] = fmt.Spr...
Change the following Python code into Go without altering its purpose.
from PIL import Image if __name__=="__main__": im = Image.open("frog.png") im2 = im.quantize(16) im2.show()
package main import ( "container/heap" "image" "image/color" "image/png" "log" "math" "os" "sort" ) func main() { f, err := os.Open("Quantum_frog.png") if err != nil { log.Fatal(err) } img, err := png.Decode(f) if ec := f.Close(); err != nil { log.Fa...
Keep all operations the same but rewrite the snippet in Go.
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)...
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 :=...
Convert the following code from Python to Go, ensuring the logic remains intact.
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)...
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 :=...
Produce a language-to-language conversion: from Python to Go, same semantics.
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)...
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 :=...
Maintain the same structure and functionality when rewriting this code in Go.
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.sor...
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}, } ...
Ensure the translated Go code behaves exactly like the original Python snippet.
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.sor...
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}, } ...
Write the same algorithm in Go as shown in this Python implementation.
import math import os def suffize(num, digits=None, base=10): suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol'] exponent_distance = 10 if base == 2 else 3 num = num.strip().replace(',', '') num_sign = num[0] if num[0] in '+-' else '' num = abs(float(num)) ...
package main import ( "fmt" "math/big" "strconv" "strings" ) var suffixes = " KMGTPEZYXWVU" var ggl = googol() func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } ...
Translate the given Python code snippet into Go without altering its behavior.
import math import os def suffize(num, digits=None, base=10): suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol'] exponent_distance = 10 if base == 2 else 3 num = num.strip().replace(',', '') num_sign = num[0] if num[0] in '+-' else '' num = abs(float(num)) ...
package main import ( "fmt" "math/big" "strconv" "strings" ) var suffixes = " KMGTPEZYXWVU" var ggl = googol() func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } ...
Write a version of this Python function in Go with identical behavior.
def longestPalindromes(s): k = s.lower() palindromes = [ palExpansion(k)(ab) for ab in palindromicNuclei(k) ] maxLength = max([ len(x) for x in palindromes ]) if palindromes else 1 return ( [ x for x in palindromes if maxLength == len(x) ...
package main import ( "fmt" "sort" ) func reverse(s string) string { var r = []rune(s) for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func longestPalSubstring(s string) []string { var le = len(s) if le <= 1 { return []str...
Write the same code in Go as shown below in Python.
import random class WumpusGame(object): def __init__(self, edges=[]): if edges: cave = {} N = max([edges[i][0] for i in range(len(edges))]) for i in range(N): exits = [edge[1] for edge in edges if edge[0] == i] cave[i] = exits else: cave = {1: [2,3,4], 2: [1,5,6], 3: [1,7,8], 4: [1...
package main import ( "bufio" "fmt" "log" "math/rand" "os" "strconv" "strings" "time" ) var cave = map[int][3]int{ 1: {2, 3, 4}, 2: {1, 5, 6}, 3: {1, 7, 8}, 4: {1, 9, 10}, 5: {2, 9, 11}, 6: {2, 7, 12}, 7: {3, 6, 13}, 8: {3, 10, 14}, 9: {4, 5, 15}, 10: {4, 8, 16}, 11: {5, 12...
Translate this program into Go but keep the logic exactly as in 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]]
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 ...
Maintain the same structure and functionality when rewriting this code in Go.
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()
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 hourglass...
Ensure the translated Go code behaves exactly like the original Python snippet.
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()
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 hourglass...
Please provide an equivalent version of this Python code in Go.
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)]))
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 {...
Translate the given Python code snippet into Go without altering its behavior.
class FibonacciHeap: class Node: def __init__(self, data): self.data = data self.parent = self.child = self.left = self.right = None self.degree = 0 self.mark = False def iterate(self, head): node = stop = head f...
package fib import "fmt" type Value interface { LT(Value) bool } type Node struct { value Value parent *Node child *Node prev, next *Node rank int mark bool } func (n Node) Value() Value { return n.value } type Heap struct{ *Node } func MakeHeap() *Heap { ret...
Preserve the algorithm and functionality while converting the code from Python to Go.
import datetime def g2m(date, gtm_correlation=True): correlation = 584283 if gtm_correlation else 584285 long_count_days = [144000, 7200, 360, 20, 1] tzolkin_months = ['Imix’', 'Ik’', 'Ak’bal', 'K’an', 'Chikchan', 'Kimi', 'Manik’', 'Lamat', 'Muluk', 'Ok', 'Chuwen', 'Eb'...
package main import ( "fmt" "strconv" "strings" "time" ) var sacred = strings.Fields("Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw") var civil = strings.Fields("Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muw...
Write a version of this Python function in Go with identical behavior.
import sys if len(sys.argv)!=2: print("Usage : python " + sys.argv[0] + " <whole number>") exit() numLimit = int(sys.argv[1]) resultSet = {} base = 1 while len(resultSet)!=numLimit: result = base**base for i in range(0,numLimit): if str(i) in str(result) and i not in resultSet: ...
package main import ( "fmt" "math/big" "strconv" "strings" ) func main() { var res []int64 for n := 0; n <= 50; n++ { ns := strconv.Itoa(n) k := int64(1) for { bk := big.NewInt(k) s := bk.Exp(bk, bk, nil).String() if strings.Contains(...
Please provide an equivalent version of this Python code in Go.
print("working...") row = 0 limit = 1500 Sophie = [] def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True for n in range(2,limit): p = 2*n + 1 if isPrime(n) and isPrime(p): Sophie.append(n) print("Found ",end = "") print(len(Sophie),end = "") print(" Sa...
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 ...
Translate this program into Go but keep the logic exactly as in Python.
print("working...") row = 0 limit = 1500 Sophie = [] def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True for n in range(2,limit): p = 2*n + 1 if isPrime(n) and isPrime(p): Sophie.append(n) print("Found ",end = "") print(len(Sophie),end = "") print(" Sa...
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 ...
Produce a functionally identical Go code for the snippet given in Python.
from __future__ import unicode_literals import argparse import fileinput import os import sys from functools import partial from itertools import count from itertools import takewhile ANSI_RESET = "\u001b[0m" RED = (255, 0, 0) GREEN = (0, 255, 0) YELLOW = (255, 255, 0) BLUE = (0, 0, 255) MAGENTA = (255, 0, 255)...
package main import ( "bufio" "fmt" "golang.org/x/crypto/ssh/terminal" "log" "os" "regexp" "strconv" ) type Color struct{ r, g, b int } type ColorEx struct { color Color code string } var colors = []ColorEx{ {Color{15, 0, 0}, "31"}, {Color{0, 15, 0}, "32"}, {Color{15...
Write the same code in Go as shown below in Python.
import sqlite3 import string import random from http import HTTPStatus from flask import Flask from flask import Blueprint from flask import abort from flask import current_app from flask import g from flask import jsonify from flask import redirect from flask import request from flask import url_for CHARS = froz...
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "time" ) const ( chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" host = "localhost:8000" ) type database map[string]string type shortener struct { Long string `json...
Maintain the same structure and functionality when rewriting this code in Go.
import sqlite3 import string import random from http import HTTPStatus from flask import Flask from flask import Blueprint from flask import abort from flask import current_app from flask import g from flask import jsonify from flask import redirect from flask import request from flask import url_for CHARS = froz...
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "time" ) const ( chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" host = "localhost:8000" ) type database map[string]string type shortener struct { Long string `json...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
import sys black_pawn = " \u265f " white_pawn = " \u2659 " empty_square = " " def draw_board(board_data): bg_black = "\u001b[48;5;237m" bg_white = "\u001b[48;5;245m" clear_to_eol = "\u001b[0m\u001b[K\n" board = ["1 ", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black,...
package main import ( "bytes" "errors" "flag" "fmt" "io" "io/ioutil" "log" "math/rand" "os" "time" ) const ( Rows = 3 Cols = 3 ) var vlog *log.Logger func main() { verbose := flag.Bool("v", false, "verbose") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } logOutput := ioutil.Disc...
Maintain the same structure and functionality when rewriting this code in Go.
import sys black_pawn = " \u265f " white_pawn = " \u2659 " empty_square = " " def draw_board(board_data): bg_black = "\u001b[48;5;237m" bg_white = "\u001b[48;5;245m" clear_to_eol = "\u001b[0m\u001b[K\n" board = ["1 ", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black,...
package main import ( "bytes" "errors" "flag" "fmt" "io" "io/ioutil" "log" "math/rand" "os" "time" ) const ( Rows = 3 Cols = 3 ) var vlog *log.Logger func main() { verbose := flag.Bool("v", false, "verbose") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } logOutput := ioutil.Disc...
Translate this program into Go but keep the logic exactly as in Python.
import re from collections import defaultdict from itertools import count connection_re = r class Graph: def __init__(self, name, connections): self.name = name self.connections = connections g = self.graph = defaultdict(list) matches = re.finditer(connection_re, connections, ...
package main import ( "fmt" "sort" ) type graph struct { nn int st int nbr [][]int } type nodeval struct { n int v int } func contains(s []int, n int) bool { for _, e := range s { if e == n { return true } } return false } func newG...
Write a version of this Python function in Go with identical behavior.
print("working...") print("Primes are:") def isprime(m): for i in range(2,int(m**0.5)+1): if m%i==0: return False return True Primes = [2,43,81,122,63,13,7,95,103] Temp = [] for n in range(len(Primes)): if isprime(Primes[n]): Temp.append(Primes[n]) Temp.sort() print(Temp) print("done....
package main import ( "fmt" "rcu" "sort" ) func main() { list := []int{2, 43, 81, 122, 63, 13, 7, 95, 103} var primes []int for _, e := range list { if rcu.IsPrime(e) { primes = append(primes, e) } } sort.Ints(primes) fmt.Println(primes) }
Rewrite the snippet below in Go so it works the same as the original Python code.
from itertools import product, compress fact = lambda n: n and n*fact(n - 1) or 1 combo_count = lambda total, coins, perm:\ sum(perm and fact(len(x)) or 1 for x in (list(compress(coins, c)) for c in product(*([(0, 1)]*len(coins)))) ...
package main import "fmt" var cnt = 0 var cnt2 = 0 var wdth = 0 func factorial(n int) int { prod := 1 for i := 2; i <= n; i++ { prod *= i } return prod } func count(want int, used []int, sum int, have, uindices, rindices []int) { if sum == want { cnt++ cnt2 += factori...
Rewrite the snippet below in Go so it works the same as the original Python code.
from itertools import product, compress fact = lambda n: n and n*fact(n - 1) or 1 combo_count = lambda total, coins, perm:\ sum(perm and fact(len(x)) or 1 for x in (list(compress(coins, c)) for c in product(*([(0, 1)]*len(coins)))) ...
package main import "fmt" var cnt = 0 var cnt2 = 0 var wdth = 0 func factorial(n int) int { prod := 1 for i := 2; i <= n; i++ { prod *= i } return prod } func count(want int, used []int, sum int, have, uindices, rindices []int) { if sum == want { cnt++ cnt2 += factori...
Produce a language-to-language conversion: from Python to Go, same semantics.
from functools import reduce from operator import mul from decimal import * getcontext().prec = MAX_PREC def expand(num): suffixes = [ ('greatgross', 7, 12, 3), ('gross', 2, 12, 2), ('dozens', 3, 12, 1), ('pairs', 4, 2, 1), ('scores', 3, 20, 1), ('googols',...
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) type minmult struct { min int mult float64 } var abbrevs = map[string]minmult{ "PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12}, "GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100}, } var metr...
Preserve the algorithm and functionality while converting the code from Python to Go.
from functools import reduce from operator import mul from decimal import * getcontext().prec = MAX_PREC def expand(num): suffixes = [ ('greatgross', 7, 12, 3), ('gross', 2, 12, 2), ('dozens', 3, 12, 1), ('pairs', 4, 2, 1), ('scores', 3, 20, 1), ('googols',...
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) type minmult struct { min int mult float64 } var abbrevs = map[string]minmult{ "PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12}, "GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100}, } var metr...
Transform the following Python implementation into Go, maintaining the same output and logic.
import math def apply_perm(omega,fbn): for m in range(len(fbn)): g = fbn[m] if g > 0: new_first = omega[m+g] omega[m+1:m+g+1] = omega[m:m+g] omega[m] = new_first return omega def int...
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func genFactBaseNums(size int, countOnly bool) ([][]int, int) { var results [][]int count := 0 for n :...