Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite this program in Go while keeping its functionality equivalent to the Python version. |
import matplotlib.pyplot as plt
from math import sin, cos, pi
def sgn(x):
return ((x>0)-(x<0))*1
a,b,n=200,200,2.5
na=2/n
step=100
piece=(pi*2)/step
xp=[];yp=[]
t=0
for t1 in range(step+1):
x=(abs((cos(t)))**na)*a*sgn(cos(t))
y=(abs((sin(t)))**na)*b*sgn(sin(t))
xp.append(x);yp.append(y)
t+=piece
plt.plo... | package main
import (
"github.com/fogleman/gg"
"math"
)
func superEllipse(dc *gg.Context, n float64, a int) {
hw := float64(dc.Width() / 2)
hh := float64(dc.Height() / 2)
y := make([]float64, a+1)
for x := 0; x <= a; x++ {
aa := math.Pow(float64(a), n)
xx := math.Pow(flo... |
Please provide an equivalent version of this Python code in Go. | from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return ... | package main
import (
"fmt"
"math/rand"
)
func MRPerm(q, n int) []int {
p := ident(n)
var r int
for n > 0 {
q, r = q/n, q%n
n--
p[n], p[r] = p[r], p[n]
}
return p
}
func ident(n int) []int {
p := make([]int, n)
for i := range p {
p[i] = i
}
... |
Translate this program into Go but keep the logic exactly as in Python. | from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return ... | package main
import (
"fmt"
"math/rand"
)
func MRPerm(q, n int) []int {
p := ident(n)
var r int
for n > 0 {
q, r = q/n, q%n
n--
p[n], p[r] = p[r], p[n]
}
return p
}
func ident(n int) []int {
p := make([]int, n)
for i := range p {
p[i] = i
}
... |
Keep all operations the same but rewrite the snippet in Go. | def main():
resources = int(input("Cantidad de recursos: "))
processes = int(input("Cantidad de procesos: "))
max_resources = [int(i) for i in input("Recursos máximos: ").split()]
print("\n-- recursos asignados para cada proceso --")
currently_allocated = [[int(i) for i in input(f"proceso {j + 1}:... | package bank
import (
"bytes"
"errors"
"fmt"
"log"
"sort"
"sync"
)
type PID string
type RID string
type RMap map[RID]int
func (m RMap) String() string {
rs := make([]string, len(m))
i := 0
for r := range m {
rs[i] = string(r)
i++
}
sort.Strings(rs)
var... |
Write a version of this Python function in Go with identical behavior. | def range_extract(lst):
'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
lenlst = len(lst)
i = 0
while i< lenlst:
low = lst[i]
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
hi = lst[i]
if hi - low >= 2:
yield (low, hi)
... | package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
func main() {
rf, err := rangeFormat([]int{
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39,
})
if err != nil {
fmt... |
Generate a Go translation of this Python snippet without changing its computational steps. | import ctypes
import os
from ctypes import c_ubyte, c_int
code = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])
code_size = len(code)
if (os.name == 'posix'):
import mmap
executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EX... | package main
import "fmt"
import "C"
func main() {
code := []byte{
0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,
0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,
0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,
0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,
}
le := len(code)
buf := C.mmap(nil, C.size_t(le), C.PROT... |
Please provide an equivalent version of this Python code in Go. | fun maxpathsum(t):
let a = val t
for i in a.length-1..-1..1, c in linearindices a[r]:
a[r, c] += max(a[r+1, c], a[r=1, c+1])
return a[1, 1]
let test = [
[55],
[94, 48],
[95, 30, 96],
[77, 71, 26, 67],
[97, 13, 76, 38, 45],
[07, 36, 79, 16, 37, 68],
[48, 07, 09, 18, 70, ... | package main
import (
"fmt"
"strconv"
"strings"
)
const t = ` 55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79... |
Please provide an equivalent version of this Python code in Go. |
beforeTxt =
smallrc01 =
rc01 =
def intarray(binstring):
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
Return 8-neighb... | package main
import (
"bytes"
"fmt"
"strings"
)
var in = `
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
0111001111001110... |
Write the same algorithm in Go as shown in this Python implementation. | import Image, ImageFilter
im = Image.open('image.ppm')
median = im.filter(ImageFilter.MedianFilter(3))
median.save('image2.ppm')
| package main
import (
"fmt"
"raster"
)
var g0, g1 *raster.Grmap
var ko [][]int
var kc []uint16
var mid int
func init() {
ko = [][]int{
{-1, -1}, {0, -1}, {1, -1},
{-1, 0}, {0, 0}, {1, 0},
{-1, 1}, {0, 1}, {1, 1}}
kc = make([]uint16, len(ko))
mid = len(ko) ... |
Write the same algorithm in Go as shown in this Python implementation. | import Image, ImageFilter
im = Image.open('image.ppm')
median = im.filter(ImageFilter.MedianFilter(3))
median.save('image2.ppm')
| package main
import (
"fmt"
"raster"
)
var g0, g1 *raster.Grmap
var ko [][]int
var kc []uint16
var mid int
func init() {
ko = [][]int{
{-1, -1}, {0, -1}, {1, -1},
{-1, 0}, {0, 0}, {1, 0},
{-1, 1}, {0, 1}, {1, 1}}
kc = make([]uint16, len(ko))
mid = len(ko) ... |
Translate this program into Go but keep the logic exactly as in Python. |
import posix
import os
import sys
pid = posix.fork()
if pid != 0:
print("Child process detached with pid %s" % pid)
sys.exit(0)
old_stdin = sys.stdin
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdin = open('/dev/null', 'rt')
sys.stdout = open('/tmp/dmn.log', 'wt')
sys.stderr = sys.stdout
old_stdin... | package main
import (
"fmt"
"github.com/sevlyar/go-daemon"
"log"
"os"
"time"
)
func work() {
f, err := os.Create("daemon_output.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
ticker := time.NewTicker(time.Second)
go func() {
for t := range ticker.C {... |
Rewrite the snippet below in Go so it works the same as the original Python code. |
import posix
import os
import sys
pid = posix.fork()
if pid != 0:
print("Child process detached with pid %s" % pid)
sys.exit(0)
old_stdin = sys.stdin
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdin = open('/dev/null', 'rt')
sys.stdout = open('/tmp/dmn.log', 'wt')
sys.stderr = sys.stdout
old_stdin... | package main
import (
"fmt"
"github.com/sevlyar/go-daemon"
"log"
"os"
"time"
)
func work() {
f, err := os.Create("daemon_output.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
ticker := time.NewTicker(time.Second)
go func() {
for t := range ticker.C {... |
Change the programming language of this snippet from Python to Go without modifying what it does. |
def Gcd(v1, v2):
a, b = v1, v2
if (a < b):
a, b = v2, v1
r = 1
while (r != 0):
r = a % b
if (r != 0):
a = b
b = r
return b
a = [1, 2]
n = 3
while (n < 50):
gcd1 = Gcd(n, a[-1])
gcd2 = Gcd(n, a[-2])
if (gcd1 == 1 a... | package main
import (
"fmt"
"rcu"
)
func contains(a []int, v int) bool {
for _, e := range a {
if e == v {
return true
}
}
return false
}
func main() {
const limit = 50
cpt := []int{1, 2}
for {
m := 1
l := len(cpt)
for contains(cpt, ... |
Maintain the same structure and functionality when rewriting this code in Go. |
def Gcd(v1, v2):
a, b = v1, v2
if (a < b):
a, b = v2, v1
r = 1
while (r != 0):
r = a % b
if (r != 0):
a = b
b = r
return b
a = [1, 2]
n = 3
while (n < 50):
gcd1 = Gcd(n, a[-1])
gcd2 = Gcd(n, a[-2])
if (gcd1 == 1 a... | package main
import (
"fmt"
"rcu"
)
func contains(a []int, v int) bool {
for _, e := range a {
if e == v {
return true
}
}
return false
}
func main() {
const limit = 50
cpt := []int{1, 2}
for {
m := 1
l := len(cpt)
for contains(cpt, ... |
Change the programming language of this snippet from Python to Go without modifying what it does. | s = [1, 2, 2, 3, 4, 4, 5]
for i in range(len(s)):
curr = s[i]
if i > 0 and curr == prev:
print(i)
prev = curr
| package main
import "fmt"
func main() {
s := []int{1, 2, 2, 3, 4, 4, 5}
for i := 0; i < len(s); i++ {
curr := s[i]
var prev int
if i > 0 && curr == prev {
fmt.Println(i)
}
prev = curr
}
var prev int
for i := 0; i < len(s); i... |
Write the same algorithm in Go as shown in this Python implementation. | from SOAPpy import WSDL
proxy = WSDL.Proxy("http://example.com/soap/wsdl")
result = proxy.soapFunc("hello")
result = proxy.anotherSoapFunc(34234)
| package main
import (
"fmt"
"github.com/tiaguinho/gosoap"
"log"
)
type CheckVatResponse struct {
CountryCode string `xml:"countryCode"`
VatNumber string `xml:"vatNumber"`
RequestDate string `xml:"requestDate"`
Valid string `xml:"valid"`
Name string `xml:"name"`
Addre... |
Change the following Python code into Go without altering its purpose. | Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import __future__
>>> __future__.all_feature_names
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals'... | |
Port the provided Python code into Go while preserving the original functionality. | def msb(x):
return x.bit_length() - 1
def lsb(x):
return msb(x & -x)
for i in range(6):
x = 42 ** i
print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
for i in range(6):
x = 1302 ** i
print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
| package main
import (
"fmt"
"math/big"
)
const (
mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota
mask1, bit1
mask2, bit2
mask3, bit3
mask4, bit4
mask5, bit5
)
func rupb(x uint64) (out int) {
if x == 0 {
return -1
}
if x&^mask5 != 0 {
x >>= bit5
out ... |
Translate the given Python code snippet into Go without altering its behavior. | def msb(x):
return x.bit_length() - 1
def lsb(x):
return msb(x & -x)
for i in range(6):
x = 42 ** i
print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
for i in range(6):
x = 1302 ** i
print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
| package main
import (
"fmt"
"math/big"
)
const (
mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota
mask1, bit1
mask2, bit2
mask3, bit3
mask4, bit4
mask5, bit5
)
func rupb(x uint64) (out int) {
if x == 0 {
return -1
}
if x&^mask5 != 0 {
x >>= bit5
out ... |
Produce a language-to-language conversion: from Python to Go, same semantics. | import itertools
def riseEqFall(num):
height = 0
d1 = num % 10
num //= 10
while num:
d2 = num % 10
height += (d1<d2) - (d1>d2)
d1 = d2
num //= 10
return height == 0
def sequence(start, fn):
num=start-1
while True:
num += 1
while... | package main
import "fmt"
func risesEqualsFalls(n int) bool {
if n < 10 {
return true
}
rises := 0
falls := 0
prev := -1
for n > 0 {
d := n % 10
if prev >= 0 {
if d < prev {
rises = rises + 1
} else if d > prev {
f... |
Convert this Python snippet to Go and keep its semantics consistent. | import curses
scr = curses.initscr()
def move_left():
y,x = curses.getyx()
curses.move(y,x-1)
def move_right():
y,x = curses.getyx()
curses.move(y,x+1)
def move_up():
y,x = curses.getyx()
curses.move(y-1,x)
def move_down():
y,x = curses.getyx()
curses.move(y+1,x)
def move_line_home()
y,x = curses... | package main
import (
"fmt"
"time"
"os"
"os/exec"
"strconv"
)
func main() {
tput("clear")
tput("cup", "6", "3")
time.Sleep(1 * time.Second)
tput("cub1")
time.Sleep(1 * time.Second)
tput("cuf1")
time.Sleep(1 * time.Second)
tput("cuu1")
time.Sleep(1 * time.Se... |
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__':
suma = 2
n = 1
for i in range(3, 2000000, 2):
if isPrime(i):
suma += i
n+=1
print(suma)
| package main
import (
"fmt"
"rcu"
)
func main() {
sum := 0
for _, p := range rcu.Primes(2e6 - 1) {
sum += p
}
fmt.Printf("The sum of all primes below 2 million is %s.\n", rcu.Commatize(sum))
}
|
Port the provided Python code into Go while preserving the original functionality. | l = 300
def setup():
size(400, 400)
background(0, 0, 255)
stroke(255)
translate(width / 2.0, height / 2.0)
translate(-l / 2.0, l * sqrt(3) / 6.0)
for i in range(4):
kcurve(0, l)
rotate(radians(120))
translate(-l, 0)
def kcurve(x1, x2):
s = (x2 - x1) / 3.0... | package main
import (
"github.com/fogleman/gg"
"math"
)
var dc = gg.NewContext(512, 512)
func koch(x1, y1, x2, y2 float64, iter int) {
angle := math.Pi / 3
x3 := (x1*2 + x2) / 3
y3 := (y1*2 + y2) / 3
x4 := (x1 + x2*2) / 3
y4 := (y1 + y2*2) / 3
x5 := x3 + (x4-x3)*math.Cos(angle) + (y4... |
Port the following code from Python to Go with equivalent syntax and logic. | import Tkinter,random
def draw_pixel_2 ( sizex=640,sizey=480 ):
pos = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )
root = Tkinter.Tk()
can = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )
can.create_rectangle( pos*2,outline='yellow' )
can.pack()
root.title('press ESCAPE ... | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"math/rand"
"time"
)
func main() {
rect := image.Rect(0, 0, 640, 480)
img := image.NewRGBA(rect)
blue := color.RGBA{0, 0, 255, 255}
draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src)
yell... |
Transform the following Python implementation into Go, maintaining the same output and logic. | def isvowel(c):
return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', "I", 'O', 'U']
def isletter(c):
return 'a' <= c <= 'z' or 'A' <= c <= 'Z'
def isconsonant(c):
return not isvowel(c) and isletter(c)
def vccounts(s):
a = list(s.lower())
au = set(a)
return sum([isvowel(c) for ... | package main
import (
"fmt"
"strings"
)
func main() {
const (
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
)
strs := []string{
"Forever Go programming language",
"Now is the time for all good men to come to the aid of their country.",
}
for _, s... |
Convert this Python block to Go, preserving its control flow and logic. | def isvowel(c):
return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', "I", 'O', 'U']
def isletter(c):
return 'a' <= c <= 'z' or 'A' <= c <= 'Z'
def isconsonant(c):
return not isvowel(c) and isletter(c)
def vccounts(s):
a = list(s.lower())
au = set(a)
return sum([isvowel(c) for ... | package main
import (
"fmt"
"strings"
)
func main() {
const (
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
)
strs := []string{
"Forever Go programming language",
"Now is the time for all good men to come to the aid of their country.",
}
for _, s... |
Preserve the algorithm and functionality while converting the code from Python to Go. | def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name... | package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type TokenType int
const (
tkEOI TokenType = iota
tkMul
tkDiv
tkMod
tkAdd
tkSub
tkNegate
tkNot
tkLss
tkLeq
tkGtr
tkGeq
tkEql
tkNeq
tkAssign
tkAnd
tkOr
t... |
Write the same code in Go as shown below in Python. | def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name... | package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type TokenType int
const (
tkEOI TokenType = iota
tkMul
tkDiv
tkMod
tkAdd
tkSub
tkNegate
tkNot
tkLss
tkLeq
tkGtr
tkGeq
tkEql
tkNeq
tkAssign
tkAnd
tkOr
t... |
Generate a Go translation of this Python snippet without changing its computational steps. | from PIL import Image
img = Image.new('RGB', (320, 240))
pixels = img.load()
pixels[100,100] = (255,0,0)
img.show()
| package main
import (
"fmt"
"image"
"image/color"
"image/draw"
)
func main() {
rect := image.Rect(0, 0, 320, 240)
img := image.NewRGBA(rect)
green := color.RGBA{0, 255, 0, 255}
draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)
red := color.RGBA{255, 0, 0, ... |
Can you help me rewrite this code in Go instead of Python, keeping it the same logically? |
def digitSumsPrime(n):
def go(bases):
return all(
isPrime(digitSum(b)(n))
for b in bases
)
return go
def digitSum(base):
def go(n):
q, r = divmod(n, base)
return go(q) + r if n else 0
return go
def main():
xs = [
... | package main
import (
"fmt"
"rcu"
)
func main() {
var numbers []int
for i := 2; i < 200; i++ {
bds := rcu.DigitSum(i, 2)
if rcu.IsPrime(bds) {
tds := rcu.DigitSum(i, 3)
if rcu.IsPrime(tds) {
numbers = append(numbers, i)
}
}
... |
Rewrite the snippet below in Go so it works the same as the original Python code. |
def digitSumsPrime(n):
def go(bases):
return all(
isPrime(digitSum(b)(n))
for b in bases
)
return go
def digitSum(base):
def go(n):
q, r = divmod(n, base)
return go(q) + r if n else 0
return go
def main():
xs = [
... | package main
import (
"fmt"
"rcu"
)
func main() {
var numbers []int
for i := 2; i < 200; i++ {
bds := rcu.DigitSum(i, 2)
if rcu.IsPrime(bds) {
tds := rcu.DigitSum(i, 3)
if rcu.IsPrime(tds) {
numbers = append(numbers, i)
}
}
... |
Translate the given Python code snippet into Go without altering its behavior. |
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 ... | 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 []strin... |
Transform the following Python implementation into Go, maintaining the same output and logic. |
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)
... | 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
}
}
... |
Write a version of this Python function in Go with identical behavior. |
from myhdl import *
@block
def NOTgate( a, q ):
@always_comb
def NOTgateLogic():
q.next = not a
return NOTgateLogic
@block
def ANDgate( a, b, q ):
@always_comb
def ANDgateLogic():
q.next = a and b
return ANDgateLogic
@block
def ORgate( a, b, q ):
@... | package main
import "fmt"
func xor(a, b byte) byte {
return a&(^b) | b&(^a)
}
func ha(a, b byte) (s, c byte) {
return xor(a, b), a & b
}
func fa(a, b, c0 byte) (s, c1 byte) {
sa, ca := ha(a, c0)
s, cb := ha(sa, b)
c1 = ca | cb
return
}
func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, ... |
Port the provided Python code into Go while preserving the original functionality. |
from myhdl import *
@block
def NOTgate( a, q ):
@always_comb
def NOTgateLogic():
q.next = not a
return NOTgateLogic
@block
def ANDgate( a, b, q ):
@always_comb
def ANDgateLogic():
q.next = a and b
return ANDgateLogic
@block
def ORgate( a, b, q ):
@... | package main
import "fmt"
func xor(a, b byte) byte {
return a&(^b) | b&(^a)
}
func ha(a, b byte) (s, c byte) {
return xor(a, b), a & b
}
func fa(a, b, c0 byte) (s, c1 byte) {
sa, ca := ha(a, c0)
s, cb := ha(sa, b)
c1 = ca | cb
return
}
func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, ... |
Please provide an equivalent version of this Python code in Go. | import math
from sys import stdout
LOG_10 = 2.302585092994
def build_oms(s):
if s % 2 == 0:
s += 1
q = [[0 for j in range(s)] for i in range(s)]
p = 1
i = s // 2
j = 0
while p <= (s * s):
q[i][j] = p
ti = i + 1
if ti >= s: ti = 0
tj = j - 1
if ... | package main
import (
"fmt"
"log"
)
func magicSquareOdd(n int) ([][]int, error) {
if n < 3 || n%2 == 0 {
return nil, fmt.Errorf("base must be odd and > 2")
}
value := 1
gridSize := n * n
c, r := n/2, 0
result := make([][]int, n)
for i := 0; i < n; i++ {
result[i] =... |
Write the same algorithm in Go as shown in this Python implementation. | >>> 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') <... | 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... |
Change the programming language of this snippet from Python to Go without modifying what it does. | >>> 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') <... | 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... |
Port the provided Python code into Go while preserving the original functionality. |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
|
package main
import "fmt"
func MeaningOfLife() int {
return 42
}
func libMain() {
fmt.Println("The meaning of life is", MeaningOfLife())
}
|
Preserve the algorithm and functionality while converting the code from Python to Go. |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
|
package main
import "fmt"
func MeaningOfLife() int {
return 42
}
func libMain() {
fmt.Println("The meaning of life is", MeaningOfLife())
}
|
Produce a functionally identical Go code for the snippet given in Python. | import math
def perlin_noise(x, y, z):
X = math.floor(x) & 255
Y = math.floor(y) & 255
Z = math.floor(z) & 255
x -= math.floor(x)
y -= math.floor(y)
z -= math.floor(z)
u = fade(x) ... | package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(noise(3.14, 42, 7))
}
func noise(x, y, z float64) float64 {
X := int(math.Floor(x)) & 255
Y := int(math.Floor(y)) & 255
Z := int(math.Floor(z)) & 255
x -= math.Floor(x)
y -= math.Floor(y)
z -= math.Floor(z)
u := fa... |
Change the following Python code into Go without altering its purpose. | 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)... | 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
}... |
Preserve the algorithm and functionality while converting the code from Python to Go. | >>> 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
>>>
| 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)
}
}
|
Port the following code from Python to Go with equivalent syntax and logic. |
from __future__ import annotations
import asyncio
import sys
from typing import Optional
from typing import TextIO
class OutOfInkError(Exception):
class Printer:
def __init__(self, name: str, backup: Optional[Printer]):
self.name = name
self.backup = backup
self.ink_level: int =... | package main
import (
"errors"
"fmt"
"strings"
"sync"
)
var hdText = `Humpty Dumpty sat on a wall.
Humpty Dumpty had a great fall.
All the king's horses and all the king's men,
Couldn't put Humpty together again.`
var mgText = `Old Mother Goose,
When she wanted to wander,
Would ride through the air,
... |
Write a version of this Python function in Go with identical behavior. |
from __future__ import annotations
import asyncio
import sys
from typing import Optional
from typing import TextIO
class OutOfInkError(Exception):
class Printer:
def __init__(self, name: str, backup: Optional[Printer]):
self.name = name
self.backup = backup
self.ink_level: int =... | package main
import (
"errors"
"fmt"
"strings"
"sync"
)
var hdText = `Humpty Dumpty sat on a wall.
Humpty Dumpty had a great fall.
All the king's horses and all the king's men,
Couldn't put Humpty together again.`
var mgText = `Old Mother Goose,
When she wanted to wander,
Would ride through the air,
... |
Rewrite this program in Go while keeping its functionality equivalent to the Python version. | 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()
| 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
... |
Rewrite the snippet below in Go so it works the same as the original Python code. |
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)'))
cha... | 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 :... |
Please provide an equivalent version of this Python code in Go. |
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)'))
cha... | 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 :... |
Ensure the translated Go code behaves exactly like the original Python snippet. |
from __future__ import division
import sys
from PIL import Image
def _fpart(x):
return x - int(x)
def _rfpart(x):
return 1 - _fpart(x)
def putpixel(img, xy, color, alpha=1):
compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))
c = compose_color(img.getpixel(xy), color)
i... | package raster
import "math"
func ipart(x float64) float64 {
return math.Floor(x)
}
func round(x float64) float64 {
return ipart(x + .5)
}
func fpart(x float64) float64 {
return x - ipart(x)
}
func rfpart(x float64) float64 {
return 1 - fpart(x)
}
func (g *Grmap) AaLine(x1, y1, x2, y2 float64) {
... |
Ensure the translated Go code behaves exactly like the original Python snippet. |
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.nocbr... | 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))),
... |
Rewrite this program in Go while keeping its functionality equivalent to the Python version. | >>> 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
>>>
| 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[... |
Write the same code in Go as shown below in 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
... | 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
mu... |
Can you help me rewrite this code in Go instead of Python, keeping it the same logically? | >>>
>>> 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
>>>
>>> na... | 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.Print... |
Convert the following code from Python to Go, ensuring the logic remains intact. | >>>
>>> 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
>>>
>>> na... | 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.Print... |
Can you help me rewrite this code in Go instead of Python, keeping it the same logically? | >>>
>>> 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
>>>
>>> na... | 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.Print... |
Rewrite the snippet below in Go so it works the same as the original Python code. | 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 =... | 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 {
... |
Please provide an equivalent version of this Python code in Go. |
import inflect
def count_letters(word):
count = 0
for letter in word:
if letter != ',' and letter !='-' and letter !=' ':
count += 1
return count
def split_with_spaces(sentence):
sentence_list = []
curr_word = ""
for c in sentence:
if... | package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
f := NewFourIsSeq()
fmt.Print("The lengths of the first 201 words are:")
for i := 1; i <= 201; i++ {
if i%25 == 1 {
fmt.Printf("\n%3d: ", i)
}
_, n := f.WordLen(i)
fmt.Printf(" %2d", n)
}
fmt.Println()
fmt.Println("Length of sentence ... |
Produce a language-to-language conversion: from Python to Go, same semantics. |
def validate(diagram):
rawlines = diagram.splitlines()
lines = []
for line in rawlines:
if line != '':
lines.append(line)
if len(lines) == 0:
print('diagram has no non-empty lines!')
return None
width = len(line... | package main
import (
"fmt"
"log"
"math/big"
"strings"
)
type result struct {
name string
size int
start int
end int
}
func (r result) String() string {
return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end)
}
func validate(diagram string) []string {
... |
Convert this Python snippet to Go and keep its semantics consistent. | 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 r... | 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))
... |
Generate a Go translation of this Python snippet without changing its computational steps. | def builtinsort(x):
x.sort()
def partition(seq, pivot):
low, middle, up = [], [], []
for x in seq:
if x < pivot:
low.append(x)
elif x == pivot:
middle.append(x)
else:
up.append(x)
return low, middle, up
import random
def qsortranpart(seq):
size = le... | package main
import (
"log"
"math/rand"
"testing"
"time"
"github.com/gonum/plot"
"github.com/gonum/plot/plotter"
"github.com/gonum/plot/plotutil"
"github.com/gonum/plot/vg"
)
func bubblesort(a []int) {
for itemCount := len(a) - 1; ; itemCount-- {
hasChanged := false
... |
Maintain the same structure and functionality when rewriting this code in Go. | 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 sa... | 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
... |
Please provide an equivalent version of this Python code in Go. | 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 sa... | 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
... |
Convert the following code from Python to Go, ensuring the logic remains intact. | from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print s... | package main
import (
"flag"
"fmt"
)
func main() {
b := flag.Bool("b", false, "just a boolean")
s := flag.String("s", "", "any ol' string")
n := flag.Int("n", 0, "your lucky number")
flag.Parse()
fmt.Println("b:", *b)
fmt.Println("s:", *s)
fmt.Println("n:", *n)
}
|
Write the same code in Go as shown below in Python. | from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print s... | package main
import (
"flag"
"fmt"
)
func main() {
b := flag.Bool("b", false, "just a boolean")
s := flag.String("s", "", "any ol' string")
n := flag.Int("n", 0, "your lucky number")
flag.Parse()
fmt.Println("b:", *b)
fmt.Println("s:", *s)
fmt.Println("n:", *n)
}
|
Write the same algorithm in Go as shown in this Python implementation. | from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print s... | package main
import (
"flag"
"fmt"
)
func main() {
b := flag.Bool("b", false, "just a boolean")
s := flag.String("s", "", "any ol' string")
n := flag.Int("n", 0, "your lucky number")
flag.Parse()
fmt.Println("b:", *b)
fmt.Println("s:", *s)
fmt.Println("n:", *n)
}
|
Change the programming language of this snippet from Python to Go without modifying what it does. | [print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
| package main
import (
"fmt"
"strconv"
"strings"
)
func a(n int) {
s, _ := strconv.Atoi(strings.Repeat("1", n) + "3")
t := s * s
fmt.Printf("%d %d\n", s, t)
}
func main() {
for n := 0; n <= 7; n++ {
a(n)
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Python version. | [print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
| package main
import (
"fmt"
"strconv"
"strings"
)
func a(n int) {
s, _ := strconv.Atoi(strings.Repeat("1", n) + "3")
t := s * s
fmt.Printf("%d %d\n", s, t)
}
func main() {
for n := 0; n <= 7; n++ {
a(n)
}
}
|
Please provide an equivalent version of this Python code in Go. | import autopy
autopy.key.type_string("Hello, world!")
autopy.key.type_string("Hello, world!", wpm=60)
autopy.key.tap(autopy.key.Code.RETURN)
autopy.key.tap(autopy.key.Code.F1)
autopy.key.tap(autopy.key.Code.LEFT_ARROW)
| package main
import (
"github.com/micmonay/keybd_event"
"log"
"runtime"
"time"
)
func main() {
kb, err := keybd_event.NewKeyBonding()
if err != nil {
log.Fatal(err)
}
if runtime.GOOS == "linux" {
time.Sleep(2 * time.Second)
}
kb.SetKeys(keybd_event.V... |
Convert this Python block to Go, preserving its control flow and logic. | from itertools import combinations, product, count
from functools import lru_cache, reduce
_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__
def place(m, n):
"Place m black and white queens, peacefully, on an n-by-n board"
board = set(product(range(n), repeat=2))
placements = {frozenset(c) for c in ... | package main
import "fmt"
const (
empty = iota
black
white
)
const (
bqueen = 'B'
wqueen = 'W'
bbullet = '•'
wbullet = '◦'
)
type position struct{ i, j int }
func iabs(i int) int {
if i < 0 {
return -i
}
return i
}
func place(m, n int, pBlackQueens, pWhiteQueens *... |
Ensure the translated Go code behaves exactly like the original Python snippet. | while 1:
print "SPAM"
| package main
import "fmt"
func main() {
for {
fmt.Printf("SPAM\n")
}
}
|
Produce a functionally identical Go code for the snippet given in Python. | from macropy.core.macros import *
from macropy.core.quotes import macros, q, ast, u
macros = Macros()
@macros.expr
def expand(tree, **kw):
addition = 10
return q[lambda x: x * ast[tree] + u[addition]]
| package main
import "fmt"
type person struct{
name string
age int
}
func copy(p person) person {
return person{p.name, p.age}
}
func main() {
p := person{"Dave", 40}
fmt.Println(p)
q := copy(p)
fmt.Println(q)
}
|
Convert this Python snippet to Go and keep its semantics consistent. | col = 0
for i in range(100000):
if set(str(i)) == set(hex(i)[2:]):
col += 1
print("{:7}".format(i), end='\n'[:col % 10 == 0])
print()
| package main
import (
"fmt"
"rcu"
"strconv"
)
func equalSets(s1, s2 map[rune]bool) bool {
if len(s1) != len(s2) {
return false
}
for k, _ := range s1 {
_, ok := s2[k]
if !ok {
return false
}
}
return true
}
func main() {
const limit = 10... |
Produce a functionally identical Go code for the snippet given in Python. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
n = 600851475143
j = 3
while not isPrime(n):
if n % j == 0:
n /= j
j += 2
print(n);
| package main
import "fmt"
func largestPrimeFactor(n uint64) uint64 {
if n < 2 {
return 1
}
inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6}
max := uint64(1)
for n%2 == 0 {
max = 2
n /= 2
}
for n%3 == 0 {
max = 3
n /= 3
}
for n%5 == 0 {
max = ... |
Generate a Go translation of this Python snippet without changing its computational steps. | def lpd(n):
for i in range(n-1,0,-1):
if n%i==0: return i
return 1
for i in range(1,101):
print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
| package main
import "fmt"
func largestProperDivisor(n int) int {
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return n / i
}
}
return 1
}
func main() {
fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:")
fmt.Print(" 1 ")
for n := 2; n... |
Write the same algorithm in Go as shown in this Python implementation. | from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
re... | package main
import (
"bytes"
"fmt"
)
type symbolTable string
func (symbols symbolTable) encode(s string) []byte {
seq := make([]byte, len(s))
pad := []byte(symbols)
for i, c := range []byte(s) {
x := bytes.IndexByte(pad, c)
seq[i] = byte(x)
copy(pad[1:], pad[:x])
pad[0] = c
}
return seq
}
func (symb... |
Produce a language-to-language conversion: from Python to Go, same semantics. | from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
re... | package main
import (
"bytes"
"fmt"
)
type symbolTable string
func (symbols symbolTable) encode(s string) []byte {
seq := make([]byte, len(s))
pad := []byte(symbols)
for i, c := range []byte(s) {
x := bytes.IndexByte(pad, c)
seq[i] = byte(x)
copy(pad[1:], pad[:x])
pad[0] = c
}
return seq
}
func (symb... |
Translate this program into Go but keep the logic exactly as in Python. | Import-Module ActiveDirectory
$searchData = "user name"
$searchBase = "DC=example,DC=com"
get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
| package main
import (
"log"
"github.com/jtblin/go-ldap-client"
)
func main() {
client := &ldap.LDAPClient{
Base: "dc=example,dc=com",
Host: "ldap.example.com",
Port: 389,
GroupFilter: "(memberUid=%s)",
}
defer client.Close()
err := client.Co... |
Port the following code from Python to Go with equivalent syntax and logic. | from numpy import *
A = matrix([[3, 0], [4, 5]])
U, Sigma, VT = linalg.svd(A)
print(U)
print(Sigma)
print(VT)
| <package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
"log"
)
func matPrint(m mat.Matrix) {
fa := mat.Formatted(m, mat.Prefix(""), mat.Squeeze())
fmt.Printf("%13.10f\n", fa)
}
func main() {
var svd mat.SVD
a := mat.NewDense(2, 2, []float64{3, 0, 4, 5})
ok := svd.Factorize(a, mat.SVDFu... |
Rewrite the snippet below in Go so it works the same as the original Python code. | def main():
fila = 0
lenCubos = 51
print("Suma de N cubos para n = [0..49]\n")
for n in range(1, lenCubos):
sumCubos = 0
for m in range(1, n):
sumCubos = sumCubos + (m ** 3)
fila += 1
print(f'{sumCubos:7} ', end='')
if fila % 5 == 0:
... | package main
import (
"fmt"
"rcu"
)
func main() {
fmt.Println("Cumulative sums of the first 50 cubes:")
sum := 0
for n := 0; n < 50; n++ {
sum += n * n * n
fmt.Printf("%9s ", rcu.Commatize(sum))
if n%10 == 9 {
fmt.Println()
}
}
fmt.Println()
|
Convert this Python snippet to Go and keep its semantics consistent. | >>> def isint(f):
return complex(f).imag == 0 and complex(f).real.is_integer()
>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]
[True, True, True, False, False, False]
>>>
...
>>> isint(25.000000)
True
>>> isint(24.999999)
False
>>> isint(25.000100)
False
>>> isint(-2.1e120)
True
>>> isint(-5... | package main
import (
"fmt"
"math"
"math/big"
"reflect"
"strings"
"unsafe"
)
func Float64IsInt(f float64) bool {
_, frac := math.Modf(f)
return frac == 0
}
func Float32IsInt(f float32) bool {
return Float64IsInt(float64(f))
}
func Complex128IsInt(c complex128) bool {
return imag(c) == 0 && Float6... |
Keep all operations the same but rewrite the snippet in Go. | import os
exit_code = os.system('ls')
output = os.popen('ls').read()
| package main
import (
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("ls", "-l")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
|
Port the provided Python code into Go while preserving the original functionality. |
from __future__ import print_function
import lxml
from lxml import etree
if __name__=="__main__":
parser = etree.XMLParser(dtd_validation=True)
schema_root = etree.XML()
schema = etree.XMLSchema(schema_root)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5</a>", parser)
print ... | package main
import (
"fmt"
"github.com/lestrrat-go/libxml2"
"github.com/lestrrat-go/libxml2/xsd"
"io/ioutil"
"log"
"os"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
xsdfile := "shiporder.xsd"
f, err := os.Open(xsdfile)
check(err)
... |
Translate this program into Go but keep the logic exactly as in Python. | def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
... | package main
import (
"fmt"
"sort"
)
type Node struct {
val int
back *Node
}
func lis (n []int) (result []int) {
var pileTops []*Node
for _, x := range n {
j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })
node := &Node{ x, nil }
if j != 0 { node.back =... |
Convert the following code from Python to Go, ensuring the logic remains intact. | import sys, math, collections
Sphere = collections.namedtuple("Sphere", "cx cy cz r")
V3 = collections.namedtuple("V3", "x y z")
def normalize((x, y, z)):
len = math.sqrt(x**2 + y**2 + z**2)
return V3(x / len, y / len, z / len)
def dot(v1, v2):
d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z
return -d if d < 0... | package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func (v *vector) normalize() {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1... |
Generate a Go translation of this Python snippet without changing its computational steps. | import sys, math, collections
Sphere = collections.namedtuple("Sphere", "cx cy cz r")
V3 = collections.namedtuple("V3", "x y z")
def normalize((x, y, z)):
len = math.sqrt(x**2 + y**2 + z**2)
return V3(x / len, y / len, z / len)
def dot(v1, v2):
d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z
return -d if d < 0... | package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func (v *vector) normalize() {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1... |
Generate a Go translation of this Python snippet without changing its computational steps. | from __future__ import print_function
def lgen(even=False, nmax=1000000):
start = 2 if even else 1
n, lst = 1, list(range(start, nmax + 1, 2))
lenlst = len(lst)
yield lst[0]
while n < lenlst and lst[n] < lenlst:
yield lst[n]
n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst... | package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
)
const luckySize = 60000
var luckyOdd = make([]int, luckySize)
var luckyEven = make([]int, luckySize)
func init() {
for i := 0; i < luckySize; i++ {
luckyOdd[i] = i*2 + 1
luckyEven[i] = i*2 + 2
}
}
func filterLu... |
Translate the given Python code snippet into Go without altering its behavior. |
import argparse
from argparse import Namespace
import datetime
import shlex
def parse_args():
'Set up, parse, and return arguments'
parser = argparse.ArgumentParser(epilog=globals()['__doc__'])
parser.add_argument('command', choices='add pl plc pa'.split(),
help=)
par... | package main
import (
"encoding/json"
"fmt"
"io"
"os"
"sort"
"strings"
"time"
"unicode"
)
type Item struct {
Stamp time.Time
Name string
Tags []string `json:",omitempty"`
Notes string `json:",omitempty"`
}
func (i *Item) String() string {
s := i.Stamp.Format... |
Can you help me rewrite this code in Go instead of Python, keeping it the same logically? | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circ... | package main
import (
"flag"
"fmt"
"math"
"runtime"
"sort"
)
type Circle struct{ X, Y, R, rsq float64 }
func NewCircle(x, y, r float64) Circle {
return Circle{x, y, r, r * r}
}
func (c Circle) ContainsPt(x, y float64) bool {
return distSq(x, y, c.... |
Produce a language-to-language conversion: from Python to Go, same semantics. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circ... | package main
import (
"flag"
"fmt"
"math"
"runtime"
"sort"
)
type Circle struct{ X, Y, R, rsq float64 }
func NewCircle(x, y, r float64) Circle {
return Circle{x, y, r, r * r}
}
func (c Circle) ContainsPt(x, y float64) bool {
return distSq(x, y, c.... |
Produce a language-to-language conversion: from Python to Go, same semantics. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circ... | package main
import (
"flag"
"fmt"
"math"
"runtime"
"sort"
)
type Circle struct{ X, Y, R, rsq float64 }
func NewCircle(x, y, r float64) Circle {
return Circle{x, y, r, r * r}
}
func (c Circle) ContainsPt(x, y float64) bool {
return distSq(x, y, c.... |
Generate a Go translation of this Python snippet without changing its computational steps. | from math import hypot, pi, cos, sin
from PIL import Image
def hough(im, ntx=460, mry=360):
"Calculate Hough transform."
pim = im.load()
nimx, mimy = im.size
mry = int(mry/2)*2
him = Image.new("L", (ntx, mry), 255)
phim = him.load()
rmax = hypot(nimx, mimy)
dr = rmax / (mry/... | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"os"
)
func hough(im image.Image, ntx, mry int) draw.Image {
nimx := im.Bounds().Max.X
mimy := im.Bounds().Max.Y
him := image.NewGray(image.Rect(0, 0, ntx, mry))
draw.Draw(him, him.Bounds(), ... |
Preserve the algorithm and functionality while converting the code from Python to Go. | import math
import random
def GammaInc_Q( a, x):
a1 = a-1
a2 = a-2
def f0( t ):
return t**a1*math.exp(-t)
def df0(t):
return (a1-t)*t**a2*math.exp(-t)
y = a1
while f0(y)*(x-y) >2.0e-8 and y < x: y += .3
if y > x: y = x
h = 3.0e-4
n = int(y/h)
h = y/n
h... | package main
import (
"fmt"
"math"
)
type ifctn func(float64) float64
func simpson38(f ifctn, a, b float64, n int) float64 {
h := (b - a) / float64(n)
h1 := h / 3
sum := f(a) + f(b)
for j := 3*n - 1; j > 0; j-- {
if j%3 == 0 {
sum += 2 * f(a+h1*float64(j))
... |
Translate this program into Go but keep the logic exactly as in Python. | import numpy as np
import scipy as sp
import scipy.stats
def welch_ttest(x1, x2):
n1 = x1.size
n2 = x2.size
m1 = np.mean(x1)
m2 = np.mean(x2)
v1 = np.var(x1, ddof=1)
v2 = np.var(x2, ddof=1)
t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)
df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - ... | package main
import (
"fmt"
"math"
)
var (
d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,
23.1, 19.6, 19.0, 21.7, 21.4}
d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,
21.9, 22.1, 22.9, 20.5, 24.4}
d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21... |
Keep all operations the same but rewrite the snippet in Go. | import numpy as np
import scipy as sp
import scipy.stats
def welch_ttest(x1, x2):
n1 = x1.size
n2 = x2.size
m1 = np.mean(x1)
m2 = np.mean(x2)
v1 = np.var(x1, ddof=1)
v2 = np.var(x2, ddof=1)
t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)
df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - ... | package main
import (
"fmt"
"math"
)
var (
d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6,
23.1, 19.6, 19.0, 21.7, 21.4}
d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2,
21.9, 22.1, 22.9, 20.5, 24.4}
d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21... |
Write the same algorithm in Go as shown in this Python implementation. | try:
from functools import reduce
except: pass
def topx(data, tops=None):
'Extract the set of top-level(s) in topological order'
for k, v in data.items():
v.discard(k)
if tops is None:
tops = toplevels(data)
return _topx(data, tops, [], set())
def _topx(data, tops, _sofar, _sofar... | package main
import (
"fmt"
"strings"
)
var data = `
FILE FILE DEPENDENCIES
==== =================
top1 des1 ip1 ip2
top2 des1 ip2 ip3
ip1 extra1 ip1a ipcommon
ip2 ip2a ip2b ip2c ipcommon
des1 des1a des1b des1c
des1a des1a1 des1a2
des1c des1c1 extra1`
func main() {
g, dep, err ... |
Produce a language-to-language conversion: from Python to Go, same semantics. | try:
from functools import reduce
except: pass
def topx(data, tops=None):
'Extract the set of top-level(s) in topological order'
for k, v in data.items():
v.discard(k)
if tops is None:
tops = toplevels(data)
return _topx(data, tops, [], set())
def _topx(data, tops, _sofar, _sofar... | package main
import (
"fmt"
"strings"
)
var data = `
FILE FILE DEPENDENCIES
==== =================
top1 des1 ip1 ip2
top2 des1 ip2 ip3
ip1 extra1 ip1a ipcommon
ip2 ip2a ip2b ip2c ipcommon
des1 des1a des1b des1c
des1a des1a1 des1a2
des1c des1c1 extra1`
func main() {
g, dep, err ... |
Port the following code from Python to Go with equivalent syntax and logic. | def getitem(s, depth=0):
out = [""]
while s:
c = s[0]
if depth and (c == ',' or c == '}'):
return out,s
if c == '{':
x = getgroup(s[1:], depth+1)
if x:
out,s = [a+b for a in out for b in x[0]], x[1]
continue
if c... | package expand
type Expander interface {
Expand() []string
}
type Text string
func (t Text) Expand() []string { return []string{string(t)} }
type Alternation []Expander
func (alt Alternation) Expand() []string {
var out []string
for _, e := range alt {
out = append(out, e.Expand()...)
}
return out
}
... |
Keep all operations the same but rewrite the snippet in Go. | def no_args():
pass
no_args()
def fixed_args(x, y):
print('x=%r, y=%r' % (x, y))
fixed_args(1, 2)
fixed_args(y=2, x=1)
myargs=(1,2)
fixed_args(*myargs)
def opt_args(x=1):
print(x)
opt_args()
opt_args(3.141)
def var_args(*v):
print(v)
var_args(1, 2, 3)
va... | import (
"image"
"image/gif"
"io/ioutil"
"strings"
"unicode"
)
func f() (int, float64) { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int) {}
|
Preserve the algorithm and functionality while converting the code from Python to Go. | def no_args():
pass
no_args()
def fixed_args(x, y):
print('x=%r, y=%r' % (x, y))
fixed_args(1, 2)
fixed_args(y=2, x=1)
myargs=(1,2)
fixed_args(*myargs)
def opt_args(x=1):
print(x)
opt_args()
opt_args(3.141)
def var_args(*v):
print(v)
var_args(1, 2, 3)
va... | import (
"image"
"image/gif"
"io/ioutil"
"strings"
"unicode"
)
func f() (int, float64) { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int) {}
|
Convert this Python block to Go, preserving its control flow and logic. | "Generate a short Superpermutation of n characters A... as a string using various algorithms."
from __future__ import print_function, division
from itertools import permutations
from math import factorial
import string
import datetime
import gc
MAXN = 7
def s_perm0(n):
allchars = string.ascii_uppercase... | package main
import "fmt"
const max = 12
var (
super []byte
pos int
cnt [max]int
)
func factSum(n int) int {
s := 0
for x, f := 0, 1; x < n; {
x++
f *= x
s += f
}
return s
}
func r(n int) bool {
if n == 0 {
return false
}
c := super[pos-n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.