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): continue print(p*q, end = " ");
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 } oss = append(oss, n) } } sort.Ints(oss) fmt.Println("Odd squarefree semiprimes under 1,000:") for i, n := range oss { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such numbers found.\n", len(oss)) }
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): continue print(p*q, end = " ");
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 } oss = append(oss, n) } } sort.Ints(oss) fmt.Println("Odd squarefree semiprimes under 1,000:") for i, n := range oss { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such numbers found.\n", len(oss)) }
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 '+': a += 1 case '-': a -= 1 case 'F' | 'G': x.append(x[-1] + np.cos(a*angle*np.pi/180)) y.append(y[-1] + np.sin(a*angle*np.pi/180)) l = len(x) for i in range(l - 1): plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7])) plt.gca().set_aspect(1) plt.show() curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
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, cy-2*h) } func lineS() { lineTo(cx, cy+2*h) } func lineE() { lineTo(cx+2*h, cy) } func lineW() { lineTo(cx-2*h, cy) } func lineNW() { lineTo(cx-h, cy-h) } func lineNE() { lineTo(cx+h, cy-h) } func lineSE() { lineTo(cx+h, cy+h) } func lineSW() { lineTo(cx-h, cy+h) } func sierN(level int) { if level == 1 { lineNE() lineN() lineNW() } else { sierN(level - 1) lineNE() sierE(level - 1) lineN() sierW(level - 1) lineNW() sierN(level - 1) } } func sierE(level int) { if level == 1 { lineSE() lineE() lineNE() } else { sierE(level - 1) lineSE() sierS(level - 1) lineE() sierN(level - 1) lineNE() sierE(level - 1) } } func sierS(level int) { if level == 1 { lineSW() lineS() lineSE() } else { sierS(level - 1) lineSW() sierW(level - 1) lineS() sierE(level - 1) lineSE() sierS(level - 1) } } func sierW(level int) { if level == 1 { lineNW() lineW() lineSW() } else { sierW(level - 1) lineNW() sierN(level - 1) lineW() sierS(level - 1) lineSW() sierW(level - 1) } } func squareCurve(level int) { sierN(level) lineNE() sierE(level) lineSE() sierS(level) lineSW() sierW(level) lineNW() lineNE() } func main() { dc.SetRGB(0, 0, 1) dc.Clear() level := 5 cx, cy = width/2, height h = cx / math.Pow(2, float64(level+1)) squareCurve(level) dc.SetRGB255(255, 255, 0) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_curve.png") }
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 '+': a += 1 case '-': a -= 1 case 'F' | 'G': x.append(x[-1] + np.cos(a*angle*np.pi/180)) y.append(y[-1] + np.sin(a*angle*np.pi/180)) l = len(x) for i in range(l - 1): plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7])) plt.gca().set_aspect(1) plt.show() curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
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, cy-2*h) } func lineS() { lineTo(cx, cy+2*h) } func lineE() { lineTo(cx+2*h, cy) } func lineW() { lineTo(cx-2*h, cy) } func lineNW() { lineTo(cx-h, cy-h) } func lineNE() { lineTo(cx+h, cy-h) } func lineSE() { lineTo(cx+h, cy+h) } func lineSW() { lineTo(cx-h, cy+h) } func sierN(level int) { if level == 1 { lineNE() lineN() lineNW() } else { sierN(level - 1) lineNE() sierE(level - 1) lineN() sierW(level - 1) lineNW() sierN(level - 1) } } func sierE(level int) { if level == 1 { lineSE() lineE() lineNE() } else { sierE(level - 1) lineSE() sierS(level - 1) lineE() sierN(level - 1) lineNE() sierE(level - 1) } } func sierS(level int) { if level == 1 { lineSW() lineS() lineSE() } else { sierS(level - 1) lineSW() sierW(level - 1) lineS() sierE(level - 1) lineSE() sierS(level - 1) } } func sierW(level int) { if level == 1 { lineNW() lineW() lineSW() } else { sierW(level - 1) lineNW() sierN(level - 1) lineW() sierS(level - 1) lineSW() sierW(level - 1) } } func squareCurve(level int) { sierN(level) lineNE() sierE(level) lineSE() sierS(level) lineSW() sierW(level) lineNW() lineNE() } func main() { dc.SetRGB(0, 0, 1) dc.Clear() level := 5 cx, cy = width/2, height h = cx / math.Pow(2, float64(level+1)) squareCurve(level) dc.SetRGB255(255, 255, 0) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_curve.png") }
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 def MostFreqKSimilarity(inputStr1, inputStr2): similarity = 0 for i in range(0, len(inputStr1), 2): c = inputStr1[i] cnt1 = int(inputStr1[i + 1]) for j in range(0, len(inputStr2), 2): if inputStr2[j] == c: cnt2 = int(inputStr2[j + 1]) similarity += cnt1 + cnt2 break return similarity def MostFreqKSDF(inputStr1, inputStr2, K, maxDistance): return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))
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) int { for i, cf := range cfs { if cf.c == r { return i } } return -1 } func minOf(i, j int) int { if i < j { return i } return j } func mostFreqKHashing(input string, k int) string { var cfs []cf for _, r := range input { ix := indexOfCf(cfs, r) if ix >= 0 { cfs[ix].f++ } else { cfs = append(cfs, cf{r, 1}) } } sort.SliceStable(cfs, func(i, j int) bool { return cfs[i].f > cfs[j].f }) acc := "" min := minOf(len(cfs), k) for _, cf := range cfs[:min] { acc += fmt.Sprintf("%c%c", cf.c, cf.f) } return acc } func mostFreqKSimilarity(input1, input2 string) int { similarity := 0 runes1, runes2 := []rune(input1), []rune(input2) for i := 0; i < len(runes1); i += 2 { for j := 0; j < len(runes2); j += 2 { if runes1[i] == runes2[j] { freq1, freq2 := runes1[i+1], runes2[j+1] if freq1 != freq2 { continue } similarity += int(freq1) } } } return similarity } func mostFreqKSDF(input1, input2 string, k, maxDistance int) { fmt.Println("input1 :", input1) fmt.Println("input2 :", input2) s1 := mostFreqKHashing(input1, k) s2 := mostFreqKHashing(input2, k) fmt.Printf("mfkh(input1, %d) = ", k) for i, c := range s1 { if i%2 == 0 { fmt.Printf("%c", c) } else { fmt.Printf("%d", c) } } fmt.Printf("\nmfkh(input2, %d) = ", k) for i, c := range s2 { if i%2 == 0 { fmt.Printf("%c", c) } else { fmt.Printf("%d", c) } } result := maxDistance - mostFreqKSimilarity(s1, s2) fmt.Printf("\nSDF(input1, input2, %d, %d) = %d\n\n", k, maxDistance, result) } func main() { pairs := [][2]string{ {"research", "seeking"}, {"night", "nacht"}, {"my", "a"}, {"research", "research"}, {"aaaaabbbb", "ababababa"}, {"significant", "capabilities"}, } for _, pair := range pairs { mostFreqKSDF(pair[0], pair[1], 2, 10) } s1 := "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV" s2 := "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG" mostFreqKSDF(s1, s2, 2, 100) s1 = "abracadabra12121212121abracadabra12121212121" s2 = reverseStr(s1) mostFreqKSDF(s1, s2, 2, 100) }
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 def MostFreqKSimilarity(inputStr1, inputStr2): similarity = 0 for i in range(0, len(inputStr1), 2): c = inputStr1[i] cnt1 = int(inputStr1[i + 1]) for j in range(0, len(inputStr2), 2): if inputStr2[j] == c: cnt2 = int(inputStr2[j + 1]) similarity += cnt1 + cnt2 break return similarity def MostFreqKSDF(inputStr1, inputStr2, K, maxDistance): return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))
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) int { for i, cf := range cfs { if cf.c == r { return i } } return -1 } func minOf(i, j int) int { if i < j { return i } return j } func mostFreqKHashing(input string, k int) string { var cfs []cf for _, r := range input { ix := indexOfCf(cfs, r) if ix >= 0 { cfs[ix].f++ } else { cfs = append(cfs, cf{r, 1}) } } sort.SliceStable(cfs, func(i, j int) bool { return cfs[i].f > cfs[j].f }) acc := "" min := minOf(len(cfs), k) for _, cf := range cfs[:min] { acc += fmt.Sprintf("%c%c", cf.c, cf.f) } return acc } func mostFreqKSimilarity(input1, input2 string) int { similarity := 0 runes1, runes2 := []rune(input1), []rune(input2) for i := 0; i < len(runes1); i += 2 { for j := 0; j < len(runes2); j += 2 { if runes1[i] == runes2[j] { freq1, freq2 := runes1[i+1], runes2[j+1] if freq1 != freq2 { continue } similarity += int(freq1) } } } return similarity } func mostFreqKSDF(input1, input2 string, k, maxDistance int) { fmt.Println("input1 :", input1) fmt.Println("input2 :", input2) s1 := mostFreqKHashing(input1, k) s2 := mostFreqKHashing(input2, k) fmt.Printf("mfkh(input1, %d) = ", k) for i, c := range s1 { if i%2 == 0 { fmt.Printf("%c", c) } else { fmt.Printf("%d", c) } } fmt.Printf("\nmfkh(input2, %d) = ", k) for i, c := range s2 { if i%2 == 0 { fmt.Printf("%c", c) } else { fmt.Printf("%d", c) } } result := maxDistance - mostFreqKSimilarity(s1, s2) fmt.Printf("\nSDF(input1, input2, %d, %d) = %d\n\n", k, maxDistance, result) } func main() { pairs := [][2]string{ {"research", "seeking"}, {"night", "nacht"}, {"my", "a"}, {"research", "research"}, {"aaaaabbbb", "ababababa"}, {"significant", "capabilities"}, } for _, pair := range pairs { mostFreqKSDF(pair[0], pair[1], 2, 10) } s1 := "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV" s2 := "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG" mostFreqKSDF(s1, s2, 2, 100) s1 = "abracadabra12121212121abracadabra12121212121" s2 = reverseStr(s1) mostFreqKSDF(s1, s2, 2, 100) }
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() ) )) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n if __name__ == '__main__': main()
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 = append(pals, p) } } fmt.Println("Palindromic primes under 1,000:") var smallPals, bigPals []int for _, p := range pals { if p < 1000 { smallPals = append(smallPals, p) } else { bigPals = append(bigPals, p) } } rcu.PrintTable(smallPals, 10, 3, false) fmt.Println() fmt.Println(len(smallPals), "such primes found.") fmt.Println("\nAdditional palindromic primes under 100,000:") rcu.PrintTable(bigPals, 10, 6, true) fmt.Println() fmt.Println(len(bigPals), "such primes found,", len(pals), "in all.") }
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() ) )) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n if __name__ == '__main__': main()
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 = append(pals, p) } } fmt.Println("Palindromic primes under 1,000:") var smallPals, bigPals []int for _, p := range pals { if p < 1000 { smallPals = append(smallPals, p) } else { bigPals = append(bigPals, p) } } rcu.PrintTable(smallPals, 10, 3, false) fmt.Println() fmt.Println(len(smallPals), "such primes found.") fmt.Println("\nAdditional palindromic primes under 100,000:") rcu.PrintTable(bigPals, 10, 6, true) fmt.Println() fmt.Println(len(bigPals), "such primes found,", len(pals), "in all.") }
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 = Counter(word.lower()) if frequency['a']==frequency['e']==frequency['i']==frequency['o']==frequency['u']==1: print(word)
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 := range bwords { s := string(bword) if utf8.RuneCountInString(s) > 10 { words = append(words, s) } } count := 0 fmt.Println("Words which contain all 5 vowels once in", wordList, "\b:\n") for _, word := range words { ca, ce, ci, co, cu := 0, 0, 0, 0, 0 for _, r := range word { switch r { case 'a': ca++ case 'e': ce++ case 'i': ci++ case 'o': co++ case 'u': cu++ } } if ca == 1 && ce == 1 && ci == 1 && co == 1 && cu == 1 { count++ fmt.Printf("%2d: %s\n", count, word) } } }
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__(self, other): assert other.x // 1 == other.x and other.x > 0, "Invalid Operation" return MaxTropical(self.x * other.x) def __eq__(self, other): return self.x == other.x if __name__ == "__main__": a = MaxTropical(-2) b = MaxTropical(-1) c = MaxTropical(-0.5) d = MaxTropical(-0.001) e = MaxTropical(0) f = MaxTropical(0.5) g = MaxTropical(1) h = MaxTropical(1.5) i = MaxTropical(2) j = MaxTropical(5) k = MaxTropical(7) l = MaxTropical(8) m = MaxTropical(-Inf) print("2 * -2 == ", i * a) print("-0.001 + -Inf == ", d + m) print("0 * -Inf == ", e * m) print("1.5 + -1 == ", h + b) print("-0.5 * 0 == ", c * e) print("5**7 == ", j**k) print("5 * (8 + 7)) == ", j * (l + k)) print("5 * 8 + 5 * 7 == ", j * l + j * k) print("5 * (8 + 7) == 5 * 8 + 5 * 7", j * (l + k) == j * l + j * k)
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} } func (t MaxTropical) eq(other MaxTropical) bool { return t.r == other.r } func (t MaxTropical) add(other MaxTropical) MaxTropical { if t.r == MinusInf { return other } if other.r == MinusInf { return t } return newMaxTropical(math.Max(t.r, other.r)) } func (t MaxTropical) mul(other MaxTropical) MaxTropical { if t.r == 0 { return other } if other.r == 0 { return t } return newMaxTropical(t.r + other.r) } func (t MaxTropical) pow(e int) MaxTropical { if e < 1 { log.Fatal("Exponent must be a positive integer.") } if e == 1 { return t } p := t for i := 2; i <= e; i++ { p = p.mul(t) } return p } func (t MaxTropical) String() string { return fmt.Sprintf("%g", t.r) } func main() { data := [][]float64{ {2, -2, 1}, {-0.001, MinusInf, 0}, {0, MinusInf, 1}, {1.5, -1, 0}, {-0.5, 0, 1}, } for _, d := range data { a := newMaxTropical(d[0]) b := newMaxTropical(d[1]) if d[2] == 0 { fmt.Printf("%s ⊕ %s = %s\n", a, b, a.add(b)) } else { fmt.Printf("%s ⊗ %s = %s\n", a, b, a.mul(b)) } } c := newMaxTropical(5) fmt.Printf("%s ^ 7 = %s\n", c, c.pow(7)) d := newMaxTropical(8) e := newMaxTropical(7) f := c.mul(d.add(e)) g := c.mul(d).add(c.mul(e)) fmt.Printf("%s ⊗ (%s ⊕ %s) = %s\n", c, d, e, f) fmt.Printf("%s ⊗ %s ⊕ %s ⊗ %s = %s\n", c, d, c, e, g) fmt.Printf("%s ⊗ (%s ⊕ %s) == %s ⊗ %s ⊕ %s ⊗ %s is %t\n", c, d, e, c, d, c, e, f.eq(g)) }
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 Player(): def __init__(self, player_index): self.player_index = player_index def __repr__(self): return '%s(%i)' % (self.__class__.__name__, self.player_index) def __call__(self, safescore, scores, game): 'Returns boolean True to roll again' pass class RandPlay(Player): def __call__(self, safe, scores, game): 'Returns random boolean choice of whether to roll again' return bool(random.randint(0, 1)) class RollTo20(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20' return (((sum(scores) + safe[self.player_index]) < maxscore) and(sum(scores) < 20)) class Desparat(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20 or someone is within 20 of winning' return (((sum(scores) + safe[self.player_index]) < maxscore) and( (sum(scores) < 20) or max(safe) >= (maxscore - 20))) def game__str__(self): 'Pretty printer for Game class' return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])" % (self.players, self.maxscore, ',\n '.join(repr(round) for round in self.rounds))) Game.__str__ = game__str__ def winningorder(players, safescores): 'Return (players in winning order, their scores)' return tuple(zip(*sorted(zip(players, safescores), key=lambda x: x[1], reverse=True))) def playpig(game): players, maxscore, rounds = game playercount = len(players) safescore = [0] * playercount player = 0 scores=[] while max(safescore) < maxscore: startscore = safescore[player] rolling = players[player](safescore, scores, game) if rolling: rolled = randint(1, 6) scores.append(rolled) if rolled == 1: round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) scores, player = [], (player + 1) % playercount else: safescore[player] += sum(scores) round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) if safescore[player] >= maxscore: break scores, player = [], (player + 1) % playercount return winningorder(players, safescore) if __name__ == '__main__': game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=20, rounds=[]) print('ONE GAME') print('Winning order: %r; Respective scores: %r\n' % playpig(game)) print(game) game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=maxscore, rounds=[]) algos = (RollTo20, RandPlay, Desparat) print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES' % (', '.join(p.__name__ for p in algos), maxgames,)) winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i) for i in range(playercount)), rounds=[]))[0]) for i in range(maxgames)) print(' Players(position) winning on left; occurrences on right:\n %s' % ',\n '.join(str(w) for w in winners.most_common()))
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 piggedOut rolls pointSpending holds turn gameOverSummary player1 = PlayerID(0) player2 = PlayerID(1) noPlayer = PlayerID(-1) maxScore = 100 scoreChaseStrat = iota rollCountStrat ) func pluralS(n int) string { if n != 1 { return "s" } return "" } func New() *PigGameData { return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false} } func (pg *PigGameData) statusMessage(id MessageID) string { var msg string switch id { case gameOver: msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount) case piggedOut: msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount)) case rolls: msg = fmt.Sprintf(" Rolls %d", pg.lastRoll) case pointSpending: msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore)) case holds: msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer)) case turn: msg = fmt.Sprintf("Player %d's turn:", pg.player+1) case gameOverSummary: msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2)) } return msg } func (pg *PigGameData) PrintStatus(id MessageID) { if pg.verbose { fmt.Println(pg.statusMessage(id)) } } func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) { if pg.GameOver() { pg.PrintStatus(gameOver) return false } if pg.turnCount == 0 { pg.player = player2 pg.NextPlayer() } pg.lastRoll = rand.Intn(6) + 1 pg.PrintStatus(rolls) pg.turnRollCount++ if pg.lastRoll == 1 { pg.PrintStatus(piggedOut) pg.NextPlayer() } else { pg.turnScore += pg.lastRoll pg.PrintStatus(pointSpending) success := false switch id { case scoreChaseStrat: success = pg.scoreChaseStrategy() case rollCountStrat: success = pg.rollCountStrategy() } if success { pg.Hold() pg.NextPlayer() } } return true } func (pg *PigGameData) PlayerScore(id PlayerID) int { if id == noPlayer { return pg.scores[pg.player] } return pg.scores[id] } func (pg *PigGameData) GameOver() bool { return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore } func (pg *PigGameData) Winner() PlayerID { for index, score := range pg.scores { if score >= maxScore { return PlayerID(index) } } return noPlayer } func (pg *PigGameData) otherPlayer() PlayerID { return 1 - pg.player } func (pg *PigGameData) Hold() { pg.scores[pg.player] += pg.turnScore pg.PrintStatus(holds) pg.turnRollCount, pg.turnScore = 0, 0 } func (pg *PigGameData) NextPlayer() { pg.turnCount++ pg.turnRollCount, pg.turnScore = 0, 0 pg.player = pg.otherPlayer() pg.PrintStatus(turn) } func (pg *PigGameData) rollCountStrategy() bool { return pg.turnRollCount >= 3 } func (pg *PigGameData) scoreChaseStrategy() bool { myScore := pg.PlayerScore(pg.player) otherScore := pg.PlayerScore(pg.otherPlayer()) myPendingScore := pg.turnScore + myScore return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5 } func main() { rand.Seed(time.Now().UnixNano()) pg := New() pg.verbose = true strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat} for !pg.GameOver() { pg.Play(strategies[pg.player]) } pg.PrintStatus(gameOverSummary) }
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 Player(): def __init__(self, player_index): self.player_index = player_index def __repr__(self): return '%s(%i)' % (self.__class__.__name__, self.player_index) def __call__(self, safescore, scores, game): 'Returns boolean True to roll again' pass class RandPlay(Player): def __call__(self, safe, scores, game): 'Returns random boolean choice of whether to roll again' return bool(random.randint(0, 1)) class RollTo20(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20' return (((sum(scores) + safe[self.player_index]) < maxscore) and(sum(scores) < 20)) class Desparat(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20 or someone is within 20 of winning' return (((sum(scores) + safe[self.player_index]) < maxscore) and( (sum(scores) < 20) or max(safe) >= (maxscore - 20))) def game__str__(self): 'Pretty printer for Game class' return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])" % (self.players, self.maxscore, ',\n '.join(repr(round) for round in self.rounds))) Game.__str__ = game__str__ def winningorder(players, safescores): 'Return (players in winning order, their scores)' return tuple(zip(*sorted(zip(players, safescores), key=lambda x: x[1], reverse=True))) def playpig(game): players, maxscore, rounds = game playercount = len(players) safescore = [0] * playercount player = 0 scores=[] while max(safescore) < maxscore: startscore = safescore[player] rolling = players[player](safescore, scores, game) if rolling: rolled = randint(1, 6) scores.append(rolled) if rolled == 1: round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) scores, player = [], (player + 1) % playercount else: safescore[player] += sum(scores) round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) if safescore[player] >= maxscore: break scores, player = [], (player + 1) % playercount return winningorder(players, safescore) if __name__ == '__main__': game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=20, rounds=[]) print('ONE GAME') print('Winning order: %r; Respective scores: %r\n' % playpig(game)) print(game) game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=maxscore, rounds=[]) algos = (RollTo20, RandPlay, Desparat) print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES' % (', '.join(p.__name__ for p in algos), maxgames,)) winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i) for i in range(playercount)), rounds=[]))[0]) for i in range(maxgames)) print(' Players(position) winning on left; occurrences on right:\n %s' % ',\n '.join(str(w) for w in winners.most_common()))
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 piggedOut rolls pointSpending holds turn gameOverSummary player1 = PlayerID(0) player2 = PlayerID(1) noPlayer = PlayerID(-1) maxScore = 100 scoreChaseStrat = iota rollCountStrat ) func pluralS(n int) string { if n != 1 { return "s" } return "" } func New() *PigGameData { return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false} } func (pg *PigGameData) statusMessage(id MessageID) string { var msg string switch id { case gameOver: msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount) case piggedOut: msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount)) case rolls: msg = fmt.Sprintf(" Rolls %d", pg.lastRoll) case pointSpending: msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore)) case holds: msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer)) case turn: msg = fmt.Sprintf("Player %d's turn:", pg.player+1) case gameOverSummary: msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2)) } return msg } func (pg *PigGameData) PrintStatus(id MessageID) { if pg.verbose { fmt.Println(pg.statusMessage(id)) } } func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) { if pg.GameOver() { pg.PrintStatus(gameOver) return false } if pg.turnCount == 0 { pg.player = player2 pg.NextPlayer() } pg.lastRoll = rand.Intn(6) + 1 pg.PrintStatus(rolls) pg.turnRollCount++ if pg.lastRoll == 1 { pg.PrintStatus(piggedOut) pg.NextPlayer() } else { pg.turnScore += pg.lastRoll pg.PrintStatus(pointSpending) success := false switch id { case scoreChaseStrat: success = pg.scoreChaseStrategy() case rollCountStrat: success = pg.rollCountStrategy() } if success { pg.Hold() pg.NextPlayer() } } return true } func (pg *PigGameData) PlayerScore(id PlayerID) int { if id == noPlayer { return pg.scores[pg.player] } return pg.scores[id] } func (pg *PigGameData) GameOver() bool { return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore } func (pg *PigGameData) Winner() PlayerID { for index, score := range pg.scores { if score >= maxScore { return PlayerID(index) } } return noPlayer } func (pg *PigGameData) otherPlayer() PlayerID { return 1 - pg.player } func (pg *PigGameData) Hold() { pg.scores[pg.player] += pg.turnScore pg.PrintStatus(holds) pg.turnRollCount, pg.turnScore = 0, 0 } func (pg *PigGameData) NextPlayer() { pg.turnCount++ pg.turnRollCount, pg.turnScore = 0, 0 pg.player = pg.otherPlayer() pg.PrintStatus(turn) } func (pg *PigGameData) rollCountStrategy() bool { return pg.turnRollCount >= 3 } func (pg *PigGameData) scoreChaseStrategy() bool { myScore := pg.PlayerScore(pg.player) otherScore := pg.PlayerScore(pg.otherPlayer()) myPendingScore := pg.turnScore + myScore return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5 } func main() { rand.Seed(time.Now().UnixNano()) pg := New() pg.verbose = true strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat} for !pg.GameOver() { pg.Play(strategies[pg.player]) } pg.PrintStatus(gameOverSummary) }
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)[::-1]) def split_roots_from_relateds(roots_and_relateds): roots = roots_and_relateds[::] i = 1 while i < len(roots): this = roots[i] if any(this.intersection(prev) for prev in roots[:i]): del roots[i] else: i += 1 root = [min(each_set) for each_set in roots] related = [min(each_set) for each_set in roots_and_relateds] related = [n for n in related if n not in root] return root, related def find_lychrel(maxn, max_reversions): 'Lychrel number generator' series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)] roots_and_relateds = [s for s in series if len(s) > max_reversions] return split_roots_from_relateds(roots_and_relateds) if __name__ == '__main__': maxn, reversion_limit = 10000, 500 print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds" % (maxn, reversion_limit)) lychrel, l_related = find_lychrel(maxn, reversion_limit) print(' Number of Lychrel numbers:', len(lychrel)) print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel)) print(' Number of Lychrel related:', len(l_related)) pals = [x for x in lychrel + l_related if x == reverse_int(x)] print(' Number of Lychrel palindromes:', len(pals)) print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
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(v.String()) result.SetString(s, 10) } else { v := new(big.Int).Set(v) digit := new(big.Int) result.SetUint64(0) for v.BitLen() > 0 { v.QuoRem(v, ten, digit) result.Mul(result, ten) result.Add(result, digit) } } } return result } func reverseUint64(v uint64) uint64 { var r uint64 for v > 0 { r *= 10 r += v % 10 v /= 10 } return r } func reverseString(s string) string { b := make([]byte, len(s)) for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 { b[i] = s[j] } return string(b) } var known = make(map[string]bool) func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) { v, r := new(big.Int).SetUint64(n), new(big.Int) reverseInt(v, r) seen := make(map[string]bool) isLychrel = true isSeed = true for i := iter; i > 0; i-- { str := v.String() if seen[str] { isLychrel = true break } if ans, ok := known[str]; ok { isLychrel = ans isSeed = false break } seen[str] = true v = v.Add(v, r) reverseInt(v, r) if v.Cmp(r) == 0 { isLychrel = false isSeed = false break } } for k := range seen { known[k] = isLychrel } return isLychrel, isSeed } func main() { max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive") iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter) var seeds []uint64 var related int var pals []uint64 for i := uint64(1); i <= *max; i++ { if l, s := Lychrel(i, *iter); l { if s { seeds = append(seeds, i) } else { related++ } if i == reverseUint64(i) { pals = append(pals, i) } } } fmt.Println(" Number of Lychrel seeds:", len(seeds)) fmt.Println(" Lychrel seeds:", seeds) fmt.Println(" Number of related:", related) fmt.Println("Number of Lychrel palindromes:", len(pals)) fmt.Println(" Lychrel palindromes:", pals) }
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)[::-1]) def split_roots_from_relateds(roots_and_relateds): roots = roots_and_relateds[::] i = 1 while i < len(roots): this = roots[i] if any(this.intersection(prev) for prev in roots[:i]): del roots[i] else: i += 1 root = [min(each_set) for each_set in roots] related = [min(each_set) for each_set in roots_and_relateds] related = [n for n in related if n not in root] return root, related def find_lychrel(maxn, max_reversions): 'Lychrel number generator' series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)] roots_and_relateds = [s for s in series if len(s) > max_reversions] return split_roots_from_relateds(roots_and_relateds) if __name__ == '__main__': maxn, reversion_limit = 10000, 500 print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds" % (maxn, reversion_limit)) lychrel, l_related = find_lychrel(maxn, reversion_limit) print(' Number of Lychrel numbers:', len(lychrel)) print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel)) print(' Number of Lychrel related:', len(l_related)) pals = [x for x in lychrel + l_related if x == reverse_int(x)] print(' Number of Lychrel palindromes:', len(pals)) print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
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(v.String()) result.SetString(s, 10) } else { v := new(big.Int).Set(v) digit := new(big.Int) result.SetUint64(0) for v.BitLen() > 0 { v.QuoRem(v, ten, digit) result.Mul(result, ten) result.Add(result, digit) } } } return result } func reverseUint64(v uint64) uint64 { var r uint64 for v > 0 { r *= 10 r += v % 10 v /= 10 } return r } func reverseString(s string) string { b := make([]byte, len(s)) for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 { b[i] = s[j] } return string(b) } var known = make(map[string]bool) func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) { v, r := new(big.Int).SetUint64(n), new(big.Int) reverseInt(v, r) seen := make(map[string]bool) isLychrel = true isSeed = true for i := iter; i > 0; i-- { str := v.String() if seen[str] { isLychrel = true break } if ans, ok := known[str]; ok { isLychrel = ans isSeed = false break } seen[str] = true v = v.Add(v, r) reverseInt(v, r) if v.Cmp(r) == 0 { isLychrel = false isSeed = false break } } for k := range seen { known[k] = isLychrel } return isLychrel, isSeed } func main() { max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive") iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter) var seeds []uint64 var related int var pals []uint64 for i := uint64(1); i <= *max; i++ { if l, s := Lychrel(i, *iter); l { if s { seeds = append(seeds, i) } else { related++ } if i == reverseUint64(i) { pals = append(pals, i) } } } fmt.Println(" Number of Lychrel seeds:", len(seeds)) fmt.Println(" Lychrel seeds:", seeds) fmt.Println(" Number of related:", related) fmt.Println("Number of Lychrel palindromes:", len(pals)) fmt.Println(" Lychrel palindromes:", pals) }
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)[::-1]) def split_roots_from_relateds(roots_and_relateds): roots = roots_and_relateds[::] i = 1 while i < len(roots): this = roots[i] if any(this.intersection(prev) for prev in roots[:i]): del roots[i] else: i += 1 root = [min(each_set) for each_set in roots] related = [min(each_set) for each_set in roots_and_relateds] related = [n for n in related if n not in root] return root, related def find_lychrel(maxn, max_reversions): 'Lychrel number generator' series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)] roots_and_relateds = [s for s in series if len(s) > max_reversions] return split_roots_from_relateds(roots_and_relateds) if __name__ == '__main__': maxn, reversion_limit = 10000, 500 print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds" % (maxn, reversion_limit)) lychrel, l_related = find_lychrel(maxn, reversion_limit) print(' Number of Lychrel numbers:', len(lychrel)) print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel)) print(' Number of Lychrel related:', len(l_related)) pals = [x for x in lychrel + l_related if x == reverse_int(x)] print(' Number of Lychrel palindromes:', len(pals)) print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
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(v.String()) result.SetString(s, 10) } else { v := new(big.Int).Set(v) digit := new(big.Int) result.SetUint64(0) for v.BitLen() > 0 { v.QuoRem(v, ten, digit) result.Mul(result, ten) result.Add(result, digit) } } } return result } func reverseUint64(v uint64) uint64 { var r uint64 for v > 0 { r *= 10 r += v % 10 v /= 10 } return r } func reverseString(s string) string { b := make([]byte, len(s)) for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 { b[i] = s[j] } return string(b) } var known = make(map[string]bool) func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) { v, r := new(big.Int).SetUint64(n), new(big.Int) reverseInt(v, r) seen := make(map[string]bool) isLychrel = true isSeed = true for i := iter; i > 0; i-- { str := v.String() if seen[str] { isLychrel = true break } if ans, ok := known[str]; ok { isLychrel = ans isSeed = false break } seen[str] = true v = v.Add(v, r) reverseInt(v, r) if v.Cmp(r) == 0 { isLychrel = false isSeed = false break } } for k := range seen { known[k] = isLychrel } return isLychrel, isSeed } func main() { max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive") iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter) var seeds []uint64 var related int var pals []uint64 for i := uint64(1); i <= *max; i++ { if l, s := Lychrel(i, *iter); l { if s { seeds = append(seeds, i) } else { related++ } if i == reverseUint64(i) { pals = append(pals, i) } } } fmt.Println(" Number of Lychrel seeds:", len(seeds)) fmt.Println(" Lychrel seeds:", seeds) fmt.Println(" Number of related:", related) fmt.Println("Number of Lychrel palindromes:", len(pals)) fmt.Println(" Lychrel palindromes:", pals) }
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 ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
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 == 0 { fmt.Println() } } } fmt.Printf("\n\n%d such numbers found.\n", c) }
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 ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
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 == 0 { fmt.Println() } } } fmt.Printf("\n\n%d such numbers found.\n", c) }
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().split(',') if r] def remove(self, rem): ranges = self.ranges for i, r in enumerate(ranges): if r[0] <= rem <= r[1]: if r[0] == rem: if r[1] > rem: r[0] += 1 else: del ranges[i] elif r[1] == rem: if r[0] < rem: r[1] -= 1 else: del ranges[i] else: r[1], splitrange = rem - 1, [rem + 1, r[1]] ranges.insert(i + 1, splitrange) break if r[0] > rem: break return self def add(self, add): ranges = self.ranges for i, r in enumerate(ranges): if r[0] <= add <= r[1]: break elif r[0] - 1 == add: r[0] = add break elif r[1] + 1 == add: r[1] = add break elif r[0] > add: ranges.insert(i, [add, add]) break else: ranges.append([add, add]) return self return self.consolidate() def consolidate(self): "Combine overlapping ranges" ranges = self.ranges for this, that in zip(ranges, ranges[1:]): if this[1] + 1 >= that[0]: if this[1] >= that[1]: this[:], that[:] = [], this else: this[:], that[:] = [], [this[0], that[1]] ranges[:] = [r for r in ranges if r] return self def __repr__(self): rr = self.ranges return ",".join(f"{r[0]}-{r[1]}" for r in rr) def demo(opp_txt): by_line = opp_txt.strip().split('\n') start = by_line.pop(0) ex = Sequence(start.strip().split()[-1][1:-1]) lines = [line.strip().split() for line in by_line] opps = [((ex.add if word[0] == "add" else ex.remove), int(word[1])) for word in lines] print(f"Start: \"{ex}\"") for op, val in opps: print(f" {op.__name__:>6} {val:2} => {op(val)}") print() if __name__ == '__main__': demo() demo() demo()
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 } for i, r := range rngs { if n < r.from-1 { rngs = append(rngs, rng{}) copy(rngs[i+1:], rngs[i:]) rngs[i] = rng{n, n} return rngs } else if n == r.from-1 { rngs[i] = rng{n, r.to} return rngs } else if n <= r.to { return rngs } else if n == r.to+1 { rngs[i] = rng{r.from, n} if i < len(rngs)-1 && (n == rngs[i+1].from || n+1 == rngs[i+1].from) { rngs[i] = rng{r.from, rngs[i+1].to} copy(rngs[i+1:], rngs[i+2:]) rngs[len(rngs)-1] = rng{} rngs = rngs[:len(rngs)-1] } return rngs } else if i == len(rngs)-1 { rngs = append(rngs, rng{n, n}) return rngs } } return rngs } func rangesRemove(rngs []rng, n int) []rng { if len(rngs) == 0 { return rngs } for i, r := range rngs { if n <= r.from-1 { return rngs } else if n == r.from && n == r.to { copy(rngs[i:], rngs[i+1:]) rngs[len(rngs)-1] = rng{} rngs = rngs[:len(rngs)-1] return rngs } else if n == r.from { rngs[i] = rng{n + 1, r.to} return rngs } else if n < r.to { rngs[i] = rng{r.from, n - 1} rngs = append(rngs, rng{}) copy(rngs[i+2:], rngs[i+1:]) rngs[i+1] = rng{n + 1, r.to} return rngs } else if n == r.to { rngs[i] = rng{r.from, n - 1} return rngs } } return rngs } func standard(rngs []rng) string { if len(rngs) == 0 { return "" } var sb strings.Builder for _, r := range rngs { sb.WriteString(fmt.Sprintf("%s,", r)) } s := sb.String() return s[:len(s)-1] } func main() { const add = 0 const remove = 1 fns := []fn{ func(prngs *[]rng, n int) { *prngs = rangesAdd(*prngs, n) fmt.Printf(" add %2d => %s\n", n, standard(*prngs)) }, func(prngs *[]rng, n int) { *prngs = rangesRemove(*prngs, n) fmt.Printf(" remove %2d => %s\n", n, standard(*prngs)) }, } var rngs []rng ops := [][2]int{{add, 77}, {add, 79}, {add, 78}, {remove, 77}, {remove, 78}, {remove, 79}} fmt.Printf("Start: %q\n", standard(rngs)) for _, op := range ops { fns[op[0]](&rngs, op[1]) } rngs = []rng{{1, 3}, {5, 5}} ops = [][2]int{{add, 1}, {remove, 4}, {add, 7}, {add, 8}, {add, 6}, {remove, 7}} fmt.Printf("\nStart: %q\n", standard(rngs)) for _, op := range ops { fns[op[0]](&rngs, op[1]) } rngs = []rng{{1, 5}, {10, 25}, {27, 30}} ops = [][2]int{{add, 26}, {add, 9}, {add, 7}, {remove, 26}, {remove, 9}, {remove, 7}} fmt.Printf("\nStart: %q\n", standard(rngs)) for _, op := range ops { fns[op[0]](&rngs, op[1]) } }
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(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}") return i print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations") print(" n l(n) i(n) h(n) or d(n)\n-------------------------------------------") for k in range(20, 40): juggler(k, False) for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]: juggler(k)
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 maxCount := 0 a := big.NewInt(n) max := big.NewInt(n) tmp := new(big.Int) for a.Cmp(one) != 0 { if tmp.Rem(a, two).Cmp(zero) == 0 { a.Sqrt(a) } else { tmp.Mul(a, a) tmp.Mul(tmp, a) a.Sqrt(tmp) } count++ if a.Cmp(max) > 0 { max.Set(a) maxCount = count } } return count, maxCount, max, len(max.String()) } func main() { fmt.Println("n l[n] i[n] h[n]") fmt.Println("-----------------------------------") for n := int64(20); n < 40; n++ { count, maxCount, max, _ := juggler(n) cmax := rcu.Commatize(int(max.Int64())) fmt.Printf("%2d %2d %2d %s\n", n, count, maxCount, cmax) } fmt.Println() nums := []int64{ 113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963, } fmt.Println(" n l[n] i[n] d[n]") fmt.Println("-------------------------------------") for _, n := range nums { count, maxCount, _, digits := juggler(n) cn := rcu.Commatize(int(n)) fmt.Printf("%11s %3d %3d %s\n", cn, count, maxCount, rcu.Commatize(digits)) } }
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(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}") return i print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations") print(" n l(n) i(n) h(n) or d(n)\n-------------------------------------------") for k in range(20, 40): juggler(k, False) for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]: juggler(k)
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 maxCount := 0 a := big.NewInt(n) max := big.NewInt(n) tmp := new(big.Int) for a.Cmp(one) != 0 { if tmp.Rem(a, two).Cmp(zero) == 0 { a.Sqrt(a) } else { tmp.Mul(a, a) tmp.Mul(tmp, a) a.Sqrt(tmp) } count++ if a.Cmp(max) > 0 { max.Set(a) maxCount = count } } return count, maxCount, max, len(max.String()) } func main() { fmt.Println("n l[n] i[n] h[n]") fmt.Println("-----------------------------------") for n := int64(20); n < 40; n++ { count, maxCount, max, _ := juggler(n) cmax := rcu.Commatize(int(max.Int64())) fmt.Printf("%2d %2d %2d %s\n", n, count, maxCount, cmax) } fmt.Println() nums := []int64{ 113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963, } fmt.Println(" n l[n] i[n] d[n]") fmt.Println("-------------------------------------") for _, n := range nums { count, maxCount, _, digits := juggler(n) cn := rcu.Commatize(int(n)) fmt.Printf("%11s %3d %3d %s\n", cn, count, maxCount, rcu.Commatize(digits)) } }
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: if c in rules: a2 += rules[c] else: a2 += c axiom = a2 return axiom def draw_lsystem(axiom, rules, angle, iterations): xp = [1] yp = [1] direction = 0 for c in expand(axiom, rules, iterations): if c == "F": xn, yn = nextPoint(xp[-1], yp[-1], direction) xp.append(xn) yp.append(yn) elif c == "-": direction = direction - angle if direction < 0: direction = 360 + direction elif c == "+": direction = (direction + angle) % 360 plt.plot(xp, yp) plt.show() if __name__ == '__main__': s_axiom = "F+XF+F+XF" s_rules = {"X": "XF-F+F-XF+F+XF-F+F-X"} s_angle = 90 draw_lsystem(s_axiom, s_rules, s_angle, 3)
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.Clear() cx, cy = 10, height/2+5 h = 6 sys := lindenmayer.Lsystem{ Variables: []rune{'X'}, Constants: []rune{'F', '+', '-'}, Axiom: "F+XF+F+XF", Rules: []lindenmayer.Rule{ {"X", "XF-F+F-XF+F+XF-F+F-X"}, }, Angle: math.Pi / 2, } result := lindenmayer.Iterate(&sys, 5) operations := map[rune]func(){ 'F': func() { newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta) dc.LineTo(newX, newY) cx, cy = newX, newY }, '+': func() { theta = math.Mod(theta+sys.Angle, twoPi) }, '-': func() { theta = math.Mod(theta-sys.Angle, twoPi) }, } if err := lindenmayer.Process(result, operations); err != nil { log.Fatal(err) } operations['+']() operations['F']() dc.SetRGB255(255, 255, 0) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_square_curve.png") }
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)) return res def kpowerful(k, upper_bound, count_only=True): ps = primepowers(k, upper_bound) def accu(i, ub): c = 0 if count_only else [] for p in ps[i]: u = ub//p if not u: break c += 1 if count_only else [p] for j in range(i + 1, len(ps)): if u < ps[j][0]: break c += accu(j, u) if count_only else [p*x for x in accu(j, u)] return c res = accu(0, upper_bound) return res if count_only else sorted(res) for k in range(2, 11): res = kpowerful(k, 10**k, count_only=False) print(f'{len(res)} {k}-powerfuls up to 10^{k}:', ' '.join(str(x) for x in res[:5]), '...', ' '.join(str(x) for x in res[-5:]) ) for k in range(2, 11): res = [kpowerful(k, 10**n) for n in range(k+10)] print(f'{k}-powerful up to 10^{k+10}:', ' '.join(str(x) for x in res))
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 uint64) bool { for _, p := range primes { p2 := p * p if p2 > x { break } if x%p2 == 0 { return false } } return true } func iroot(x, p uint64) uint64 { return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj) } func ipow(x, p uint64) uint64 { prod := uint64(1) for p > 0 { if p&1 != 0 { prod *= x } p >>= 1 x *= x } return prod } func powerful(n, k uint64) []uint64 { set := make(map[uint64]bool) var f func(m, r uint64) f = func(m, r uint64) { if r < k { set[m] = true return } for v := uint64(1); v <= iroot(n/m, r); v++ { if r > k { if !isSquareFree(v) || gcd(m, v) != 1 { continue } } f(m*ipow(v, r), r-1) } } f(1, (1<<k)-1) list := make([]uint64, 0, len(set)) for key := range set { list = append(list, key) } sort.Slice(list, func(i, j int) bool { return list[i] < list[j] }) return list } func main() { power := uint64(10) for k := uint64(2); k <= 10; k++ { power *= 10 a := powerful(power, k) le := len(a) h, t := a[0:5], a[le-5:] fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t) } fmt.Println() for k := uint64(2); k <= 10; k++ { power := uint64(1) var counts []int for j := uint64(0); j < k+10; j++ { a := powerful(power, k) counts = append(counts, len(a)) power *= 10 } j := k + 10 fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts) } }
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)) return res def kpowerful(k, upper_bound, count_only=True): ps = primepowers(k, upper_bound) def accu(i, ub): c = 0 if count_only else [] for p in ps[i]: u = ub//p if not u: break c += 1 if count_only else [p] for j in range(i + 1, len(ps)): if u < ps[j][0]: break c += accu(j, u) if count_only else [p*x for x in accu(j, u)] return c res = accu(0, upper_bound) return res if count_only else sorted(res) for k in range(2, 11): res = kpowerful(k, 10**k, count_only=False) print(f'{len(res)} {k}-powerfuls up to 10^{k}:', ' '.join(str(x) for x in res[:5]), '...', ' '.join(str(x) for x in res[-5:]) ) for k in range(2, 11): res = [kpowerful(k, 10**n) for n in range(k+10)] print(f'{k}-powerful up to 10^{k+10}:', ' '.join(str(x) for x in res))
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 uint64) bool { for _, p := range primes { p2 := p * p if p2 > x { break } if x%p2 == 0 { return false } } return true } func iroot(x, p uint64) uint64 { return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj) } func ipow(x, p uint64) uint64 { prod := uint64(1) for p > 0 { if p&1 != 0 { prod *= x } p >>= 1 x *= x } return prod } func powerful(n, k uint64) []uint64 { set := make(map[uint64]bool) var f func(m, r uint64) f = func(m, r uint64) { if r < k { set[m] = true return } for v := uint64(1); v <= iroot(n/m, r); v++ { if r > k { if !isSquareFree(v) || gcd(m, v) != 1 { continue } } f(m*ipow(v, r), r-1) } } f(1, (1<<k)-1) list := make([]uint64, 0, len(set)) for key := range set { list = append(list, key) } sort.Slice(list, func(i, j int) bool { return list[i] < list[j] }) return list } func main() { power := uint64(10) for k := uint64(2); k <= 10; k++ { power *= 10 a := powerful(power, k) le := len(a) h, t := a[0:5], a[le-5:] fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t) } fmt.Println() for k := uint64(2); k <= 10; k++ { power := uint64(1) var counts []int for j := uint64(0); j < k+10; j++ { a := powerful(power, k) counts = append(counts, len(a)) power *= 10 } j := k + 10 fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts) } }
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 := os.Open("infile.dat") check(err) defer in.Close() out, err := os.Create("outfile.dat") check(err) record := make([]byte, 80) empty := make([]byte, 80) for { n, err := in.Read(record) if err != nil { if n == 0 { break } else { out.Close() log.Fatal(err) } } reverseBytes(record) out.Write(record) copy(record, empty) } out.Close() cmd := exec.Command("dd", "if=outfile.dat", "cbs=80", "conv=unblock") bytes, err := cmd.Output() check(err) fmt.Println(string(bytes)) }
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(word)
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 bwords { s := string(bword) if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) { count++ fmt.Printf("%d: %s\n", count, s) } } }
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: return False if __name__ == '__main__': n = 3 c = 0 print("The first 4 Giuga numbers are: ") while c < 4: if isGiuga(n): c += 1 print(n) n += 1
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 = 3 factors = append(factors, 3) n /= 3 } for n%5 == 0 { if last == 5 { factors = factors[:0] return } last = 5 factors = append(factors, 5) n /= 5 } for k, i := 7, 0; k*k <= n; { if n%k == 0 { if last == k { factors = factors[:0] return } last = k factors = append(factors, k) n /= k } else { k += inc[i] i = (i + 1) % 8 } } if n > 1 { factors = append(factors, n) } } func main() { const limit = 5 var giuga []int for n := 6; len(giuga) < limit; n += 4 { primeFactors(n) if len(factors) > 2 { isGiuga := true for _, f := range factors { if (n/f-1)%f != 0 { isGiuga = false break } } if isGiuga { giuga = append(giuga, n) } } } fmt.Println("The first", limit, "Giuga numbers are:") fmt.Println(giuga) }
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 = out[i] if coef != 0: for j in xrange(1, len(divisor)): out[i + j] += -divisor[j] * coef separator = -(len(divisor)-1) return out[:separator], out[separator:] if __name__ == '__main__': print("POLYNOMIAL SYNTHETIC DIVISION") N = [1, -12, 0, -42] D = [1, -3] print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
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(out[i], divisor[0]) if coef := out[i]; coef.Sign() != 0 { var a big.Rat for j := 1; j < len(divisor); j++ { out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef)) } } } separator := len(out) - (len(divisor) - 1) return out[:separator], out[separator:] } func main() { N := []*big.Rat{ big.NewRat(1, 1), big.NewRat(-12, 1), big.NewRat(0, 1), big.NewRat(-42, 1)} D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)} Q, R := div(N, D) fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R) }
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 = out[i] if coef != 0: for j in xrange(1, len(divisor)): out[i + j] += -divisor[j] * coef separator = -(len(divisor)-1) return out[:separator], out[separator:] if __name__ == '__main__': print("POLYNOMIAL SYNTHETIC DIVISION") N = [1, -12, 0, -42] D = [1, -3] print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
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(out[i], divisor[0]) if coef := out[i]; coef.Sign() != 0 { var a big.Rat for j := 1; j < len(divisor); j++ { out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef)) } } } separator := len(out) - (len(divisor) - 1) return out[:separator], out[separator:] } func main() { N := []*big.Rat{ big.NewRat(1, 1), big.NewRat(-12, 1), big.NewRat(0, 1), big.NewRat(-42, 1)} D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)} Q, R := div(N, D) fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R) }
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: oddWordSet.add(word[::2]) [print(i) for i in sorted(oddWordSet)]
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)) for i, bword := range bwords { words[i] = string(bword) } count := 0 fmt.Println("The odd words with length > 4 in", wordList, "are:") for _, word := range words { rword := []rune(word) if len(rword) > 8 { var sb strings.Builder for i := 0; i < len(rword); i += 2 { sb.WriteRune(rword[i]) } s := sb.String() idx := sort.SearchStrings(words, s) if idx < len(words) && words[idx] == s { count = count + 1 fmt.Printf("%2d: %-12s -> %s\n", count, word, s) } } } }
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: oddWordSet.add(word[::2]) [print(i) for i in sorted(oddWordSet)]
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)) for i, bword := range bwords { words[i] = string(bword) } count := 0 fmt.Println("The odd words with length > 4 in", wordList, "are:") for _, word := range words { rword := []rune(word) if len(rword) > 8 { var sb strings.Builder for i := 0; i < len(rword); i += 2 { sb.WriteRune(rword[i]) } s := sb.String() idx := sort.SearchStrings(words, s) if idx < len(words) && words[idx] == s { count = count + 1 fmt.Printf("%2d: %-12s -> %s\n", count, word, s) } } } }
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: level = [] while lst: d, name = lst[0] if d == depth: children = [] level.append((name, children)) lst.pop(0) elif d > depth: to_nest(lst, d, children) elif d < depth: return return level[0] if level else None if __name__ == '__main__': print('Start Nest format:') nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), ('mocks', [('trolling', [])])]) pp(nest, width=25) print('\n... To Indent format:') as_ind = to_indent(nest) pp(as_ind, width=25) print('\n... To Nest format:') as_nest = to_nest(as_ind) pp(as_nest, width=25) if nest != as_nest: print("Whoops round-trip issues")
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.Fprintf(w, "%s%s\n", strings.Repeat(" ", level), n.name) for _, c := range n.children { fmt.Fprintf(w, "%s", strings.Repeat(" ", level+1)) printNest(c, level+1, w) } } func toNest(iNodes []iNode, start, level int, n *nNode) { if level == 0 { n.name = iNodes[0].name } for i := start + 1; i < len(iNodes); i++ { if iNodes[i].level == level+1 { c := nNode{iNodes[i].name, nil} toNest(iNodes, i, level+1, &c) n.children = append(n.children, c) } else if iNodes[i].level <= level { return } } } func printIndent(iNodes []iNode, w io.Writer) { fmt.Fprintln(w, "\n==Indent form==\n") for _, n := range iNodes { fmt.Fprintf(w, "%d %s\n", n.level, n.name) } } func toIndent(n nNode, level int, iNodes *[]iNode) { *iNodes = append(*iNodes, iNode{level, n.name}) for _, c := range n.children { toIndent(c, level+1, iNodes) } } func main() { n1 := nNode{"RosettaCode", nil} n2 := nNode{"rocks", []nNode{{"code", nil}, {"comparison", nil}, {"wiki", nil}}} n3 := nNode{"mocks", []nNode{{"trolling", nil}}} n1.children = append(n1.children, n2, n3) var sb strings.Builder printNest(n1, 0, &sb) s1 := sb.String() fmt.Print(s1) var iNodes []iNode toIndent(n1, 0, &iNodes) printIndent(iNodes, os.Stdout) var n nNode toNest(iNodes, 0, 0, &n) sb.Reset() printNest(n, 0, &sb) s2 := sb.String() fmt.Print(s2) fmt.Println("\nRound trip test satisfied? ", s1 == s2) }
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: level = [] while lst: d, name = lst[0] if d == depth: children = [] level.append((name, children)) lst.pop(0) elif d > depth: to_nest(lst, d, children) elif d < depth: return return level[0] if level else None if __name__ == '__main__': print('Start Nest format:') nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), ('mocks', [('trolling', [])])]) pp(nest, width=25) print('\n... To Indent format:') as_ind = to_indent(nest) pp(as_ind, width=25) print('\n... To Nest format:') as_nest = to_nest(as_ind) pp(as_nest, width=25) if nest != as_nest: print("Whoops round-trip issues")
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.Fprintf(w, "%s%s\n", strings.Repeat(" ", level), n.name) for _, c := range n.children { fmt.Fprintf(w, "%s", strings.Repeat(" ", level+1)) printNest(c, level+1, w) } } func toNest(iNodes []iNode, start, level int, n *nNode) { if level == 0 { n.name = iNodes[0].name } for i := start + 1; i < len(iNodes); i++ { if iNodes[i].level == level+1 { c := nNode{iNodes[i].name, nil} toNest(iNodes, i, level+1, &c) n.children = append(n.children, c) } else if iNodes[i].level <= level { return } } } func printIndent(iNodes []iNode, w io.Writer) { fmt.Fprintln(w, "\n==Indent form==\n") for _, n := range iNodes { fmt.Fprintf(w, "%d %s\n", n.level, n.name) } } func toIndent(n nNode, level int, iNodes *[]iNode) { *iNodes = append(*iNodes, iNode{level, n.name}) for _, c := range n.children { toIndent(c, level+1, iNodes) } } func main() { n1 := nNode{"RosettaCode", nil} n2 := nNode{"rocks", []nNode{{"code", nil}, {"comparison", nil}, {"wiki", nil}}} n3 := nNode{"mocks", []nNode{{"trolling", nil}}} n1.children = append(n1.children, n2, n3) var sb strings.Builder printNest(n1, 0, &sb) s1 := sb.String() fmt.Print(s1) var iNodes []iNode toIndent(n1, 0, &iNodes) printIndent(iNodes, os.Stdout) var n nNode toNest(iNodes, 0, 0, &n) sb.Reset() printNest(n, 0, &sb) s2 := sb.String() fmt.Print(s2) fmt.Println("\nRound trip test satisfied? ", s1 == s2) }
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 repdict[c] else c) seen[c] += 1 return ''.join(newchars) print('abracadabra ->', trstring('abracadabra', rep))
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 = string(ss) s = strings.Replace(s, "b", "E", 1) s = strings.Replace(s, "r", "F", 2) s = strings.Replace(s, "F", "r", 1) fmt.Println(s) }
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 repdict[c] else c) seen[c] += 1 return ''.join(newchars) print('abracadabra ->', trstring('abracadabra', rep))
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 = string(ss) s = strings.Replace(s, "b", "E", 1) s = strings.Replace(s, "r", "F", 2) s = strings.Replace(s, "F", "r", 1) fmt.Println(s) }
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) if s.ProbablyPrime(15) { rPrimes = append(rPrimes, p) } } fmt.Printf("Base %2d: %v\n", b, rPrimes) } }
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) if s.ProbablyPrime(15) { rPrimes = append(rPrimes, p) } } fmt.Printf("Base %2d: %v\n", b, rPrimes) } }
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(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '') print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
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.NewInt(k) z := new(big.Int) var curzon50 []int64 for { z.Add(pow, one) d := k*n + 1 bd := big.NewInt(d) if z.Rem(z, bd).Cmp(zero) == 0 { if count < 50 { curzon50 = append(curzon50, n) } count++ if count == 50 { for i := 0; i < len(curzon50); i++ { fmt.Printf("%4d ", curzon50[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Print("\nOne thousandth: ") } if count == 1000 { fmt.Println(n) break } } n++ pow.Mul(pow, bk) } fmt.Println() } }
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(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '') print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
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.NewInt(k) z := new(big.Int) var curzon50 []int64 for { z.Add(pow, one) d := k*n + 1 bd := big.NewInt(d) if z.Rem(z, bd).Cmp(zero) == 0 { if count < 50 { curzon50 = append(curzon50, n) } count++ if count == 50 { for i := 0; i < len(curzon50); i++ { fmt.Printf("%4d ", curzon50[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Print("\nOne thousandth: ") } if count == 1000 { fmt.Println(n) break } } n++ pow.Mul(pow, bk) } fmt.Println() } }
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(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
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).SetInt64(d) t.Sqrt(t) t.Mul(pi, t) return bigfloat.Exp(t) } func main() { fmt.Println("Ramanujan's constant to 32 decimal places is:") fmt.Printf("%.32f\n", q(163)) heegners := [4][2]int64{ {19, 96}, {43, 960}, {67, 5280}, {163, 640320}, } fmt.Println("\nHeegner numbers yielding 'almost' integers:") t := new(big.Float).SetPrec(prec) for _, h := range heegners { qh := q(h[0]) c := h[1]*h[1]*h[1] + 744 t.SetInt64(c) t.Sub(t, qh) fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t) } }
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(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
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).SetInt64(d) t.Sqrt(t) t.Mul(pi, t) return bigfloat.Exp(t) } func main() { fmt.Println("Ramanujan's constant to 32 decimal places is:") fmt.Printf("%.32f\n", q(163)) heegners := [4][2]int64{ {19, 96}, {43, 960}, {67, 5280}, {163, 640320}, } fmt.Println("\nHeegner numbers yielding 'almost' integers:") t := new(big.Float).SetPrec(prec) for _, h := range heegners { qh := q(h[0]) c := h[1]*h[1]*h[1] + 744 t.SetInt64(c) t.Sub(t, qh) fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t) } }
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(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
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).SetInt64(d) t.Sqrt(t) t.Mul(pi, t) return bigfloat.Exp(t) } func main() { fmt.Println("Ramanujan's constant to 32 decimal places is:") fmt.Printf("%.32f\n", q(163)) heegners := [4][2]int64{ {19, 96}, {43, 960}, {67, 5280}, {163, 640320}, } fmt.Println("\nHeegner numbers yielding 'almost' integers:") t := new(big.Float).SetPrec(prec) for _, h := range heegners { qh := q(h[0]) c := h[1]*h[1]*h[1] + 744 t.SetInt64(c) t.Sub(t, qh) fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t) } }
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)) return method example = Example() example.foo() example.bar() example.grill() example.ding("dong")
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:", n) return 0 } func main() { var e example fmt.Println(e.CallMethod("Foo")) fmt.Println(e.CallMethod("Bar")) }
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( w, go(s[len(w):]) ) if s.startswith(w) else [] def parse(w, xs): return [Node(w)(xs)] if xs else xs return lambda s: go(s) def showParse(tree): def showTokens(x): xs = x['nest'] return ' ' + x['root'] + (showTokens(xs[0]) if xs else '') parses = tree['nest'] return tree['root'] + ':\n' + ( '\n'.join( map(showTokens, parses) ) if parses else ' ( Not parseable in terms of these words )' ) def main(): lexicon = 'a bc abc cd b'.split() testSamples = 'abcd abbc abcbcd acdbc abcdd'.split() print(unlines( map( showParse, map( stringParse(lexicon), testSamples ) ) )) def Node(v): return lambda xs: {'type': 'Node', 'root': v, 'nest': xs} def concatMap(f): return lambda xs: list( chain.from_iterable(map(f, xs)) ) def unlines(xs): return '\n'.join(xs) if __name__ == '__main__': main()
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 } type prefix struct { length int broken []string } bp := []prefix{{0, nil}} for end := 1; end <= len(s); end++ { for i := len(bp) - 1; i >= 0; i-- { w := s[bp[i].length:end] if d[w] { b := append(bp[i].broken, w) if end == len(s) { return b, true } bp = append(bp, prefix{end, b}) break } } } return nil, false } func main() { d := newDict("a", "bc", "abc", "cd", "b") for _, s := range []string{"abcd", "abbc", "abcbcd", "acdbc", "abcdd"} { if b, ok := d.wordBreak(s); ok { fmt.Printf("%s: %s\n", s, strings.Join(b, " ")) } else { fmt.Println("can't break") } } }
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 + 1)//2 continue i = np.searchsorted(blk, root, 'left') i += blk[i]*blk[i] < lb if not i: return blk[0]*blk[0], pos p = blk[:i + 1] q = (lb - 1)//p idx = np.searchsorted(blk, q, 'right') sel = idx < n p, idx = p[sel], idx[sel] q = blk[idx] sel = q >= p p, q, idx = p[sel], q[sel], idx[sel] pos += np.sum(idx - np.arange(len(idx))) return np.min(p*q), pos res = [] p = 0 for i in range(100): p, _ = smallest_brilliant(p + 1) res.append(p) print(f'first 100 are {res}') for i in range(max_order*2): thresh = 10**i p, pos = smallest_brilliant(thresh) print(f'Above 10^{i:2d}: {p:20d} at
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; k++ { var s []int for _, p := range primes { if p >= pow*10 { break } if p > pow { s = append(s, p) } } for i := 0; i < len(s); i++ { for j := i; j < len(s); j++ { prod := s[i] * s[j] if prod < limit { if countOnly { count++ } else { brilliant = append(brilliant, prod) } } else { if next > prod { next = prod } break } } } pow *= 10 } if countOnly { return res{count, next} } return res{brilliant, next} } func main() { fmt.Println("First 100 brilliant numbers:") brilliant := getBrilliant(2, 10000, false).bc.([]int) sort.Ints(brilliant) brilliant = brilliant[0:100] for i := 0; i < len(brilliant); i++ { fmt.Printf("%4d ", brilliant[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() for k := 1; k <= 13; k++ { limit := int(math.Pow(10, float64(k))) r := getBrilliant(k, limit, true) total := r.bc.(int) next := r.next climit := rcu.Commatize(limit) ctotal := rcu.Commatize(total + 1) cnext := rcu.Commatize(next) fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext) } }
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 + 1)//2 continue i = np.searchsorted(blk, root, 'left') i += blk[i]*blk[i] < lb if not i: return blk[0]*blk[0], pos p = blk[:i + 1] q = (lb - 1)//p idx = np.searchsorted(blk, q, 'right') sel = idx < n p, idx = p[sel], idx[sel] q = blk[idx] sel = q >= p p, q, idx = p[sel], q[sel], idx[sel] pos += np.sum(idx - np.arange(len(idx))) return np.min(p*q), pos res = [] p = 0 for i in range(100): p, _ = smallest_brilliant(p + 1) res.append(p) print(f'first 100 are {res}') for i in range(max_order*2): thresh = 10**i p, pos = smallest_brilliant(thresh) print(f'Above 10^{i:2d}: {p:20d} at
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; k++ { var s []int for _, p := range primes { if p >= pow*10 { break } if p > pow { s = append(s, p) } } for i := 0; i < len(s); i++ { for j := i; j < len(s); j++ { prod := s[i] * s[j] if prod < limit { if countOnly { count++ } else { brilliant = append(brilliant, prod) } } else { if next > prod { next = prod } break } } } pow *= 10 } if countOnly { return res{count, next} } return res{brilliant, next} } func main() { fmt.Println("First 100 brilliant numbers:") brilliant := getBrilliant(2, 10000, false).bc.([]int) sort.Ints(brilliant) brilliant = brilliant[0:100] for i := 0; i < len(brilliant); i++ { fmt.Printf("%4d ", brilliant[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() for k := 1; k <= 13; k++ { limit := int(math.Pow(10, float64(k))) r := getBrilliant(k, limit, true) total := r.bc.(int) next := r.next climit := rcu.Commatize(limit) ctotal := rcu.Commatize(total + 1) cnext := rcu.Commatize(next) fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext) } }
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 ) open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' ))) return s dico_url = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt' read_url = lambda url : urllib.request.urlopen( url ).read() load_dico = lambda url : tuple( cache( read_url,url ).split( b'\n')) isnext = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1 def build_map ( words ): map = [(w.decode('ascii'),[]) for w in words] for i1,(w1,n1) in enumerate( map ): for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ): if isnext( w1,w2 ): n1.append( i2 ) n2.append( i1 ) return map def find_path ( words,w1,w2 ): i = [w[0] for w in words].index( w1 ) front,done,res = [i],{i:-1},[] while front : i = front.pop(0) word,next = words[i] for n in next : if n in done : continue done[n] = i if words[n][0] == w2 : while n >= 0 : res = [words[n][0]] + res n = done[n] return ' '.join( res ) front.append( n ) return '%s can not be turned into %s'%( w1,w2 ) for w in ('boy man','girl lady','john jane','alien drool','child adult'): print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))
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++ { if a[i] != b[i] { sum++ } } return sum == 1 } func wordLadder(words []string, a, b string) { l := len(a) var poss []string for _, word := range words { if len(word) == l { poss = append(poss, word) } } todo := [][]string{{a}} for len(todo) > 0 { curr := todo[0] todo = todo[1:] var next []string for _, word := range poss { if oneAway(word, curr[len(curr)-1]) { next = append(next, word) } } if contains(next, b) { curr = append(curr, b) fmt.Println(strings.Join(curr, " -> ")) return } for i := len(poss) - 1; i >= 0; i-- { if contains(next, poss[i]) { copy(poss[i:], poss[i+1:]) poss[len(poss)-1] = "" poss = poss[:len(poss)-1] } } for _, s := range next { temp := make([]string, len(curr)) copy(temp, curr) temp = append(temp, s) todo = append(todo, temp) } } fmt.Println(a, "into", b, "cannot be done.") } func main() { b, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords)) for i, bword := range bwords { words[i] = string(bword) } pairs := [][]string{ {"boy", "man"}, {"girl", "lady"}, {"john", "jane"}, {"child", "adult"}, } for _, pair := range pairs { wordLadder(words, pair[0], pair[1]) } }
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") frameRect = pygame.Rect((45, 45), (510, 510)) crosshair = pygame.surface.Surface((10, 10)) crosshair.fill(pygame.Color("magenta")) pygame.draw.circle(crosshair, pygame.Color("blue"), (5,5), 5, 0) crosshair.set_colorkey(pygame.Color("magenta"), pygame.RLEACCEL) crosshair = crosshair.convert() writer = pygame.font.Font(pygame.font.get_default_font(), 15) buttons = {} for b in range(joy.get_numbuttons()): buttons[b] = [ writer.render( hex(b)[2:].upper(), 1, pygame.Color("red"), pygame.Color("black") ).convert(), ((15*b)+45, 560) ] while True: pygame.event.pump() for events in pygame.event.get(): if events.type == pygame.QUIT: pygame.quit() sys.exit() screen.fill(pygame.Color("black")) x = joy.get_axis(0) y = joy.get_axis(1) screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5)) pygame.draw.rect(screen, pygame.Color("red"), frameRect, 1) for b in range(joy.get_numbuttons()): if joy.get_button(b): screen.blit(buttons[b][0], buttons[b][1]) pygame.display.flip() clk.tick(40)
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 readJoystick(js joystick.Joystick, hidden bool) { jinfo, err := js.Read() check(err) w, h := termbox.Size() tbcd := termbox.ColorDefault termbox.Clear(tbcd, tbcd) printAt(1, h-1, "q - quit") if hidden { printAt(11, h-1, "s - show buttons:") } else { bs := "" printAt(11, h-1, "h - hide buttons:") for button := 0; button < js.ButtonCount(); button++ { if jinfo.Buttons&(1<<uint32(button)) != 0 { bs += fmt.Sprintf(" %X", button+1) } } printAt(28, h-1, bs) } x := int(float64((jinfo.AxisData[0]+32767)*(w-1)) / 65535) y := int(float64((jinfo.AxisData[1]+32767)*(h-2)) / 65535) printAt(x, y, "+") termbox.Flush() } func check(err error) { if err != nil { log.Fatal(err) } } func main() { jsid := 0 if len(os.Args) > 1 { i, err := strconv.Atoi(os.Args[1]) check(err) jsid = i } js, jserr := joystick.Open(jsid) check(jserr) err := termbox.Init() check(err) defer termbox.Close() eventQueue := make(chan termbox.Event) go func() { for { eventQueue <- termbox.PollEvent() } }() ticker := time.NewTicker(time.Millisecond * 40) hidden := false for doQuit := false; !doQuit; { select { case ev := <-eventQueue: if ev.Type == termbox.EventKey { if ev.Ch == 'q' { doQuit = true } else if ev.Ch == 'h' { hidden = true } else if ev.Ch == 's' { hidden = false } } if ev.Type == termbox.EventResize { termbox.Flush() } case <-ticker.C: readJoystick(js, hidden) } } }
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[GAP1] GAP2 = GAP1 + 2 if GAP2 not in gapstarts: GAP1 = GAP2 + 2 continue start2 = gapstarts[GAP2] diff = abs(start2 - start1) if diff > PM: print(f"Earliest difference >{PM: ,} between adjacent prime gap starting primes:") print(f"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\n") if PM == LIMIT: break PM *= 10 else: GAP1 = GAP2
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] } } pm := 10 gap1 := 2 for { for _, ok := gapStarts[gap1]; !ok; { gap1 += 2 } start1 := gapStarts[gap1] gap2 := gap1 + 2 if _, ok := gapStarts[gap2]; !ok { gap1 = gap2 + 2 continue } start2 := gapStarts[gap2] diff := start2 - start1 if diff < 0 { diff = -diff } if diff > pm { cpm := rcu.Commatize(pm) cst1 := rcu.Commatize(start1) cst2 := rcu.Commatize(start2) cd := rcu.Commatize(diff) fmt.Printf("Earliest difference > %s between adjacent prime gap starting primes:\n", cpm) fmt.Printf("Gap %d starts at %s, gap %d starts at %s, difference is %s.\n\n", gap1, cst1, gap2, cst2, cd) if pm == limit { break } pm *= 10 } else { gap1 = gap2 } } }
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: return b = [x + 1 for x in a] r.append(b) return for i in xrange(last, 0, -1): a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] recurse(n - 1) return r def printSquare(latin,n): for row in latin: print row print def reducedLatinSquares(n,echo): if n <= 0: if echo: print [] return 0 elif n == 1: if echo: print [1] return 1 rlatin = [None] * n for i in xrange(n): rlatin[i] = [None] * n for j in xrange(0, n): rlatin[0][j] = j + 1 class OuterScope: count = 0 def recurse(i): rows = dList(n, i) for r in xrange(len(rows)): rlatin[i - 1] = rows[r] justContinue = False k = 0 while not justContinue and k < i - 1: for j in xrange(1, n): if rlatin[k][j] == rlatin[i - 1][j]: if r < len(rows) - 1: justContinue = True break if i > 2: return k += 1 if not justContinue: if i < n: recurse(i + 1) else: OuterScope.count += 1 if echo: printSquare(rlatin, n) recurse(2) return OuterScope.count def factorial(n): if n == 0: return 1 prod = 1 for i in xrange(2, n + 1): prod *= i return prod print "The four reduced latin squares of order 4 are:\n" reducedLatinSquares(4,True) print "The size of the set of reduced latin squares for the following orders" print "and hence the total number of latin squares of these orders are:\n" for n in xrange(1, 7): size = reducedLatinSquares(n, False) f = factorial(n - 1) f *= f * n * size print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f)
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(last int) { if last == first { for j, v := range a[1:] { if j+1 == v { return } } b := make([]int, n) copy(b, a) for i := range b { b[i]++ } r = append(r, b) return } for i := last; i >= 1; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func reducedLatinSquare(n int, echo bool) uint64 { if n <= 0 { if echo { fmt.Println("[]\n") } return 0 } else if n == 1 { if echo { fmt.Println("[1]\n") } return 1 } rlatin := make(matrix, n) for i := 0; i < n; i++ { rlatin[i] = make([]int, n) } for j := 0; j < n; j++ { rlatin[0][j] = j + 1 } count := uint64(0) var recurse func(i int) recurse = func(i int) { rows := dList(n, i) outer: for r := 0; r < len(rows); r++ { copy(rlatin[i-1], rows[r]) for k := 0; k < i-1; k++ { for j := 1; j < n; j++ { if rlatin[k][j] == rlatin[i-1][j] { if r < len(rows)-1 { continue outer } else if i > 2 { return } } } } if i < n { recurse(i + 1) } else { count++ if echo { printSquare(rlatin, n) } } } return } recurse(2) return count } func printSquare(latin matrix, n int) { for i := 0; i < n; i++ { fmt.Println(latin[i]) } fmt.Println() } func factorial(n uint64) uint64 { if n == 0 { return 1 } prod := uint64(1) for i := uint64(2); i <= n; i++ { prod *= i } return prod } func main() { fmt.Println("The four reduced latin squares of order 4 are:\n") reducedLatinSquare(4, true) fmt.Println("The size of the set of reduced latin squares for the following orders") fmt.Println("and hence the total number of latin squares of these orders are:\n") for n := uint64(1); n <= 6; n++ { size := reducedLatinSquare(int(n), false) f := factorial(n - 1) f *= f * n * size fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f) } }
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 enumerate(ORMISTONS): if i < 30: print(f'({o[0] : 6} {o[1] : 6} )', end='\n' if (i + 1) % 5 == 0 else ' ') else: break print(len(ORMISTONS), 'is the count of Ormiston pairs up to one million.')
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 { continue } key1 := 1 for _, dig := range rcu.Digits(p1, 10) { key1 *= primes[dig] } key2 := 1 for _, dig := range rcu.Digits(p2, 10) { key2 *= primes[dig] } if key1 == key2 { if count < 30 { orm30 = append(orm30, [2]int{p1, p2}) } if p1 >= j { counts = append(counts, count) j *= 10 } count++ } } counts = append(counts, count) fmt.Println("First 30 Ormiston pairs:") for i := 0; i < 30; i++ { fmt.Printf("%5v ", orm30[i]) if (i+1)%3 == 0 { fmt.Println() } } fmt.Println() j = int(1e5) for i := 0; i < len(counts); i++ { fmt.Printf("%s Ormiston pairs before %s\n", rcu.Commatize(counts[i]), rcu.Commatize(j)) j *= 10 } }
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, 1, 1, 1, 0, 1): 3, (0, 1, 0, 0, 0, 1, 1): 4, (0, 1, 1, 0, 0, 0, 1): 5, (0, 1, 0, 1, 1, 1, 1): 6, (0, 1, 1, 1, 0, 1, 1): 7, (0, 1, 1, 0, 1, 1, 1): 8, (0, 0, 0, 1, 0, 1, 1): 9, } RIGHT_DIGITS = { (1, 1, 1, 0, 0, 1, 0): 0, (1, 1, 0, 0, 1, 1, 0): 1, (1, 1, 0, 1, 1, 0, 0): 2, (1, 0, 0, 0, 0, 1, 0): 3, (1, 0, 1, 1, 1, 0, 0): 4, (1, 0, 0, 1, 1, 1, 0): 5, (1, 0, 1, 0, 0, 0, 0): 6, (1, 0, 0, 0, 1, 0, 0): 7, (1, 0, 0, 1, 0, 0, 0): 8, (1, 1, 1, 0, 1, 0, 0): 9, } MODULES = { " ": 0, " } DIGITS_PER_SIDE = 6 MODULES_PER_DIGIT = 7 class ParityError(Exception): class ChecksumError(Exception): def group(iterable, n): args = [iter(iterable)] * n return tuple(itertools.zip_longest(*args)) def parse(barcode): match = RE_BARCODE.match(barcode) left = group((MODULES[c] for c in match.group("left")), MODULES_PER_DIGIT) right = group((MODULES[c] for c in match.group("right")), MODULES_PER_DIGIT) left, right = check_parity(left, right) return tuple( itertools.chain( (LEFT_DIGITS[d] for d in left), (RIGHT_DIGITS[d] for d in right), ) ) def check_parity(left, right): left_parity = sum(sum(d) % 2 for d in left) right_parity = sum(sum(d) % 2 for d in right) if left_parity == 0 and right_parity == DIGITS_PER_SIDE: _left = tuple(tuple(reversed(d)) for d in reversed(right)) right = tuple(tuple(reversed(d)) for d in reversed(left)) left = _left elif left_parity != DIGITS_PER_SIDE or right_parity != 0: error = tuple( itertools.chain( (LEFT_DIGITS.get(d, "_") for d in left), (RIGHT_DIGITS.get(d, "_") for d in right), ) ) raise ParityError(" ".join(str(d) for d in error)) return left, right def checksum(digits): odds = (digits[i] for i in range(0, 11, 2)) evens = (digits[i] for i in range(1, 10, 2)) check_digit = (sum(odds) * 3 + sum(evens)) % 10 if check_digit != 0: check_digit = 10 - check_digit if digits[-1] != check_digit: raise ChecksumError(str(check_digit)) return check_digit def main(): barcodes = [ " " " " " " " " " " " ] for barcode in barcodes: try: digits = parse(barcode) except ParityError as err: print(f"{err} parity error!") continue try: check_digit = checksum(digits) except ChecksumError as err: print(f"{' '.join(str(d) for d in digits)} checksum error! ({err})") continue print(f"{' '.join(str(d) for d in digits)}") if __name__ == "__main__": main()
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[string]int) rhs = make(map[string]int) ) var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1} const ( s = "# #" m = " # # " e = "# #" d = "(?:#| ){7}" ) func init() { for i := 0; i <= 9; i++ { lt := make([]byte, 7) rt := make([]byte, 7) for j := 0; j < 14; j += 2 { if bits[i][j] == '1' { lt[j/2] = '#' rt[j/2] = ' ' } else { lt[j/2] = ' ' rt[j/2] = '#' } } lhs[string(lt)] = i rhs[string(rt)] = i } } func reverse(s string) string { b := []byte(s) for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } return string(b) } func main() { barcodes := []string{ " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", } expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`, s, d, d, d, d, d, d, m, d, d, d, d, d, d, e) rx := regexp.MustCompile(expr) fmt.Println("UPC-A barcodes:") for i, bc := range barcodes { for j := 0; j <= 1; j++ { if !rx.MatchString(bc) { fmt.Printf("%2d: Invalid format\n", i+1) break } codes := rx.FindStringSubmatch(bc) digits := make([]int, 12) var invalid, ok bool for i := 1; i <= 6; i++ { digits[i-1], ok = lhs[codes[i]] if !ok { invalid = true } digits[i+5], ok = rhs[codes[i+6]] if !ok { invalid = true } } if invalid { if j == 0 { bc = reverse(bc) continue } else { fmt.Printf("%2d: Invalid digit(s)\n", i+1) break } } sum := 0 for i, d := range digits { sum += weights[i] * d } if sum%10 != 0 { fmt.Printf("%2d: Checksum error\n", i+1) break } else { ud := "" if j == 1 { ud = "(upside down)" } fmt.Printf("%2d: %v %s\n", i+1, digits, ud) break } } } }
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 to is None: to = 'I' if from_ == 'J' else '' def canonicalize(s): return filter(str.isupper, s.upper()).replace(from_, to) m = partition(uniq(canonicalize(key + ascii_uppercase)), 5) enc = {} for row in m: for i, j in product(xrange(5), repeat=2): if i != j: enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5] for c in zip(*m): for i, j in product(xrange(5), repeat=2): if i != j: enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5] for i1, j1, i2, j2 in product(xrange(5), repeat=4): if i1 != i2 and j1 != j2: enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1] dec = dict((v, k) for k, v in enc.iteritems()) def sub_enc(txt): lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt)) return " ".join(enc[a + (b if b else 'X')] for a, b in lst) def sub_dec(encoded): return " ".join(dec[p] for p in partition(canonicalize(encoded), 2)) return sub_enc, sub_dec (encode, decode) = playfair("Playfair example") orig = "Hide the gold in...the TREESTUMP!!!" print "Original:", orig enc = encode(orig) print "Encoded:", enc print "Decoded:", decode(enc)
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 { used[16] = true } else { used[9] = true } alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i, j, k := 0, 0, 0; k < len(alphabet); k++ { c := alphabet[k] if c < 'A' || c > 'Z' { continue } d := int(c - 65) if !used[d] { p.table[i][j] = c used[d] = true j++ if j == 5 { i++ if i == 5 { break } j = 0 } } } } func (p *playfair) getCleanText(plainText string) string { plainText = strings.ToUpper(plainText) var cleanText strings.Builder prevByte := byte('\000') for i := 0; i < len(plainText); i++ { nextByte := plainText[i] if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) { continue } if nextByte == 'J' && p.pfo == iEqualsJ { nextByte = 'I' } if nextByte != prevByte { cleanText.WriteByte(nextByte) } else { cleanText.WriteByte('X') cleanText.WriteByte(nextByte) } prevByte = nextByte } l := cleanText.Len() if l%2 == 1 { if cleanText.String()[l-1] != 'X' { cleanText.WriteByte('X') } else { cleanText.WriteByte('Z') } } return cleanText.String() } func (p *playfair) findByte(c byte) (int, int) { for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { if p.table[i][j] == c { return i, j } } } return -1, -1 } func (p *playfair) encode(plainText string) string { cleanText := p.getCleanText(plainText) var cipherText strings.Builder l := len(cleanText) for i := 0; i < l; i += 2 { row1, col1 := p.findByte(cleanText[i]) row2, col2 := p.findByte(cleanText[i+1]) switch { case row1 == row2: cipherText.WriteByte(p.table[row1][(col1+1)%5]) cipherText.WriteByte(p.table[row2][(col2+1)%5]) case col1 == col2: cipherText.WriteByte(p.table[(row1+1)%5][col1]) cipherText.WriteByte(p.table[(row2+1)%5][col2]) default: cipherText.WriteByte(p.table[row1][col2]) cipherText.WriteByte(p.table[row2][col1]) } if i < l-1 { cipherText.WriteByte(' ') } } return cipherText.String() } func (p *playfair) decode(cipherText string) string { var decodedText strings.Builder l := len(cipherText) for i := 0; i < l; i += 3 { row1, col1 := p.findByte(cipherText[i]) row2, col2 := p.findByte(cipherText[i+1]) switch { case row1 == row2: temp := 4 if col1 > 0 { temp = col1 - 1 } decodedText.WriteByte(p.table[row1][temp]) temp = 4 if col2 > 0 { temp = col2 - 1 } decodedText.WriteByte(p.table[row2][temp]) case col1 == col2: temp := 4 if row1 > 0 { temp = row1 - 1 } decodedText.WriteByte(p.table[temp][col1]) temp = 4 if row2 > 0 { temp = row2 - 1 } decodedText.WriteByte(p.table[temp][col2]) default: decodedText.WriteByte(p.table[row1][col2]) decodedText.WriteByte(p.table[row2][col1]) } if i < l-1 { decodedText.WriteByte(' ') } } return decodedText.String() } func (p *playfair) printTable() { fmt.Println("The table to be used is :\n") for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { fmt.Printf("%c ", p.table[i][j]) } fmt.Println() } } func main() { scanner := bufio.NewScanner(os.Stdin) fmt.Print("Enter Playfair keyword : ") scanner.Scan() keyword := scanner.Text() var ignoreQ string for ignoreQ != "y" && ignoreQ != "n" { fmt.Print("Ignore Q when building table y/n : ") scanner.Scan() ignoreQ = strings.ToLower(scanner.Text()) } pfo := noQ if ignoreQ == "n" { pfo = iEqualsJ } var table [5][5]byte pf := &playfair{keyword, pfo, table} pf.init() pf.printTable() fmt.Print("\nEnter plain text : ") scanner.Scan() plainText := scanner.Text() if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) return } encodedText := pf.encode(plainText) fmt.Println("\nEncoded text is :", encodedText) decodedText := pf.decode(encodedText) fmt.Println("Deccoded text is :", decodedText) }
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 to is None: to = 'I' if from_ == 'J' else '' def canonicalize(s): return filter(str.isupper, s.upper()).replace(from_, to) m = partition(uniq(canonicalize(key + ascii_uppercase)), 5) enc = {} for row in m: for i, j in product(xrange(5), repeat=2): if i != j: enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5] for c in zip(*m): for i, j in product(xrange(5), repeat=2): if i != j: enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5] for i1, j1, i2, j2 in product(xrange(5), repeat=4): if i1 != i2 and j1 != j2: enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1] dec = dict((v, k) for k, v in enc.iteritems()) def sub_enc(txt): lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt)) return " ".join(enc[a + (b if b else 'X')] for a, b in lst) def sub_dec(encoded): return " ".join(dec[p] for p in partition(canonicalize(encoded), 2)) return sub_enc, sub_dec (encode, decode) = playfair("Playfair example") orig = "Hide the gold in...the TREESTUMP!!!" print "Original:", orig enc = encode(orig) print "Encoded:", enc print "Decoded:", decode(enc)
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 { used[16] = true } else { used[9] = true } alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i, j, k := 0, 0, 0; k < len(alphabet); k++ { c := alphabet[k] if c < 'A' || c > 'Z' { continue } d := int(c - 65) if !used[d] { p.table[i][j] = c used[d] = true j++ if j == 5 { i++ if i == 5 { break } j = 0 } } } } func (p *playfair) getCleanText(plainText string) string { plainText = strings.ToUpper(plainText) var cleanText strings.Builder prevByte := byte('\000') for i := 0; i < len(plainText); i++ { nextByte := plainText[i] if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) { continue } if nextByte == 'J' && p.pfo == iEqualsJ { nextByte = 'I' } if nextByte != prevByte { cleanText.WriteByte(nextByte) } else { cleanText.WriteByte('X') cleanText.WriteByte(nextByte) } prevByte = nextByte } l := cleanText.Len() if l%2 == 1 { if cleanText.String()[l-1] != 'X' { cleanText.WriteByte('X') } else { cleanText.WriteByte('Z') } } return cleanText.String() } func (p *playfair) findByte(c byte) (int, int) { for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { if p.table[i][j] == c { return i, j } } } return -1, -1 } func (p *playfair) encode(plainText string) string { cleanText := p.getCleanText(plainText) var cipherText strings.Builder l := len(cleanText) for i := 0; i < l; i += 2 { row1, col1 := p.findByte(cleanText[i]) row2, col2 := p.findByte(cleanText[i+1]) switch { case row1 == row2: cipherText.WriteByte(p.table[row1][(col1+1)%5]) cipherText.WriteByte(p.table[row2][(col2+1)%5]) case col1 == col2: cipherText.WriteByte(p.table[(row1+1)%5][col1]) cipherText.WriteByte(p.table[(row2+1)%5][col2]) default: cipherText.WriteByte(p.table[row1][col2]) cipherText.WriteByte(p.table[row2][col1]) } if i < l-1 { cipherText.WriteByte(' ') } } return cipherText.String() } func (p *playfair) decode(cipherText string) string { var decodedText strings.Builder l := len(cipherText) for i := 0; i < l; i += 3 { row1, col1 := p.findByte(cipherText[i]) row2, col2 := p.findByte(cipherText[i+1]) switch { case row1 == row2: temp := 4 if col1 > 0 { temp = col1 - 1 } decodedText.WriteByte(p.table[row1][temp]) temp = 4 if col2 > 0 { temp = col2 - 1 } decodedText.WriteByte(p.table[row2][temp]) case col1 == col2: temp := 4 if row1 > 0 { temp = row1 - 1 } decodedText.WriteByte(p.table[temp][col1]) temp = 4 if row2 > 0 { temp = row2 - 1 } decodedText.WriteByte(p.table[temp][col2]) default: decodedText.WriteByte(p.table[row1][col2]) decodedText.WriteByte(p.table[row2][col1]) } if i < l-1 { decodedText.WriteByte(' ') } } return decodedText.String() } func (p *playfair) printTable() { fmt.Println("The table to be used is :\n") for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { fmt.Printf("%c ", p.table[i][j]) } fmt.Println() } } func main() { scanner := bufio.NewScanner(os.Stdin) fmt.Print("Enter Playfair keyword : ") scanner.Scan() keyword := scanner.Text() var ignoreQ string for ignoreQ != "y" && ignoreQ != "n" { fmt.Print("Ignore Q when building table y/n : ") scanner.Scan() ignoreQ = strings.ToLower(scanner.Text()) } pfo := noQ if ignoreQ == "n" { pfo = iEqualsJ } var table [5][5]byte pf := &playfair{keyword, pfo, table} pf.init() pf.printTable() fmt.Print("\nEnter plain text : ") scanner.Scan() plainText := scanner.Text() if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) return } encodedText := pf.encode(plainText) fmt.Println("\nEncoded text is :", encodedText) decodedText := pf.decode(encodedText) fmt.Println("Deccoded text is :", decodedText) }
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, '/', d)
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 rational form, are:") numbers := make([]int, 21) for i := 1; i <= 20; i++ { numbers[i-1] = i } numbers[20] = 100 for _, i := range numbers { fmt.Printf("%3d : %s\n", i, harmonic(i)) } fmt.Println("\nThe first harmonic number to exceed the following integers is:") const limit = 10 for i, n, h := 1, 1, 0.0; i <= limit; n++ { h += 1.0 / float64(n) if h > float64(i) { fmt.Printf("integer = %2d -> n = %6d -> harmonic number = %9.6f (to 6dp)\n", i, n, h) i++ } } }
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)) mergers.append(merge_me) merge_me.seek(0) stack_tops = [f.read(1) for f in mergers] while stack_tops: c = min(stack_tops) sink.write(c) i = stack_tops.index(c) t = mergers[i].read(1) if t: stack_tops[i] = t else: del stack_tops[i] mergers[i].close() del mergers[i] def main(): input_file_too_large_for_memory = io.StringIO('678925341') t = list(input_file_too_large_for_memory.read()) t.sort() expect = ''.join(t) print('expect', expect) for memory_size in range(1,12): input_file_too_large_for_memory.seek(0) output_file_too_large_for_memory = io.StringIO() sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO) output_file_too_large_for_memory.seek(0) assert(output_file_too_large_for_memory.read() == expect) print('memory size {} passed'.format(memory_size)) if __name__ == '__main__': example = main example()
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 []MinHeapNode) *MinHeap { mh := new(MinHeap) mh.nodes = nodes for i := (len(nodes) - 1) / 2; i >= 0; i-- { mh.minHeapify(i) } return mh } func (mh *MinHeap) getMin() MinHeapNode { return mh.nodes[0] } func (mh *MinHeap) replaceMin(x MinHeapNode) { mh.nodes[0] = x mh.minHeapify(0) } func (mh *MinHeap) minHeapify(i int) { l, r := left(i), right(i) smallest := i heapSize := len(mh.nodes) if l < heapSize && mh.nodes[l].element < mh.nodes[i].element { smallest = l } if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element { smallest = r } if smallest != i { mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i] mh.minHeapify(smallest) } } func merge(arr []int, l, m, r int) { n1, n2 := m-l+1, r-m tl := make([]int, n1) tr := make([]int, n2) copy(tl, arr[l:]) copy(tr, arr[m+1:]) i, j, k := 0, 0, l for i < n1 && j < n2 { if tl[i] <= tr[j] { arr[k] = tl[i] k++ i++ } else { arr[k] = tr[j] k++ j++ } } for i < n1 { arr[k] = tl[i] k++ i++ } for j < n2 { arr[k] = tr[j] k++ j++ } } func mergeSort(arr []int, l, r int) { if l < r { m := l + (r-l)/2 mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r) } } func mergeFiles(outputFile string, n, k int) { in := make([]*os.File, k) var err error for i := 0; i < k; i++ { fileName := fmt.Sprintf("es%d", i) in[i], err = os.Open(fileName) check(err) } out, err := os.Create(outputFile) check(err) nodes := make([]MinHeapNode, k) i := 0 for ; i < k; i++ { _, err = fmt.Fscanf(in[i], "%d", &nodes[i].element) if err == io.EOF { break } check(err) nodes[i].index = i } hp := newMinHeap(nodes[:i]) count := 0 for count != i { root := hp.getMin() fmt.Fprintf(out, "%d ", root.element) _, err = fmt.Fscanf(in[root.index], "%d", &root.element) if err == io.EOF { root.element = math.MaxInt32 count++ } else { check(err) } hp.replaceMin(root) } for j := 0; j < k; j++ { in[j].Close() } out.Close() } func check(err error) { if err != nil { log.Fatal(err) } } func createInitialRuns(inputFile string, runSize, numWays int) { in, err := os.Open(inputFile) out := make([]*os.File, numWays) for i := 0; i < numWays; i++ { fileName := fmt.Sprintf("es%d", i) out[i], err = os.Create(fileName) check(err) } arr := make([]int, runSize) moreInput := true nextOutputFile := 0 var i int for moreInput { for i = 0; i < runSize; i++ { _, err := fmt.Fscanf(in, "%d", &arr[i]) if err == io.EOF { moreInput = false break } check(err) } mergeSort(arr, 0, i-1) for j := 0; j < i; j++ { fmt.Fprintf(out[nextOutputFile], "%d ", arr[j]) } nextOutputFile++ } for j := 0; j < numWays; j++ { out[j].Close() } in.Close() } func externalSort(inputFile, outputFile string, numWays, runSize int) { createInitialRuns(inputFile, runSize, numWays) mergeFiles(outputFile, runSize, numWays) } func main() { numWays := 4 runSize := 10 inputFile := "input.txt" outputFile := "output.txt" in, err := os.Create(inputFile) check(err) rand.Seed(time.Now().UnixNano()) for i := 0; i < numWays*runSize; i++ { fmt.Fprintf(in, "%d ", rand.Intn(math.MaxInt32)) } in.Close() externalSort(inputFile, outputFile, numWays, runSize) for i := 0; i < numWays; i++ { fileName := fmt.Sprintf("es%d", i) err = os.Remove(fileName) check(err) } }
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)) mergers.append(merge_me) merge_me.seek(0) stack_tops = [f.read(1) for f in mergers] while stack_tops: c = min(stack_tops) sink.write(c) i = stack_tops.index(c) t = mergers[i].read(1) if t: stack_tops[i] = t else: del stack_tops[i] mergers[i].close() del mergers[i] def main(): input_file_too_large_for_memory = io.StringIO('678925341') t = list(input_file_too_large_for_memory.read()) t.sort() expect = ''.join(t) print('expect', expect) for memory_size in range(1,12): input_file_too_large_for_memory.seek(0) output_file_too_large_for_memory = io.StringIO() sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO) output_file_too_large_for_memory.seek(0) assert(output_file_too_large_for_memory.read() == expect) print('memory size {} passed'.format(memory_size)) if __name__ == '__main__': example = main example()
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 []MinHeapNode) *MinHeap { mh := new(MinHeap) mh.nodes = nodes for i := (len(nodes) - 1) / 2; i >= 0; i-- { mh.minHeapify(i) } return mh } func (mh *MinHeap) getMin() MinHeapNode { return mh.nodes[0] } func (mh *MinHeap) replaceMin(x MinHeapNode) { mh.nodes[0] = x mh.minHeapify(0) } func (mh *MinHeap) minHeapify(i int) { l, r := left(i), right(i) smallest := i heapSize := len(mh.nodes) if l < heapSize && mh.nodes[l].element < mh.nodes[i].element { smallest = l } if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element { smallest = r } if smallest != i { mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i] mh.minHeapify(smallest) } } func merge(arr []int, l, m, r int) { n1, n2 := m-l+1, r-m tl := make([]int, n1) tr := make([]int, n2) copy(tl, arr[l:]) copy(tr, arr[m+1:]) i, j, k := 0, 0, l for i < n1 && j < n2 { if tl[i] <= tr[j] { arr[k] = tl[i] k++ i++ } else { arr[k] = tr[j] k++ j++ } } for i < n1 { arr[k] = tl[i] k++ i++ } for j < n2 { arr[k] = tr[j] k++ j++ } } func mergeSort(arr []int, l, r int) { if l < r { m := l + (r-l)/2 mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r) } } func mergeFiles(outputFile string, n, k int) { in := make([]*os.File, k) var err error for i := 0; i < k; i++ { fileName := fmt.Sprintf("es%d", i) in[i], err = os.Open(fileName) check(err) } out, err := os.Create(outputFile) check(err) nodes := make([]MinHeapNode, k) i := 0 for ; i < k; i++ { _, err = fmt.Fscanf(in[i], "%d", &nodes[i].element) if err == io.EOF { break } check(err) nodes[i].index = i } hp := newMinHeap(nodes[:i]) count := 0 for count != i { root := hp.getMin() fmt.Fprintf(out, "%d ", root.element) _, err = fmt.Fscanf(in[root.index], "%d", &root.element) if err == io.EOF { root.element = math.MaxInt32 count++ } else { check(err) } hp.replaceMin(root) } for j := 0; j < k; j++ { in[j].Close() } out.Close() } func check(err error) { if err != nil { log.Fatal(err) } } func createInitialRuns(inputFile string, runSize, numWays int) { in, err := os.Open(inputFile) out := make([]*os.File, numWays) for i := 0; i < numWays; i++ { fileName := fmt.Sprintf("es%d", i) out[i], err = os.Create(fileName) check(err) } arr := make([]int, runSize) moreInput := true nextOutputFile := 0 var i int for moreInput { for i = 0; i < runSize; i++ { _, err := fmt.Fscanf(in, "%d", &arr[i]) if err == io.EOF { moreInput = false break } check(err) } mergeSort(arr, 0, i-1) for j := 0; j < i; j++ { fmt.Fprintf(out[nextOutputFile], "%d ", arr[j]) } nextOutputFile++ } for j := 0; j < numWays; j++ { out[j].Close() } in.Close() } func externalSort(inputFile, outputFile string, numWays, runSize int) { createInitialRuns(inputFile, runSize, numWays) mergeFiles(outputFile, runSize, numWays) } func main() { numWays := 4 runSize := 10 inputFile := "input.txt" outputFile := "output.txt" in, err := os.Create(inputFile) check(err) rand.Seed(time.Now().UnixNano()) for i := 0; i < numWays*runSize; i++ { fmt.Fprintf(in, "%d ", rand.Intn(math.MaxInt32)) } in.Close() externalSort(inputFile, outputFile, numWays, runSize) for i := 0; i < numWays; i++ { fileName := fmt.Sprintf("es%d", i) err = os.Remove(fileName) check(err) } }
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//self.b == self.a1//self.b1 @property def egress(self): n = self.a // self.b self.a, self.b = self.b, self.a - self.b * n self.a1, self.b1 = self.b1, self.a1 - self.b1 * n return n @property def egress_done(self): if self.needterm: self.a, self.b = self.a1, self.b1 return self.egress @property def done(self): return self.b == 0 and self.b1 == 0
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) { ng.A1, ng.A, ng.B1, ng.B = ng.A+ng.A1*t, ng.A1, ng.B+ng.B1*t, ng.B1 } func (ng *NG4) ingestInfinite() { ng.A, ng.B = ng.A1, ng.B1 } func (ng *NG4) egest(t int64) { ng.A1, ng.A, ng.B1, ng.B = ng.B1, ng.B, ng.A1-ng.B1*t, ng.A-ng.B*t } func (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction { return func() NextFn { next := cf() done := false return func() (int64, bool) { if done { return 0, false } for ng.needsIngest() { if t, ok := next(); ok { ng.ingest(t) } else { ng.ingestInfinite() } } t := ng.A1 / ng.B1 ng.egest(t) done = ng.isDone() return t, true } } }
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, divmod(num, den) yield digit def get_term_num(rational): ans, dig, pwr = 0, 1, 0 for n in r2cf(rational): for _ in range(n): ans |= dig << pwr pwr += 1 dig ^= 1 return ans if __name__ == '__main__': print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20))) x = Fraction(83116, 51639) print(f"\n{x} is the {get_term_num(x):_}'th term.")
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, _ := t.Float64() f = math.Floor(f) t.SetFloat64(f) t.Mul(t, two) t.Sub(t, cw[i-1]) t.Add(t, one) t.Inv(t) cw[i] = new(big.Rat).Set(t) } return cw } func toContinued(r *big.Rat) []int { a := r.Num().Int64() b := r.Denom().Int64() var res []int for { res = append(res, int(a/b)) t := a % b a, b = b, t if a == 1 { break } } le := len(res) if le%2 == 0 { res[le-1]-- res = append(res, 1) } return res } func getTermNumber(cf []int) int { b := "" d := "1" for _, n := range cf { b = strings.Repeat(d, n) + b if d == "1" { d = "0" } else { d = "1" } } i, _ := strconv.ParseInt(b, 2, 64) return int(i) } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { cw := calkinWilf(20) fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:") for i := 1; i <= 20; i++ { fmt.Printf("%2d: %s\n", i, cw[i-1].RatString()) } fmt.Println() r := big.NewRat(83116, 51639) cf := toContinued(r) tn := getTermNumber(cf) fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn)) }
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, divmod(num, den) yield digit def get_term_num(rational): ans, dig, pwr = 0, 1, 0 for n in r2cf(rational): for _ in range(n): ans |= dig << pwr pwr += 1 dig ^= 1 return ans if __name__ == '__main__': print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20))) x = Fraction(83116, 51639) print(f"\n{x} is the {get_term_num(x):_}'th term.")
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, _ := t.Float64() f = math.Floor(f) t.SetFloat64(f) t.Mul(t, two) t.Sub(t, cw[i-1]) t.Add(t, one) t.Inv(t) cw[i] = new(big.Rat).Set(t) } return cw } func toContinued(r *big.Rat) []int { a := r.Num().Int64() b := r.Denom().Int64() var res []int for { res = append(res, int(a/b)) t := a % b a, b = b, t if a == 1 { break } } le := len(res) if le%2 == 0 { res[le-1]-- res = append(res, 1) } return res } func getTermNumber(cf []int) int { b := "" d := "1" for _, n := range cf { b = strings.Repeat(d, n) + b if d == "1" { d = "0" } else { d = "1" } } i, _ := strconv.ParseInt(b, 2, 64) return int(i) } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { cw := calkinWilf(20) fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:") for i := 1; i <= 20; i++ { fmt.Printf("%2d: %s\n", i, cw[i-1].RatString()) } fmt.Println() r := big.NewRat(83116, 51639) cf := toContinued(r) tn := getTermNumber(cf) fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn)) }
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 factorials from 1 to {} is {}.".format(N, psum / N)) return proportions for n in [100, 1000, 10000]: facpropzeros(n) props = facpropzeros(47500, False) n = (next(i for i in reversed(range(len(props))) if props[i] > 0.16)) print("The mean proportion dips permanently below 0.16 at {}.".format(n + 2))
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++ { fact.Mul(fact, big.NewInt(n)) bytes := []byte(fact.String()) digits := len(bytes) zeros := 0 for _, b := range bytes { if b == '0' { zeros++ } } sum += float64(zeros)/float64(digits) ratio := sum / float64(n) if n == 100 || n == 1000 || n == 10000 { fmt.Printf("%6s = %12.10f\n", rcu.Commatize(int(n)), ratio) } if first > 0 && ratio >= 0.16 { first = 0 firstRatio = 0.0 } else if first == 0 && ratio < 0.16 { first = n firstRatio = ratio } } fmt.Printf("%6s = %12.10f", rcu.Commatize(int(first)), firstRatio) fmt.Println(" (stays below 0.16 after this)") fmt.Printf("%6s = %12.10f\n", "50,000", sum / 50000) }
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 i in range(numPoints-1) for j in range(i+1,numPoints)), key=itemgetter(0)) def closestPair(point): xP = sorted(point, key= attrgetter('real')) yP = sorted(point, key= attrgetter('imag')) return _closestPair(xP, yP) def _closestPair(xP, yP): numPoints = len(xP) if numPoints <= 3: return bruteForceClosestPair(xP) Pl = xP[:numPoints/2] Pr = xP[numPoints/2:] Yl, Yr = [], [] xDivider = Pl[-1].real for p in yP: if p.real <= xDivider: Yl.append(p) else: Yr.append(p) dl, pairl = _closestPair(Pl, Yl) dr, pairr = _closestPair(Pr, Yr) dm, pairm = (dl, pairl) if dl < dr else (dr, pairr) closeY = [p for p in yP if abs(p.real - xDivider) < dm] numCloseY = len(closeY) if numCloseY > 1: closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j])) for i in range(numCloseY-1) for j in range(i+1,min(i+8, numCloseY))), key=itemgetter(0)) return (dm, pairm) if dm <= closestY[0] else closestY else: return dm, pairm def times(): import timeit functions = [bruteForceClosestPair, closestPair] for f in functions: print 'Time for', f.__name__, timeit.Timer( '%s(pointList)' % f.__name__, 'from closestpair import %s, pointList' % f.__name__).timeit(number=1) pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)] if __name__ == '__main__': pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)] print pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) for i in range(10): pointList = [randrange(11)+1j*randrange(11) for i in range(10)] print '\n', pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) print '\n' times() times() times()
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 points { points[i] = xy{rand.Float64() * scale, rand.Float64() * scale} } p1, p2 := closestPair(points) fmt.Println(p1, p2) fmt.Println("distance:", d(p1, p2)) } func closestPair(points []xy) (p1, p2 xy) { if len(points) < 2 { panic("at least two points expected") } min := 2 * scale for i, q1 := range points[:len(points)-1] { for _, q2 := range points[i+1:] { if dq := d(q1, q2); dq < min { p1, p2 = q1, q2 min = dq } } } return }
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 = int64(uintptr(ptr)) fmt.Printf("Pointer stored in int64: %#016x\n", addr64) } if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) { addr32 = int32(uintptr(ptr)) fmt.Printf("Pointer stored in int32: %#08x\n", addr32) } addr := uintptr(ptr) fmt.Printf("Pointer stored in uintptr: %#08x\n", addr) fmt.Println("value as float:", myVar) i := (*int32)(unsafe.Pointer(&myVar)) fmt.Printf("value as int32: %#08x\n", *i) }
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 = true pet.obedienceTrained = false pet.color = "yellow" }
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) / 2.0 colorMode(HSB) c = color(int(h * 255), int(s * 255), 255) set(x, y, c)
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*(1-sat)*255 + 0.5) q := int(bri*(1-sat*f)*255 + 0.5) t := int(bri*(1-sat*(1-f))*255 + 0.5) switch int(h) { case 0: r, g, b = u, t, p case 1: r, g, b = q, u, p case 2: r, g, b = p, u, t case 3: r, g, b = p, q, u case 4: r, g, b = t, p, u case 5: r, g, b = u, p, q } } return } func colorWheel(dc *gg.Context) { width, height := dc.Width(), dc.Height() centerX, centerY := width/2, height/2 radius := centerX if centerY < radius { radius = centerY } for y := 0; y < height; y++ { dy := float64(y - centerY) for x := 0; x < width; x++ { dx := float64(x - centerX) dist := math.Sqrt(dx*dx + dy*dy) if dist <= float64(radius) { theta := math.Atan2(dy, dx) hue := (theta + math.Pi) / tau r, g, b := hsb2rgb(hue, 1, 1) dc.SetRGB255(r, g, b) dc.SetPixel(x, y) } } } } func main() { const width, height = 480, 480 dc := gg.NewContext(width, height) dc.SetRGB(1, 1, 1) dc.Clear() colorWheel(dc) dc.SavePNG("color_wheel.png") }
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 * cos(y / 32.0))) + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4) buffer[x + y * width] = value def draw(): global r, g, b, rd, gd, bd if r > 128: rd = True if not rd: r += 1 else: r-=1 if r < 0: rd = False if g > 128: gd = True if not gd: g += 1 else: g- = 1 if r < 0: gd = False if b > 128: bd = True if not bd: b += 1 else: b- = 1 if b < 0: bd = False for i in range(128): s_1 = sin(i * PI / 25) s_2 = sin(i * PI / 50 + PI / 4) pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128) loadPixels() for i, b in enumerate(buffer): pixels[i] = pal[(b + frameCount) % 127] updatePixels()
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 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*(1-sat)*255 + 0.5) q := int(bri*(1-sat*f)*255 + 0.5) t := int(bri*(1-sat*(1-f))*255 + 0.5) switch int(h) { case 0: r, g, b = u, t, p case 1: r, g, b = q, u, p case 2: r, g, b = p, u, t case 3: r, g, b = p, q, u case 4: r, g, b = t, p, u case 5: r, g, b = u, p, q } } return } func main() { const degToRad = math.Pi / 180 const nframes = 100 const delay = 4 w, h := 640, 640 anim := gif.GIF{LoopCount: nframes} rect := image.Rect(0, 0, w, h) palette := make([]color.Color, nframes+1) palette[0] = color.White for i := 1; i <= nframes; i++ { r, g, b := hsb2rgb(float64(i)/nframes, 1, 1) palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255} } for f := 1; f <= nframes; f++ { img := image.NewPaletted(rect, palette) setBackgroundColor(img, w, h, 0) for y := 0; y < h; y++ { for x := 0; x < w; x++ { fx, fy := float64(x), float64(y) value := math.Sin(fx / 16) value += math.Sin(fy / 8) value += math.Sin((fx + fy) / 16) value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8) value += 4 value /= 8 _, rem := math.Modf(value + float64(f)/float64(nframes)) ci := uint8(nframes*rem) + 1 img.SetColorIndex(x, y, ci) } } anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } file, err := os.Create("plasma.gif") if err != nil { log.Fatal(err) } defer file.Close() if err2 := gif.EncodeAll(file, &anim); err != nil { log.Fatal(err2) } }
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 enumerate(array)}) _border = set((r, c) for r, c in product(range(-1, 4), repeat=2) if not 0 <= r <= 2 or not 0 <= c <= 2 ) _cell_coords = list(product(range(3), repeat=2)) def topple(self): g = self.grid for r, c in self._cell_coords: if g[(r, c)] >= 4: g[(r - 1, c)] += 1 g[(r + 1, c)] += 1 g[(r, c - 1)] += 1 g[(r, c + 1)] += 1 g[(r, c)] -= 4 return True return False def stabilise(self): while self.topple(): pass g = self.grid for row_col in self._border.intersection(g.keys()): del g[row_col] return self __pos__ = stabilise def __eq__(self, other): g = self.grid return all(g[row_col] == other.grid[row_col] for row_col in self._cell_coords) def __add__(self, other): g = self.grid ans = Sandpile("") for row_col in self._cell_coords: ans.grid[row_col] = g[row_col] + other.grid[row_col] return ans.stabilise() def __str__(self): g, txt = self.grid, [] for row in range(3): txt.append(' '.join(str(g[(row, col)]) for col in range(3))) return '\n'.join(txt) def __repr__(self): return f'{self.__class__.__name__}()' unstable = Sandpile() s1 = Sandpile() s2 = Sandpile() s3 = Sandpile("3 3 3 3 3 3 3 3 3") s3_id = Sandpile("2 1 2 1 0 1 2 1 2")
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 *sandpile) *sandpile { b := [9]int{} for i := 0; i < 9; i++ { b[i] = s.a[i] + other.a[i] } return &sandpile{b} } func (s *sandpile) isStable() bool { for _, e := range s.a { if e > 3 { return false } } return true } func (s *sandpile) topple() { for i := 0; i < 9; i++ { if s.a[i] > 3 { s.a[i] -= 4 for _, j := range neighbors[i] { s.a[j]++ } return } } } func (s *sandpile) String() string { var sb strings.Builder for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { sb.WriteString(strconv.Itoa(s.a[3*i+j]) + " ") } sb.WriteString("\n") } return sb.String() } func main() { fmt.Println("Avalanche of topplings:\n") s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3}) fmt.Println(s4) for !s4.isStable() { s4.topple() fmt.Println(s4) } fmt.Println("Commutative additions:\n") s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3}) s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0}) s3_a := s1.plus(s2) for !s3_a.isStable() { s3_a.topple() } s3_b := s2.plus(s1) for !s3_b.isStable() { s3_b.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s1, s2, s3_a) fmt.Printf("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s\n", s2, s1, s3_b) fmt.Println("Addition of identity sandpile:\n") s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3}) s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2}) s4 = s3.plus(s3_id) for !s4.isStable() { s4.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s3, s3_id, s4) fmt.Println("Addition of identities:\n") s5 := s3_id.plus(s3_id) for !s5.isStable() { s5.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s", s3_id, s3_id, s5) }
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 enumerate(array)}) _border = set((r, c) for r, c in product(range(-1, 4), repeat=2) if not 0 <= r <= 2 or not 0 <= c <= 2 ) _cell_coords = list(product(range(3), repeat=2)) def topple(self): g = self.grid for r, c in self._cell_coords: if g[(r, c)] >= 4: g[(r - 1, c)] += 1 g[(r + 1, c)] += 1 g[(r, c - 1)] += 1 g[(r, c + 1)] += 1 g[(r, c)] -= 4 return True return False def stabilise(self): while self.topple(): pass g = self.grid for row_col in self._border.intersection(g.keys()): del g[row_col] return self __pos__ = stabilise def __eq__(self, other): g = self.grid return all(g[row_col] == other.grid[row_col] for row_col in self._cell_coords) def __add__(self, other): g = self.grid ans = Sandpile("") for row_col in self._cell_coords: ans.grid[row_col] = g[row_col] + other.grid[row_col] return ans.stabilise() def __str__(self): g, txt = self.grid, [] for row in range(3): txt.append(' '.join(str(g[(row, col)]) for col in range(3))) return '\n'.join(txt) def __repr__(self): return f'{self.__class__.__name__}()' unstable = Sandpile() s1 = Sandpile() s2 = Sandpile() s3 = Sandpile("3 3 3 3 3 3 3 3 3") s3_id = Sandpile("2 1 2 1 0 1 2 1 2")
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 *sandpile) *sandpile { b := [9]int{} for i := 0; i < 9; i++ { b[i] = s.a[i] + other.a[i] } return &sandpile{b} } func (s *sandpile) isStable() bool { for _, e := range s.a { if e > 3 { return false } } return true } func (s *sandpile) topple() { for i := 0; i < 9; i++ { if s.a[i] > 3 { s.a[i] -= 4 for _, j := range neighbors[i] { s.a[j]++ } return } } } func (s *sandpile) String() string { var sb strings.Builder for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { sb.WriteString(strconv.Itoa(s.a[3*i+j]) + " ") } sb.WriteString("\n") } return sb.String() } func main() { fmt.Println("Avalanche of topplings:\n") s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3}) fmt.Println(s4) for !s4.isStable() { s4.topple() fmt.Println(s4) } fmt.Println("Commutative additions:\n") s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3}) s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0}) s3_a := s1.plus(s2) for !s3_a.isStable() { s3_a.topple() } s3_b := s2.plus(s1) for !s3_b.isStable() { s3_b.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s1, s2, s3_a) fmt.Printf("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s\n", s2, s1, s3_b) fmt.Println("Addition of identity sandpile:\n") s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3}) s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2}) s4 = s3.plus(s3_id) for !s4.isStable() { s4.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s3, s3_id, s4) fmt.Println("Addition of identities:\n") s5 := s3_id.plus(s3_id) for !s5.isStable() { s5.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s", s3_id, s3_id, s5) }
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.radius = radius def __repr__(self): return '<Circle 0x%x x: %f y: %f radius: %f>' % ( id(self), self.center.x, self.center.y, self.radius)
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 = newPoint(3, 4) i.print() i = newCircle(5, 12, 13) i.print() } func (p *point) getX() float64 { return p.x } func (p *point) getY() float64 { return p.y } func (p *point) setX(v float64) { p.x = v } func (p *point) setY(v float64) { p.y = v } func (c *circle) getX() float64 { return c.x } func (c *circle) getY() float64 { return c.y } func (c *circle) getR() float64 { return c.r } func (c *circle) setX(v float64) { c.x = v } func (c *circle) setY(v float64) { c.y = v } func (c *circle) setR(v float64) { c.r = v } func (p *point) clone() *point { r := *p; return &r } func (c *circle) clone() *circle { r := *c; return &r } func (p *point) set(q *point) { *p = *q } func (c *circle) set(d *circle) { *c = *d } func newPoint(x, y float64) *point { return &point{x, y} } func newCircle(x, y, r float64) *circle { return &circle{x, y, r} }
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.radius = radius def __repr__(self): return '<Circle 0x%x x: %f y: %f radius: %f>' % ( id(self), self.center.x, self.center.y, self.radius)
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 = newPoint(3, 4) i.print() i = newCircle(5, 12, 13) i.print() } func (p *point) getX() float64 { return p.x } func (p *point) getY() float64 { return p.y } func (p *point) setX(v float64) { p.x = v } func (p *point) setY(v float64) { p.y = v } func (c *circle) getX() float64 { return c.x } func (c *circle) getY() float64 { return c.y } func (c *circle) getR() float64 { return c.r } func (c *circle) setX(v float64) { c.x = v } func (c *circle) setY(v float64) { c.y = v } func (c *circle) setR(v float64) { c.r = v } func (p *point) clone() *point { r := *p; return &r } func (c *circle) clone() *circle { r := *c; return &r } func (p *point) set(q *point) { *p = *q } func (c *circle) set(d *circle) { *c = *d } func newPoint(x, y float64) *point { return &point{x, y} } func newCircle(x, y, r float64) *circle { return &circle{x, y, r} }
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 self.default: self.data[key] = self.default[key] else: raise NotImplementedError def __setitem__(self, key, item): if self.__init: super().__setitem__(key, item) elif key in self.data: self.data[key] = item else: raise KeyError def __repr__(self): return "%s(%s)" % (type(self).__name__, super().__repr__()) def fromkeys(cls, iterable, value=None): if self.__init: super().fromkeys(cls, iterable, value) else: for key in iterable: if key in self.data: self.data[key] = value else: raise KeyError def clear(self): self.data.update(copy.deepcopy(self.default)) def pop(self, key, default=None): raise NotImplementedError def popitem(self): raise NotImplementedError def update(self, E, **F): if self.__init: super().update(E, **F) else: haskeys = False try: keys = E.keys() haskeys = Ture except AttributeError: pass if haskeys: for key in keys: self[key] = E[key] else: for key, val in E: self[key] = val for key in F: self[key] = F[key] def setdefault(self, key, default=None): if key not in self.data: raise KeyError else: return super().setdefault(key, default)
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] if ok { rom.imap[key] = 0 } }
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 int(str(n)[::-1]) def is_palindrome(n): return n == reverse(n) def rare(n): r = reverse(n) return ( not is_palindrome(n) and n > r and is_square(n+r) and is_square(n-r) ) if __name__ == '__main__': main()
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(digits[i]) } } else { for i := len(digits) - 1; i >= 0; i-- { sum = sum*10 + uint64(digits[i]) } } return sum } func isSquare(n uint64) bool { if 0x202021202030213&(1<<(n&63)) != 0 { root := uint64(math.Sqrt(float64(n))) return root*root == n } return false } func seq(from, to, step int8) []int8 { var res []int8 for i := from; i <= to; i += step { res = append(res, i) } return res } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { start := time.Now() pow := uint64(1) fmt.Println("Aggregate timings to process all numbers up to:") allTerms := make([][]term, maxDigits-1) for r := 2; r <= maxDigits; r++ { var terms []term pow *= 10 pow1, pow2 := pow, uint64(1) for i1, i2 := int8(0), int8(r-1); i1 < i2; i1, i2 = i1+1, i2-1 { terms = append(terms, term{pow1 - pow2, i1, i2}) pow1 /= 10 pow2 *= 10 } allTerms[r-2] = terms } fml := map[int8][][]int8{ 0: {{2, 2}, {8, 8}}, 1: {{6, 5}, {8, 7}}, 4: {{4, 0}}, 6: {{6, 0}, {8, 2}}, } dmd := make(map[int8][][]int8) for i := int8(0); i < 100; i++ { a := []int8{i / 10, i % 10} d := a[0] - a[1] dmd[d] = append(dmd[d], a) } fl := []int8{0, 1, 4, 6} dl := seq(-9, 9, 1) zl := []int8{0} el := seq(-8, 8, 2) ol := seq(-9, 9, 2) il := seq(0, 9, 1) var rares []uint64 lists := make([][][]int8, 4) for i, f := range fl { lists[i] = [][]int8{{f}} } var digits []int8 count := 0 var fnpr func(cand, di []int8, dis [][]int8, indices [][2]int8, nmr uint64, nd, level int) fnpr = func(cand, di []int8, dis [][]int8, indices [][2]int8, nmr uint64, nd, level int) { if level == len(dis) { digits[indices[0][0]] = fml[cand[0]][di[0]][0] digits[indices[0][1]] = fml[cand[0]][di[0]][1] le := len(di) if nd%2 == 1 { le-- digits[nd/2] = di[le] } for i, d := range di[1:le] { digits[indices[i+1][0]] = dmd[cand[i+1]][d][0] digits[indices[i+1][1]] = dmd[cand[i+1]][d][1] } r := toUint64(digits, true) npr := nmr + 2*r if !isSquare(npr) { return } count++ fmt.Printf(" R/N %2d:", count) ms := uint64(time.Since(start).Milliseconds()) fmt.Printf(" %9s ms", commatize(ms)) n := toUint64(digits, false) fmt.Printf(" (%s)\n", commatize(n)) rares = append(rares, n) } else { for _, num := range dis[level] { di[level] = num fnpr(cand, di, dis, indices, nmr, nd, level+1) } } } var fnmr func(cand []int8, list [][]int8, indices [][2]int8, nd, level int) fnmr = func(cand []int8, list [][]int8, indices [][2]int8, nd, level int) { if level == len(list) { var nmr, nmr2 uint64 for i, t := range allTerms[nd-2] { if cand[i] >= 0 { nmr += t.coeff * uint64(cand[i]) } else { nmr2 += t.coeff * uint64(-cand[i]) if nmr >= nmr2 { nmr -= nmr2 nmr2 = 0 } else { nmr2 -= nmr nmr = 0 } } } if nmr2 >= nmr { return } nmr -= nmr2 if !isSquare(nmr) { return } var dis [][]int8 dis = append(dis, seq(0, int8(len(fml[cand[0]]))-1, 1)) for i := 1; i < len(cand); i++ { dis = append(dis, seq(0, int8(len(dmd[cand[i]]))-1, 1)) } if nd%2 == 1 { dis = append(dis, il) } di := make([]int8, len(dis)) fnpr(cand, di, dis, indices, nmr, nd, 0) } else { for _, num := range list[level] { cand[level] = num fnmr(cand, list, indices, nd, level+1) } } } for nd := 2; nd <= maxDigits; nd++ { digits = make([]int8, nd) if nd == 4 { lists[0] = append(lists[0], zl) lists[1] = append(lists[1], ol) lists[2] = append(lists[2], el) lists[3] = append(lists[3], ol) } else if len(allTerms[nd-2]) > len(lists[0]) { for i := 0; i < 4; i++ { lists[i] = append(lists[i], dl) } } var indices [][2]int8 for _, t := range allTerms[nd-2] { indices = append(indices, [2]int8{t.ix1, t.ix2}) } for _, list := range lists { cand := make([]int8, len(list)) fnmr(cand, list, indices, nd, 0) } ms := uint64(time.Since(start).Milliseconds()) fmt.Printf(" %2d digits: %9s ms\n", nd, commatize(ms)) } sort.Slice(rares, func(i, j int) bool { return rares[i] < rares[j] }) fmt.Printf("\nThe rare numbers with up to %d digits are:\n", maxDigits) for i, rare := range rares { fmt.Printf(" %2d: %25s\n", i+1, commatize(rare)) } }
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 len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)] if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)
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.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) > 10 { words = append(words, s) } } vowelIndices := []int{0, 4, 8, 14, 20} wordGroups := make([][]string, 12) for _, word := range words { letters := make([]int, 26) for _, c := range word { index := c - 97 if index >= 0 && index < 26 { letters[index]++ } } eligible := true uc := 0 for i := 0; i < 26; i++ { if !contains(vowelIndices, i) { if letters[i] > 1 { eligible = false break } else if letters[i] == 1 { uc++ } } } if eligible { wordGroups[uc] = append(wordGroups[uc], word) } } for i := 11; i >= 0; i-- { count := len(wordGroups[i]) if count > 0 { s := "s" if count == 1 { s = "" } fmt.Printf("%d word%s found with %d unique consonants:\n", count, s, i) for j := 0; j < count; j++ { fmt.Printf("%-15s", wordGroups[i][j]) if j > 0 && (j+1)%5 == 0 { fmt.Println() } } fmt.Println() if count%5 != 0 { fmt.Println() } } } }
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 len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)] if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)
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.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) > 10 { words = append(words, s) } } vowelIndices := []int{0, 4, 8, 14, 20} wordGroups := make([][]string, 12) for _, word := range words { letters := make([]int, 26) for _, c := range word { index := c - 97 if index >= 0 && index < 26 { letters[index]++ } } eligible := true uc := 0 for i := 0; i < 26; i++ { if !contains(vowelIndices, i) { if letters[i] > 1 { eligible = false break } else if letters[i] == 1 { uc++ } } } if eligible { wordGroups[uc] = append(wordGroups[uc], word) } } for i := 11; i >= 0; i-- { count := len(wordGroups[i]) if count > 0 { s := "s" if count == 1 { s = "" } fmt.Printf("%d word%s found with %d unique consonants:\n", count, s, i) for j := 0; j < count; j++ { fmt.Printf("%-15s", wordGroups[i][j]) if j > 0 && (j+1)%5 == 0 { fmt.Println() } } fmt.Println() if count%5 != 0 { fmt.Println() } } } }
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 false } d += 2 if n%d == 0 { return false } d += 4 } return true } func main() { var primeRunes []rune for i := 33; i < 256; i += 2 { if isPrime(i) { primeRunes = append(primeRunes, rune(i)) } } primeString := string(primeRunes) wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) fmt.Println("Prime words in", wordList, "are:") for _, bword := range bwords { word := string(bword) ok := true for _, c := range word { if !strings.ContainsRune(primeString, c) { ok = false break } } if ok { fmt.Println(word) } } }
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 false } d += 2 if n%d == 0 { return false } d += 4 } return true } func main() { var primeRunes []rune for i := 33; i < 256; i += 2 { if isPrime(i) { primeRunes = append(primeRunes, rune(i)) } } primeString := string(primeRunes) wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) fmt.Println("Prime words in", wordList, "are:") for _, bword := range bwords { word := string(bword) ok := true for _, c := range word { if !strings.ContainsRune(primeString, c) { ok = false break } } if ok { fmt.Println(word) } } }
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 '') if FOUND == 500: print(f'\nFive hundreth: {num:,}') if FOUND == 5000: print(f'\nFive thousandth: {num:,}') if FOUND == 50000: print(f'\nFifty thousandth: {num:,}') break
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 { count++ } } } return count } func main() { var numbers50 []int count := 0 for n := 1; count < 50000; n++ { dc := divisorCount(n) if n == 1 || dc == 8 { count++ if count <= 50 { numbers50 = append(numbers50, n) if count == 50 { rcu.PrintTable(numbers50, 10, 3, false) } } else if count == 500 { fmt.Printf("\n500th  : %s", rcu.Commatize(n)) } else if count == 5000 { fmt.Printf("\n5,000th : %s", rcu.Commatize(n)) } else if count == 50000 { fmt.Printf("\n50,000th: %s\n", rcu.Commatize(n)) } } } }
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 '') if FOUND == 500: print(f'\nFive hundreth: {num:,}') if FOUND == 5000: print(f'\nFive thousandth: {num:,}') if FOUND == 50000: print(f'\nFifty thousandth: {num:,}') break
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 { count++ } } } return count } func main() { var numbers50 []int count := 0 for n := 1; count < 50000; n++ { dc := divisorCount(n) if n == 1 || dc == 8 { count++ if count <= 50 { numbers50 = append(numbers50, n) if count == 50 { rcu.PrintTable(numbers50, 10, 3, false) } } else if count == 500 { fmt.Printf("\n500th  : %s", rcu.Commatize(n)) } else if count == 5000 { fmt.Printf("\n5,000th : %s", rcu.Commatize(n)) } else if count == 50000 { fmt.Printf("\n50,000th: %s\n", rcu.Commatize(n)) } } } }
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)): yield a, b, c def is_anagram(a: int, b: int, c: int) -> bool: return sorted(str(a)) == sorted(str(b)) == sorted(str(c)) def up_to_one_billion() -> int: count = 0 for triple in triplewise(primes()): if is_anagram(*triple): count += 1 if triple[2] >= 1_000_000_000: break return count def up_to_ten_billion() -> int: count = 0 for triple in triplewise(primes()): if is_anagram(*triple): count += 1 if triple[2] >= 10_000_000_000: break return count def first_25() -> List[int]: rv: List[int] = [] for triple in triplewise(primes()): if is_anagram(*triple): rv.append(triple[0]) if len(rv) >= 25: break return rv if __name__ == "__main__": print("Smallest members of first 25 Ormiston triples:") print(textwrap.fill(" ".join(str(i) for i in first_25())), "\n") print(up_to_one_billion(), "Ormiston triples before 1,000,000,000") print(up_to_ten_billion(), "Ormiston triples before 10,000,000,000")
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-p1)%18 != 0 || (p3-p2)%18 != 0 { continue } key1 := 1 for _, dig := range rcu.Digits(p1, 10) { key1 *= primes[dig] } key2 := 1 for _, dig := range rcu.Digits(p2, 10) { key2 *= primes[dig] } if key1 != key2 { continue } key3 := 1 for _, dig := range rcu.Digits(p3, 10) { key3 *= primes[dig] } if key2 == key3 { if count < 25 { orm25 = append(orm25, p1) } if p1 >= j { counts = append(counts, count) j *= 10 } count++ } } counts = append(counts, count) fmt.Println("Smallest members of first 25 Ormiston triples:") for i := 0; i < 25; i++ { fmt.Printf("%8v ", orm25[i]) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println() j = int(1e9) for i := 0; i < len(counts); i++ { fmt.Printf("%s Ormiston triples before %s\n", rcu.Commatize(counts[i]), rcu.Commatize(j)) j *= 10 fmt.Println() } }
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 = xgrid * ygrid minecount = random.randint(int(minecount*minmines), int(minecount*maxmines)) grid = set(product(range(xgrid), range(ygrid))) mines = set(random.sample(grid, minecount)) show = {xy:'.' for xy in grid} return grid, mines, show def printgrid(show, gridsize=gridsize): xgrid, ygrid = gridsize grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid)) for y in range(ygrid)) print( grid ) def resign(showgrid, mines, markedmines): for m in mines: showgrid[m] = 'Y' if m in markedmines else 'N' def clear(x,y, showgrid, grid, mines, markedmines): if showgrid[(x, y)] == '.': xychar = str(sum(1 for xx in (x-1, x, x+1) for yy in (y-1, y, y+1) if (xx, yy) in mines )) if xychar == '0': xychar = '.' showgrid[(x,y)] = xychar for xx in (x-1, x, x+1): for yy in (y-1, y, y+1): xxyy = (xx, yy) if ( xxyy != (x, y) and xxyy in grid and xxyy not in mines | markedmines ): clear(xx, yy, showgrid, grid, mines, markedmines) if __name__ == '__main__': grid, mines, showgrid = gridandmines() markedmines = set([]) print( __doc__ ) print( '\nThere are %i true mines of fixed position in the grid\n' % len(mines) ) printgrid(showgrid) while markedmines != mines: inp = raw_input('m x y/c x y/p/r: ').strip().split() if inp: if inp[0] == 'm': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in markedmines: markedmines.remove((x,y)) showgrid[(x,y)] = '.' else: markedmines.add((x,y)) showgrid[(x,y)] = '?' elif inp[0] == 'p': printgrid(showgrid) elif inp[0] == 'c': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in mines | markedmines: print( '\nKLABOOM!! You hit a mine.\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break clear(x,y, showgrid, grid, mines, markedmines) printgrid(showgrid) elif inp[0] == 'r': print( '\nResigning!\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break print( '\nYou got %i and missed %i of the %i mines' % (len(mines.intersection(markedmines)), len(markedmines.difference(mines)), len(mines)) )
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.NewScanner(os.Stdin) func makeGrid(n, m int) { if n <= 0 || m <= 0 { panic("Grid dimensions must be positive.") } grid = make([][]cell, n) for i := 0; i < n; i++ { grid[i] = make([]cell, m) for j := 0; j < m; j++ { grid[i][j].display = '.' } } min := int(math.Round(float64(n*m) * 0.1)) max := int(math.Round(float64(n*m) * 0.2)) mineCount = min + rand.Intn(max-min+1) rm := mineCount for rm > 0 { x, y := rand.Intn(n), rand.Intn(m) if !grid[x][y].isMine { rm-- grid[x][y].isMine = true } } minesMarked = 0 isGameOver = false } func displayGrid(isEndOfGame bool) { if !isEndOfGame { fmt.Println("Grid has", mineCount, "mine(s),", minesMarked, "mine(s) marked.") } margin := strings.Repeat(" ", lMargin) fmt.Print(margin, " ") for i := 1; i <= len(grid); i++ { fmt.Print(i) } fmt.Println() fmt.Println(margin, strings.Repeat("-", len(grid))) for y := 0; y < len(grid[0]); y++ { fmt.Printf("%*d:", lMargin, y+1) for x := 0; x < len(grid); x++ { fmt.Printf("%c", grid[x][y].display) } fmt.Println() } } func endGame(msg string) { isGameOver = true fmt.Println(msg) ans := "" for ans != "y" && ans != "n" { fmt.Print("Another game (y/n)? : ") scanner.Scan() ans = strings.ToLower(scanner.Text()) } if scanner.Err() != nil || ans == "n" { return } makeGrid(6, 4) displayGrid(false) } func resign() { found := 0 for y := 0; y < len(grid[0]); y++ { for x := 0; x < len(grid); x++ { if grid[x][y].isMine { if grid[x][y].display == '?' { grid[x][y].display = 'Y' found++ } else if grid[x][y].display != 'x' { grid[x][y].display = 'N' } } } } displayGrid(true) msg := fmt.Sprint("You found ", found, " out of ", mineCount, " mine(s).") endGame(msg) } func usage() { fmt.Println("h or ? - this help,") fmt.Println("c x y - clear cell (x,y),") fmt.Println("m x y - marks (toggles) cell (x,y),") fmt.Println("n - start a new game,") fmt.Println("q - quit/resign the game,") fmt.Println("where x is the (horizontal) column number and y is the (vertical) row number.\n") } func markCell(x, y int) { if grid[x][y].display == '?' { minesMarked-- grid[x][y].display = '.' } else if grid[x][y].display == '.' { minesMarked++ grid[x][y].display = '?' } } func countAdjMines(x, y int) int { count := 0 for j := y - 1; j <= y+1; j++ { if j >= 0 && j < len(grid[0]) { for i := x - 1; i <= x+1; i++ { if i >= 0 && i < len(grid) { if grid[i][j].isMine { count++ } } } } } return count } func clearCell(x, y int) bool { if x >= 0 && x < len(grid) && y >= 0 && y < len(grid[0]) { if grid[x][y].display == '.' { if !grid[x][y].isMine { count := countAdjMines(x, y) if count > 0 { grid[x][y].display = string(48 + count)[0] } else { grid[x][y].display = ' ' clearCell(x+1, y) clearCell(x+1, y+1) clearCell(x, y+1) clearCell(x-1, y+1) clearCell(x-1, y) clearCell(x-1, y-1) clearCell(x, y-1) clearCell(x+1, y-1) } } else { grid[x][y].display = 'x' fmt.Println("Kaboom! You lost!") return false } } } return true } func testForWin() bool { isCleared := false if minesMarked == mineCount { isCleared = true for x := 0; x < len(grid); x++ { for y := 0; y < len(grid[0]); y++ { if grid[x][y].display == '.' { isCleared = false } } } } if isCleared { fmt.Println("You won!") } return isCleared } func splitAction(action string) (int, int, bool) { fields := strings.Fields(action) if len(fields) != 3 { return 0, 0, false } x, err := strconv.Atoi(fields[1]) if err != nil || x < 1 || x > len(grid) { return 0, 0, false } y, err := strconv.Atoi(fields[2]) if err != nil || y < 1 || y > len(grid[0]) { return 0, 0, false } return x, y, true } func main() { rand.Seed(time.Now().UnixNano()) usage() makeGrid(6, 4) displayGrid(false) for !isGameOver { fmt.Print("\n>") scanner.Scan() action := strings.ToLower(scanner.Text()) if scanner.Err() != nil || len(action) == 0 { continue } switch action[0] { case 'h', '?': usage() case 'n': makeGrid(6, 4) displayGrid(false) case 'c': x, y, ok := splitAction(action) if !ok { continue } if clearCell(x-1, y-1) { displayGrid(false) if testForWin() { resign() } } else { resign() } case 'm': x, y, ok := splitAction(action) if !ok { continue } markCell(x-1, y-1) displayGrid(false) if testForWin() { resign() } case 'q': resign() } } }
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[-1])*2 c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1)) if __name__ == '__main__': lines = 25 for rule in (90, 30): print('\nRule: %i' % rule) for i, c in zip(range(lines), eca_infinite('1', rule)): print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '
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.Printf("%*s\n", width, cells) cells = step(cells, rule) } } func step(cells string, rule int) string { newCells := new(strings.Builder) for i := 0; i < len(cells)-2; i++ { bin := 0 b := uint(2) for n := i; n < i+3; n++ { bin += btoi(cells[n] == 'O') << b b >>= 1 } a := '.' if rule&(1<<uint(bin)) != 0 { a = 'O' } newCells.WriteRune(a) } return newCells.String() } func addNoCells(cells string) string { l, r := "O", "O" if cells[0] == 'O' { l = "." } if cells[len(cells)-1] == 'O' { r = "." } cells = l + cells + r cells = l + cells + r return cells } func main() { for _, r := range []int{90, 30} { evolve(25, r) fmt.Println() } }
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 = "" loc = 0 while(loc < len(lines)): command = lines[loc].strip() try: if(command == "Copy"): clipboard += lines[loc + 1] elif(command == "CopyFile"): if(lines[loc + 1] == "TheF*ckingCode"): clipboard += source else: filetext = open(lines[loc+1]).read() clipboard += filetext elif(command == "Duplicate"): clipboard += clipboard * ((int(lines[loc + 1])) - 1) elif(command == "Pasta!"): print(clipboard) sys.exit(0) else: fatal_error("unknown command '" + command + "' encountered on line " + str(loc + 1)) except Exception as e: fatal_error("error while executing command '" + command + "' on line " + str(loc + 1) + ": " + e) loc += 2
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 runtime.GOOS == "windows" { source2 = strings.ReplaceAll(source, "\r\n", "\n") } lines := strings.Split(source2, "\n") le := len(lines) for i := 0; i < le; i++ { lines[i] = strings.TrimSpace(lines[i]) switch lines[i] { case "Copy": if i == le-1 { log.Fatal("There are no lines after the Copy command.") } i++ err := clipboard.WriteAll(lines[i]) check(err) case "CopyFile": if i == le-1 { log.Fatal("There are no lines after the CopyFile command.") } i++ if lines[i] == "TheF*ckingCode" { err := clipboard.WriteAll(source) check(err) } else { bytes, err := ioutil.ReadFile(lines[i]) check(err) err = clipboard.WriteAll(string(bytes)) check(err) } case "Duplicate": if i == le-1 { log.Fatal("There are no lines after the Duplicate command.") } i++ times, err := strconv.Atoi(lines[i]) check(err) if times < 0 { log.Fatal("Can't duplicate text a negative number of times.") } text, err := clipboard.ReadAll() check(err) err = clipboard.WriteAll(strings.Repeat(text, times+1)) check(err) case "Pasta!": text, err := clipboard.ReadAll() check(err) fmt.Println(text) return default: if lines[i] == "" { continue } log.Fatal("Unknown command, " + lines[i]) } } } func main() { if len(os.Args) != 2 { log.Fatal("There should be exactly one command line argument, the CopyPasta file path.") } bytes, err := ioutil.ReadFile(os.Args[1]) check(err) interpret(string(bytes)) err = clipboard.WriteAll("") check(err) }
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 = "" loc = 0 while(loc < len(lines)): command = lines[loc].strip() try: if(command == "Copy"): clipboard += lines[loc + 1] elif(command == "CopyFile"): if(lines[loc + 1] == "TheF*ckingCode"): clipboard += source else: filetext = open(lines[loc+1]).read() clipboard += filetext elif(command == "Duplicate"): clipboard += clipboard * ((int(lines[loc + 1])) - 1) elif(command == "Pasta!"): print(clipboard) sys.exit(0) else: fatal_error("unknown command '" + command + "' encountered on line " + str(loc + 1)) except Exception as e: fatal_error("error while executing command '" + command + "' on line " + str(loc + 1) + ": " + e) loc += 2
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 runtime.GOOS == "windows" { source2 = strings.ReplaceAll(source, "\r\n", "\n") } lines := strings.Split(source2, "\n") le := len(lines) for i := 0; i < le; i++ { lines[i] = strings.TrimSpace(lines[i]) switch lines[i] { case "Copy": if i == le-1 { log.Fatal("There are no lines after the Copy command.") } i++ err := clipboard.WriteAll(lines[i]) check(err) case "CopyFile": if i == le-1 { log.Fatal("There are no lines after the CopyFile command.") } i++ if lines[i] == "TheF*ckingCode" { err := clipboard.WriteAll(source) check(err) } else { bytes, err := ioutil.ReadFile(lines[i]) check(err) err = clipboard.WriteAll(string(bytes)) check(err) } case "Duplicate": if i == le-1 { log.Fatal("There are no lines after the Duplicate command.") } i++ times, err := strconv.Atoi(lines[i]) check(err) if times < 0 { log.Fatal("Can't duplicate text a negative number of times.") } text, err := clipboard.ReadAll() check(err) err = clipboard.WriteAll(strings.Repeat(text, times+1)) check(err) case "Pasta!": text, err := clipboard.ReadAll() check(err) fmt.Println(text) return default: if lines[i] == "" { continue } log.Fatal("Unknown command, " + lines[i]) } } } func main() { if len(os.Args) != 2 { log.Fatal("There should be exactly one command line argument, the CopyPasta file path.") } bytes, err := ioutil.ReadFile(os.Args[1]) check(err) interpret(string(bytes)) err = clipboard.WriteAll("") check(err) }
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): if tpri[i] and tpri[j]: twinsums[i + j] = True return [i for i in range(2, limit+1, 2) if not twinsums[i]] print('Non twin prime sums:') for k, p in enumerate(nonpairsums()): print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '') print('\n\nNon twin prime sums (including 1):') for k, p in enumerate(nonpairsums(include1=True)): print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')
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 } sieve[sum] = true } } var res []int for i := 2; i < limit; i += 2 { if !sieve[i] { res = append(res, i) } } return res } func main() { primes := rcu.Primes(limit)[2:] twins := []int{3} for i := 0; i < len(primes)-1; i++ { if primes[i+1]-primes[i] == 2 { if twins[len(twins)-1] != primes[i] { twins = append(twins, primes[i]) } twins = append(twins, primes[i+1]) } } fmt.Println("Non twin prime sums:") ntps := nonTwinSums(twins) rcu.PrintTable(ntps, 10, 4, false) fmt.Println("Found", len(ntps)) fmt.Println("\nNon twin prime sums (including 1):") twins = append([]int{1}, twins...) ntps = nonTwinSums(twins) rcu.PrintTable(ntps, 10, 4, false) fmt.Println("Found", len(ntps)) }
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 main(): xs = [ str(n) for n in takewhile( lambda n: 1000 > n, filter(monotonicDigits(10), primes()) ) ] w = len(xs[-1]) print(f'{len(xs)} matches for base 10:\n') print('\n'.join( ' '.join(row) for row in chunksOf(10)([ x.rjust(w, ' ') for x in xs ]) )) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitFromInt(n): return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if ( 0 <= n < 36 ) else '?' def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n def showIntAtBase(base): def wrap(toChr, n, rs): def go(nd, r): n, d = nd r_ = toChr(d) + r return go(divmod(n, base), r_) if 0 != n else r_ return 'unsupported base' if 1 >= base else ( 'negative number' if 0 > n else ( go(divmod(n, base), rs)) ) return lambda toChr: lambda n: lambda rs: ( wrap(toChr, n, rs) ) if __name__ == '__main__': main()
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 } func main() { primes := rcu.Primes(999) var nonDesc []int for _, p := range primes { if nonDescending(p) { nonDesc = append(nonDesc, p) } } fmt.Println("Primes below 1,000 with digits in non-decreasing order:") for i, n := range nonDesc { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n%d such primes found.\n", len(nonDesc)) }
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 main(): xs = [ str(n) for n in takewhile( lambda n: 1000 > n, filter(monotonicDigits(10), primes()) ) ] w = len(xs[-1]) print(f'{len(xs)} matches for base 10:\n') print('\n'.join( ' '.join(row) for row in chunksOf(10)([ x.rjust(w, ' ') for x in xs ]) )) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitFromInt(n): return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if ( 0 <= n < 36 ) else '?' def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n def showIntAtBase(base): def wrap(toChr, n, rs): def go(nd, r): n, d = nd r_ = toChr(d) + r return go(divmod(n, base), r_) if 0 != n else r_ return 'unsupported base' if 1 >= base else ( 'negative number' if 0 > n else ( go(divmod(n, base), rs)) ) return lambda toChr: lambda n: lambda rs: ( wrap(toChr, n, rs) ) if __name__ == '__main__': main()
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 } func main() { primes := rcu.Primes(999) var nonDesc []int for _, p := range primes { if nonDescending(p) { nonDesc = append(nonDesc, p) } } fmt.Println("Primes below 1,000 with digits in non-decreasing order:") for i, n := range nonDesc { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n%d such primes found.\n", len(nonDesc)) }
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)__') __reBleh = re.compile('\Wbleh$') @property def reBleh(self): return self.__reBleh def __init__(self, name, *args): super(Child, self).__init__(name) self.args = args def __dir__(self): myDir = filter( lambda p: not self.__rePrivate.match(p), list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ ))) return myDir + map( lambda p: p + '_bleh', filter( lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)), myDir)) def __getattr__(self, name): if name[-5:] == '_bleh': return str(getattr(self, name[:-5])) + ' bleh' if hasattr(super(Child, chld), '__getattr__'): return super(Child, self).__getattr__(name) raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) def __setattr__(self, name, value): if name[-5:] == '_bleh': if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))): setattr(self, name[:-5], self.reBleh.sub('', value)) elif hasattr(super(Child, self), '__setattr__'): super(Child, self).__setattr__(name, value) elif hasattr(self, '__dict__'): self.__dict__[name] = value def __repr__(self): return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()')) def doStuff(self): return (1+1.0/1e6) ** 1e6 par = Parent('par') par.parent = True dir(par) inspect.getmembers(par) chld = Child('chld', 0, 'I', 'two') chld.own = "chld's own" dir(chld) inspect.getmembers(chld)
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 < n; i++ { f := t.Field(i) fmt.Printf("%-8s %-8v %-8t\n", f.Name, f.Type, f.PkgPath == "", ) } fmt.Println() }
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: return 0, ['=1'] possibles = {} for d in self.divs: if n % d == 0: possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d) for s in self.subs: if n > s: possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s) thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1]) ret = 1 + count, [thiskind] + otherkinds return ret def __call__(self, n): "Recursive, memoised" ans = self._minrec(n)[1][:-1] return len(ans), ans if __name__ == '__main__': for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]: minrec = Minrec(DIVS, SUBS) print('\nMINIMUM STEPS TO 1: Recursive algorithm') print(' Possible divisors: ', DIVS) print(' Possible decrements:', SUBS) for n in range(1, 11): steps, how = minrec(n) print(f' minrec({n:2}) in {steps:2} by: ', ', '.join(how)) upto = 2000 print(f'\n Those numbers up to {upto} that take the maximum, "minimal steps down to 1":') stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1)) mx = stepn[-1][0] ans = [x[1] for x in stepn if x[0] == mx] print(' Taking', mx, f'steps is/are the {len(ans)} numbers:', ', '.join(str(n) for n in sorted(ans))) print()
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 { d := n / div steps := len(mins[d]) + 1 if steps < min { min = steps p, q, op = d, div, '/' } } } for _, sub := range subs { if d := n - sub; d >= 1 { steps := len(mins[d]) + 1 if steps < min { min = steps p, q, op = d, sub, '-' } } } mins[n] = append(mins[n], fmt.Sprintf("%c%d -> %d", op, q, p)) mins[n] = append(mins[n], mins[p]...) } func main() { for r := 0; r < 2; r++ { divs = []int{2, 3} if r == 0 { subs = []int{1} } else { subs = []int{2} } mins = make([][]string, limit+1) fmt.Printf("With: Divisors: %v, Subtractors: %v =>\n", divs, subs) fmt.Println(" Minimum number of steps to diminish the following numbers down to 1 is:") for i := 1; i <= limit; i++ { minsteps(i) if i <= 10 { steps := len(mins[i]) plural := "s" if steps == 1 { plural = " " } fmt.Printf(" %2d: %d step%s: %s\n", i, steps, plural, strings.Join(mins[i], ", ")) } } for _, lim := range []int{2000, 20000, 50000} { max := 0 for _, min := range mins[0 : lim+1] { m := len(min) if m > max { max = m } } var maxs []int for i, min := range mins[0 : lim+1] { if len(min) == max { maxs = append(maxs, i) } } nums := len(maxs) verb, verb2, plural := "are", "have", "s" if nums == 1 { verb, verb2, plural = "is", "has", "" } fmt.Printf(" There %s %d number%s in the range 1-%d ", verb, nums, plural, lim) fmt.Printf("that %s maximum 'minimal steps' of %d:\n", verb2, max) fmt.Println(" ", maxs) } fmt.Println() } }
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} column-aligned output:\n") for line in parts: print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line))) print("- " * 52)
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$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.` type formatter struct { text [][]string width []int } func newFormatter(text string) *formatter { var f formatter for _, line := range strings.Split(text, "\n") { words := strings.Split(line, "$") for words[len(words)-1] == "" { words = words[:len(words)-1] } f.text = append(f.text, words) for i, word := range words { if i == len(f.width) { f.width = append(f.width, len(word)) } else if len(word) > f.width[i] { f.width[i] = len(word) } } } return &f } const ( left = iota middle right ) func (f formatter) print(j int) { for _, line := range f.text { for i, word := range line { fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s", len(word)+(f.width[i]-len(word))*j/2, word)) } fmt.Println("") } fmt.Println("") } func main() { f := newFormatter(text) f.print(left) f.print(middle) f.print(right) }
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) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
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:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
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) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
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:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
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) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
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:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
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 sum3 > num: break return True row = 0 for n in range(1, 2000): if is_idoneal(n): row += 1 print(f'{n:5}', end='\n' if row % 13 == 0 else '')
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 { return false } if sum > n { break } } } } return true } func main() { var idoneals []int for n := 1; n <= 1850; n++ { if isIdoneal(n) { idoneals = append(idoneals, n) } } rcu.PrintTable(idoneals, 13, 4, false) }
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("%-56d -> %s" % (s, b)) hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e] for num in hash_arr: b = convertToBase58(num) print("0x%-54x -> %s" % (num, b))
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 { r[i], r[j] = r[j], r[i] } return string(r) } func convertToBase58(hash string, base int) (string, error) { var x, ok = new(big.Int).SetString(hash, base) if !ok { return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base) } var sb strings.Builder var rem = new(big.Int) for x.Cmp(big0) == 1 { x.QuoRem(x, big58, rem) r := rem.Int64() sb.WriteByte(alphabet[r]) } return reverse(sb.String()), nil } func main() { s := "25420294593250030202636073700053352635053786165627414518" b, err := convertToBase58(s, 10) if err != nil { log.Fatal(err) } fmt.Println(s, "->", b) hashes := [...]string{ "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", } for _, hash := range hashes { b58, err := convertToBase58(hash, 0) if err != nil { log.Fatal(err) } fmt.Printf("%-56s -> %s\n", hash, b58) } }
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("%-56d -> %s" % (s, b)) hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e] for num in hash_arr: b = convertToBase58(num) print("0x%-54x -> %s" % (num, b))
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 { r[i], r[j] = r[j], r[i] } return string(r) } func convertToBase58(hash string, base int) (string, error) { var x, ok = new(big.Int).SetString(hash, base) if !ok { return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base) } var sb strings.Builder var rem = new(big.Int) for x.Cmp(big0) == 1 { x.QuoRem(x, big58, rem) r := rem.Int64() sb.WriteByte(alphabet[r]) } return reverse(sb.String()), nil } func main() { s := "25420294593250030202636073700053352635053786165627414518" b, err := convertToBase58(s, 10) if err != nil { log.Fatal(err) } fmt.Println(s, "->", b) hashes := [...]string{ "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", } for _, hash := range hashes { b58, err := convertToBase58(hash, 0) if err != nil { log.Fatal(err) } fmt.Printf("%-56s -> %s\n", hash, b58) } }
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 to create (max 5) : ") scanner.Scan() n, _ = strconv.Atoi(scanner.Text()) check(scanner.Err()) } vars := make(map[string]int) fmt.Println("OK, enter the variable names and their values, below") for i := 1; i <= n; { fmt.Println("\n Variable", i) fmt.Print(" Name  : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if _, ok := vars[name]; ok { fmt.Println(" Sorry, you've already created a variable of that name, try again") continue } var value int var err error for { fmt.Print(" Value : ") scanner.Scan() value, err = strconv.Atoi(scanner.Text()) check(scanner.Err()) if err != nil { fmt.Println(" Not a valid integer, try again") } else { break } } vars[name] = value i++ } fmt.Println("\nEnter q to quit") for { fmt.Print("\nWhich variable do you want to inspect : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if s := strings.ToLower(name); s == "q" { return } v, ok := vars[name] if !ok { fmt.Println("Sorry there's no variable of that name, try again") } else { fmt.Println("It's value is", v) } } }
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, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 ) PC1 = ( 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ) PC2 = ( 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ) E = ( 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 ) Sboxes = { 0: ( 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 ), 1: ( 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 ), 2: ( 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 ), 3: ( 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 ), 4: ( 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 ), 5: ( 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 ), 6: ( 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 ), 7: ( 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 ) } P = ( 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 ) def encrypt(msg, key, decrypt=False): assert isinstance(msg, int) and isinstance(key, int) assert not msg.bit_length() > 64 assert not key.bit_length() > 64 key = permutation_by_table(key, 64, PC1) C0 = key >> 28 D0 = key & (2**28-1) round_keys = generate_round_keys(C0, D0) msg_block = permutation_by_table(msg, 64, IP) L0 = msg_block >> 32 R0 = msg_block & (2**32-1) L_last = L0 R_last = R0 for i in range(1,17): if decrypt: i = 17-i L_round = R_last R_round = L_last ^ round_function(R_last, round_keys[i]) L_last = L_round R_last = R_round cipher_block = (R_round<<32) + L_round cipher_block = permutation_by_table(cipher_block, 64, IP_INV) return cipher_block def round_function(Ri, Ki): Ri = permutation_by_table(Ri, 32, E) Ri ^= Ki Ri_blocks = [((Ri & (0b111111 << shift_val)) >> shift_val) for shift_val in (42,36,30,24,18,12,6,0)] for i, block in enumerate(Ri_blocks): row = ((0b100000 & block) >> 4) + (0b1 & block) col = (0b011110 & block) >> 1 Ri_blocks[i] = Sboxes[i][16*row+col] Ri_blocks = zip(Ri_blocks, (28,24,20,16,12,8,4,0)) Ri = 0 for block, lshift_val in Ri_blocks: Ri += (block << lshift_val) Ri = permutation_by_table(Ri, 32, P) return Ri def permutation_by_table(block, block_len, table): block_str = bin(block)[2:].zfill(block_len) perm = [] for pos in range(len(table)): perm.append(block_str[table[pos]-1]) return int(''.join(perm), 2) def generate_round_keys(C0, D0): round_keys = dict.fromkeys(range(0,17)) lrot_values = (1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1) lrot = lambda val, r_bits, max_bits: \ (val << r_bits%max_bits) & (2**max_bits-1) | \ ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits))) C0 = lrot(C0, 0, 28) D0 = lrot(D0, 0, 28) round_keys[0] = (C0, D0) for i, rot_val in enumerate(lrot_values): i+=1 Ci = lrot(round_keys[i-1][0], rot_val, 28) Di = lrot(round_keys[i-1][1], rot_val, 28) round_keys[i] = (Ci, Di) del round_keys[0] for i, (Ci, Di) in round_keys.items(): Ki = (Ci << 28) + Di round_keys[i] = permutation_by_table(Ki, 56, PC2) return round_keys k = 0x0e329232ea6d0d73 k2 = 0x133457799BBCDFF1 m = 0x8787878787878787 m2 = 0x0123456789ABCDEF def prove(key, msg): print('key: {:x}'.format(key)) print('message: {:x}'.format(msg)) cipher_text = encrypt(msg, key) print('encrypted: {:x}'.format(cipher_text)) plain_text = encrypt(cipher_text, key, decrypt=True) print('decrypted: {:x}'.format(plain_text)) prove(k, m) print('----------') prove(k2, m2)
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("8787878787878787") if err != nil { log.Fatal(err) } dst := make([]byte, des.BlockSize) c.Encrypt(dst, src) fmt.Printf("%x\n", dst) }
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(hi)[:len(hs) - len(ds) + 1]) + 1 shift += len(ds) - 1 elif len(ls) > 100: lo = int(str(ls)[:100]) hi = lo + 1 shift = len(ls) - 100 self.lo, self.hi, self.shift = lo, hi, shift def __mul__(self, other): lo = self.lo*other.lo hi = self.hi*other.hi shift = self.shift + other.shift return Head(lo, hi, shift) def __add__(self, other): if self.shift < other.shift: return other + self sh = self.shift - other.shift if sh >= len(str(other.hi)): return Head(self.lo, self.hi, self.shift) ls = str(other.lo) hs = str(other.hi) lo = self.lo + int(ls[:len(ls)-sh]) hi = self.hi + int(hs[:len(hs)-sh]) return Head(lo, hi, self.shift) def __repr__(self): return str(self.hi)[:20] class Tail(): def __init__(self, v): self.v = int(f'{v:020d}'[-20:]) def __add__(self, other): return Tail(self.v + other.v) def __mul__(self, other): return Tail(self.v*other.v) def __repr__(self): return f'{self.v:020d}'[-20:] def mul(a, b): return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2] def fibo(n, cls): n -= 1 zero, one = cls(0), cls(1) m = (one, one, zero) e = (one, zero, one) while n: if n&1: e = mul(m, e) m = mul(m, m) n >>= 1 return f'{e[0]}' for i in range(2, 10): n = 10**i print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail)) for i in range(3, 8): n = 2**i s = f'2^{n}' print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))
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 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) temp := new(big.Int) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { result[i][j] = new(big.Int) for k := 0; k < rows2; k++ { temp.Mul(m1[i][k], m2[k][j]) result[i][j].Add(result[i][j], temp) } } } return result } func identityMatrix(n uint64) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := uint64(0); i < n; i++ { ident[i] = make(vector, n) for j := uint64(0); j < n; j++ { ident[i][j] = new(big.Int) if i == j { ident[i][j].Set(one) } } } return ident } func (m matrix) pow(n *big.Int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n.Cmp(zero) == -1: panic("Negative exponents not supported") case n.Cmp(zero) == 0: return identityMatrix(uint64(le)) case n.Cmp(one) == 0: return m } pow := identityMatrix(uint64(le)) base := m e := new(big.Int).Set(n) temp := new(big.Int) for e.Cmp(zero) > 0 { temp.And(e, one) if temp.Cmp(one) == 0 { pow = pow.mul(base) } e.Rsh(e, 1) base = base.mul(base) } return pow } func fibonacci(n *big.Int) *big.Int { if n.Cmp(zero) == 0 { return zero } m := matrix{{one, one}, {one, zero}} m = m.pow(n.Sub(n, one)) return m[0][0] } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { start := time.Now() n := new(big.Int) for i := uint64(10); i <= 1e7; i *= 10 { n.SetUint64(i) s := fibonacci(n).String() fmt.Printf("The digits of the %sth Fibonacci number (%s) are:\n", commatize(i), commatize(uint64(len(s)))) if len(s) > 20 { fmt.Printf(" First 20 : %s\n", s[0:20]) if len(s) < 40 { fmt.Printf(" Final %-2d : %s\n", len(s)-20, s[20:]) } else { fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) } } else { fmt.Printf(" All %-2d  : %s\n", len(s), s) } fmt.Println() } sfxs := []string{"nd", "th"} for i, e := range []uint{16, 32} { n.Lsh(one, e) s := fibonacci(n).String() fmt.Printf("The digits of the 2^%d%s Fibonacci number (%s) are:\n", e, sfxs[i], commatize(uint64(len(s)))) fmt.Printf(" First 20 : %s\n", s[0:20]) fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) fmt.Println() } fmt.Printf("Took %s\n\n", time.Since(start)) }
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(hi)[:len(hs) - len(ds) + 1]) + 1 shift += len(ds) - 1 elif len(ls) > 100: lo = int(str(ls)[:100]) hi = lo + 1 shift = len(ls) - 100 self.lo, self.hi, self.shift = lo, hi, shift def __mul__(self, other): lo = self.lo*other.lo hi = self.hi*other.hi shift = self.shift + other.shift return Head(lo, hi, shift) def __add__(self, other): if self.shift < other.shift: return other + self sh = self.shift - other.shift if sh >= len(str(other.hi)): return Head(self.lo, self.hi, self.shift) ls = str(other.lo) hs = str(other.hi) lo = self.lo + int(ls[:len(ls)-sh]) hi = self.hi + int(hs[:len(hs)-sh]) return Head(lo, hi, self.shift) def __repr__(self): return str(self.hi)[:20] class Tail(): def __init__(self, v): self.v = int(f'{v:020d}'[-20:]) def __add__(self, other): return Tail(self.v + other.v) def __mul__(self, other): return Tail(self.v*other.v) def __repr__(self): return f'{self.v:020d}'[-20:] def mul(a, b): return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2] def fibo(n, cls): n -= 1 zero, one = cls(0), cls(1) m = (one, one, zero) e = (one, zero, one) while n: if n&1: e = mul(m, e) m = mul(m, m) n >>= 1 return f'{e[0]}' for i in range(2, 10): n = 10**i print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail)) for i in range(3, 8): n = 2**i s = f'2^{n}' print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))
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 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) temp := new(big.Int) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { result[i][j] = new(big.Int) for k := 0; k < rows2; k++ { temp.Mul(m1[i][k], m2[k][j]) result[i][j].Add(result[i][j], temp) } } } return result } func identityMatrix(n uint64) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := uint64(0); i < n; i++ { ident[i] = make(vector, n) for j := uint64(0); j < n; j++ { ident[i][j] = new(big.Int) if i == j { ident[i][j].Set(one) } } } return ident } func (m matrix) pow(n *big.Int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n.Cmp(zero) == -1: panic("Negative exponents not supported") case n.Cmp(zero) == 0: return identityMatrix(uint64(le)) case n.Cmp(one) == 0: return m } pow := identityMatrix(uint64(le)) base := m e := new(big.Int).Set(n) temp := new(big.Int) for e.Cmp(zero) > 0 { temp.And(e, one) if temp.Cmp(one) == 0 { pow = pow.mul(base) } e.Rsh(e, 1) base = base.mul(base) } return pow } func fibonacci(n *big.Int) *big.Int { if n.Cmp(zero) == 0 { return zero } m := matrix{{one, one}, {one, zero}} m = m.pow(n.Sub(n, one)) return m[0][0] } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { start := time.Now() n := new(big.Int) for i := uint64(10); i <= 1e7; i *= 10 { n.SetUint64(i) s := fibonacci(n).String() fmt.Printf("The digits of the %sth Fibonacci number (%s) are:\n", commatize(i), commatize(uint64(len(s)))) if len(s) > 20 { fmt.Printf(" First 20 : %s\n", s[0:20]) if len(s) < 40 { fmt.Printf(" Final %-2d : %s\n", len(s)-20, s[20:]) } else { fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) } } else { fmt.Printf(" All %-2d  : %s\n", len(s), s) } fmt.Println() } sfxs := []string{"nd", "th"} for i, e := range []uint{16, 32} { n.Lsh(one, e) s := fibonacci(n).String() fmt.Printf("The digits of the 2^%d%s Fibonacci number (%s) are:\n", e, sfxs[i], commatize(uint64(len(s)))) fmt.Printf(" First 20 : %s\n", s[0:20]) fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) fmt.Println() } fmt.Printf("Took %s\n\n", time.Since(start)) }
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) if I!=J: it = double(it) for t1, t2 in it: if ((I+t1)*(J+t2)+1)%10**n == 0: l.add((I+t1, J+t2)) T.append(l) return T[n] def largestPalindrome(n): m, tail = 0, n // 2 head = n - tail up = 10**head for L in range(1, 9*10**(head-1)+1): m = 0 sol = None for i in range(1, L + 1): lo = max(i, int(up - (up - L + 1)**2 / (up - i)) + 1) hi = int(up - (up - L)**2 / (up - i)) for j in range(lo, hi + 1): I = (up-i) * 10**tail J = (up-j) * 10**tail it = tails(tail) if I!=J: it = double(it) for t1, t2 in it: val = (I + t1)*(J + t2) s = str(val) if s == s[::-1] and val>m: sol = (I + t1, J + t2) m = val if m: print("{:2d}\t{:4d}".format(n, m % 1337), sol, sol[0] * sol[1]) return m % 1337 return 0 if __name__ == "__main__": for k in range(1, 14): largestPalindrome(k)
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("Largest palindromic product of two %d-digit integers: ", n) for i := high; i >= low; i-- { j := reverse(i) p := i*pow + j for k := high; k > low; k -= 2 { if k % 10 == 5 { continue } l := p / k if l > high { break } if p%k == 0 { fmt.Printf("%d x %d = %d\n", k, l, p) continue nextN } } } } }