Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Change the following Python code into Go without altering its purpose.
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18] list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27] print([ ''.join(str(n) for n in z) for z in zip(list1, list2, list3) ])
package main import "fmt" func main() { list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9} list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18} list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27} var list [9]int for i := 0; i < 9; i++ { list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i] } fmt...
Produce a language-to-language conversion: from Python to Go, same semantics.
from itertools import takewhile from functools import reduce def longestCommonSuffix(xs): def allSame(cs): h = cs[0] return all(h == c for c in cs[1:]) def firstCharPrepended(s, cs): return cs[0] + s return reduce( firstCharPrepended, takewhile( ...
package main import ( "fmt" "strings" ) func lcs(a []string) string { le := len(a) if le == 0 { return "" } if le == 1 { return a[0] } le0 := len(a[0]) minLen := le0 for i := 1; i < le; i++ { if len(a[i]) < minLen { minLen = len(a[i]) ...
Write the same algorithm in Go as shown in this Python implementation.
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name...
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string st...
Convert the following code from Python to Go, ensuring the logic remains intact.
classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal, str.isdigit, str.isidentifier, str.isnumeric, str.isprintable, str.isspace, str.istitle) for stringclass in classes: chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i))) print('\nString clas...
package main import ( "fmt" "unicode" ) const ( lcASCII = "abcdefghijklmnopqrstuvwxyz" ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) func main() { fmt.Println("ASCII lower case:") fmt.Println(lcASCII) for l := 'a'; l <= 'z'; l++ { fmt.Print(string(l)) } fmt.Println() fmt.Println("\nASCII upper case:") fmt.P...
Change the programming language of this snippet from Python to Go without modifying what it does.
from numpy import array, tril, sum A = [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]] print(sum(tril(A, -1)))
package main import ( "fmt" "log" ) func main() { m := [][]int{ {1, 3, 7, 8, 10}, {2, 4, 16, 14, 4}, {3, 1, 9, 18, 11}, {12, 14, 17, 18, 20}, {7, 1, 3, 9, 5}, } if len(m) != len(m[0]) { log.Fatal("Matrix must be square.") } sum := 0 for i...
Rewrite the snippet below in Go so it works the same as the original Python code.
import datetime import re import urllib.request import sys def get(url): with urllib.request.urlopen(url) as response: html = response.read().decode('utf-8') if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html): return None return html def main(): template = 'http://...
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "strings" "time" ) func get(url string) (res string, err error) { resp, err := http.Get(url) if err != nil { return "", err } buf, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(buf), nil } func grep(need...
Convert the following code from Python to Go, ensuring the logic remains intact.
import requests URL = "http://rosettacode.org/mw/api.php" PARAMS = { "action": "query", "format": "json", "formatversion": 2, "generator": "categorymembers", "gcmtitle": "Category:Language users", "gcmlimit": 500, "prop": "categoryinfo", } def fetch_data(): counts = {} contin...
package main import ( "fmt" "io/ioutil" "net/http" "regexp" "sort" "strconv" ) type Result struct { lang string users int } func main() { const minimum = 25 ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)` re := regexp.MustCompile(ex) page := "http...
Translate the given Python code snippet into Go without altering its behavior.
import requests URL = "http://rosettacode.org/mw/api.php" PARAMS = { "action": "query", "format": "json", "formatversion": 2, "generator": "categorymembers", "gcmtitle": "Category:Language users", "gcmlimit": 500, "prop": "categoryinfo", } def fetch_data(): counts = {} contin...
package main import ( "fmt" "io/ioutil" "net/http" "regexp" "sort" "strconv" ) type Result struct { lang string users int } func main() { const minimum = 25 ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)` re := regexp.MustCompile(ex) page := "http...
Keep all operations the same but rewrite the snippet in Go.
"exec" "python" "$0" print "Hello World"
#!/bin/bash sed -n -e '12,$p' < "$0" > ttmmpp.go go build ttmmpp.go rm ttmmpp.go binfile="${0%.*}" mv ttmmpp $binfile $binfile "$@" STATUS=$? rm $binfile exit $STATUS ######## Go Code start on line 12 package main import ( "fmt" "os" ) func main() { for i, x := range os.Args { if i == 0 { fmt.Printf("...
Change the programming language of this snippet from Python to Go without modifying what it does.
"exec" "python" "$0" print "Hello World"
#!/bin/bash sed -n -e '12,$p' < "$0" > ttmmpp.go go build ttmmpp.go rm ttmmpp.go binfile="${0%.*}" mv ttmmpp $binfile $binfile "$@" STATUS=$? rm $binfile exit $STATUS ######## Go Code start on line 12 package main import ( "fmt" "os" ) func main() { for i, x := range os.Args { if i == 0 { fmt.Printf("...
Produce a functionally identical Go code for the snippet given in Python.
import sys if "UTF-8" in sys.stdout.encoding: print("△") else: raise Exception("Terminal can't handle UTF-8")
package main import ( "fmt" "os" "strings" ) func main() { lang := strings.ToUpper(os.Getenv("LANG")) if strings.Contains(lang, "UTF") { fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3') } else { fmt.Println("This terminal does not support unicode") ...
Convert this Python snippet to Go and keep its semantics consistent.
import sys if "UTF-8" in sys.stdout.encoding: print("△") else: raise Exception("Terminal can't handle UTF-8")
package main import ( "fmt" "os" "strings" ) func main() { lang := strings.ToUpper(os.Getenv("LANG")) if strings.Contains(lang, "UTF") { fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3') } else { fmt.Println("This terminal does not support unicode") ...
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
import math print("working...") limit = 1000000 Primes = [] oldPrime = 0 newPrime = 0 x = 0 def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issquare(x): for n in range(x): if (x == n*n): return 1 return 0 for n in range(limit): if isPrim...
package main import ( "fmt" "math" "rcu" ) func main() { limit := 999999 primes := rcu.Primes(limit) fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:") for i := 1; i < len(primes); i++ { diff := primes[i] - primes[i-1] if diff > 36 { ...
Convert this Python snippet to Go and keep its semantics consistent.
import math print("working...") limit = 1000000 Primes = [] oldPrime = 0 newPrime = 0 x = 0 def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issquare(x): for n in range(x): if (x == n*n): return 1 return 0 for n in range(limit): if isPrim...
package main import ( "fmt" "math" "rcu" ) func main() { limit := 999999 primes := rcu.Primes(limit) fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:") for i := 1; i < len(primes); i++ { diff := primes[i] - primes[i-1] if diff > 36 { ...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
import ( "fmt" "os" ) if err := os.Truncate("filename", newSize); err != nil { fmt.Println(err) }
Port the provided Python code into Go while preserving the original functionality.
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
import ( "fmt" "os" ) if err := os.Truncate("filename", newSize); err != nil { fmt.Println(err) }
Rewrite the snippet below in Go so it works the same as the original Python code.
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
package main import ( "fmt" "log" "os/exec" "time" ) func main() { out, err := exec.Command("xrandr", "-q").Output() if err != nil { log.Fatal(err) } fmt.Println(string(out)) time.Sleep(3 * time.Second) err = exec.Command("xrandr", "-s", "1024x768").Run() ...
Write the same code in Go as shown below in Python.
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
package main import ( "fmt" "log" "os/exec" "time" ) func main() { out, err := exec.Command("xrandr", "-q").Output() if err != nil { log.Fatal(err) } fmt.Println(string(out)) time.Sleep(3 * time.Second) err = exec.Command("xrandr", "-s", "1024x768").Run() ...
Produce a language-to-language conversion: from Python to Go, same semantics.
def flush_input(): try: import msvcrt while msvcrt.kbhit(): msvcrt.getch() except ImportError: import sys, termios termios.tcflush(sys.stdin, termios.TCIOFLUSH)
package main import ( "log" gc "code.google.com/p/goncurses" ) func main() { _, err := gc.Init() if err != nil { log.Fatal("init:", err) } defer gc.End() gc.FlushInput() }
Convert this Python snippet to Go and keep its semantics consistent.
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: ca...
package main import ( "fmt" "math" ) type F = func(float64) float64 func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) { m = (a + b) / 2 fm = f(m) simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb) return } func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float...
Keep all operations the same but rewrite the snippet in Go.
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: ca...
package main import ( "fmt" "math" ) type F = func(float64) float64 func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) { m = (a + b) / 2 fm = f(m) simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb) return } func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float...
Rewrite the snippet below in Go so it works the same as the original Python code.
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: ca...
package main import ( "fmt" "math" ) type F = func(float64) float64 func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) { m = (a + b) / 2 fm = f(m) simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb) return } func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float...
Port the following code from Python to Go with equivalent syntax and logic.
import io FASTA= infile = io.StringIO(FASTA) def fasta_parse(infile): key = '' for line in infile: if line.startswith('>'): if key: yield key, val key, val = line[1:].rstrip().split()[0], '' elif key: val += line.rstrip() if key: ...
package main import ( "bufio" "fmt" "os" ) func main() { f, err := os.Open("rc.fasta") if err != nil { fmt.Println(err) return } defer f.Close() s := bufio.NewScanner(f) headerFound := false for s.Scan() { ...
Produce a functionally identical Go code for the snippet given in Python.
from itertools import chain, takewhile def cousinPrimes(): def go(x): n = 4 + x return [(x, n)] if isPrime(n) else [] return chain.from_iterable( map(go, primes()) ) def main(): pairs = list( takewhile( lambda ab: 1000 > ab[1], ...
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d...
Produce a functionally identical Go code for the snippet given in Python.
from itertools import chain, takewhile def cousinPrimes(): def go(x): n = 4 + x return [(x, n)] if isPrime(n) else [] return chain.from_iterable( map(go, primes()) ) def main(): pairs = list( takewhile( lambda ab: 1000 > ab[1], ...
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d...
Ensure the translated Go code behaves exactly like the original Python snippet.
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] retu...
package main import ( "fmt" "strconv" "time" ) func isPalindrome2(n uint64) bool { x := uint64(0) if (n & 1) == 0 { return n == 0 } for x < n { x = (x << 1) | (n & 1) n >>= 1 } return n == x || n == (x>>1) } func reverse3(n uint64) uint64 { x := uint64(...
Convert the following code from Python to Go, ensuring the logic remains intact.
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] retu...
package main import ( "fmt" "strconv" "time" ) func isPalindrome2(n uint64) bool { x := uint64(0) if (n & 1) == 0 { return n == 0 } for x < n { x = (x << 1) | (n & 1) n >>= 1 } return n == x || n == (x>>1) } func reverse3(n uint64) uint64 { x := uint64(...
Produce a language-to-language conversion: from Python to Go, same semantics.
from sys import stdin if stdin.isatty(): print("Input comes from tty.") else: print("Input doesn't come from tty.")
package main import ( "golang.org/x/crypto/ssh/terminal" "fmt" "os" ) func main() { if terminal.IsTerminal(int(os.Stdin.Fd())) { fmt.Println("Hello terminal") } else { fmt.Println("Who are you? You're not a terminal.") } }
Port the provided Python code into Go while preserving the original functionality.
from sys import stdin if stdin.isatty(): print("Input comes from tty.") else: print("Input doesn't come from tty.")
package main import ( "golang.org/x/crypto/ssh/terminal" "fmt" "os" ) func main() { if terminal.IsTerminal(int(os.Stdin.Fd())) { fmt.Println("Hello terminal") } else { fmt.Println("Who are you? You're not a terminal.") } }
Preserve the algorithm and functionality while converting the code from Python to Go.
from Xlib import X, display class Window: def __init__(self, display, msg): self.display = display self.msg = msg self.screen = self.display.screen() self.window = self.screen.root.create_window( 10, 10, 100, 100, 1, self.screen.root_depth, ...
package main import ( "log" "github.com/jezek/xgb" "github.com/jezek/xgb/xproto" ) func main() { X, err := xgb.NewConn() if err != nil { log.Fatal(err) } points := []xproto.Point{ {10, 10}, {10, 20}, {20, 10}, {20, 20}}; ...
Transform the following Python implementation into Go, maintaining the same output and logic.
from elementary_cellular_automaton import eca, eca_wrap def rule30bytes(lencells=100): cells = '1' + '0' * (lencells - 1) gen = eca(cells, 30) while True: yield int(''.join(next(gen)[0] for i in range(8)), 2) if __name__ == '__main__': print([b for i,b in zip(range(10), rule30bytes())])
package main import "fmt" const n = 64 func pow2(x uint) uint64 { return uint64(1) << x } func evolve(state uint64, rule int) { for p := 0; p < 10; p++ { b := uint64(0) for q := 7; q >= 0; q-- { st := state b |= (st & 1) << uint(q) state = 0 fo...
Convert this Python snippet to Go and keep its semantics consistent.
import os def get_windows_terminal(): from ctypes import windll, create_string_buffer h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if not res: return 80, 25 import struct (bufx, bufy, curx, cury, watt...
package main import ( "fmt" "os" "golang.org/x/crypto/ssh/terminal" ) func main() { w, h, err := terminal.GetSize(int(os.Stdout.Fd())) if err != nil { fmt.Println(err) return } fmt.Println(h, w) }
Produce a language-to-language conversion: from Python to Go, same semantics.
states = { 'ready':{ 'prompt' : 'Machine ready: (d)eposit, or (q)uit?', 'responses' : ['d','q']}, 'waiting':{ 'prompt' : 'Machine waiting: (s)elect, or (r)efund?', 'responses' : ['s','r']}, 'dispense' : { 'prompt'...
package main import ( "bufio" "fmt" "log" "os" "strings" ) type state int const ( ready state = iota waiting exit dispense refunding ) func check(err error) { if err != nil { log.Fatal(err) } } func fsm() { fmt.Println("Please enter your option when promp...
Produce a functionally identical Go code for the snippet given in Python.
import turtle from itertools import cycle from time import sleep def rect(t, x, y): x2, y2 = x/2, y/2 t.setpos(-x2, -y2) t.pendown() for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: t.goto(pos) t.penup() def rects(t, colour, wait_between_rect=0.1): for x in range(550, 0, -25):...
package main import ( "image" "image/color" "image/gif" "log" "os" ) var ( black = color.RGBA{0, 0, 0, 255} red = color.RGBA{255, 0, 0, 255} green = color.RGBA{0, 255, 0, 255} blue = color.RGBA{0, 0, 255, 255} magenta = color.RGBA{255, 0, 255, 255} cyan = colo...
Generate a Go translation of this Python snippet without changing its computational steps.
import turtle from itertools import cycle from time import sleep def rect(t, x, y): x2, y2 = x/2, y/2 t.setpos(-x2, -y2) t.pendown() for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: t.goto(pos) t.penup() def rects(t, colour, wait_between_rect=0.1): for x in range(550, 0, -25):...
package main import ( "image" "image/color" "image/gif" "log" "os" ) var ( black = color.RGBA{0, 0, 0, 255} red = color.RGBA{255, 0, 0, 255} green = color.RGBA{0, 255, 0, 255} blue = color.RGBA{0, 0, 255, 255} magenta = color.RGBA{255, 0, 255, 255} cyan = colo...
Keep all operations the same but rewrite the snippet in Go.
def add_least_reduce(lis): while len(lis) > 1: lis.append(lis.pop(lis.index(min(lis))) + lis.pop(lis.index(min(lis)))) print('Interim list:', lis) return lis LIST = [6, 81, 243, 14, 25, 49, 123, 69, 11] print(LIST, ' ==> ', add_least_reduce(LIST.copy()))
package main import ( "fmt" "sort" ) func main() { a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11} for len(a) > 1 { sort.Ints(a) fmt.Println("Sorted list:", a) sum := a[0] + a[1] fmt.Printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum) a = append(a, sum) ...
Preserve the algorithm and functionality while converting the code from Python to Go.
numbers1 = [5,45,23,21,67] numbers2 = [43,22,78,46,38] numbers3 = [9,98,12,98,53] numbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))] print(numbers)
package main import ( "fmt" "rcu" ) func main() { numbers1 := [5]int{5, 45, 23, 21, 67} numbers2 := [5]int{43, 22, 78, 46, 38} numbers3 := [5]int{9, 98, 12, 98, 53} numbers := [5]int{} for n := 0; n < 5; n++ { numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n]) ...
Ensure the translated Go code behaves exactly like the original Python snippet.
numbers1 = [5,45,23,21,67] numbers2 = [43,22,78,46,38] numbers3 = [9,98,12,98,53] numbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))] print(numbers)
package main import ( "fmt" "rcu" ) func main() { numbers1 := [5]int{5, 45, 23, 21, 67} numbers2 := [5]int{43, 22, 78, 46, 38} numbers3 := [5]int{9, 98, 12, 98, 53} numbers := [5]int{} for n := 0; n < 5; n++ { numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n]) ...
Produce a functionally identical Go code for the snippet given in Python.
def convertToBase(n, b): if(n < 2): return [n]; temp = n; ans = []; while(temp != 0): ans = [temp % b]+ ans; temp /= b; return ans; def cipolla(n,p): n %= p if(n == 0 or n == 1): return (n,-n%p) phi = p - 1 if(pow(n, phi/2, p) != 1): return () if(p%4 == 3): ans = pow(n,(p+1)/4,p) return (a...
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { re...
Change the programming language of this snippet from Python to Go without modifying what it does.
def convertToBase(n, b): if(n < 2): return [n]; temp = n; ans = []; while(temp != 0): ans = [temp % b]+ ans; temp /= b; return ans; def cipolla(n,p): n %= p if(n == 0 or n == 1): return (n,-n%p) phi = p - 1 if(pow(n, phi/2, p) != 1): return () if(p%4 == 3): ans = pow(n,(p+1)/4,p) return (a...
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { re...
Change the following Python code into Go without altering its purpose.
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 CONST = 6364136223846793005 class PCG32(): def __init__(self, seed_state=None, seed_sequence=None): if all(type(x) == int for x in (seed_state, seed_sequence)): self.seed(seed_state, seed_sequence) else: self.state = self.i...
package main import ( "fmt" "math" ) const CONST = 6364136223846793005 type Pcg32 struct{ state, inc uint64 } func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} } func (pcg *Pcg32) seed(seedState, seedSequence uint64) { pcg.state = 0 pcg.inc = (seedSequence << 1) | 1 ...
Ensure the translated Go code behaves exactly like the original Python snippet.
def ToReducedRowEchelonForm( M ): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r ...
package main import "fmt" func main() { h := []float64{-8, -9, -3, -1, -6, 7} f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1} g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7} fmt.Println(h) fmt.Println(deconv(...
Keep all operations the same but rewrite the snippet in Go.
from PIL import Image im = Image.open("boxes_1.ppm") im.save("boxes_1.jpg")
package main import ( "fmt" "math/rand" "os/exec" "raster" ) func main() { b := raster.NewBitmap(400, 300) b.FillRgb(0xc08040) for i := 0; i < 2000; i++ { b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020) } for x := 0; x < 400; x++ { for y := 240; y < 24...
Port the provided Python code into Go while preserving the original functionality.
import binascii import functools import hashlib digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def b58(n): return b58(n//58) + digits58[n%58:n%58+1] if n else b'' def public_point_to_address(x, y): c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y) r = hashlib.new('ri...
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _,...
Please provide an equivalent version of this Python code in Go.
import binascii import functools import hashlib digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def b58(n): return b58(n//58) + digits58[n%58:n%58+1] if n else b'' def public_point_to_address(x, y): c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y) r = hashlib.new('ri...
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _,...
Please provide an equivalent version of this Python code in Go.
import re _vowels = 'AEIOU' def replace_at(text, position, fromlist, tolist): for f, t in zip(fromlist, tolist): if text[position:].startswith(f): return ''.join([text[:position], t, text[position+len(f):]]) return text def replace_e...
package main import ( "fmt" "strings" ) type pair struct{ first, second string } var ( fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}} lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND"...
Generate an equivalent Go version of this Python code.
import re _vowels = 'AEIOU' def replace_at(text, position, fromlist, tolist): for f, t in zip(fromlist, tolist): if text[position:].startswith(f): return ''.join([text[:position], t, text[position+len(f):]]) return text def replace_e...
package main import ( "fmt" "strings" ) type pair struct{ first, second string } var ( fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}} lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND"...
Change the following Python code into Go without altering its purpose.
def isDisarium(n): digitos = len(str(n)) suma = 0 x = n while x != 0: suma += (x % 10) ** digitos digitos -= 1 x //= 10 if suma == n: return True else: return False if __name__ == '__main__': limite = 19 cont = 0 n = 0 print("The first",...
package main import ( "fmt" "strconv" ) const DMAX = 20 const LIMIT = 20 func main() { EXP := make([][]uint64, 1+DMAX) POW := make([][]uint64, 1+DMAX) EXP[0] = make([]uint64, 11) EXP[1] = make([]uint64, 11) POW[0] = make([]uint64, 11) POW[1] = make([]uint64, 11) for i := ...
Please provide an equivalent version of this Python code in Go.
def isDisarium(n): digitos = len(str(n)) suma = 0 x = n while x != 0: suma += (x % 10) ** digitos digitos -= 1 x //= 10 if suma == n: return True else: return False if __name__ == '__main__': limite = 19 cont = 0 n = 0 print("The first",...
package main import ( "fmt" "strconv" ) const DMAX = 20 const LIMIT = 20 func main() { EXP := make([][]uint64, 1+DMAX) POW := make([][]uint64, 1+DMAX) EXP[0] = make([]uint64, 11) EXP[1] = make([]uint64, 11) POW[0] = make([]uint64, 11) POW[1] = make([]uint64, 11) for i := ...
Write a version of this Python function in Go with identical behavior.
from turtle import * import math speed(0) hideturtle() part_ratio = 2 * math.cos(math.radians(72)) side_ratio = 1 / (part_ratio + 2) hide_turtles = True path_color = "black" fill_color = "black" def pentagon(t, s): t.color(path_color, fill_color) t.pendown() t.right(36) t.begin_fill() for i...
package main import ( "github.com/fogleman/gg" "image/color" "math" ) var ( red = color.RGBA{255, 0, 0, 255} green = color.RGBA{0, 255, 0, 255} blue = color.RGBA{0, 0, 255, 255} magenta = color.RGBA{255, 0, 255, 255} cyan = color.RGBA{0, 255, 255, 255} ) var ( w, h ...
Ensure the translated Go code behaves exactly like the original Python snippet.
from PIL import Image image = Image.open("lena.jpg") width, height = image.size amount = width * height total = 0 bw_image = Image.new('L', (width, height), 0) bm_image = Image.new('1', (width, height), 0) for h in range(0, height): for w in range(0, width): r, g, b = image.getpixel((w, h)) ...
package raster import "math" func (g *Grmap) Histogram(bins int) []int { if bins <= 0 { bins = g.cols } h := make([]int, bins) for _, p := range g.px { h[int(p)*(bins-1)/math.MaxUint16]++ } return h } func (g *Grmap) Threshold(t uint16) { for i, p := range g.px { i...
Preserve the algorithm and functionality while converting the code from Python to Go.
from PIL import Image image = Image.open("lena.jpg") width, height = image.size amount = width * height total = 0 bw_image = Image.new('L', (width, height), 0) bm_image = Image.new('1', (width, height), 0) for h in range(0, height): for w in range(0, width): r, g, b = image.getpixel((w, h)) ...
package raster import "math" func (g *Grmap) Histogram(bins int) []int { if bins <= 0 { bins = g.cols } h := make([]int, bins) for _, p := range g.px { h[int(p)*(bins-1)/math.MaxUint16]++ } return h } func (g *Grmap) Threshold(t uint16) { for i, p := range g.px { i...
Write the same code in Go as shown below in Python.
def pad_like(max_n=8, t=15): start = [[], [1, 1, 1]] for n in range(2, max_n+1): this = start[n-1][:n+1] while len(this) < t: this.append(sum(this[i] for i in range(-2, -n - 2, -1))) start.append(this) return start[2:] def pr(p): print(.strip()) fo...
package main import "fmt" func padovanN(n, t int) []int { if n < 2 || t < 3 { ones := make([]int, t) for i := 0; i < t; i++ { ones[i] = 1 } return ones } p := padovanN(n-1, t) for i := n + 1; i < t; i++ { p[i] = 0 for j := i - 2; j >= i-n-1; ...
Generate an equivalent Go version of this Python code.
import threading from time import sleep res = 2 sema = threading.Semaphore(res) class res_thread(threading.Thread): def run(self): global res n = self.getName() for i in range(1, 4): sema.acquire() res = res - 1 p...
package main import ( "fmt" "sync" "time" ) var value int var m sync.Mutex var wg sync.WaitGroup func slowInc() { m.Lock() v := value time.Sleep(1e8) value = v+1 m.Unlock() wg.Done() } func main() { wg.Add(2) go slowInc() go slowInc() wg.Wait() fmt.Println(val...
Translate this program into Go but keep the logic exactly as in Python.
import threading from time import sleep res = 2 sema = threading.Semaphore(res) class res_thread(threading.Thread): def run(self): global res n = self.getName() for i in range(1, 4): sema.acquire() res = res - 1 p...
package main import ( "fmt" "sync" "time" ) var value int var m sync.Mutex var wg sync.WaitGroup func slowInc() { m.Lock() v := value time.Sleep(1e8) value = v+1 m.Unlock() wg.Done() } func main() { wg.Add(2) go slowInc() go slowInc() wg.Wait() fmt.Println(val...
Produce a functionally identical Go code for the snippet given in Python.
import time def main(bpm = 72, bpb = 4): sleep = 60.0 / bpm counter = 0 while True: counter += 1 if counter % bpb: print 'tick' else: print 'TICK' time.sleep(sleep) main()
package main import ( "fmt" "time" ) func main() { var bpm = 72.0 var bpb = 4 d := time.Duration(float64(time.Minute) / bpm) fmt.Println("Delay:", d) t := time.NewTicker(d) i := 1 for _ = range t.C { i-- if i == 0 { i = bpb fmt.Printf("\nTICK ") } else { fmt.Printf("tick ") } } }
Port the provided Python code into Go while preserving the original functionality.
import sys print " ".join(sys.argv[1:])
package main import ( "fmt" "os" ) func main() { if len(os.Args) > 1 { fmt.Println(os.Args[1]) } }
Generate a Go translation of this Python snippet without changing its computational steps.
import sys print " ".join(sys.argv[1:])
package main import ( "fmt" "os" ) func main() { if len(os.Args) > 1 { fmt.Println(os.Args[1]) } }
Please provide an equivalent version of this Python code in Go.
from itertools import count, islice, takewhile from math import gcd def EKG_gen(start=2): c = count(start + 1) last, so_far = start, list(range(2, start)) yield 1, [] yield last, [] while True: for index, sf in enumerate(so_far): if gcd(last, sf) > 1: last =...
package main import ( "fmt" "sort" ) func contains(a []int, b int) bool { for _, j := range a { if j == b { return true } } return false } func gcd(a, b int) int { for a != b { if a > b { a -= b } else { b -= a } ...
Preserve the algorithm and functionality while converting the code from Python to Go.
def is_repeated(text): 'check if the first part of the string is repeated throughout the string' for x in range(len(text)//2, 0, -1): if text.startswith(text[x:]): return x return 0 matchstr = for line in matchstr.split(): ln = is_repeated(line) print('%r has a repetition length of %i i.e....
package main import ( "fmt" "strings" ) func rep(s string) int { for x := len(s) / 2; x > 0; x-- { if strings.HasPrefix(s, s[x:]) { return x } } return 0 } const m = ` 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1` func main() {...
Convert this Python snippet to Go and keep its semantics consistent.
import time print "\033[?1049h\033[H" print "Alternate buffer!" for i in xrange(5, 0, -1): print "Going back in:", i time.sleep(1) print "\033[?1049l"
package main import ( "fmt" "time" ) func main() { fmt.Print("\033[?1049h\033[H") fmt.Println("Alternate screen buffer\n") s := "s" for i := 5; i > 0; i-- { if i == 1 { s = "" } fmt.Printf("\rgoing back in %d second%s...", i, s) time.Sleep(time.Secon...
Transform the following Python implementation into Go, maintaining the same output and logic.
'c' == "c" 'text' == "text" ' " ' " ' " '\x20' == ' ' u'unicode string' u'\u05d0'
ch := 'z' ch = 122 ch = '\x7a' ch = '\u007a' ch = '\U0000007a' ch = '\172'
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
from collections import defaultdict, Counter def getwords(minlength=11, fname='unixdict.txt'): "Return set of lowercased words of > given number of characters" with open(fname) as f: words = f.read().strip().lower().split() return {w for w in words if len(w) > minlength} words11 = getwords() word...
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func hammingDist(s1, s2 string) int { r1 := []rune(s1) r2 := []rune(s2) if len(r1) != len(r2) { return 0 } count := 0 for i := 0; i < len(r1); i++ { if r1[i] != r2[i] { coun...
Ensure the translated Go code behaves exactly like the original Python snippet.
from tkinter import * import tkinter.messagebox def maximise(): root.geometry("{}x{}+{}+{}".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0)) def minimise(): root.iconify() def delete(): if tkinter.messagebox.askokcancel("OK/Cancel","Are you sure?"): root.quit() root = Tk() mx=Button...
package main import ( "github.com/gotk3/gotk3/gtk" "log" "time" ) func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetRes...
Generate an equivalent Go version of this Python code.
from tkinter import * import tkinter.messagebox def maximise(): root.geometry("{}x{}+{}+{}".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0)) def minimise(): root.iconify() def delete(): if tkinter.messagebox.askokcancel("OK/Cancel","Are you sure?"): root.quit() root = Tk() mx=Button...
package main import ( "github.com/gotk3/gotk3/gtk" "log" "time" ) func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetRes...
Port the following code from Python to Go with equivalent syntax and logic.
from __future__ import annotations from itertools import chain from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import TypeVar T = TypeVar("T") class MList(List[T]): @classmethod def unit(cls, value: Iterable[T]) -> MList[T]: return...
package main import "fmt" type mlist struct{ value []int } func (m mlist) bind(f func(lst []int) mlist) mlist { return f(m.value) } func unit(lst []int) mlist { return mlist{lst} } func increment(lst []int) mlist { lst2 := make([]int, len(lst)) for i, v := range lst { lst2[i] = v + 1 } ...
Change the following Python code into Go without altering its purpose.
limit = 1000 print("working...") def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issquare(x): for n in range(1,x+1): if (x == n*n): return 1 return 0 for n in range(limit-1): if issquare(n) and isprime(n+1): print(n,end=" ") print() prin...
package main import ( "fmt" "math" "rcu" ) func main() { var squares []int limit := int(math.Sqrt(1000)) i := 1 for i <= limit { n := i * i if rcu.IsPrime(n + 1) { squares = append(squares, n) } if i == 1 { i = 2 } else { ...
Produce a functionally identical Go code for the snippet given in Python.
limit = 1000 print("working...") def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issquare(x): for n in range(1,x+1): if (x == n*n): return 1 return 0 for n in range(limit-1): if issquare(n) and isprime(n+1): print(n,end=" ") print() prin...
package main import ( "fmt" "math" "rcu" ) func main() { var squares []int limit := int(math.Sqrt(1000)) i := 1 for i <= limit { n := i * i if rcu.IsPrime(n + 1) { squares = append(squares, n) } if i == 1 { i = 2 } else { ...
Convert this Python snippet to Go and keep its semantics consistent.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 3 i = 2 print("2 3", end = " "); while True: if isPrime(p + i) == 1: p += i print(p, end = " "); i +...
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } ...
Convert the following code from Python to Go, ensuring the logic remains intact.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 3 i = 2 print("2 3", end = " "); while True: if isPrime(p + i) == 1: p += i print(p, end = " "); i +...
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } ...
Translate this program into Go but keep the logic exactly as in Python.
from functools import (reduce) def mayanNumerals(n): return showIntAtBase(20)( mayanDigit )(n)([]) def mayanDigit(n): if 0 < n: r = n % 5 return [ (['●' * r] if 0 < r else []) + (['━━'] * (n // 5)) ] else: return ['Θ'] ...
package main import ( "fmt" "strconv" ) const ( ul = "╔" uc = "╦" ur = "╗" ll = "╚" lc = "╩" lr = "╝" hb = "═" vb = "║" ) var mayan = [5]string{ " ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙", } const ( m0 = " Θ " m5 = "────" ) func dec2vig(n uint64) []u...
Write a version of this Python function in Go with identical behavior.
from math import prod def superFactorial(n): return prod([prod(range(1,i+1)) for i in range(1,n+1)]) def hyperFactorial(n): return prod([i**i for i in range(1,n+1)]) def alternatingFactorial(n): return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)]) def exponentialFactorial(n): if n in...
package main import ( "fmt" "math/big" ) func sf(n int) *big.Int { if n < 2 { return big.NewInt(1) } sfact := big.NewInt(1) fact := big.NewInt(1) for i := 2; i <= n; i++ { fact.Mul(fact, big.NewInt(int64(i))) sfact.Mul(sfact, fact) } return sfact } func H(n...
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 def nextPrime(n): if n == 0: return 2 if n < 3: return n + 1 q = n + 2 while not isPrime(q): q += 2 return q if __name__ == "__main__": ...
package main import ( "fmt" "rcu" ) const MAX = 1e7 - 1 var primes = rcu.Primes(MAX) func specialNP(limit int, showAll bool) { if showAll { fmt.Println("Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:") } count := 0 for i := 1; i < len(primes); i++ { p2 := primes[i] ...
Ensure the translated Go code behaves exactly like the original Python snippet.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def nextPrime(n): if n == 0: return 2 if n < 3: return n + 1 q = n + 2 while not isPrime(q): q += 2 return q if __name__ == "__main__": ...
package main import ( "fmt" "rcu" ) const MAX = 1e7 - 1 var primes = rcu.Primes(MAX) func specialNP(limit int, showAll bool) { if showAll { fmt.Println("Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:") } count := 0 for i := 1; i < len(primes); i++ { p2 := primes[i] ...
Change the following Python code into Go without altering its purpose.
range17 = range(17) a = [['0'] * 17 for i in range17] idx = [0] * 4 def find_group(mark, min_n, max_n, depth=1): if (depth == 4): prefix = "" if (mark == '1') else "un" print("Fail, found totally {}connected group:".format(prefix)) for i in range(4): print(idx[i]) retur...
package main import "fmt" var ( a [17][17]int idx [4]int ) func findGroup(ctype, min, max, depth int) bool { if depth == 4 { cs := "" if ctype == 0 { cs = "un" } fmt.Printf("Totally %sconnected group:", cs) for i := 0; i < 4; i++ { fmt.Pri...
Change the programming language of this snippet from Python to Go without modifying what it does.
import tkinter as tk root = tk.Tk() root.state('zoomed') root.update_idletasks() tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())), font=("Helvetica", 25)).pack() root.mainloop()
package main import ( "fmt" "github.com/go-vgo/robotgo" ) func main() { w, h := robotgo.GetScreenSize() fmt.Printf("Screen size: %d x %d\n", w, h) fpid, err := robotgo.FindIds("firefox") if err == nil && len(fpid) > 0 { pid := fpid[0] robotgo.ActivePID(pid) robotgo.MaxW...
Write the same algorithm in Go as shown in this Python implementation.
print "\033[7mReversed\033[m Normal"
package main import ( "fmt" "os" "os/exec" ) func main() { tput("rev") fmt.Print("Rosetta") tput("sgr0") fmt.Println(" Code") } func tput(arg string) error { cmd := exec.Command("tput", arg) cmd.Stdout = os.Stdout return cmd.Run() }
Change the following Python code into Go without altering its purpose.
import random from collections import OrderedDict numbers = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 's...
package main import ( "fmt" "math" "strings" ) func main() { for _, n := range [...]int64{ 0, 4, 6, 11, 13, 75, 100, 337, -164, math.MaxInt64, } { fmt.Println(fourIsMagic(n)) } } func fourIsMagic(n int64) string { s := say(n) s = strings.ToUpper(s[:1]) + s[1:] t := s for n != 4 { n = int64(len(s)) ...
Write the same algorithm in Go as shown in this Python implementation.
In [6]: def dec(n): ...: return len(n.rsplit('.')[-1]) if '.' in n else 0 In [7]: dec('12.345') Out[7]: 3 In [8]: dec('12.3450') Out[8]: 4 In [9]:
package main import ( "fmt" "log" "math" "strings" ) var error = "Argument must be a numeric literal or a decimal numeric string." func getNumDecimals(n interface{}) int { switch v := n.(type) { case int: return 0 case float64: if v == math.Trunc(v) { return 0 ...
Port the provided Python code into Go while preserving the original functionality.
>>> from enum import Enum >>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE') >>> Contact.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)])) >>> >>> >>> class Contact2(Enum): FIRST_NAME = 1 LAST_NAME = 2 P...
const ( apple = iota banana cherry )
Change the programming language of this snippet from Python to Go without modifying what it does.
try: import psyco psyco.full() except ImportError: pass MAX_N = 300 BRANCH = 4 ra = [0] * MAX_N unrooted = [0] * MAX_N def tree(br, n, l, sum = 1, cnt = 1): global ra, unrooted, MAX_N, BRANCH for b in xrange(br + 1, BRANCH + 1): sum += n if sum >= MAX_N: return ...
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > ...
Produce a functionally identical Go code for the snippet given in Python.
try: import psyco psyco.full() except ImportError: pass MAX_N = 300 BRANCH = 4 ra = [0] * MAX_N unrooted = [0] * MAX_N def tree(br, n, l, sum = 1, cnt = 1): global ra, unrooted, MAX_N, BRANCH for b in xrange(br + 1, BRANCH + 1): sum += n if sum >= MAX_N: return ...
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > ...
Preserve the algorithm and functionality while converting the code from Python to Go.
try: import psyco psyco.full() except ImportError: pass MAX_N = 300 BRANCH = 4 ra = [0] * MAX_N unrooted = [0] * MAX_N def tree(br, n, l, sum = 1, cnt = 1): global ra, unrooted, MAX_N, BRANCH for b in xrange(br + 1, BRANCH + 1): sum += n if sum >= MAX_N: return ...
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > ...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
def min_cells_matrix(siz): return [[min(row, col, siz - row - 1, siz - col - 1) for col in range(siz)] for row in range(siz)] def display_matrix(mat): siz = len(mat) spaces = 2 if siz < 20 else 3 if siz < 200 else 4 print(f"\nMinimum number of cells after, before, above and below {siz} x {siz} square:"...
package main import "fmt" func printMinCells(n int) { fmt.Printf("Minimum number of cells after, before, above and below %d x %d square:\n", n, n) p := 1 if n > 20 { p = 2 } for r := 0; r < n; r++ { cells := make([]int, n) for c := 0; c < n; c++ { nums := []int{...
Rewrite the snippet below in Go so it works the same as the original Python code.
import turtle turtle.bgcolor("green") t = turtle.Turtle() t.color("red", "blue") t.begin_fill() for i in range(0, 5): t.forward(200) t.right(144) t.end_fill()
package main import ( "github.com/fogleman/gg" "math" ) func Pentagram(x, y, r float64) []gg.Point { points := make([]gg.Point, 5) for i := 0; i < 5; i++ { fi := float64(i) angle := 2*math.Pi*fi/5 - math.Pi/2 points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)} ...
Convert the following code from Python to Go, ensuring the logic remains intact.
import turtle turtle.bgcolor("green") t = turtle.Turtle() t.color("red", "blue") t.begin_fill() for i in range(0, 5): t.forward(200) t.right(144) t.end_fill()
package main import ( "github.com/fogleman/gg" "math" ) func Pentagram(x, y, r float64) []gg.Point { points := make([]gg.Point, 5) for i := 0; i < 5; i++ { fi := float64(i) angle := 2*math.Pi*fi/5 - math.Pi/2 points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)} ...
Rewrite the snippet below in Go so it works the same as the original Python code.
from ipaddress import ip_address from urllib.parse import urlparse tests = [ "127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "::192.168.0.1", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80" ] def parse_ip_port(netloc): try: ip = ip_address(netloc) port = Non...
package main import ( "encoding/hex" "fmt" "io" "net" "os" "strconv" "strings" "text/tabwriter" ) func parseIPPort(address string) (net.IP, *uint64, error) { ip := net.ParseIP(address) if ip != nil { return ip, nil, nil } host, portStr, err := net.SplitHostPort(address) if err != nil { return nil,...
Maintain the same structure and functionality when rewriting this code in Go.
import curses import random import time ROW_DELAY=.0001 def get_rand_in_range(min, max): return random.randrange(min,max+1) try: chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] total_chars = len(chars) stdscr = curses.initscr() curses.noecho() curses.curs_set...
package main import ( gc "github.com/rthornton128/goncurses" "log" "math/rand" "time" ) const rowDelay = 40000 func main() { start := time.Now() rand.Seed(time.Now().UnixNano()) chars := []byte("0123456789") totalChars := len(chars) stdscr, err := gc.Init() if er...
Port the following code from Python to Go with equivalent syntax and logic.
import curses import random import time ROW_DELAY=.0001 def get_rand_in_range(min, max): return random.randrange(min,max+1) try: chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] total_chars = len(chars) stdscr = curses.initscr() curses.noecho() curses.curs_set...
package main import ( gc "github.com/rthornton128/goncurses" "log" "math/rand" "time" ) const rowDelay = 40000 func main() { start := time.Now() rand.Seed(time.Now().UnixNano()) chars := []byte("0123456789") totalChars := len(chars) stdscr, err := gc.Init() if er...
Port the following code from Python to Go with equivalent syntax and logic.
import random n = 52 Black, Red = 'Black', 'Red' blacks = [Black] * (n // 2) reds = [Red] * (n // 2) pack = blacks + reds random.shuffle(pack) black_stack, red_stack, discard = [], [], [] while pack: top = pack.pop() if top == Black: black_stack.append(pack.pop()) else: red_stack.appen...
package main import ( "fmt" "math/rand" "time" ) func main() { var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { pack[i], pack[j] = pack[j], pack[i] }) ...
Port the provided Python code into Go while preserving the original functionality.
import random n = 52 Black, Red = 'Black', 'Red' blacks = [Black] * (n // 2) reds = [Red] * (n // 2) pack = blacks + reds random.shuffle(pack) black_stack, red_stack, discard = [], [], [] while pack: top = pack.pop() if top == Black: black_stack.append(pack.pop()) else: red_stack.appen...
package main import ( "fmt" "math/rand" "time" ) func main() { var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { pack[i], pack[j] = pack[j], pack[i] }) ...
Write a version of this Python function in Go with identical behavior.
from collections import defaultdict import urllib.request CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars} URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt' def getwords(url): return urllib.request.urlopen(url).read().decode("utf-8").lower(...
package main import ( "bufio" "flag" "fmt" "io" "log" "os" "strings" "unicode" ) func main() { log.SetFlags(0) log.SetPrefix("textonyms: ") wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } t ...
Produce a language-to-language conversion: from Python to Go, same semantics.
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] -...
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func...
Keep all operations the same but rewrite the snippet in Go.
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] -...
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func...
Preserve the algorithm and functionality while converting the code from Python to Go.
from itertools import chain, groupby from os.path import expanduser from functools import reduce def main(): print('\n'.join( concatMap(circularGroup)( anagrams(3)( lines(readFile('~/mitWords.txt')) ) ) )) def anagrams(n): ...
package main import ( "bufio" "fmt" "log" "os" "sort" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func readWords(fileName string) []string { file, err := os.Open(fileName) check(err) defer file.Close() var words []string scanner :...
Write a version of this Python function in Go with identical behavior.
def digit_sum(n, sum): sum += 1 while n > 0 and n % 10 == 0: sum -= 9 n /= 10 return sum previous = 1 gap = 0 sum = 0 niven_index = 0 gap_index = 1 print("Gap index Gap Niven index Niven number") niven = 1 while gap_index <= 22: sum = digit_sum(niven, sum) ...
package main import "fmt" type is func() uint64 func newSum() is { var ms is ms = func() uint64 { ms = newSum() return ms() } var msd, d uint64 return func() uint64 { if d < 9 { d++ } else { d = 0 msd = ms() } ret...
Port the provided Python code into Go while preserving the original functionality.
import logging, logging.handlers LOG_FILENAME = "logdemo.log" FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s" LOGLEVEL = logging.DEBUG def print_squares(number): logger.info("In print_squares") for i in range(number): print("square of {0} is {1}".format(...
package main import ( "fmt" "runtime" ) type point struct { x, y float64 } func add(x, y int) int { result := x + y debug("x", x) debug("y", y) debug("result", result) debug("result+1", result+1) return result } func debug(s string, x interface{}) { _, _, lineNo, _ := runtime...
Translate the given Python code snippet into Go without altering its behavior.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def isBackPrime(n): if not isPrime(n): return False m = 0 while n: m *= 10 m += n % 10 n //= 10 return isPrime(m) if __name__ == '__main__':...
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := 4; i < limit; i += 2 { c[i] = true } p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < ...
Change the programming language of this snippet from Python to Go without modifying what it does.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def isBackPrime(n): if not isPrime(n): return False m = 0 while n: m *= 10 m += n % 10 n //= 10 return isPrime(m) if __name__ == '__main__':...
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := 4; i < limit; i += 2 { c[i] = true } p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < ...
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 def isBackPrime(n): if not isPrime(n): return False m = 0 while n: m *= 10 m += n % 10 n //= 10 return isPrime(m) if __name__ == '__main__':...
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := 4; i < limit; i += 2 { c[i] = true } p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < ...