Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Keep all operations the same but rewrite the snippet in Go.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 999): if not isPrime(p): continue for q in range(p+1, 1000//p): if not isPrime(q): ...
package main import ( "fmt" "rcu" "sort" ) func main() { primes := rcu.Primes(333) var oss []int for i := 1; i < len(primes)-1; i++ { for j := i + 1; j < len(primes); j++ { n := primes[i] * primes[j] if n >= 1000 { break } ...
Transform the following Python implementation into Go, maintaining the same output and logic.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 999): if not isPrime(p): continue for q in range(p+1, 1000//p): if not isPrime(q): ...
package main import ( "fmt" "rcu" "sort" ) func main() { primes := rcu.Primes(333) var oss []int for i := 1; i < len(primes)-1; i++ { for j := i + 1; j < len(primes); j++ { n := primes[i] * primes[j] if n >= 1000 { break } ...
Please provide an equivalent version of this Python code in Go.
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import hsv_to_rgb as hsv def curve(axiom, rules, angle, depth): for _ in range(depth): axiom = ''.join(rules[c] if c in rules else c for c in axiom) a, x, y = 0, [0], [0] for c in axiom: match c: case '+'...
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx...
Ensure the translated Go code behaves exactly like the original Python snippet.
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import hsv_to_rgb as hsv def curve(axiom, rules, angle, depth): for _ in range(depth): axiom = ''.join(rules[c] if c in rules else c for c in axiom) a, x, y = 0, [0], [0] for c in axiom: match c: case '+'...
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx...
Convert this Python snippet to Go and keep its semantics consistent.
import collections def MostFreqKHashing(inputString, K): occuDict = collections.defaultdict(int) for c in inputString: occuDict[c] += 1 occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True) outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K]) return outputStr d...
package main import ( "fmt" "sort" ) type cf struct { c rune f int } func reverseStr(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func indexOfCf(cfs []cf, r rune) i...
Rewrite the snippet below in Go so it works the same as the original Python code.
import collections def MostFreqKHashing(inputString, K): occuDict = collections.defaultdict(int) for c in inputString: occuDict[c] += 1 occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True) outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K]) return outputStr d...
package main import ( "fmt" "sort" ) type cf struct { c rune f int } func reverseStr(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func indexOfCf(cfs []cf, r rune) i...
Rewrite the snippet below in Go so it works the same as the original Python code.
from itertools import takewhile def palindromicPrimes(): def p(n): s = str(n) return s == s[::-1] return (n for n in primes() if p(n)) def main(): print('\n'.join( str(x) for x in takewhile( lambda n: 1000 > n, palindromicPrimes() ) ...
package main import ( "fmt" "rcu" ) func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n /= 10 } return rev } func main() { primes := rcu.Primes(99999) var pals []int for _, p := range primes { if p == reversed(p) { pals = appen...
Keep all operations the same but rewrite the snippet in Go.
from itertools import takewhile def palindromicPrimes(): def p(n): s = str(n) return s == s[::-1] return (n for n in primes() if p(n)) def main(): print('\n'.join( str(x) for x in takewhile( lambda n: 1000 > n, palindromicPrimes() ) ...
package main import ( "fmt" "rcu" ) func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n /= 10 } return rev } func main() { primes := rcu.Primes(99999) var pals []int for _, p := range primes { if p == reversed(p) { pals = appen...
Convert the following code from Python to Go, ensuring the logic remains intact.
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() for word in wordList: if len(word)>10: frequency = Co...
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := ran...
Translate this program into Go but keep the logic exactly as in Python.
from numpy import Inf class MaxTropical: def __init__(self, x=0): self.x = x def __str__(self): return str(self.x) def __add__(self, other): return MaxTropical(max(self.x, other.x)) def __mul__(self, other): return MaxTropical(self.x + other.x) def __pow__(s...
package main import ( "fmt" "log" "math" ) var MinusInf = math.Inf(-1) type MaxTropical struct{ r float64 } func newMaxTropical(r float64) MaxTropical { if math.IsInf(r, 1) || math.IsNaN(r) { log.Fatal("Argument must be a real number or negative infinity.") } return MaxTropical{r} } ...
Port the provided Python code into Go while preserving the original functionality.
from random import randint from collections import namedtuple import random from pprint import pprint as pp from collections import Counter playercount = 2 maxscore = 100 maxgames = 100000 Game = namedtuple('Game', 'players, maxscore, rounds') Round = namedtuple('Round', 'who, start, scores, safe') class Play...
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota pigged...
Ensure the translated Go code behaves exactly like the original Python snippet.
from random import randint from collections import namedtuple import random from pprint import pprint as pp from collections import Counter playercount = 2 maxscore = 100 maxgames = 100000 Game = namedtuple('Game', 'players, maxscore, rounds') Round = namedtuple('Round', 'who, start, scores, safe') class Play...
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota pigged...
Transform the following Python implementation into Go, maintaining the same output and logic.
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)...
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
Write the same code in Go as shown below in Python.
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)...
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
Convert this Python snippet to Go and keep its semantics consistent.
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)...
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
Maintain the same structure and functionality when rewriting this code in Go.
def p(n): return 9 < n and (9 < n % 16 or p(n // 16)) def main(): xs = [ str(n) for n in range(1, 1 + 500) if p(n) ] print(f'{len(xs)} matches for the predicate:\n') print( table(6)(xs) ) def chunksOf(n): def go(xs): return ( ...
package main import ( "fmt" "strconv" "strings" ) func main() { const nondecimal = "abcdef" c := 0 for i := int64(0); i <= 500; i++ { hex := strconv.FormatInt(i, 16) if strings.ContainsAny(nondecimal, hex) { fmt.Printf("%3d ", i) c++ if c%15 ...
Keep all operations the same but rewrite the snippet in Go.
def p(n): return 9 < n and (9 < n % 16 or p(n // 16)) def main(): xs = [ str(n) for n in range(1, 1 + 500) if p(n) ] print(f'{len(xs)} matches for the predicate:\n') print( table(6)(xs) ) def chunksOf(n): def go(xs): return ( ...
package main import ( "fmt" "strconv" "strings" ) func main() { const nondecimal = "abcdef" c := 0 for i := int64(0); i <= 500; i++ { hex := strconv.FormatInt(i, 16) if strings.ContainsAny(nondecimal, hex) { fmt.Printf("%3d ", i) c++ if c%15 ...
Ensure the translated Go code behaves exactly like the original Python snippet.
class Sequence(): def __init__(self, sequence_string): self.ranges = self.to_ranges(sequence_string) assert self.ranges == sorted(self.ranges), "Sequence order error" def to_ranges(self, txt): return [[int(x) for x in r.strip().split('-')] for r in txt.strip...
package main import ( "fmt" "strings" ) type rng struct{ from, to int } type fn func(rngs *[]rng, n int) func (r rng) String() string { return fmt.Sprintf("%d-%d", r.from, r.to) } func rangesAdd(rngs []rng, n int) []rng { if len(rngs) == 0 { rngs = append(rngs, rng{n, n}) return rngs ...
Transform the following Python implementation into Go, maintaining the same output and logic.
from math import isqrt def juggler(k, countdig=True, maxiters=1000): m, maxj, maxjpos = k, k, 0 for i in range(1, maxiters): m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m) if m >= maxj: maxj, maxjpos = m, i if m == 1: print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(...
package main import ( "fmt" "log" big "github.com/ncw/gmp" "rcu" ) var zero = new(big.Int) var one = big.NewInt(1) var two = big.NewInt(2) func juggler(n int64) (int, int, *big.Int, int) { if n < 1 { log.Fatal("Starting value must be a positive integer.") } count := 0 max...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
from math import isqrt def juggler(k, countdig=True, maxiters=1000): m, maxj, maxjpos = k, k, 0 for i in range(1, maxiters): m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m) if m >= maxj: maxj, maxjpos = m, i if m == 1: print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(...
package main import ( "fmt" "log" big "github.com/ncw/gmp" "rcu" ) var zero = new(big.Int) var one = big.NewInt(1) var two = big.NewInt(2) func juggler(n int64) (int, int, *big.Int, int) { if n < 1 { log.Fatal("Starting value must be a positive integer.") } count := 0 max...
Generate an equivalent Go version of this Python code.
import matplotlib.pyplot as plt import math def nextPoint(x, y, angle): a = math.pi * angle / 180 x2 = (int)(round(x + (1 * math.cos(a)))) y2 = (int)(round(y + (1 * math.sin(a)))) return x2, y2 def expand(axiom, rules, level): for l in range(0, level): a2 = "" for c in axiom: ...
package main import ( "github.com/fogleman/gg" "github.com/trubitsyn/go-lindenmayer" "log" "math" ) const twoPi = 2 * math.Pi var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h, theta float64 func main() { dc.SetRGB(0, 0, 1) dc.C...
Convert this Python block to Go, preserving its control flow and logic.
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) ...
package main import ( "fmt" "math" "sort" ) const adj = 0.0001 var primes = []uint64{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } func isSquareFree(x ui...
Generate an equivalent Go version of this Python code.
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) ...
package main import ( "fmt" "math" "sort" ) const adj = 0.0001 var primes = []uint64{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } func isSquareFree(x ui...
Preserve the algorithm and functionality while converting the code from Python to Go.
infile = open('infile.dat', 'rb') outfile = open('outfile.dat', 'wb') while True: onerecord = infile.read(80) if len(onerecord) < 80: break onerecordreversed = bytes(reversed(onerecord)) outfile.write(onerecordreversed) infile.close() outfile.close()
package main import ( "fmt" "log" "os" "os/exec" ) func reverseBytes(bytes []byte) { for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 { bytes[i], bytes[j] = bytes[j], bytes[i] } } func check(err error) { if err != nil { log.Fatal(err) } } func main() { in, err ...
Preserve the algorithm and functionality while converting the code from Python to Go.
import urllib.request 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() for word in wordList: if len(word)>5 and word[:3].lower()==word[-3:].lower(): print(wo...
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) count := 0 for _, bword := range bword...
Port the following code from Python to Go with equivalent syntax and logic.
from math import sqrt def isGiuga(m): n = m f = 2 l = sqrt(n) while True: if n % f == 0: if ((m / f) - 1) % f != 0: return False n /= f if f > n: return True else: f += 1 if f > l: ...
package main import "fmt" var factors []int var inc = []int{4, 2, 4, 2, 4, 6, 2, 6} func primeFactors(n int) { factors = factors[:0] factors = append(factors, 2) last := 2 n /= 2 for n%3 == 0 { if last == 3 { factors = factors[:0] return } last = ...
Convert this Python snippet to Go and keep its semantics consistent.
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef...
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo...
Convert the following code from Python to Go, ensuring the logic remains intact.
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef...
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo...
Write the same algorithm in Go as shown in this Python implementation.
import urllib.request 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() oddWordSet = set({}) for word in wordList: if len(word)>=9 and word[::2] in wordList: ...
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords))...
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
import urllib.request 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() oddWordSet = set({}) for word in wordList: if len(word)>=9 and word[::2] in wordList: ...
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords))...
Change the following Python code into Go without altering its purpose.
from pprint import pprint as pp def to_indent(node, depth=0, flat=None): if flat is None: flat = [] if node: flat.append((depth, node[0])) for child in node[1]: to_indent(child, depth + 1, flat) return flat def to_nest(lst, depth=0, level=None): if level is None: le...
package main import ( "fmt" "io" "os" "strings" ) type nNode struct { name string children []nNode } type iNode struct { level int name string } func printNest(n nNode, level int, w io.Writer) { if level == 0 { fmt.Fprintln(w, "\n==Nest form==\n") } fmt.Fprin...
Transform the following Python implementation into Go, maintaining the same output and logic.
from pprint import pprint as pp def to_indent(node, depth=0, flat=None): if flat is None: flat = [] if node: flat.append((depth, node[0])) for child in node[1]: to_indent(child, depth + 1, flat) return flat def to_nest(lst, depth=0, level=None): if level is None: le...
package main import ( "fmt" "io" "os" "strings" ) type nNode struct { name string children []nNode } type iNode struct { level int name string } func printNest(n nNode, level int, w io.Writer) { if level == 0 { fmt.Fprintln(w, "\n==Nest form==\n") } fmt.Fprin...
Translate this program into Go but keep the logic exactly as in Python.
from collections import defaultdict rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}} def trstring(oldstring, repdict): seen, newchars = defaultdict(lambda:1, {}), [] for c in oldstring: i = seen[c] newchars.append(repdict[c][i] if c in repdict and i in repd...
package main import ( "fmt" "strings" ) func main() { s := "abracadabra" ss := []byte(s) var ixs []int for ix, c := range s { if c == 'a' { ixs = append(ixs, ix) } } repl := "ABaCD" for i := 0; i < 5; i++ { ss[ixs[i]] = repl[i] } s = stri...
Port the provided Python code into Go while preserving the original functionality.
from collections import defaultdict rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}} def trstring(oldstring, repdict): seen, newchars = defaultdict(lambda:1, {}), [] for c in oldstring: i = seen[c] newchars.append(repdict[c][i] if c in repdict and i in repd...
package main import ( "fmt" "strings" ) func main() { s := "abracadabra" ss := []byte(s) var ixs []int for ix, c := range s { if c == 'a' { ixs = append(ixs, ix) } } repl := "ABaCD" for i := 0; i < 5; i++ { ss[ixs[i]] = repl[i] } s = stri...
Write the same algorithm in Go as shown in this Python implementation.
from sympy import isprime for b in range(2, 17): print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" "strings" ) func main() { limit := 2700 primes := rcu.Primes(limit) s := new(big.Int) for b := 2; b <= 36; b++ { var rPrimes []int for _, p := range primes { s.SetString(strings.Repeat("1", p), b) ...
Produce a language-to-language conversion: from Python to Go, same semantics.
from sympy import isprime for b in range(2, 17): print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" "strings" ) func main() { limit := 2700 primes := rcu.Primes(limit) s := new(big.Int) for b := 2; b <= 36; b++ { var rPrimes []int for _, p := range primes { s.SetString(strings.Repeat("1", p), b) ...
Change the programming language of this snippet from Python to Go without modifying what it does.
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print...
package main import ( "fmt" "math/big" ) func main() { zero := big.NewInt(0) one := big.NewInt(1) for k := int64(2); k <= 10; k += 2 { bk := big.NewInt(k) fmt.Println("The first 50 Curzon numbers using a base of", k, ":") count := 0 n := int64(1) pow := big....
Produce a language-to-language conversion: from Python to Go, same semantics.
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print...
package main import ( "fmt" "math/big" ) func main() { zero := big.NewInt(0) one := big.NewInt(1) for k := int64(2); k <= 10; k += 2 { bk := big.NewInt(k) fmt.Println("The first 50 Curzon numbers using a base of", k, ":") count := 0 n := int64(1) pow := big....
Convert this Python block to Go, preserving its control flow and logic.
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt...
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" ) const ( prec = 256 ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" ) func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec)....
Translate the given Python code snippet into Go without altering its behavior.
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt...
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" ) const ( prec = 256 ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" ) func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec)....
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt...
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" ) const ( prec = 256 ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" ) func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec)....
Generate an equivalent Go version of this Python code.
class Example(object): def foo(self): print("this is foo") def bar(self): print("this is bar") def __getattr__(self, name): def method(*args): print("tried to handle unknown method " + name) if args: print("it had arguments: " + str(args)) ...
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func (e example) CallMethod(n string) int { if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() { return int(m.Call(nil)[0].Int()) } fmt.Println("Unknown method:", ...
Change the programming language of this snippet from Python to Go without modifying what it does.
from itertools import (chain) def stringParse(lexicon): return lambda s: Node(s)( tokenTrees(lexicon)(s) ) def tokenTrees(wds): def go(s): return [Node(s)([])] if s in wds else ( concatMap(nxt(s))(wds) ) def nxt(s): return lambda w: parse( ...
package main import ( "fmt" "strings" ) type dict map[string]bool func newDict(words ...string) dict { d := dict{} for _, w := range words { d[w] = true } return d } func (d dict) wordBreak(s string) (broken []string, ok bool) { if s == "" { return nil, true } typ...
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n...
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits;...
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n...
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits;...
Please provide an equivalent version of this Python code in Go.
import os,sys,zlib,urllib.request def h ( str,x=9 ): for c in str : x = ( x*33 + ord( c )) & 0xffffffffff return x def cache ( func,*param ): n = 'cache_%x.bin'%abs( h( repr( param ))) try : return eval( zlib.decompress( open( n,'rb' ).read())) except : pass s = func( *param ) ...
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func contains(a []string, s string) bool { for _, e := range a { if e == s { return true } } return false } func oneAway(a, b string) bool { sum := 0 for i := 0; i < len(a); i++ { ...
Produce a language-to-language conversion: from Python to Go, same semantics.
import sys import pygame pygame.init() clk = pygame.time.Clock() if pygame.joystick.get_count() == 0: raise IOError("No joystick detected") joy = pygame.joystick.Joystick(0) joy.init() size = width, height = 600, 600 screen = pygame.display.set_mode(size) pygame.display.set_caption("Joystick Tester") frame...
package main import ( "fmt" "github.com/nsf/termbox-go" "github.com/simulatedsimian/joystick" "log" "os" "strconv" "time" ) func printAt(x, y int, s string) { for _, r := range s { termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault) x++ } } func re...
Produce a language-to-language conversion: from Python to Go, same semantics.
from primesieve import primes LIMIT = 10**9 pri = primes(LIMIT * 5) gapstarts = {} for i in range(1, len(pri)): if pri[i] - pri[i - 1] not in gapstarts: gapstarts[pri[i] - pri[i - 1]] = pri[i - 1] PM, GAP1, = 10, 2 while True: while GAP1 not in gapstarts: GAP1 += 2 start1 = gapstarts[GAP...
package main import ( "fmt" "rcu" ) func main() { limit := int(1e9) gapStarts := make(map[int]int) primes := rcu.Primes(limit * 5) for i := 1; i < len(primes); i++ { gap := primes[i] - primes[i-1] if _, ok := gapStarts[gap]; !ok { gapStarts[gap] = primes[i-1] ...
Change the following Python code into Go without altering its purpose.
def dList(n, start): start -= 1 a = range(n) a[start] = a[0] a[0] = start a[1:] = sorted(a[1:]) first = a[1] r = [] def recurse(last): if (last == first): for j,v in enumerate(a[1:]): if j + 1 == v: ...
package main import ( "fmt" "sort" ) type matrix [][]int func dList(n, start int) (r matrix) { start-- a := make([]int, n) for i := range a { a[i] = i } a[0], a[start] = start, a[0] sort.Ints(a[1:]) first := a[1] var recurse func(last int) recurse = func(las...
Change the programming language of this snippet from Python to Go without modifying what it does.
from sympy import primerange PRIMES1M = list(primerange(1, 1_000_000)) ASBASE10SORT = [str(sorted(list(str(i)))) for i in PRIMES1M] ORMISTONS = [(PRIMES1M[i - 1], PRIMES1M[i]) for i in range(1, len(PRIMES1M)) if ASBASE10SORT[i - 1] == ASBASE10SORT[i]] print('First 30 Ormiston pairs:') for (i, o) in en...
package main import ( "fmt" "rcu" ) func main() { const limit = 1e9 primes := rcu.Primes(limit) var orm30 [][2]int j := int(1e5) count := 0 var counts []int for i := 0; i < len(primes)-1; i++ { p1 := primes[i] p2 := primes[i+1] if (p2-p1)%18 != 0 { ...
Port the provided Python code into Go while preserving the original functionality.
import itertools import re RE_BARCODE = re.compile( r"^(?P<s_quiet> +)" r"(?P<s_guard> r"(?P<left>[ r"(?P<m_guard> r"(?P<right>[ r"(?P<e_guard> r"(?P<e_quiet> +)$" ) LEFT_DIGITS = { (0, 0, 0, 1, 1, 0, 1): 0, (0, 0, 1, 1, 0, 0, 1): 1, (0, 0, 1, 0, 0, 1, 1): 2, (0, 1,...
package main import ( "fmt" "regexp" ) var bits = []string{ "0 0 0 1 1 0 1 ", "0 0 1 1 0 0 1 ", "0 0 1 0 0 1 1 ", "0 1 1 1 1 0 1 ", "0 1 0 0 0 1 1 ", "0 1 1 0 0 0 1 ", "0 1 0 1 1 1 1 ", "0 1 1 1 0 1 1 ", "0 1 1 0 1 1 1 ", "0 0 0 1 0 1 1 ", } var ( lhs = make(map[st...
Convert this Python snippet to Go and keep its semantics consistent.
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if ...
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ...
Please provide an equivalent version of this Python code in Go.
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if ...
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ...
Write the same code in Go as shown below in Python.
from fractions import Fraction def harmonic_series(): n, h = Fraction(1), Fraction(1) while True: yield h h += 1 / (n + 1) n += 1 if __name__ == '__main__': from itertools import islice for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)): print(n,...
package main import ( "fmt" "math/big" ) func harmonic(n int) *big.Rat { sum := new(big.Rat) for i := int64(1); i <= int64(n); i++ { r := big.NewRat(1, i) sum.Add(sum, r) } return sum } func main() { fmt.Println("The first 20 harmonic numbers and the 100th, expressed in ra...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
import io def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None: mergers = [] while True: text = list(source.read(n)) if not len(text): break; text.sort() merge_me = file_opener() merge_me.write(''.join(text)) ...
package main import ( "fmt" "io" "log" "math" "math/rand" "os" "time" ) type MinHeapNode struct{ element, index int } type MinHeap struct{ nodes []MinHeapNode } func left(i int) int { return (2*i + 1) } func right(i int) int { return (2*i + 2) } func newMinHeap(nodes []MinHeapN...
Please provide an equivalent version of this Python code in Go.
import io def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None: mergers = [] while True: text = list(source.read(n)) if not len(text): break; text.sort() merge_me = file_opener() merge_me.write(''.join(text)) ...
package main import ( "fmt" "io" "log" "math" "math/rand" "os" "time" ) type MinHeapNode struct{ element, index int } type MinHeap struct{ nodes []MinHeapNode } func left(i int) int { return (2*i + 1) } func right(i int) int { return (2*i + 2) } func newMinHeap(nodes []MinHeapN...
Ensure the translated Go code behaves exactly like the original Python snippet.
class NG: def __init__(self, a1, a, b1, b): self.a1, self.a, self.b1, self.b = a1, a, b1, b def ingress(self, n): self.a, self.a1 = self.a1, self.a + self.a1 * n self.b, self.b1 = self.b1, self.b + self.b1 * n @property def needterm(self): return (self.b == 0 or self.b1 == 0) or not self.a//se...
package cf type NG4 struct { A1, A int64 B1, B int64 } func (ng NG4) needsIngest() bool { if ng.isDone() { panic("b₁==b==0") } return ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B } func (ng NG4) isDone() bool { return ng.B1 == 0 && ng.B == 0 } func (ng *NG4) ingest(t int64) { ...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
from fractions import Fraction from math import floor from itertools import islice, groupby def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a) def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = den, ...
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) func calkinWilf(n int) []*big.Rat { cw := make([]*big.Rat, n+1) cw[0] = big.NewRat(1, 1) one := big.NewRat(1, 1) two := big.NewRat(2, 1) for i := 1; i < n; i++ { t := new(big.Rat).Set(cw[i-1]) f...
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
from fractions import Fraction from math import floor from itertools import islice, groupby def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a) def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = den, ...
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) func calkinWilf(n int) []*big.Rat { cw := make([]*big.Rat, n+1) cw[0] = big.NewRat(1, 1) one := big.NewRat(1, 1) two := big.NewRat(2, 1) for i := 1; i < n; i++ { t := new(big.Rat).Set(cw[i-1]) f...
Please provide an equivalent version of this Python code in Go.
def facpropzeros(N, verbose = True): proportions = [0.0] * N fac, psum = 1, 0.0 for i in range(N): fac *= i + 1 d = list(str(fac)) psum += sum(map(lambda x: x == '0', d)) / len(d) proportions[i] = psum / (i + 1) if verbose: print("The mean proportion of 0 in fact...
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" ) func main() { fact := big.NewInt(1) sum := 0.0 first := int64(0) firstRatio := 0.0 fmt.Println("The mean proportion of zero digits in factorials up to the following are:") for n := int64(1); n <= 50000; n++ { ...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for ...
package main import ( "fmt" "math" "math/rand" "time" ) type xy struct { x, y float64 } const n = 1000 const scale = 100. func d(p1, p2 xy) float64 { return math.Hypot(p2.x-p1.x, p2.y-p1.y) } func main() { rand.Seed(time.Now().Unix()) points := make([]xy, n) for i := range point...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
var num = 12 var pointer = ptr(num) print pointer @unsafe pointer.addr = 0xFFFE
package main import ( "fmt" "unsafe" ) func main() { myVar := 3.14 myPointer := &myVar fmt.Println("Address:", myPointer, &myVar) fmt.Printf("Address: %p %p\n", myPointer, &myVar) var addr64 int64 var addr32 int32 ptr := unsafe.Pointer(myPointer) if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) { addr64 = ...
Port the following code from Python to Go with equivalent syntax and logic.
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass class Lab(Dog): pass class Collie(Dog): pass
package main type animal struct { alive bool } type dog struct { animal obedienceTrained bool } type cat struct { animal litterBoxTrained bool } type lab struct { dog color string } type collie struct { dog catchesFrisbee bool } func main() { var pet lab pet.alive = tru...
Change the programming language of this snippet from Python to Go without modifying what it does.
hash = dict() hash = dict(red="FF0000", green="00FF00", blue="0000FF") hash = { 'key1':1, 'key2':2, } value = hash[key]
var x map[string]int x = make(map[string]int) x = make(map[string]int, 42) x["foo"] = 3 y1 := x["bar"] y2, ok := x["bar"] delete(x, "foo") x = map[string]int{ "foo": 2, "bar": 42, "baz": -1, }
Convert this Python block to Go, preserving its control flow and logic.
size(300, 300) background(0) radius = min(width, height) / 2.0 cx, cy = width / 2, width / 2 for x in range(width): for y in range(height): rx = x - cx ry = y - cy s = sqrt(rx ** 2 + ry ** 2) / radius if s <= 1.0: h = ((atan2(ry, rx) / PI) + 1.0) /...
package main import ( "github.com/fogleman/gg" "math" ) const tau = 2 * math.Pi func hsb2rgb(hue, sat, bri float64) (r, g, b int) { u := int(bri*255 + 0.5) if sat == 0 { r, g, b = u, u, u } else { h := (hue - math.Floor(hue)) * 6 f := h - math.Floor(h) p := int(bri...
Convert this Python block to Go, preserving its control flow and logic.
pal = [0] * 128 r = 42 g = 84 b = 126 rd = gd = bd = False def setup(): global buffer size(600, 600) frameRate(25) buffer = [None] * width * height for x in range(width): for y in range(width): value = int(((128 + (128 * sin(x / 32.0))) + (128 + (128 *...
package main import ( "image" "image/color" "image/gif" "log" "math" "os" ) func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) { for x := 0; x < w; x++ { for y := 0; y < h; y++ { img.SetColorIndex(x, y, ci) } } } func hsb2rgb(hue, sat, bri flo...
Ensure the translated Go code behaves exactly like the original Python snippet.
from itertools import product from collections import defaultdict class Sandpile(): def __init__(self, gridtext): array = [int(x) for x in gridtext.strip().split()] self.grid = defaultdict(int, {(i //3, i % 3): x for i, x in enumera...
package main import ( "fmt" "strconv" "strings" ) type sandpile struct{ a [9]int } var neighbors = [][]int{ {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7}, } func newSandpile(a [9]int) *sandpile { return &sandpile{a} } func (s *sandpile) plus(other *sandpi...
Ensure the translated Go code behaves exactly like the original Python snippet.
from itertools import product from collections import defaultdict class Sandpile(): def __init__(self, gridtext): array = [int(x) for x in gridtext.strip().split()] self.grid = defaultdict(int, {(i //3, i % 3): x for i, x in enumera...
package main import ( "fmt" "strconv" "strings" ) type sandpile struct{ a [9]int } var neighbors = [][]int{ {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7}, } func newSandpile(a [9]int) *sandpile { return &sandpile{a} } func (s *sandpile) plus(other *sandpi...
Maintain the same structure and functionality when rewriting this code in Go.
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y) class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.rad...
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = ...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y) class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.rad...
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = ...
Convert the following code from Python to Go, ensuring the logic remains intact.
from collections import UserDict import copy class Dict(UserDict): def __init__(self, dict=None, **kwargs): self.__init = True super().__init__(dict, **kwargs) self.default = copy.deepcopy(self.data) self.__init = False def __delitem__(self, key): if key in sel...
package romap type Romap struct{ imap map[byte]int } func New(m map[byte]int) *Romap { if m == nil { return nil } return &Romap{m} } func (rom *Romap) Get(key byte) (int, bool) { i, ok := rom.imap[key] return i, ok } func (rom *Romap) Reset(key byte) { _, ok := rom.imap[key] i...
Port the provided Python code into Go while preserving the original functionality.
from math import floor, sqrt from datetime import datetime def main(): start = datetime.now() for i in xrange(1, 10 ** 11): if rare(i): print "found a rare:", i end = datetime.now() print "time elapsed:", end - start def is_square(n): s = floor(sqrt(n + 0.5)) return s * s == n def reverse(n): return ...
package main import ( "fmt" "math" "sort" "time" ) type term struct { coeff uint64 ix1, ix2 int8 } const maxDigits = 19 func toUint64(digits []int8, reverse bool) uint64 { sum := uint64(0) if !reverse { for i := 0; i < len(digits); i++ { sum = sum*10 + uint64(d...
Write the same algorithm in Go as shown in this Python implementation.
print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w) for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if...
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func contains(list []int, value int) bool { for _, v := range list { if v == value { return true } } return false } func main() { wordList := "unixdict.txt" b, err := ioutil.Read...
Port the provided Python code into Go while preserving the original functionality.
print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w) for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if...
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func contains(list []int, value int) bool { for _, v := range list { if v == value { return true } } return false } func main() { wordList := "unixdict.txt" b, err := ioutil.Read...
Translate the given Python code snippet into Go without altering its behavior.
for i in range(65,123): check = 1 for j in range(2,i): if i%j == 0: check = 0 if check==1: print(chr(i),end='')
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func isPrime(n int) bool { if n < 2 { return false } if n%2 == 0 { return n == 2 } if n%3 == 0 { return n == 3 } d := 5 for d*d <= n { if n%d == 0 { return ...
Convert this Python snippet to Go and keep its semantics consistent.
for i in range(65,123): check = 1 for j in range(2,i): if i%j == 0: check = 0 if check==1: print(chr(i),end='')
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func isPrime(n int) bool { if n < 2 { return false } if n%2 == 0 { return n == 2 } if n%3 == 0 { return n == 3 } d := 5 for d*d <= n { if n%d == 0 { return ...
Write a version of this Python function in Go with identical behavior.
from functools import reduce from sympy import divisors FOUND = 0 for num in range(1, 1_000_000): divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1 if num * num * num == divprod: FOUND += 1 if FOUND <= 50: print(f'{num:5}', end='\n' if FOUND % 10 == 0 else...
package main import ( "fmt" "math" "rcu" ) func divisorCount(n int) int { k := 1 if n%2 == 1 { k = 2 } count := 0 sqrt := int(math.Sqrt(float64(n))) for i := 1; i <= sqrt; i += k { if n%i == 0 { count++ j := n / i if j != i { ...
Generate an equivalent Go version of this Python code.
from functools import reduce from sympy import divisors FOUND = 0 for num in range(1, 1_000_000): divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1 if num * num * num == divprod: FOUND += 1 if FOUND <= 50: print(f'{num:5}', end='\n' if FOUND % 10 == 0 else...
package main import ( "fmt" "math" "rcu" ) func divisorCount(n int) int { k := 1 if n%2 == 1 { k = 2 } count := 0 sqrt := int(math.Sqrt(float64(n))) for i := 1; i <= sqrt; i += k { if n%i == 0 { count++ j := n / i if j != i { ...
Translate the given Python code snippet into Go without altering its behavior.
import textwrap from itertools import pairwise from typing import Iterator from typing import List import primesieve def primes() -> Iterator[int]: it = primesieve.Iterator() while True: yield it.next_prime() def triplewise(iterable): for (a, _), (b, c) in pairwise(pairwise(iterable)): ...
package main import ( "fmt" "rcu" ) func main() { const limit = 1e10 primes := rcu.Primes(limit) var orm25 []int j := int(1e9) count := 0 var counts []int for i := 0; i < len(primes)-2; i++ { p1 := primes[i] p2 := primes[i+1] p3 := primes[i+2] if (p2...
Port the following code from Python to Go with equivalent syntax and logic.
gridsize = (6, 4) minerange = (0.2, 0.6) try: raw_input except: raw_input = input import random from itertools import product from pprint import pprint as pp def gridandmines(gridsize=gridsize, minerange=minerange): xgrid, ygrid = gridsize minmines, maxmines = minerange minecount = xgri...
package main import ( "bufio" "fmt" "math" "math/rand" "os" "strconv" "strings" "time" ) type cell struct { isMine bool display byte } const lMargin = 4 var ( grid [][]cell mineCount int minesMarked int isGameOver bool ) var scanner = bufio.NewSca...
Translate the given Python code snippet into Go without altering its behavior.
def _notcell(c): return '0' if c == '1' else '1' def eca_infinite(cells, rule): lencells = len(cells) rulebits = '{0:08b}'.format(rule) neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)} c = cells while True: yield c c = _notcell(c[0])*2 + c + _notcell(c...
package main import ( "fmt" "strings" ) func btoi(b bool) int { if b { return 1 } return 0 } func evolve(l, rule int) { fmt.Printf(" Rule #%d:\n", rule) cells := "O" for x := 0; x < l; x++ { cells = addNoCells(cells) width := 40 + (len(cells) >> 1) fmt....
Port the provided Python code into Go while preserving the original functionality.
import sys def fatal_error(errtext): print("%" + errtext) print("usage: " + sys.argv[0] + " [filename.cp]") sys.exit(1) fname = None source = None try: fname = sys.argv[1] source = open(fname).read() except: fatal_error("error while trying to read from specified file") lines = source.split("\n") clipboard...
package main import ( "fmt" "github.com/atotto/clipboard" "io/ioutil" "log" "os" "runtime" "strconv" "strings" ) func check(err error) { if err != nil { clipboard.WriteAll("") log.Fatal(err) } } func interpret(source string) { source2 := source if run...
Transform the following Python implementation into Go, maintaining the same output and logic.
import sys def fatal_error(errtext): print("%" + errtext) print("usage: " + sys.argv[0] + " [filename.cp]") sys.exit(1) fname = None source = None try: fname = sys.argv[1] source = open(fname).read() except: fatal_error("error while trying to read from specified file") lines = source.split("\n") clipboard...
package main import ( "fmt" "github.com/atotto/clipboard" "io/ioutil" "log" "os" "runtime" "strconv" "strings" ) func check(err error) { if err != nil { clipboard.WriteAll("") log.Fatal(err) } } func interpret(source string) { source2 := source if run...
Change the following Python code into Go without altering its purpose.
from sympy import sieve def nonpairsums(include1=False, limit=20_000): tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve) for i in range(limit+2)] if include1: tpri[1] = True twinsums = [False] * (limit * 2) for i in range(limit): for j in range(limit-i+1): ...
package main import ( "fmt" "rcu" ) const limit = 100000 func nonTwinSums(twins []int) []int { sieve := make([]bool, limit+1) for i := 0; i < len(twins); i++ { for j := i; j < len(twins); j++ { sum := twins[i] + twins[j] if sum > limit { break ...
Please provide an equivalent version of this Python code in Go.
from operator import le from itertools import takewhile def monotonicDigits(base): def go(n): return monotonic(le)( showIntAtBase(base)(digitFromInt)(n)('') ) return go def monotonic(op): def go(xs): return all(map(op, xs, xs[1:])) return go def ...
package main import ( "fmt" "rcu" ) func nonDescending(p int) bool { var digits []int for p > 0 { digits = append(digits, p%10) p = p / 10 } for i := 0; i < len(digits)-1; i++ { if digits[i+1] > digits[i] { return false } } return true } fun...
Transform the following Python implementation into Go, maintaining the same output and logic.
from operator import le from itertools import takewhile def monotonicDigits(base): def go(n): return monotonic(le)( showIntAtBase(base)(digitFromInt)(n)('') ) return go def monotonic(op): def go(xs): return all(map(op, xs, xs[1:])) return go def ...
package main import ( "fmt" "rcu" ) func nonDescending(p int) bool { var digits []int for p > 0 { digits = append(digits, p%10) p = p / 10 } for i := 0; i < len(digits)-1; i++ { if digits[i+1] > digits[i] { return false } } return true } fun...
Preserve the algorithm and functionality while converting the code from Python to Go.
class Parent(object): __priv = 'private' def __init__(self, name): self.name = name def __repr__(self): return '%s(%s)' % (type(self).__name__, self.name) def doNothing(self): pass import re class Child(Parent): __rePrivate = re.compile('^_(Child|Parent)...
package main import ( "fmt" "image" "reflect" ) type t struct { X int next *t } func main() { report(t{}) report(image.Point{}) } func report(x interface{}) { t := reflect.TypeOf(x) n := t.NumField() fmt.Printf("Type %v has %d fields:\n", t, n) fmt.Println("Name Type Exported") for i := 0; i...
Keep all operations the same but rewrite the snippet in Go.
from functools import lru_cache DIVS = {2, 3} SUBS = {1} class Minrec(): "Recursive, memoised minimised steps to 1" def __init__(self, divs=DIVS, subs=SUBS): self.divs, self.subs = divs, subs @lru_cache(maxsize=None) def _minrec(self, n): "Recursive, memoised" if n == 1: ...
package main import ( "fmt" "strings" ) const limit = 50000 var ( divs, subs []int mins [][]string ) func minsteps(n int) { if n == 1 { mins[1] = []string{} return } min := limit var p, q int var op byte for _, div := range divs { if n%div == 0 ...
Write the same algorithm in Go as shown in this Python implementation.
from itertools import zip_longest txt = parts = [line.rstrip("$").split("$") for line in txt.splitlines()] widths = [max(len(word) for word in col) for col in zip_longest(*parts, fillvalue='')] for justify in "<_Left ^_Center >_Right".split(): j, jtext = justify.split('_') print(f"{jtext} colum...
package main import ( "fmt" "strings" ) const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$eac...
Keep all operations the same but rewrite the snippet in Go.
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) p...
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:s...
Convert this Python snippet to Go and keep its semantics consistent.
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) p...
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:s...
Keep all operations the same but rewrite the snippet in Go.
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) p...
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:s...
Please provide an equivalent version of this Python code in Go.
def is_idoneal(num): for a in range(1, num): for b in range(a + 1, num): if a * b + a + b > num: break for c in range(b + 1, num): sum3 = a * b + b * c + a * c if sum3 == num: return False if ...
package main import "rcu" func isIdoneal(n int) bool { for a := 1; a < n; a++ { for b := a + 1; b < n; b++ { if a*b+a+b > n { break } for c := b + 1; c < n; c++ { sum := a*b + b*c + a*c if sum == n { re...
Port the provided Python code into Go while preserving the original functionality.
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def convertToBase58(num): sb = '' while (num > 0): r = num % 58 sb = sb + ALPHABET[r] num = num // 58; return sb[::-1] s = 25420294593250030202636073700053352635053786165627414518 b = convertToBase58(s) print("...
package main import ( "fmt" "log" "math/big" "strings" ) const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" var big0 = new(big.Int) var big58 = big.NewInt(58) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { ...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def convertToBase58(num): sb = '' while (num > 0): r = num % 58 sb = sb + ALPHABET[r] num = num // 58; return sb[::-1] s = 25420294593250030202636073700053352635053786165627414518 b = convertToBase58(s) print("...
package main import ( "fmt" "log" "math/big" "strings" ) const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" var big0 = new(big.Int) var big58 = big.NewInt(58) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { ...
Convert this Python snippet to Go and keep its semantics consistent.
>>> name = raw_input("Enter a variable name: ") Enter a variable name: X >>> globals()[name] = 42 >>> X 42
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) n := 0 for n < 1 || n > 5 { fmt.Print("How many integer variables do you want...
Port the following code from Python to Go with equivalent syntax and logic.
IP = ( 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 ) IP_INV = ( 40, 8, 48, 1...
package main import ( "crypto/des" "encoding/hex" "fmt" "log" ) func main() { key, err := hex.DecodeString("0e329232ea6d0d73") if err != nil { log.Fatal(err) } c, err := des.NewCipher(key) if err != nil { log.Fatal(err) } src, err := hex.DecodeString("878787...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
class Head(): def __init__(self, lo, hi=None, shift=0): if hi is None: hi = lo d = hi - lo ds, ls, hs = str(d), str(lo), str(hi) if d and len(ls) > len(ds): assert(len(ls) - len(ds) + 1 > 21) lo = int(str(lo)[:len(ls) - len(ds) + 1]) hi = int(str...
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) type vector = []*big.Int type matrix []vector var ( zero = new(big.Int) one = big.NewInt(1) ) func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != ro...
Translate this program into Go but keep the logic exactly as in Python.
class Head(): def __init__(self, lo, hi=None, shift=0): if hi is None: hi = lo d = hi - lo ds, ls, hs = str(d), str(lo), str(hi) if d and len(ls) > len(ds): assert(len(ls) - len(ds) + 1 > 21) lo = int(str(lo)[:len(ls) - len(ds) + 1]) hi = int(str...
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) type vector = []*big.Int type matrix []vector var ( zero = new(big.Int) one = big.NewInt(1) ) func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != ro...
Convert this Python snippet to Go and keep its semantics consistent.
T=[set([(0, 0)])] def double(it): for a, b in it: yield a, b yield b, a def tails(n): if len(T)<=n: l = set() for i in range(10): for j in range(i, 10): I = i*10**(n-1) J = j*10**(n-1) it = tails(n-1) ...
package main import "fmt" func reverse(n uint64) uint64 { r := uint64(0) for n > 0 { r = n%10 + r*10 n /= 10 } return r } func main() { pow := uint64(10) nextN: for n := 2; n < 10; n++ { low := pow * 9 pow *= 10 high := pow - 1 fmt.Printf("Large...