Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Ensure the translated Go code behaves exactly like the original Python snippet.
import re as RegEx def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ): outString = "" strPos = 0 matches = RegEx.findall( "[0-9]*", _string ) for match in matches[:-1]: if not match: outString += _string[ strPos ] strPos += 1 else: if len(match) > _periodLen: leadIn = match[:_startPos] periods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ] outString += leadIn + _separator.join( periods ) else: outString += match strPos += len( match ) return outString print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) ) print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." )) print ( Commatize( "\"-in Aus$+1411.8millions\"" )) print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" )) print ( Commatize( "123.e8000 is pretty big." )) print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." )) print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." )) print ( Commatize( "James was never known as 0000000007" )) print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." )) print ( Commatize( "␢␢␢$-140000±100 millions." )) print ( Commatize( "6/9/1946 was a good year for some." ))
package main import ( "fmt" "regexp" "strings" ) var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func commatize(s string, startIndex, period int, sep string) string { if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == "" { return s } m := reg.FindString(s[startIndex:]) if m == "" { return s } splits := strings.Split(m, ".") ip := splits[0] if len(ip) > period { pi := reverse(ip) for i := (len(ip) - 1) / period * period; i >= period; i -= period { pi = pi[:i] + sep + pi[i:] } ip = reverse(pi) } if strings.Contains(m, ".") { dp := splits[1] if len(dp) > period { for i := (len(dp) - 1) / period * period; i >= period; i -= period { dp = dp[:i] + sep + dp[i:] } } ip += "." + dp } return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1) } func main() { tests := [...]string{ "123456789.123456789", ".123456789", "57256.1D-4", "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "-in Aus$+1411.8millions", "===US$0017440 millions=== (in 2000 dollars)", "123.e8000 is pretty big.", "The land area of the earth is 57268900(29% of the surface) square miles.", "Ain't no numbers in this here words, nohow, no way, Jose.", "James was never known as 0000000007", "Arthur Eddington wrote: I believe there are " + "15747724136275002577605653961181555468044717914527116709366231425076185631031296" + " protons in the universe.", " $-140000±100 millions.", "6/9/1946 was a good year for some.", } fmt.Println(commatize(tests[0], 0, 2, "*")) fmt.Println(commatize(tests[1], 0, 3, "-")) fmt.Println(commatize(tests[2], 0, 4, "__")) fmt.Println(commatize(tests[3], 0, 5, " ")) fmt.Println(commatize(tests[4], 0, 3, ".")) for _, test := range tests[5:] { fmt.Println(commatize(test, 0, 3, ",")) } }
Write the same algorithm in Go as shown in this Python implementation.
import re as RegEx def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ): outString = "" strPos = 0 matches = RegEx.findall( "[0-9]*", _string ) for match in matches[:-1]: if not match: outString += _string[ strPos ] strPos += 1 else: if len(match) > _periodLen: leadIn = match[:_startPos] periods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ] outString += leadIn + _separator.join( periods ) else: outString += match strPos += len( match ) return outString print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) ) print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." )) print ( Commatize( "\"-in Aus$+1411.8millions\"" )) print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" )) print ( Commatize( "123.e8000 is pretty big." )) print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." )) print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." )) print ( Commatize( "James was never known as 0000000007" )) print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." )) print ( Commatize( "␢␢␢$-140000±100 millions." )) print ( Commatize( "6/9/1946 was a good year for some." ))
package main import ( "fmt" "regexp" "strings" ) var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func commatize(s string, startIndex, period int, sep string) string { if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == "" { return s } m := reg.FindString(s[startIndex:]) if m == "" { return s } splits := strings.Split(m, ".") ip := splits[0] if len(ip) > period { pi := reverse(ip) for i := (len(ip) - 1) / period * period; i >= period; i -= period { pi = pi[:i] + sep + pi[i:] } ip = reverse(pi) } if strings.Contains(m, ".") { dp := splits[1] if len(dp) > period { for i := (len(dp) - 1) / period * period; i >= period; i -= period { dp = dp[:i] + sep + dp[i:] } } ip += "." + dp } return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1) } func main() { tests := [...]string{ "123456789.123456789", ".123456789", "57256.1D-4", "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "-in Aus$+1411.8millions", "===US$0017440 millions=== (in 2000 dollars)", "123.e8000 is pretty big.", "The land area of the earth is 57268900(29% of the surface) square miles.", "Ain't no numbers in this here words, nohow, no way, Jose.", "James was never known as 0000000007", "Arthur Eddington wrote: I believe there are " + "15747724136275002577605653961181555468044717914527116709366231425076185631031296" + " protons in the universe.", " $-140000±100 millions.", "6/9/1946 was a good year for some.", } fmt.Println(commatize(tests[0], 0, 2, "*")) fmt.Println(commatize(tests[1], 0, 3, "-")) fmt.Println(commatize(tests[2], 0, 4, "__")) fmt.Println(commatize(tests[3], 0, 5, " ")) fmt.Println(commatize(tests[4], 0, 3, ".")) for _, test := range tests[5:] { fmt.Println(commatize(test, 0, 3, ",")) } }
Produce a language-to-language conversion: from Python to Go, same semantics.
from collections import Counter def cumulative_freq(freq): cf = {} total = 0 for b in range(256): if b in freq: cf[b] = total total += freq[b] return cf def arithmethic_coding(bytes, radix): freq = Counter(bytes) cf = cumulative_freq(freq) base = len(bytes) lower = 0 pf = 1 for b in bytes: lower = lower*base + cf[b]*pf pf *= freq[b] upper = lower+pf pow = 0 while True: pf //= radix if pf==0: break pow += 1 enc = (upper-1) // radix**pow return enc, pow, freq def arithmethic_decoding(enc, radix, pow, freq): enc *= radix**pow; base = sum(freq.values()) cf = cumulative_freq(freq) dict = {} for k,v in cf.items(): dict[v] = k lchar = None for i in range(base): if i in dict: lchar = dict[i] elif lchar is not None: dict[i] = lchar decoded = bytearray() for i in range(base-1, -1, -1): pow = base**i div = enc//pow c = dict[div] fv = freq[c] cv = cf[c] rem = (enc - pow*cv) // fv enc = rem decoded.append(c) return bytes(decoded) radix = 10 for str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split(): enc, pow, freq = arithmethic_coding(str, radix) dec = arithmethic_decoding(enc, radix, pow, freq) print("%-25s=> %19s * %d^%s" % (str, enc, radix, pow)) if str != dec: raise Exception("\tHowever that is incorrect!")
package main import ( "fmt" "math/big" ) func cumulative_freq(freq map[byte]int64) map[byte]int64 { total := int64(0) cf := make(map[byte]int64) for i := 0; i < 256; i++ { b := byte(i) if v, ok := freq[b]; ok { cf[b] = total total += v } } return cf } func arithmethic_coding(str string, radix int64) (*big.Int, *big.Int, map[byte]int64) { chars := []byte(str) freq := make(map[byte]int64) for _, c := range chars { freq[c] += 1 } cf := cumulative_freq(freq) base := len(chars) L := big.NewInt(0) pf := big.NewInt(1) bigBase := big.NewInt(int64(base)) for _, c := range chars { x := big.NewInt(cf[c]) L.Mul(L, bigBase) L.Add(L, x.Mul(x, pf)) pf.Mul(pf, big.NewInt(freq[c])) } U := big.NewInt(0) U.Set(L) U.Add(U, pf) bigOne := big.NewInt(1) bigZero := big.NewInt(0) bigRadix := big.NewInt(radix) tmp := big.NewInt(0).Set(pf) powr := big.NewInt(0) for { tmp.Div(tmp, bigRadix) if tmp.Cmp(bigZero) == 0 { break } powr.Add(powr, bigOne) } diff := big.NewInt(0) diff.Sub(U, bigOne) diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil)) return diff, powr, freq } func arithmethic_decoding(num *big.Int, radix int64, pow *big.Int, freq map[byte]int64) string { powr := big.NewInt(radix) enc := big.NewInt(0).Set(num) enc.Mul(enc, powr.Exp(powr, pow, nil)) base := int64(0) for _, v := range freq { base += v } cf := cumulative_freq(freq) dict := make(map[int64]byte) for k, v := range cf { dict[v] = k } lchar := -1 for i := int64(0); i < base; i++ { if v, ok := dict[i]; ok { lchar = int(v) } else if lchar != -1 { dict[i] = byte(lchar) } } decoded := make([]byte, base) bigBase := big.NewInt(base) for i := base - 1; i >= 0; i-- { pow := big.NewInt(0) pow.Exp(bigBase, big.NewInt(i), nil) div := big.NewInt(0) div.Div(enc, pow) c := dict[div.Int64()] fv := freq[c] cv := cf[c] prod := big.NewInt(0).Mul(pow, big.NewInt(cv)) diff := big.NewInt(0).Sub(enc, prod) enc.Div(diff, big.NewInt(fv)) decoded[base-i-1] = c } return string(decoded) } func main() { var radix = int64(10) strSlice := []string{ `DABDDB`, `DABDDBBDDBA`, `ABRACADABRA`, `TOBEORNOTTOBEORTOBEORNOT`, } for _, str := range strSlice { enc, pow, freq := arithmethic_coding(str, radix) dec := arithmethic_decoding(enc, radix, pow, freq) fmt.Printf("%-25s=> %19s * %d^%s\n", str, enc, radix, pow) if str != dec { panic("\tHowever that is incorrect!") } } }
Convert the following code from Python to Go, ensuring the logic remains intact.
from collections import Counter def cumulative_freq(freq): cf = {} total = 0 for b in range(256): if b in freq: cf[b] = total total += freq[b] return cf def arithmethic_coding(bytes, radix): freq = Counter(bytes) cf = cumulative_freq(freq) base = len(bytes) lower = 0 pf = 1 for b in bytes: lower = lower*base + cf[b]*pf pf *= freq[b] upper = lower+pf pow = 0 while True: pf //= radix if pf==0: break pow += 1 enc = (upper-1) // radix**pow return enc, pow, freq def arithmethic_decoding(enc, radix, pow, freq): enc *= radix**pow; base = sum(freq.values()) cf = cumulative_freq(freq) dict = {} for k,v in cf.items(): dict[v] = k lchar = None for i in range(base): if i in dict: lchar = dict[i] elif lchar is not None: dict[i] = lchar decoded = bytearray() for i in range(base-1, -1, -1): pow = base**i div = enc//pow c = dict[div] fv = freq[c] cv = cf[c] rem = (enc - pow*cv) // fv enc = rem decoded.append(c) return bytes(decoded) radix = 10 for str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split(): enc, pow, freq = arithmethic_coding(str, radix) dec = arithmethic_decoding(enc, radix, pow, freq) print("%-25s=> %19s * %d^%s" % (str, enc, radix, pow)) if str != dec: raise Exception("\tHowever that is incorrect!")
package main import ( "fmt" "math/big" ) func cumulative_freq(freq map[byte]int64) map[byte]int64 { total := int64(0) cf := make(map[byte]int64) for i := 0; i < 256; i++ { b := byte(i) if v, ok := freq[b]; ok { cf[b] = total total += v } } return cf } func arithmethic_coding(str string, radix int64) (*big.Int, *big.Int, map[byte]int64) { chars := []byte(str) freq := make(map[byte]int64) for _, c := range chars { freq[c] += 1 } cf := cumulative_freq(freq) base := len(chars) L := big.NewInt(0) pf := big.NewInt(1) bigBase := big.NewInt(int64(base)) for _, c := range chars { x := big.NewInt(cf[c]) L.Mul(L, bigBase) L.Add(L, x.Mul(x, pf)) pf.Mul(pf, big.NewInt(freq[c])) } U := big.NewInt(0) U.Set(L) U.Add(U, pf) bigOne := big.NewInt(1) bigZero := big.NewInt(0) bigRadix := big.NewInt(radix) tmp := big.NewInt(0).Set(pf) powr := big.NewInt(0) for { tmp.Div(tmp, bigRadix) if tmp.Cmp(bigZero) == 0 { break } powr.Add(powr, bigOne) } diff := big.NewInt(0) diff.Sub(U, bigOne) diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil)) return diff, powr, freq } func arithmethic_decoding(num *big.Int, radix int64, pow *big.Int, freq map[byte]int64) string { powr := big.NewInt(radix) enc := big.NewInt(0).Set(num) enc.Mul(enc, powr.Exp(powr, pow, nil)) base := int64(0) for _, v := range freq { base += v } cf := cumulative_freq(freq) dict := make(map[int64]byte) for k, v := range cf { dict[v] = k } lchar := -1 for i := int64(0); i < base; i++ { if v, ok := dict[i]; ok { lchar = int(v) } else if lchar != -1 { dict[i] = byte(lchar) } } decoded := make([]byte, base) bigBase := big.NewInt(base) for i := base - 1; i >= 0; i-- { pow := big.NewInt(0) pow.Exp(bigBase, big.NewInt(i), nil) div := big.NewInt(0) div.Div(enc, pow) c := dict[div.Int64()] fv := freq[c] cv := cf[c] prod := big.NewInt(0).Mul(pow, big.NewInt(cv)) diff := big.NewInt(0).Sub(enc, prod) enc.Div(diff, big.NewInt(fv)) decoded[base-i-1] = c } return string(decoded) } func main() { var radix = int64(10) strSlice := []string{ `DABDDB`, `DABDDBBDDBA`, `ABRACADABRA`, `TOBEORNOTTOBEORTOBEORNOT`, } for _, str := range strSlice { enc, pow, freq := arithmethic_coding(str, radix) dec := arithmethic_decoding(enc, radix, pow, freq) fmt.Printf("%-25s=> %19s * %d^%s\n", str, enc, radix, pow) if str != dec { panic("\tHowever that is incorrect!") } } }
Generate a Go translation of this Python snippet without changing its computational steps.
def kosaraju(g): class nonlocal: pass size = len(g) vis = [False]*size l = [0]*size nonlocal.x = size t = [[]]*size def visit(u): if not vis[u]: vis[u] = True for v in g[u]: visit(v) t[v] = t[v] + [u] nonlocal.x = nonlocal.x - 1 l[nonlocal.x] = u for u in range(len(g)): visit(u) c = [0]*size def assign(u, root): if vis[u]: vis[u] = False c[u] = root for v in t[u]: assign(v, root) for u in l: assign(u, u) return c g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]] print kosaraju(g)
package main import "fmt" var g = [][]int{ 0: {1}, 1: {2}, 2: {0}, 3: {1, 2, 4}, 4: {3, 5}, 5: {2, 6}, 6: {5}, 7: {4, 6, 7}, } func main() { fmt.Println(kosaraju(g)) } func kosaraju(g [][]int) []int { vis := make([]bool, len(g)) L := make([]int, len(g)) x := len(L) t := make([][]int, len(g)) var Visit func(int) Visit = func(u int) { if !vis[u] { vis[u] = true for _, v := range g[u] { Visit(v) t[v] = append(t[v], u) } x-- L[x] = u } } for u := range g { Visit(u) } c := make([]int, len(g)) var Assign func(int, int) Assign = func(u, root int) { if vis[u] { vis[u] = false c[u] = root for _, v := range t[u] { Assign(v, root) } } } for _, u := range L { Assign(u, u) } return c }
Port the provided Python code into Go while preserving the original functionality.
import inspect class Super(object): def __init__(self, name): self.name = name def __str__(self): return "Super(%s)" % (self.name,) def doSup(self): return 'did super stuff' @classmethod def cls(cls): return 'cls method (in sup)' @classmethod def supCls(cls): return 'Super method' @staticmethod def supStatic(): return 'static method' class Other(object): def otherMethod(self): return 'other method' class Sub(Other, Super): def __init__(self, name, *args): super(Sub, self).__init__(name); self.rest = args; self.methods = {} def __dir__(self): return list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ + self.methods.keys() \ )) def __getattr__(self, name): if name in self.methods: if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0: if self.methods[name].__code__.co_varnames[0] == 'self': return self.methods[name].__get__(self, type(self)) if self.methods[name].__code__.co_varnames[0] == 'cls': return self.methods[name].__get__(type(self), type) return self.methods[name] raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) def __str__(self): return "Sub(%s)" % self.name def doSub(): return 'did sub stuff' @classmethod def cls(cls): return 'cls method (in Sub)' @classmethod def subCls(cls): return 'Sub method' @staticmethod def subStatic(): return 'Sub method' sup = Super('sup') sub = Sub('sub', 0, 'I', 'two') sub.methods['incr'] = lambda x: x+1 sub.methods['strs'] = lambda self, x: str(self) * x [method for method in dir(sub) if callable(getattr(sub, method))] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)] [method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)] inspect.getmembers(sub, predicate=inspect.ismethod) map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
package main import ( "fmt" "image" "reflect" ) type t int func (r t) Twice() t { return r * 2 } func (r t) Half() t { return r / 2 } func (r t) Less(r2 t) bool { return r < r2 } func (r t) privateMethod() {} func main() { report(t(0)) report(image.Point{}) } func report(x interface{}) { v := reflect.ValueOf(x) t := reflect.TypeOf(x) n := t.NumMethod() fmt.Printf("Type %v has %d exported methods:\n", t, n) const format = "%-6s %-46s %s\n" fmt.Printf(format, "Name", "Method expression", "Method value") for i := 0; i < n; i++ { fmt.Printf(format, t.Method(i).Name, t.Method(i).Func.Type(), v.Method(i).Type(), ) } fmt.Println() }
Change the programming language of this snippet from Python to Go without modifying what it does.
from itertools import product minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)), ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)), ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)), ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)), ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)), ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)), ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)), ((4311810305, 8, 4), (31, 4, 8)), ((132866, 6, 6),)) boxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋' boxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)] patterns = boxchar_single_width tiles = [] for row in reversed(minos): tiles.append([]) for n, x, y in row: for shift in (b*8 + a for a, b in product(range(x), range(y))): tiles[-1].append(n << shift) def img(seq): b = [[0]*10 for _ in range(10)] for i, s in enumerate(seq): for j, k in product(range(8), range(8)): if s & (1<<(j*8 + k)): b[j + 1][k + 1] = i + 1 idices = [[0]*9 for _ in range(9)] for i, j in product(range(9), range(9)): n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1]) idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:]))) return '\n'.join(''.join(patterns[i] for i in row) for row in idices) def tile(board=0, seq=tuple(), tiles=tiles): if not tiles: yield img(seq) return for c in tiles[0]: b = board | c tnext = [] for t in tiles[1:]: tnext.append(tuple(n for n in t if not n&b)) if not tnext[-1]: break else: yield from tile(b, seq + (c,), tnext) for x in tile(): print(x)
package main import ( "fmt" "math/rand" "time" ) var F = [][]int{ {1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}, } var I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}} var L = [][]int{ {1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}, } var N = [][]int{ {0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3}, {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}, } var P = [][]int{ {0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1}, {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2}, {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}, } var T = [][]int{ {0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0}, {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}, } var U = [][]int{ {0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1}, {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}, } var V = [][]int{ {1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0}, {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}, } var W = [][]int{ {1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}, } var X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}} var Y = [][]int{ {1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2}, {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}, } var Z = [][]int{ {0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2}, {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}, } var shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z} var symbols = []byte("FILNPTUVWXYZ-") const ( nRows = 8 nCols = 8 blank = 12 ) var grid [nRows][nCols]int var placed [12]bool func tryPlaceOrientation(o []int, r, c, shapeIndex int) bool { for i := 0; i < len(o); i += 2 { x := c + o[i+1] y := r + o[i] if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 { return false } } grid[r][c] = shapeIndex for i := 0; i < len(o); i += 2 { grid[r+o[i]][c+o[i+1]] = shapeIndex } return true } func removeOrientation(o []int, r, c int) { grid[r][c] = -1 for i := 0; i < len(o); i += 2 { grid[r+o[i]][c+o[i+1]] = -1 } } func solve(pos, numPlaced int) bool { if numPlaced == len(shapes) { return true } row := pos / nCols col := pos % nCols if grid[row][col] != -1 { return solve(pos+1, numPlaced) } for i := range shapes { if !placed[i] { for _, orientation := range shapes[i] { if !tryPlaceOrientation(orientation, row, col, i) { continue } placed[i] = true if solve(pos+1, numPlaced+1) { return true } removeOrientation(orientation, row, col) placed[i] = false } } } return false } func shuffleShapes() { rand.Shuffle(len(shapes), func(i, j int) { shapes[i], shapes[j] = shapes[j], shapes[i] symbols[i], symbols[j] = symbols[j], symbols[i] }) } func printResult() { for _, r := range grid { for _, i := range r { fmt.Printf("%c ", symbols[i]) } fmt.Println() } } func main() { rand.Seed(time.Now().UnixNano()) shuffleShapes() for r := 0; r < nRows; r++ { for i := range grid[r] { grid[r][i] = -1 } } for i := 0; i < 4; i++ { var randRow, randCol int for { randRow = rand.Intn(nRows) randCol = rand.Intn(nCols) if grid[randRow][randCol] != blank { break } } grid[randRow][randCol] = blank } if solve(0, 0) { printResult() } else { fmt.Println("No solution") } }
Change the following Python code into Go without altering its purpose.
class Example(object): def foo(self, x): return 42 + x name = "foo" getattr(Example(), name)(5)
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func main() { var e example m := reflect.ValueOf(e).MethodByName("Foo") r := m.Call(nil) fmt.Println(r[0].Int()) }
Convert the following code from Python to Go, ensuring the logic remains intact.
example1 = 3 example2 = 3.0 example3 = True example4 = "hello" example1 = "goodbye"
x := 3
Generate a Go translation of this Python snippet without changing its computational steps.
import math import random INFINITY = 1 << 127 MAX_INT = 1 << 31 class Parameters: def __init__(self, omega, phip, phig): self.omega = omega self.phip = phip self.phig = phig class State: def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims): self.iter = iter self.gbpos = gbpos self.gbval = gbval self.min = min self.max = max self.parameters = parameters self.pos = pos self.vel = vel self.bpos = bpos self.bval = bval self.nParticles = nParticles self.nDims = nDims def report(self, testfunc): print "Test Function :", testfunc print "Iterations  :", self.iter print "Global Best Position :", self.gbpos print "Global Best Value  : %.16f" % self.gbval def uniform01(): v = random.random() assert 0.0 <= v and v < 1.0 return v def psoInit(min, max, parameters, nParticles): nDims = len(min) pos = [min[:]] * nParticles vel = [[0.0] * nDims] * nParticles bpos = [min[:]] * nParticles bval = [INFINITY] * nParticles iter = 0 gbpos = [INFINITY] * nDims gbval = INFINITY return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims); def pso(fn, y): p = y.parameters v = [0.0] * (y.nParticles) bpos = [y.min[:]] * (y.nParticles) bval = [0.0] * (y.nParticles) gbpos = [0.0] * (y.nDims) gbval = INFINITY for j in xrange(0, y.nParticles): v[j] = fn(y.pos[j]) if v[j] < y.bval[j]: bpos[j] = y.pos[j][:] bval[j] = v[j] else: bpos[j] = y.bpos[j][:] bval[j] = y.bval[j] if bval[j] < gbval: gbval = bval[j] gbpos = bpos[j][:] rg = uniform01() pos = [[None] * (y.nDims)] * (y.nParticles) vel = [[None] * (y.nDims)] * (y.nParticles) for j in xrange(0, y.nParticles): rp = uniform01() ok = True vel[j] = [0.0] * (len(vel[j])) pos[j] = [0.0] * (len(pos[j])) for k in xrange(0, y.nDims): vel[j][k] = p.omega * y.vel[j][k] \ + p.phip * rp * (bpos[j][k] - y.pos[j][k]) \ + p.phig * rg * (gbpos[k] - y.pos[j][k]) pos[j][k] = y.pos[j][k] + vel[j][k] ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k] if not ok: for k in xrange(0, y.nDims): pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01() iter = 1 + y.iter return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims); def iterate(fn, n, y): r = y old = y if n == MAX_INT: while True: r = pso(fn, r) if r == old: break old = r else: for _ in xrange(0, n): r = pso(fn, r) return r def mccormick(x): (a, b) = x return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a def michalewicz(x): m = 10 d = len(x) sum = 0.0 for i in xrange(1, d): j = x[i - 1] k = math.sin(i * j * j / math.pi) sum += math.sin(j) * k ** (2.0 * m) return -sum def main(): state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100) state = iterate(mccormick, 40, state) state.report("McCormick") print "f(-.54719, -1.54719) : %.16f" % (mccormick([-.54719, -1.54719])) print state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000) state = iterate(michalewicz, 30, state) state.report("Michalewicz (2D)") print "f(2.20, 1.57)  : %.16f" % (michalewicz([2.2, 1.57])) main()
package main import ( "fmt" "math" "math/rand" "time" ) type ff = func([]float64) float64 type parameters struct{ omega, phip, phig float64 } type state struct { iter int gbpos []float64 gbval float64 min []float64 max []float64 params parameters pos [][]float64 vel [][]float64 bpos [][]float64 bval []float64 nParticles int nDims int } func (s state) report(testfunc string) { fmt.Println("Test Function  :", testfunc) fmt.Println("Iterations  :", s.iter) fmt.Println("Global Best Position :", s.gbpos) fmt.Println("Global Best Value  :", s.gbval) } func psoInit(min, max []float64, params parameters, nParticles int) *state { nDims := len(min) pos := make([][]float64, nParticles) vel := make([][]float64, nParticles) bpos := make([][]float64, nParticles) bval := make([]float64, nParticles) for i := 0; i < nParticles; i++ { pos[i] = min vel[i] = make([]float64, nDims) bpos[i] = min bval[i] = math.Inf(1) } iter := 0 gbpos := make([]float64, nDims) for i := 0; i < nDims; i++ { gbpos[i] = math.Inf(1) } gbval := math.Inf(1) return &state{iter, gbpos, gbval, min, max, params, pos, vel, bpos, bval, nParticles, nDims} } func pso(fn ff, y *state) *state { p := y.params v := make([]float64, y.nParticles) bpos := make([][]float64, y.nParticles) bval := make([]float64, y.nParticles) gbpos := make([]float64, y.nDims) gbval := math.Inf(1) for j := 0; j < y.nParticles; j++ { v[j] = fn(y.pos[j]) if v[j] < y.bval[j] { bpos[j] = y.pos[j] bval[j] = v[j] } else { bpos[j] = y.bpos[j] bval[j] = y.bval[j] } if bval[j] < gbval { gbval = bval[j] gbpos = bpos[j] } } rg := rand.Float64() pos := make([][]float64, y.nParticles) vel := make([][]float64, y.nParticles) for j := 0; j < y.nParticles; j++ { pos[j] = make([]float64, y.nDims) vel[j] = make([]float64, y.nDims) rp := rand.Float64() ok := true for z := 0; z < y.nDims; z++ { pos[j][z] = 0 vel[j][z] = 0 } for k := 0; k < y.nDims; k++ { vel[j][k] = p.omega*y.vel[j][k] + p.phip*rp*(bpos[j][k]-y.pos[j][k]) + p.phig*rg*(gbpos[k]-y.pos[j][k]) pos[j][k] = y.pos[j][k] + vel[j][k] ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k] } if !ok { for k := 0; k < y.nDims; k++ { pos[j][k] = y.min[k] + (y.max[k]-y.min[k])*rand.Float64() } } } iter := 1 + y.iter return &state{iter, gbpos, gbval, y.min, y.max, y.params, pos, vel, bpos, bval, y.nParticles, y.nDims} } func iterate(fn ff, n int, y *state) *state { r := y for i := 0; i < n; i++ { r = pso(fn, r) } return r } func mccormick(x []float64) float64 { a, b := x[0], x[1] return math.Sin(a+b) + (a-b)*(a-b) + 1.0 + 2.5*b - 1.5*a } func michalewicz(x []float64) float64 { m := 10.0 sum := 0.0 for i := 1; i <= len(x); i++ { j := x[i-1] k := math.Sin(float64(i) * j * j / math.Pi) sum += math.Sin(j) * math.Pow(k, 2*m) } return -sum } func main() { rand.Seed(time.Now().UnixNano()) st := psoInit( []float64{-1.5, -3.0}, []float64{4.0, 4.0}, parameters{0.0, 0.6, 0.3}, 100, ) st = iterate(mccormick, 40, st) st.report("McCormick") fmt.Println("f(-.54719, -1.54719) :", mccormick([]float64{-.54719, -1.54719})) fmt.Println() st = psoInit( []float64{0.0, 0.0}, []float64{math.Pi, math.Pi}, parameters{0.3, 0.3, 0.3}, 1000, ) st = iterate(michalewicz, 30, st) st.report("Michalewicz (2D)") fmt.Println("f(2.20, 1.57)  :", michalewicz([]float64{2.2, 1.57}))
Transform the following Python implementation into Go, maintaining the same output and logic.
python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(string1, string2, separator): return separator.join([string1, '', string2]) >>> f('Rosetta', 'Code', ':') 'Rosetta::Code' >>>
package main import "fmt" func f(s1, s2, sep string) string { return s1 + sep + sep + s2 } func main() { fmt.Println(f("Rosetta", "Code", ":")) }
Convert this Python snippet to Go and keep its semantics consistent.
python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(string1, string2, separator): return separator.join([string1, '', string2]) >>> f('Rosetta', 'Code', ':') 'Rosetta::Code' >>>
package main import "fmt" func f(s1, s2, sep string) string { return s1 + sep + sep + s2 } func main() { fmt.Println(f("Rosetta", "Code", ":")) }
Change the following Python code into Go without altering its purpose.
def rank(x): return int('a'.join(map(str, [1] + x)), 11) def unrank(n): s = '' while n: s,n = "0123456789a"[n%11] + s, n//11 return map(int, s.split('a'))[1:] l = [1, 2, 3, 10, 100, 987654321] print l n = rank(l) print n l = unrank(n) print l
package main import ( "fmt" "math/big" ) func rank(l []uint) (r big.Int) { for _, n := range l { r.Lsh(&r, n+1) r.SetBit(&r, int(n), 1) } return } func unrank(n big.Int) (l []uint) { m := new(big.Int).Set(&n) for a := m.BitLen(); a > 0; { m.SetBit(m, a-1, 0) b := m.BitLen() l = append(l, uint(a-b-1)) a = b } return } func main() { var b big.Int for i := 0; i <= 10; i++ { b.SetInt64(int64(i)) u := unrank(b) r := rank(u) fmt.Println(i, u, &r) } b.SetString("12345678901234567890", 10) u := unrank(b) r := rank(u) fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r) }
Please provide an equivalent version of this Python code in Go.
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
package main import ( "fmt" "io/ioutil" "os" ) func main() { fn := "myth" bx := ".backup" var err error if tf, err := os.Readlink(fn); err == nil { fn = tf } var fi os.FileInfo if fi, err = os.Stat(fn); err != nil { fmt.Println(err) return } if err = os.Rename(fn, fn+bx); err != nil { fmt.Println(err) return } err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm()) if err != nil { fmt.Println(err) } }
Port the provided Python code into Go while preserving the original functionality.
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
package main import ( "fmt" "io/ioutil" "os" ) func main() { fn := "myth" bx := ".backup" var err error if tf, err := os.Readlink(fn); err == nil { fn = tf } var fi os.FileInfo if fi, err = os.Stat(fn); err != nil { fmt.Println(err) return } if err = os.Rename(fn, fn+bx); err != nil { fmt.Println(err) return } err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm()) if err != nil { fmt.Println(err) } }
Change the programming language of this snippet from Python to Go without modifying what it does.
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
package main import ( "fmt" "io/ioutil" "os" ) func main() { fn := "myth" bx := ".backup" var err error if tf, err := os.Readlink(fn); err == nil { fn = tf } var fi os.FileInfo if fi, err = os.Stat(fn); err != nil { fmt.Println(err) return } if err = os.Rename(fn, fn+bx); err != nil { fmt.Println(err) return } err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm()) if err != nil { fmt.Println(err) } }
Change the following Python code into Go without altering its purpose.
import re male2female=u re_nl=re.compile(r",[ \n]*") m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ] switch={} words=[] re_plural=re.compile("E*S$") re_ES=re.compile("ES$") def gen_pluralize(m,f): yield re_plural.sub("",m),re_plural.sub("",f) yield re_ES.sub("es",m),re_ES.sub("es",f) yield re_plural.sub("s",m),re_plural.sub("s",f) def gen_capitalize_pluralize(m,f): for m,f in gen_pluralize(m,f): yield m.capitalize(), f.capitalize() yield m,f def gen_switch_role_capitalize_pluralize(m,f): for m,f in gen_capitalize_pluralize(m,f): yield m,f yield f,m for m,f in m2f: for xy,xx in gen_switch_role_capitalize_pluralize(m,f): if xy not in switch: switch[xy]=xx words.append(xy) words="|".join(words) re_word=re.compile(ur"\b("+words+ur")\b") text=u def rev_gender(text): text=re_word.split(text) return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1] print rev_gender(text)
package main import ( "fmt" "strings" ) func reverseGender(s string) string { if strings.Contains(s, "She") { return strings.Replace(s, "She", "He", -1) } else if strings.Contains(s, "He") { return strings.Replace(s, "He", "She", -1) } return s } func main() { s := "She was a soul stripper. She took my heart!" t := reverseGender(s) fmt.Println(t) fmt.Println(reverseGender(t)) }
Change the programming language of this snippet from Python to Go without modifying what it does.
import re male2female=u re_nl=re.compile(r",[ \n]*") m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ] switch={} words=[] re_plural=re.compile("E*S$") re_ES=re.compile("ES$") def gen_pluralize(m,f): yield re_plural.sub("",m),re_plural.sub("",f) yield re_ES.sub("es",m),re_ES.sub("es",f) yield re_plural.sub("s",m),re_plural.sub("s",f) def gen_capitalize_pluralize(m,f): for m,f in gen_pluralize(m,f): yield m.capitalize(), f.capitalize() yield m,f def gen_switch_role_capitalize_pluralize(m,f): for m,f in gen_capitalize_pluralize(m,f): yield m,f yield f,m for m,f in m2f: for xy,xx in gen_switch_role_capitalize_pluralize(m,f): if xy not in switch: switch[xy]=xx words.append(xy) words="|".join(words) re_word=re.compile(ur"\b("+words+ur")\b") text=u def rev_gender(text): text=re_word.split(text) return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1] print rev_gender(text)
package main import ( "fmt" "strings" ) func reverseGender(s string) string { if strings.Contains(s, "She") { return strings.Replace(s, "She", "He", -1) } else if strings.Contains(s, "He") { return strings.Replace(s, "He", "She", -1) } return s } func main() { s := "She was a soul stripper. She took my heart!" t := reverseGender(s) fmt.Println(t) fmt.Println(reverseGender(t)) }
Generate an equivalent Go version of this Python code.
import time import os seconds = input("Enter a number of seconds: ") sound = input("Enter an mp3 filename: ") time.sleep(float(seconds)) os.startfile(sound + ".mp3")
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" "time" ) func main() { scanner := bufio.NewScanner(os.Stdin) number := 0 for number < 1 { fmt.Print("Enter number of seconds delay > 0 : ") scanner.Scan() input := scanner.Text() if err := scanner.Err(); err != nil { log.Fatal(err) } number, _ = strconv.Atoi(input) } filename := "" for filename == "" { fmt.Print("Enter name of .mp3 file to play (without extension) : ") scanner.Scan() filename = scanner.Text() if err := scanner.Err(); err != nil { log.Fatal(err) } } cls := "\033[2J\033[0;0H" fmt.Printf("%sAlarm will sound in %d seconds...", cls, number) time.Sleep(time.Duration(number) * time.Second) fmt.Printf(cls) cmd := exec.Command("play", filename+".mp3") if err := cmd.Run(); err != nil { log.Fatal(err) } }
Convert this Python snippet to Go and keep its semantics consistent.
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char in hx[2:p]) return (('-' if neg else '') + bn.strip('0') + hx[p:p+2] + bin(int(hx[p+2:]))[2:]) def float_bin2dec(bn): neg = False if bn[0] == '-': bn = bn[1:] neg = True dp = bn.index('.') extra0 = '0' * (4 - (dp % 4)) bn2 = extra0 + bn dp = bn2.index('.') p = bn2.index('p') hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i]) for i in range(0, dp+1, 4)) bn3 = bn2[dp+1:p] extra0 = '0' * (4 - (len(bn3) % 4)) bn4 = bn3 + extra0 hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0')) for i in range(0, len(bn4), 4)) hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2] + str(int('0b' + bn2[p+2:], 2))) return float.fromhex(hx)
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" dd = r - 1.0 } else { binary += "0" dd = r } } return binary } func binToDec(s string) float64 { ss := strings.Replace(s, ".", "", 1) num, _ := strconv.ParseInt(ss, 2, 64) ss = strings.Split(s, ".")[1] ss = strings.Replace(ss, "1", "0", -1) den, _ := strconv.ParseInt("1" + ss, 2, 64) return float64(num) / float64(den) } func main() { f := 23.34375 fmt.Printf("%v\t => %s\n", f, decToBin(f)) s := "1011.11101" fmt.Printf("%s\t => %v\n", s, binToDec(s)) }
Transform the following Python implementation into Go, maintaining the same output and logic.
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char in hx[2:p]) return (('-' if neg else '') + bn.strip('0') + hx[p:p+2] + bin(int(hx[p+2:]))[2:]) def float_bin2dec(bn): neg = False if bn[0] == '-': bn = bn[1:] neg = True dp = bn.index('.') extra0 = '0' * (4 - (dp % 4)) bn2 = extra0 + bn dp = bn2.index('.') p = bn2.index('p') hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i]) for i in range(0, dp+1, 4)) bn3 = bn2[dp+1:p] extra0 = '0' * (4 - (len(bn3) % 4)) bn4 = bn3 + extra0 hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0')) for i in range(0, len(bn4), 4)) hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2] + str(int('0b' + bn2[p+2:], 2))) return float.fromhex(hx)
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" dd = r - 1.0 } else { binary += "0" dd = r } } return binary } func binToDec(s string) float64 { ss := strings.Replace(s, ".", "", 1) num, _ := strconv.ParseInt(ss, 2, 64) ss = strings.Split(s, ".")[1] ss = strings.Replace(ss, "1", "0", -1) den, _ := strconv.ParseInt("1" + ss, 2, 64) return float64(num) / float64(den) } func main() { f := 23.34375 fmt.Printf("%v\t => %s\n", f, decToBin(f)) s := "1011.11101" fmt.Printf("%s\t => %v\n", s, binToDec(s)) }
Please provide an equivalent version of this Python code in Go.
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char in hx[2:p]) return (('-' if neg else '') + bn.strip('0') + hx[p:p+2] + bin(int(hx[p+2:]))[2:]) def float_bin2dec(bn): neg = False if bn[0] == '-': bn = bn[1:] neg = True dp = bn.index('.') extra0 = '0' * (4 - (dp % 4)) bn2 = extra0 + bn dp = bn2.index('.') p = bn2.index('p') hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i]) for i in range(0, dp+1, 4)) bn3 = bn2[dp+1:p] extra0 = '0' * (4 - (len(bn3) % 4)) bn4 = bn3 + extra0 hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0')) for i in range(0, len(bn4), 4)) hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2] + str(int('0b' + bn2[p+2:], 2))) return float.fromhex(hx)
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" dd = r - 1.0 } else { binary += "0" dd = r } } return binary } func binToDec(s string) float64 { ss := strings.Replace(s, ".", "", 1) num, _ := strconv.ParseInt(ss, 2, 64) ss = strings.Split(s, ".")[1] ss = strings.Replace(ss, "1", "0", -1) den, _ := strconv.ParseInt("1" + ss, 2, 64) return float64(num) / float64(den) } func main() { f := 23.34375 fmt.Printf("%v\t => %s\n", f, decToBin(f)) s := "1011.11101" fmt.Printf("%s\t => %v\n", s, binToDec(s)) }
Generate an equivalent Go version of this Python code.
>>> def eval_with_x(code, a, b): return eval(code, {'x':b}) - eval(code, {'x':a}) >>> eval_with_x('2 ** x', 3, 5) 24
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
Ensure the translated Go code behaves exactly like the original Python snippet.
>>> def eval_with_x(code, a, b): return eval(code, {'x':b}) - eval(code, {'x':a}) >>> eval_with_x('2 ** x', 3, 5) 24
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
Produce a functionally identical Go code for the snippet given in Python.
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and part: machins.append(part) part = [] part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1), Fraction(int(numer), (int(denom) if denom else 1)) ) ) machins.append(part) return machins def tans(xs): xslen = len(xs) if xslen == 1: return tanEval(*xs[0]) aa, bb = xs[:xslen//2], xs[xslen//2:] a, b = tans(aa), tans(bb) return (a + b) / (1 - a * b) def tanEval(coef, f): if coef == 1: return f if coef < 0: return -tanEval(-coef, f) ca = coef // 2 cb = coef - ca a, b = tanEval(ca, f), tanEval(cb, f) return (a + b) / (1 - a * b) if __name__ == '__main__': machins = parse_eqn() for machin, eqn in zip(machins, equationtext.split('\n')): ans = tans(machin) print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}}, {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}}, {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}}, {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}}, {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}}, {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}}, {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}}, {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}}, } func main() { for _, m := range testCases { fmt.Printf("tan %v = %v\n", m, tans(m)) } } var one = big.NewRat(1, 1) func tans(m []mTerm) *big.Rat { if len(m) == 1 { return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d)) } half := len(m) / 2 a := tans(m[:half]) b := tans(m[half:]) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) } func tanEval(coef int64, f *big.Rat) *big.Rat { if coef == 1 { return f } if coef < 0 { r := tanEval(-coef, f) return r.Neg(r) } ca := coef / 2 cb := coef - ca a := tanEval(ca, f) b := tanEval(cb, f) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) }
Change the following Python code into Go without altering its purpose.
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and part: machins.append(part) part = [] part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1), Fraction(int(numer), (int(denom) if denom else 1)) ) ) machins.append(part) return machins def tans(xs): xslen = len(xs) if xslen == 1: return tanEval(*xs[0]) aa, bb = xs[:xslen//2], xs[xslen//2:] a, b = tans(aa), tans(bb) return (a + b) / (1 - a * b) def tanEval(coef, f): if coef == 1: return f if coef < 0: return -tanEval(-coef, f) ca = coef // 2 cb = coef - ca a, b = tanEval(ca, f), tanEval(cb, f) return (a + b) / (1 - a * b) if __name__ == '__main__': machins = parse_eqn() for machin, eqn in zip(machins, equationtext.split('\n')): ans = tans(machin) print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}}, {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}}, {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}}, {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}}, {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}}, {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}}, {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}}, {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}}, } func main() { for _, m := range testCases { fmt.Printf("tan %v = %v\n", m, tans(m)) } } var one = big.NewRat(1, 1) func tans(m []mTerm) *big.Rat { if len(m) == 1 { return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d)) } half := len(m) / 2 a := tans(m[:half]) b := tans(m[half:]) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) } func tanEval(coef int64, f *big.Rat) *big.Rat { if coef == 1 { return f } if coef < 0 { r := tanEval(-coef, f) return r.Neg(r) } ca := coef / 2 cb := coef - ca a := tanEval(ca, f) b := tanEval(cb, f) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) }
Port the provided Python code into Go while preserving the original functionality.
import math rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] constants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)] init_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] functions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \ 16*[lambda b, c, d: (d & b) | (~d & c)] + \ 16*[lambda b, c, d: b ^ c ^ d] + \ 16*[lambda b, c, d: c ^ (b | ~d)] index_functions = 16*[lambda i: i] + \ 16*[lambda i: (5*i + 1)%16] + \ 16*[lambda i: (3*i + 5)%16] + \ 16*[lambda i: (7*i)%16] def left_rotate(x, amount): x &= 0xFFFFFFFF return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF def md5(message): message = bytearray(message) orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff message.append(0x80) while len(message)%64 != 56: message.append(0) message += orig_len_in_bits.to_bytes(8, byteorder='little') hash_pieces = init_values[:] for chunk_ofst in range(0, len(message), 64): a, b, c, d = hash_pieces chunk = message[chunk_ofst:chunk_ofst+64] for i in range(64): f = functions[i](b, c, d) g = index_functions[i](i) to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little') new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF a, b, c, d = d, new_b, b, c for i, val in enumerate([a, b, c, d]): hash_pieces[i] += val hash_pieces[i] &= 0xFFFFFFFF return sum(x<<(32*i) for i, x in enumerate(hash_pieces)) def md5_to_hex(digest): raw = digest.to_bytes(16, byteorder='little') return '{:032x}'.format(int.from_bytes(raw, byteorder='big')) if __name__=='__main__': demo = [b"", b"a", b"abc", b"message digest", b"abcdefghijklmnopqrstuvwxyz", b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"] for message in demo: print(md5_to_hex(md5(message)),' <= "',message.decode('ascii'),'"', sep='')
package main import ( "fmt" "math" "bytes" "encoding/binary" ) type testCase struct { hashCode string string } var testCases = []testCase{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"}, {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"}, {"d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"}, {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" + "123456789012345678901234567890123456789012345678901234567890"}, } func main() { for _, tc := range testCases { fmt.Printf("%s\n%x\n\n", tc.hashCode, md5(tc.string)) } } var shift = [...]uint{7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21} var table [64]uint32 func init() { for i := range table { table[i] = uint32((1 << 32) * math.Abs(math.Sin(float64(i + 1)))) } } func md5(s string) (r [16]byte) { padded := bytes.NewBuffer([]byte(s)) padded.WriteByte(0x80) for padded.Len() % 64 != 56 { padded.WriteByte(0) } messageLenBits := uint64(len(s)) * 8 binary.Write(padded, binary.LittleEndian, messageLenBits) var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476 var buffer [16]uint32 for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil { a1, b1, c1, d1 := a, b, c, d for j := 0; j < 64; j++ { var f uint32 bufferIndex := j round := j >> 4 switch round { case 0: f = (b1 & c1) | (^b1 & d1) case 1: f = (b1 & d1) | (c1 & ^d1) bufferIndex = (bufferIndex*5 + 1) & 0x0F case 2: f = b1 ^ c1 ^ d1 bufferIndex = (bufferIndex*3 + 5) & 0x0F case 3: f = c1 ^ (b1 | ^d1) bufferIndex = (bufferIndex * 7) & 0x0F } sa := shift[(round<<2)|(j&3)] a1 += f + buffer[bufferIndex] + table[j] a1, d1, c1, b1 = d1, c1, b1, a1<<sa|a1>>(32-sa)+b1 } a, b, c, d = a+a1, b+b1, c+c1, d+d1 } binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d}) return }
Translate this program into Go but keep the logic exactly as in Python.
from math import pi, sin, cos from collections import namedtuple from random import random, choice from copy import copy try: import psyco psyco.full() except ImportError: pass FLOAT_MAX = 1e100 class Point: __slots__ = ["x", "y", "group"] def __init__(self, x=0.0, y=0.0, group=0): self.x, self.y, self.group = x, y, group def generate_points(npoints, radius): points = [Point() for _ in xrange(npoints)] for p in points: r = random() * radius ang = random() * 2 * pi p.x = r * cos(ang) p.y = r * sin(ang) return points def nearest_cluster_center(point, cluster_centers): def sqr_distance_2D(a, b): return (a.x - b.x) ** 2 + (a.y - b.y) ** 2 min_index = point.group min_dist = FLOAT_MAX for i, cc in enumerate(cluster_centers): d = sqr_distance_2D(cc, point) if min_dist > d: min_dist = d min_index = i return (min_index, min_dist) def kpp(points, cluster_centers): cluster_centers[0] = copy(choice(points)) d = [0.0 for _ in xrange(len(points))] for i in xrange(1, len(cluster_centers)): sum = 0 for j, p in enumerate(points): d[j] = nearest_cluster_center(p, cluster_centers[:i])[1] sum += d[j] sum *= random() for j, di in enumerate(d): sum -= di if sum > 0: continue cluster_centers[i] = copy(points[j]) break for p in points: p.group = nearest_cluster_center(p, cluster_centers)[0] def lloyd(points, nclusters): cluster_centers = [Point() for _ in xrange(nclusters)] kpp(points, cluster_centers) lenpts10 = len(points) >> 10 changed = 0 while True: for cc in cluster_centers: cc.x = 0 cc.y = 0 cc.group = 0 for p in points: cluster_centers[p.group].group += 1 cluster_centers[p.group].x += p.x cluster_centers[p.group].y += p.y for cc in cluster_centers: cc.x /= cc.group cc.y /= cc.group changed = 0 for p in points: min_i = nearest_cluster_center(p, cluster_centers)[0] if min_i != p.group: changed += 1 p.group = min_i if changed <= lenpts10: break for i, cc in enumerate(cluster_centers): cc.group = i return cluster_centers def print_eps(points, cluster_centers, W=400, H=400): Color = namedtuple("Color", "r g b"); colors = [] for i in xrange(len(cluster_centers)): colors.append(Color((3 * (i + 1) % 11) / 11.0, (7 * i % 11) / 11.0, (9 * i % 11) / 11.0)) max_x = max_y = -FLOAT_MAX min_x = min_y = FLOAT_MAX for p in points: if max_x < p.x: max_x = p.x if min_x > p.x: min_x = p.x if max_y < p.y: max_y = p.y if min_y > p.y: min_y = p.y scale = min(W / (max_x - min_x), H / (max_y - min_y)) cx = (max_x + min_x) / 2 cy = (max_y + min_y) / 2 print "%%!PS-Adobe-3.0\n%%%%BoundingBox: -5 -5 %d %d" % (W + 10, H + 10) print ("/l {rlineto} def /m {rmoveto} def\n" + "/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\n" + "/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath " + " gsave 1 setgray fill grestore gsave 3 setlinewidth" + " 1 setgray stroke grestore 0 setgray stroke }def") for i, cc in enumerate(cluster_centers): print ("%g %g %g setrgbcolor" % (colors[i].r, colors[i].g, colors[i].b)) for p in points: if p.group != i: continue print ("%.3f %.3f c" % ((p.x - cx) * scale + W / 2, (p.y - cy) * scale + H / 2)) print ("\n0 setgray %g %g s" % ((cc.x - cx) * scale + W / 2, (cc.y - cy) * scale + H / 2)) print "\n%%%%EOF" def main(): npoints = 30000 k = 7 points = generate_points(npoints, 10) cluster_centers = lloyd(points, k) print_eps(points, cluster_centers) main()
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "math/rand" "os" "time" ) type r2 struct { x, y float64 } type r2c struct { r2 c int } func kmpp(k int, data []r2c) { kMeans(data, kmppSeeds(k, data)) } func kmppSeeds(k int, data []r2c) []r2 { s := make([]r2, k) s[0] = data[rand.Intn(len(data))].r2 d2 := make([]float64, len(data)) for i := 1; i < k; i++ { var sum float64 for j, p := range data { _, dMin := nearest(p, s[:i]) d2[j] = dMin * dMin sum += d2[j] } target := rand.Float64() * sum j := 0 for sum = d2[0]; sum < target; sum += d2[j] { j++ } s[i] = data[j].r2 } return s } func nearest(p r2c, mean []r2) (int, float64) { iMin := 0 dMin := math.Hypot(p.x-mean[0].x, p.y-mean[0].y) for i := 1; i < len(mean); i++ { d := math.Hypot(p.x-mean[i].x, p.y-mean[i].y) if d < dMin { dMin = d iMin = i } } return iMin, dMin } func kMeans(data []r2c, mean []r2) { for i, p := range data { cMin, _ := nearest(p, mean) data[i].c = cMin } mLen := make([]int, len(mean)) for { for i := range mean { mean[i] = r2{} mLen[i] = 0 } for _, p := range data { mean[p.c].x += p.x mean[p.c].y += p.y mLen[p.c]++ } for i := range mean { inv := 1 / float64(mLen[i]) mean[i].x *= inv mean[i].y *= inv } var changes int for i, p := range data { if cMin, _ := nearest(p, mean); cMin != p.c { changes++ data[i].c = cMin } } if changes == 0 { return } } } type ecParam struct { k int nPoints int xBox, yBox int stdv int } func main() { ec := &ecParam{6, 30000, 300, 200, 30} origin, data := genECData(ec) vis(ec, data, "origin") fmt.Println("Data set origins:") fmt.Println(" x y") for _, o := range origin { fmt.Printf("%5.1f %5.1f\n", o.x, o.y) } kmpp(ec.k, data) fmt.Println( "\nCluster centroids, mean distance from centroid, number of points:") fmt.Println(" x y distance points") cent := make([]r2, ec.k) cLen := make([]int, ec.k) inv := make([]float64, ec.k) for _, p := range data { cent[p.c].x += p.x cent[p.c].y += p.y cLen[p.c]++ } for i, iLen := range cLen { inv[i] = 1 / float64(iLen) cent[i].x *= inv[i] cent[i].y *= inv[i] } dist := make([]float64, ec.k) for _, p := range data { dist[p.c] += math.Hypot(p.x-cent[p.c].x, p.y-cent[p.c].y) } for i, iLen := range cLen { fmt.Printf("%5.1f %5.1f %8.1f %6d\n", cent[i].x, cent[i].y, dist[i]*inv[i], iLen) } vis(ec, data, "clusters") } func genECData(ec *ecParam) (orig []r2, data []r2c) { rand.Seed(time.Now().UnixNano()) orig = make([]r2, ec.k) data = make([]r2c, ec.nPoints) for i, n := 0, 0; i < ec.k; i++ { x := rand.Float64() * float64(ec.xBox) y := rand.Float64() * float64(ec.yBox) orig[i] = r2{x, y} for j := ec.nPoints / ec.k; j > 0; j-- { data[n].x = rand.NormFloat64()*float64(ec.stdv) + x data[n].y = rand.NormFloat64()*float64(ec.stdv) + y data[n].c = i n++ } } return } func vis(ec *ecParam, data []r2c, fn string) { colors := make([]color.NRGBA, ec.k) for i := range colors { i3 := i * 3 third := i3 / ec.k frac := uint8((i3 % ec.k) * 255 / ec.k) switch third { case 0: colors[i] = color.NRGBA{frac, 255 - frac, 0, 255} case 1: colors[i] = color.NRGBA{0, frac, 255 - frac, 255} case 2: colors[i] = color.NRGBA{255 - frac, 0, frac, 255} } } bounds := image.Rect(-ec.stdv, -ec.stdv, ec.xBox+ec.stdv, ec.yBox+ec.stdv) im := image.NewNRGBA(bounds) draw.Draw(im, bounds, image.NewUniform(color.White), image.ZP, draw.Src) fMinX := float64(bounds.Min.X) fMaxX := float64(bounds.Max.X) fMinY := float64(bounds.Min.Y) fMaxY := float64(bounds.Max.Y) for _, p := range data { imx := math.Floor(p.x) imy := math.Floor(float64(ec.yBox) - p.y) if imx >= fMinX && imx < fMaxX && imy >= fMinY && imy < fMaxY { im.SetNRGBA(int(imx), int(imy), colors[p.c]) } } f, err := os.Create(fn + ".png") if err != nil { fmt.Println(err) return } err = png.Encode(f, im) if err != nil { fmt.Println(err) } err = f.Close() if err != nil { fmt.Println(err) } }
Generate a Go translation of this Python snippet without changing its computational steps.
def Dijkstra(Graph, source): infinity = float('infinity') n = len(graph) dist = [infinity]*n previous = [infinity]*n dist[source] = 0 Q = list(range(n)) while Q: u = min(Q, key=lambda n:dist[n]) Q.remove(u) if dist[u] == infinity: break for v in range(n): if Graph[u][v] and (v in Q): alt = dist[u] + Graph[u][v] if alt < dist[v]: dist[v] = alt previous[v] = u return dist,previous def display_solution(predecessor): cell = len(predecessor)-1 while cell: print(cell,end='<') cell = predecessor[cell] print(0)
package main import ( "bytes" "fmt" "math/rand" "time" ) type maze struct { c2 [][]byte h2 [][]byte v2 [][]byte } func newMaze(rows, cols int) *maze { c := make([]byte, rows*cols) h := bytes.Repeat([]byte{'-'}, rows*cols) v := bytes.Repeat([]byte{'|'}, rows*cols) c2 := make([][]byte, rows) h2 := make([][]byte, rows) v2 := make([][]byte, rows) for i := range h2 { c2[i] = c[i*cols : (i+1)*cols] h2[i] = h[i*cols : (i+1)*cols] v2[i] = v[i*cols : (i+1)*cols] } return &maze{c2, h2, v2} } func (m *maze) String() string { hWall := []byte("+---") hOpen := []byte("+ ") vWall := []byte("| ") vOpen := []byte(" ") rightCorner := []byte("+\n") rightWall := []byte("|\n") var b []byte for r, hw := range m.h2 { for _, h := range hw { if h == '-' || r == 0 { b = append(b, hWall...) } else { b = append(b, hOpen...) if h != '-' && h != 0 { b[len(b)-2] = h } } } b = append(b, rightCorner...) for c, vw := range m.v2[r] { if vw == '|' || c == 0 { b = append(b, vWall...) } else { b = append(b, vOpen...) if vw != '|' && vw != 0 { b[len(b)-4] = vw } } if m.c2[r][c] != 0 { b[len(b)-2] = m.c2[r][c] } } b = append(b, rightWall...) } for _ = range m.h2[0] { b = append(b, hWall...) } b = append(b, rightCorner...) return string(b) } func (m *maze) gen() { m.g2(rand.Intn(len(m.c2)), rand.Intn(len(m.c2[0]))) } const ( up = iota dn rt lf ) func (m *maze) g2(r, c int) { m.c2[r][c] = ' ' for _, dir := range rand.Perm(4) { switch dir { case up: if r > 0 && m.c2[r-1][c] == 0 { m.h2[r][c] = 0 m.g2(r-1, c) } case lf: if c > 0 && m.c2[r][c-1] == 0 { m.v2[r][c] = 0 m.g2(r, c-1) } case dn: if r < len(m.c2)-1 && m.c2[r+1][c] == 0 { m.h2[r+1][c] = 0 m.g2(r+1, c) } case rt: if c < len(m.c2[0])-1 && m.c2[r][c+1] == 0 { m.v2[r][c+1] = 0 m.g2(r, c+1) } } } } func main() { rand.Seed(time.Now().UnixNano()) const height = 4 const width = 7 m := newMaze(height, width) m.gen() m.solve( rand.Intn(height), rand.Intn(width), rand.Intn(height), rand.Intn(width)) fmt.Print(m) } func (m *maze) solve(ra, ca, rz, cz int) { var rSolve func(ra, ca, dir int) bool rSolve = func(r, c, dir int) bool { if r == rz && c == cz { m.c2[r][c] = 'F' return true } if dir != dn && m.h2[r][c] == 0 { if rSolve(r-1, c, up) { m.c2[r][c] = '^' m.h2[r][c] = '^' return true } } if dir != up && r+1 < len(m.h2) && m.h2[r+1][c] == 0 { if rSolve(r+1, c, dn) { m.c2[r][c] = 'v' m.h2[r+1][c] = 'v' return true } } if dir != lf && c+1 < len(m.v2[0]) && m.v2[r][c+1] == 0 { if rSolve(r, c+1, rt) { m.c2[r][c] = '>' m.v2[r][c+1] = '>' return true } } if dir != rt && m.v2[r][c] == 0 { if rSolve(r, c-1, lf) { m.c2[r][c] = '<' m.v2[r][c] = '<' return true } } return false } rSolve(ra, ca, -1) m.c2[ra][ca] = 'S' }
Write the same code in Go as shown below in Python.
import random print(random.sample(range(1, 21), 20))
package main import ( "fmt" "log" "math/rand" "time" ) func generate(from, to int64) { if to < from || from < 0 { log.Fatal("Invalid range.") } span := to - from + 1 generated := make([]bool, span) count := span for count > 0 { n := from + rand.Int63n(span) if !generated[n-from] { generated[n-from] = true fmt.Printf("%2d ", n) count-- } } fmt.Println() } func main() { rand.Seed(time.Now().UnixNano()) for i := 1; i <= 5; i++ { generate(1, 20) } }
Maintain the same structure and functionality when rewriting this code in Go.
def DrawBoard(board): peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for n in xrange(1,16): peg[n] = '.' if n in board: peg[n] = "%X" % n print " %s" % peg[1] print " %s %s" % (peg[2],peg[3]) print " %s %s %s" % (peg[4],peg[5],peg[6]) print " %s %s %s %s" % (peg[7],peg[8],peg[9],peg[10]) print " %s %s %s %s %s" % (peg[11],peg[12],peg[13],peg[14],peg[15]) def RemovePeg(board,n): board.remove(n) def AddPeg(board,n): board.append(n) def IsPeg(board,n): return n in board JumpMoves = { 1: [ (2,4),(3,6) ], 2: [ (4,7),(5,9) ], 3: [ (5,8),(6,10) ], 4: [ (2,1),(5,6),(7,11),(8,13) ], 5: [ (8,12),(9,14) ], 6: [ (3,1),(5,4),(9,13),(10,15) ], 7: [ (4,2),(8,9) ], 8: [ (5,3),(9,10) ], 9: [ (5,2),(8,7) ], 10: [ (9,8) ], 11: [ (12,13) ], 12: [ (8,5),(13,14) ], 13: [ (8,4),(9,6),(12,11),(14,15) ], 14: [ (9,5),(13,12) ], 15: [ (10,6),(14,13) ] } Solution = [] def Solve(board): if len(board) == 1: return board for peg in xrange(1,16): if IsPeg(board,peg): movelist = JumpMoves[peg] for over,land in movelist: if IsPeg(board,over) and not IsPeg(board,land): saveboard = board[:] RemovePeg(board,peg) RemovePeg(board,over) AddPeg(board,land) Solution.append((peg,over,land)) board = Solve(board) if len(board) == 1: return board board = saveboard[:] del Solution[-1] return board def InitSolve(empty): board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] RemovePeg(board,empty_start) Solve(board) empty_start = 1 InitSolve(empty_start) board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] RemovePeg(board,empty_start) for peg,over,land in Solution: RemovePeg(board,peg) RemovePeg(board,over) AddPeg(board,land) DrawBoard(board) print "Peg %X jumped over %X to land on %X\n" % (peg,over,land)
package main import "fmt" type solution struct{ peg, over, land int } type move struct{ from, to int } var emptyStart = 1 var board [16]bool var jumpMoves = [16][]move{ {}, {{2, 4}, {3, 6}}, {{4, 7}, {5, 9}}, {{5, 8}, {6, 10}}, {{2, 1}, {5, 6}, {7, 11}, {8, 13}}, {{8, 12}, {9, 14}}, {{3, 1}, {5, 4}, {9, 13}, {10, 15}}, {{4, 2}, {8, 9}}, {{5, 3}, {9, 10}}, {{5, 2}, {8, 7}}, {{9, 8}}, {{12, 13}}, {{8, 5}, {13, 14}}, {{8, 4}, {9, 6}, {12, 11}, {14, 15}}, {{9, 5}, {13, 12}}, {{10, 6}, {14, 13}}, } var solutions []solution func initBoard() { for i := 1; i < 16; i++ { board[i] = true } board[emptyStart] = false } func (sol solution) split() (int, int, int) { return sol.peg, sol.over, sol.land } func (mv move) split() (int, int) { return mv.from, mv.to } func drawBoard() { var pegs [16]byte for i := 1; i < 16; i++ { if board[i] { pegs[i] = fmt.Sprintf("%X", i)[0] } else { pegs[i] = '-' } } fmt.Printf(" %c\n", pegs[1]) fmt.Printf(" %c %c\n", pegs[2], pegs[3]) fmt.Printf(" %c %c %c\n", pegs[4], pegs[5], pegs[6]) fmt.Printf(" %c %c %c %c\n", pegs[7], pegs[8], pegs[9], pegs[10]) fmt.Printf(" %c %c %c %c %c\n", pegs[11], pegs[12], pegs[13], pegs[14], pegs[15]) } func solved() bool { count := 0 for _, b := range board { if b { count++ } } return count == 1 } func solve() { if solved() { return } for peg := 1; peg < 16; peg++ { if board[peg] { for _, mv := range jumpMoves[peg] { over, land := mv.split() if board[over] && !board[land] { saveBoard := board board[peg] = false board[over] = false board[land] = true solutions = append(solutions, solution{peg, over, land}) solve() if solved() { return } board = saveBoard solutions = solutions[:len(solutions)-1] } } } } } func main() { initBoard() solve() initBoard() drawBoard() fmt.Printf("Starting with peg %X removed\n\n", emptyStart) for _, solution := range solutions { peg, over, land := solution.split() board[peg] = false board[over] = false board[land] = true drawBoard() fmt.Printf("Peg %X jumped over %X to land on %X\n\n", peg, over, land) } }
Convert this Python block to Go, preserving its control flow and logic.
from itertools import combinations_with_replacement as cmbr from time import time def dice_gen(n, faces, m): dice = list(cmbr(faces, n)) succ = [set(j for j, b in enumerate(dice) if sum((x>y) - (x<y) for x in a for y in b) > 0) for a in dice] def loops(seq): s = succ[seq[-1]] if len(seq) == m: if seq[0] in s: yield seq return for d in (x for x in s if x > seq[0] and not x in seq): yield from loops(seq + (d,)) yield from (tuple(''.join(dice[s]) for s in x) for i, v in enumerate(succ) for x in loops((i,))) t = time() for n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]: for i, x in enumerate(dice_gen(n, faces, loop_len)): pass print(f'{n}-sided, markings {faces}, loop length {loop_len}:') print(f'\t{i + 1}*{loop_len} solutions, e.g. {" > ".join(x)} > [loop]') t, t0 = time(), t print(f'\ttime: {t - t0:.4f} seconds\n')
package main import ( "fmt" "sort" ) func fourFaceCombs() (res [][4]int) { found := make([]bool, 256) for i := 1; i <= 4; i++ { for j := 1; j <= 4; j++ { for k := 1; k <= 4; k++ { for l := 1; l <= 4; l++ { c := [4]int{i, j, k, l} sort.Ints(c[:]) key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1) if !found[key] { found[key] = true res = append(res, c) } } } } } return } func cmp(x, y [4]int) int { xw := 0 yw := 0 for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { if x[i] > y[j] { xw++ } else if y[j] > x[i] { yw++ } } } if xw < yw { return -1 } else if xw > yw { return 1 } return 0 } func findIntransitive3(cs [][4]int) (res [][3][4]int) { var c = len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[i], cs[k]) if third == 1 { res = append(res, [3][4]int{cs[i], cs[j], cs[k]}) } } } } } } return } func findIntransitive4(cs [][4]int) (res [][4][4]int) { c := len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { for l := 0; l < c; l++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[k], cs[l]) if third == -1 { fourth := cmp(cs[i], cs[l]) if fourth == 1 { res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]}) } } } } } } } } return } func main() { combs := fourFaceCombs() fmt.Println("Number of eligible 4-faced dice", len(combs)) it3 := findIntransitive3(combs) fmt.Printf("\n%d ordered lists of 3 non-transitive dice found, namely:\n", len(it3)) for _, a := range it3 { fmt.Println(a) } it4 := findIntransitive4(combs) fmt.Printf("\n%d ordered lists of 4 non-transitive dice found, namely:\n", len(it4)) for _, a := range it4 { fmt.Println(a) } }
Write the same code in Go as shown below in Python.
from itertools import combinations_with_replacement as cmbr from time import time def dice_gen(n, faces, m): dice = list(cmbr(faces, n)) succ = [set(j for j, b in enumerate(dice) if sum((x>y) - (x<y) for x in a for y in b) > 0) for a in dice] def loops(seq): s = succ[seq[-1]] if len(seq) == m: if seq[0] in s: yield seq return for d in (x for x in s if x > seq[0] and not x in seq): yield from loops(seq + (d,)) yield from (tuple(''.join(dice[s]) for s in x) for i, v in enumerate(succ) for x in loops((i,))) t = time() for n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]: for i, x in enumerate(dice_gen(n, faces, loop_len)): pass print(f'{n}-sided, markings {faces}, loop length {loop_len}:') print(f'\t{i + 1}*{loop_len} solutions, e.g. {" > ".join(x)} > [loop]') t, t0 = time(), t print(f'\ttime: {t - t0:.4f} seconds\n')
package main import ( "fmt" "sort" ) func fourFaceCombs() (res [][4]int) { found := make([]bool, 256) for i := 1; i <= 4; i++ { for j := 1; j <= 4; j++ { for k := 1; k <= 4; k++ { for l := 1; l <= 4; l++ { c := [4]int{i, j, k, l} sort.Ints(c[:]) key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1) if !found[key] { found[key] = true res = append(res, c) } } } } } return } func cmp(x, y [4]int) int { xw := 0 yw := 0 for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { if x[i] > y[j] { xw++ } else if y[j] > x[i] { yw++ } } } if xw < yw { return -1 } else if xw > yw { return 1 } return 0 } func findIntransitive3(cs [][4]int) (res [][3][4]int) { var c = len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[i], cs[k]) if third == 1 { res = append(res, [3][4]int{cs[i], cs[j], cs[k]}) } } } } } } return } func findIntransitive4(cs [][4]int) (res [][4][4]int) { c := len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { for l := 0; l < c; l++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[k], cs[l]) if third == -1 { fourth := cmp(cs[i], cs[l]) if fourth == 1 { res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]}) } } } } } } } } return } func main() { combs := fourFaceCombs() fmt.Println("Number of eligible 4-faced dice", len(combs)) it3 := findIntransitive3(combs) fmt.Printf("\n%d ordered lists of 3 non-transitive dice found, namely:\n", len(it3)) for _, a := range it3 { fmt.Println(a) } it4 := findIntransitive4(combs) fmt.Printf("\n%d ordered lists of 4 non-transitive dice found, namely:\n", len(it4)) for _, a := range it4 { fmt.Println(a) } }
Ensure the translated Go code behaves exactly like the original Python snippet.
import sys HIST = {} def trace(frame, event, arg): for name,val in frame.f_locals.items(): if name not in HIST: HIST[name] = [] else: if HIST[name][-1] is val: continue HIST[name].append(val) return trace def undo(name): HIST[name].pop(-1) return HIST[name][-1] def main(): a = 10 a = 20 for i in range(5): c = i print "c:", c, "-> undo x3 ->", c = undo('c') c = undo('c') c = undo('c') print c print 'HIST:', HIST sys.settrace(trace) main()
package main import ( "fmt" "sort" "sync" "time" ) type history struct { timestamp tsFunc hs []hset } type tsFunc func() time.Time type hset struct { int t time.Time } func newHistory(ts tsFunc) history { return history{ts, []hset{{t: ts()}}} } func (h history) int() int { return h.hs[len(h.hs)-1].int } func (h *history) set(x int) time.Time { t := h.timestamp() h.hs = append(h.hs, hset{x, t}) return t } func (h history) dump() { for _, hs := range h.hs { fmt.Println(hs.t.Format(time.StampNano), hs.int) } } func (h history) recall(t time.Time) (int, bool) { i := sort.Search(len(h.hs), func(i int) bool { return h.hs[i].t.After(t) }) if i > 0 { return h.hs[i-1].int, true } return 0, false } func newTimestamper() tsFunc { var last time.Time return func() time.Time { if t := time.Now(); t.After(last) { last = t } else { last.Add(1) } return last } } func newProtectedTimestamper() tsFunc { var last time.Time var m sync.Mutex return func() (t time.Time) { t = time.Now() m.Lock() if t.After(last) { last = t } else { last.Add(1) t = last } m.Unlock() return } } func main() { ts := newTimestamper() h := newHistory(ts) ref := []time.Time{h.set(3), h.set(1), h.set(4)} fmt.Println("History of variable h:") h.dump() fmt.Println("Recalling values:") for _, t := range ref { rv, _ := h.recall(t) fmt.Println(rv) } }
Keep all operations the same but rewrite the snippet in Go.
import random TRAINING_LENGTH = 2000 class Perceptron: def __init__(self,n): self.c = .01 self.weights = [random.uniform(-1.0, 1.0) for _ in range(n)] def feed_forward(self, inputs): vars = [] for i in range(len(inputs)): vars.append(inputs[i] * self.weights[i]) return self.activate(sum(vars)) def activate(self, value): return 1 if value > 0 else -1 def train(self, inputs, desired): guess = self.feed_forward(inputs) error = desired - guess for i in range(len(inputs)): self.weights[i] += self.c * error * inputs[i] class Trainer(): def __init__(self, x, y, a): self.inputs = [x, y, 1] self.answer = a def F(x): return 2 * x + 1 if __name__ == "__main__": ptron = Perceptron(3) training = [] for i in range(TRAINING_LENGTH): x = random.uniform(-10,10) y = random.uniform(-10,10) answer = 1 if y < F(x): answer = -1 training.append(Trainer(x,y,answer)) result = [] for y in range(-10,10): temp = [] for x in range(-10,10): if ptron.feed_forward([x,y,1]) == 1: temp.append('^') else: temp.append('.') result.append(temp) print('Untrained') for row in result: print(''.join(v for v in row)) for t in training: ptron.train(t.inputs, t.answer) result = [] for y in range(-10,10): temp = [] for x in range(-10,10): if ptron.feed_forward([x,y,1]) == 1: temp.append('^') else: temp.append('.') result.append(temp) print('Trained') for row in result: print(''.join(v for v in row))
package main import ( "github.com/fogleman/gg" "math/rand" "time" ) const c = 0.00001 func linear(x float64) float64 { return x*0.7 + 40 } type trainer struct { inputs []float64 answer int } func newTrainer(x, y float64, a int) *trainer { return &trainer{[]float64{x, y, 1}, a} } type perceptron struct { weights []float64 training []*trainer } func newPerceptron(n, w, h int) *perceptron { weights := make([]float64, n) for i := 0; i < n; i++ { weights[i] = rand.Float64()*2 - 1 } training := make([]*trainer, 2000) for i := 0; i < 2000; i++ { x := rand.Float64() * float64(w) y := rand.Float64() * float64(h) answer := 1 if y < linear(x) { answer = -1 } training[i] = newTrainer(x, y, answer) } return &perceptron{weights, training} } func (p *perceptron) feedForward(inputs []float64) int { if len(inputs) != len(p.weights) { panic("weights and input length mismatch, program terminated") } sum := 0.0 for i, w := range p.weights { sum += inputs[i] * w } if sum > 0 { return 1 } return -1 } func (p *perceptron) train(inputs []float64, desired int) { guess := p.feedForward(inputs) err := float64(desired - guess) for i := range p.weights { p.weights[i] += c * err * inputs[i] } } func (p *perceptron) draw(dc *gg.Context, iterations int) { le := len(p.training) for i, count := 0, 0; i < iterations; i, count = i+1, (count+1)%le { p.train(p.training[count].inputs, p.training[count].answer) } x := float64(dc.Width()) y := linear(x) dc.SetLineWidth(2) dc.SetRGB255(0, 0, 0) dc.DrawLine(0, linear(0), x, y) dc.Stroke() dc.SetLineWidth(1) for i := 0; i < le; i++ { guess := p.feedForward(p.training[i].inputs) x := p.training[i].inputs[0] - 4 y := p.training[i].inputs[1] - 4 if guess > 0 { dc.SetRGB(0, 0, 1) } else { dc.SetRGB(1, 0, 0) } dc.DrawCircle(x, y, 8) dc.Stroke() } } func main() { rand.Seed(time.Now().UnixNano()) w, h := 640, 360 perc := newPerceptron(3, w, h) dc := gg.NewContext(w, h) dc.SetRGB(1, 1, 1) dc.Clear() perc.draw(dc, 2000) dc.SavePNG("perceptron.png") }
Translate this program into Go but keep the logic exactly as in Python.
>>> exec 10
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time error"); return; } fmt.Println("Return value:", val) }
Generate a Go translation of this Python snippet without changing its computational steps.
>>> exec 10
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time error"); return; } fmt.Println("Return value:", val) }
Change the programming language of this snippet from Python to Go without modifying what it does.
from sympy import isprime, lcm, factorint, primerange from functools import reduce def pisano1(m): "Simple definition" if m < 2: return 1 lastn, n = 0, 1 for i in range(m ** 2): lastn, n = n, (lastn + n) % m if lastn == 0 and n == 1: return i + 1 return 1 def pisanoprime(p, k): "Use conjecture π(p ** k) == p ** (k − 1) * π(p) for prime p and int k > 1" assert isprime(p) and k > 0 return p ** (k - 1) * pisano1(p) def pisano_mult(m, n): "pisano(m*n) where m and n assumed coprime integers" return lcm(pisano1(m), pisano1(n)) def pisano2(m): "Uses prime factorization of m" return reduce(lcm, (pisanoprime(prime, mult) for prime, mult in factorint(m).items()), 1) if __name__ == '__main__': for n in range(1, 181): assert pisano1(n) == pisano2(n), "Wall-Sun-Sun prime exists??!!" print("\nPisano period (p, 2) for primes less than 50\n ", [pisanoprime(prime, 2) for prime in primerange(1, 50)]) print("\nPisano period (p, 1) for primes less than 180\n ", [pisanoprime(prime, 1) for prime in primerange(1, 180)]) print("\nPisano period (p) for integers 1 to 180") for i in range(1, 181): print(" %3d" % pisano2(i), end="" if i % 10 else "\n")
package main import "fmt" func gcd(a, b uint) uint { if b == 0 { return a } return gcd(b, a%b) } func lcm(a, b uint) uint { return a / gcd(a, b) * b } func ipow(x, p uint) uint { prod := uint(1) for p > 0 { if p&1 != 0 { prod *= x } p >>= 1 x *= x } return prod } func getPrimes(n uint) []uint { var primes []uint for i := uint(2); i <= n; i++ { div := n / i mod := n % i for mod == 0 { primes = append(primes, i) n = div div = n / i mod = n % i } } return primes } func isPrime(n uint) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := uint(5) for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func pisanoPeriod(m uint) uint { var p, c uint = 0, 1 for i := uint(0); i < m*m; i++ { p, c = c, (p+c)%m if p == 0 && c == 1 { return i + 1 } } return 1 } func pisanoPrime(p uint, k uint) uint { if !isPrime(p) || k == 0 { return 0 } return ipow(p, k-1) * pisanoPeriod(p) } func pisano(m uint) uint { primes := getPrimes(m) primePowers := make(map[uint]uint) for _, p := range primes { primePowers[p]++ } var pps []uint for k, v := range primePowers { pps = append(pps, pisanoPrime(k, v)) } if len(pps) == 0 { return 1 } if len(pps) == 1 { return pps[0] } f := pps[0] for i := 1; i < len(pps); i++ { f = lcm(f, pps[i]) } return f } func main() { for p := uint(2); p < 15; p++ { pp := pisanoPrime(p, 2) if pp > 0 { fmt.Printf("pisanoPrime(%2d: 2) = %d\n", p, pp) } } fmt.Println() for p := uint(2); p < 180; p++ { pp := pisanoPrime(p, 1) if pp > 0 { fmt.Printf("pisanoPrime(%3d: 1) = %d\n", p, pp) } } fmt.Println() fmt.Println("pisano(n) for integers 'n' from 1 to 180 are:") for n := uint(1); n <= 180; n++ { fmt.Printf("%3d ", pisano(n)) if n != 1 && n%15 == 0 { fmt.Println() } } fmt.Println() }
Write the same code in Go as shown below in Python.
from itertools import count, islice import numpy as np from numpy import sin, cos, pi ANGDIV = 12 ANG = 2*pi/ANGDIV def draw_all(sols): import matplotlib.pyplot as plt def draw_track(ax, s): turn, xend, yend = 0, [0], [0] for d in s: x0, y0 = xend[-1], yend[-1] a = turn*ANG cs, sn = cos(a), sin(a) ang = a + d*pi/2 cx, cy = x0 + cos(ang), y0 + sin(ang) da = np.linspace(ang, ang + d*ANG, 10) xs = cx - cos(da) ys = cy - sin(da) ax.plot(xs, ys, 'green' if d == -1 else 'orange') xend.append(xs[-1]) yend.append(ys[-1]) turn += d ax.plot(xend, yend, 'k.', markersize=1) ax.set_aspect(1) ls = len(sols) if ls == 0: return w, h = min((abs(w*2 - h*3) + w*h - ls, w, h) for w, h in ((w, (ls + w - 1)//w) for w in range(1, ls + 1)))[1:] fig, ax = plt.subplots(h, w, squeeze=False) for a in ax.ravel(): a.set_axis_off() for i, s in enumerate(sols): draw_track(ax[i//w, i%w], s) plt.show() def match_up(this, that, equal_lr, seen): if not this or not that: return n = len(this[0][-1]) n2 = n*2 l_lo, l_hi, r_lo, r_hi = 0, 0, 0, 0 def record(m): for _ in range(n2): seen[m] = True m = (m&1) << (n2 - 1) | (m >> 1) if equal_lr: m ^= (1<<n2) - 1 for _ in range(n2): seen[m] = True m = (m&1) << (n2 - 1) | (m >> 1) l_n, r_n = len(this), len(that) tol = 1e-3 while l_lo < l_n: while l_hi < l_n and this[l_hi][0] - this[l_lo][0] <= tol: l_hi += 1 while r_lo < r_n and that[r_lo][0] < this[l_lo][0] - tol: r_lo += 1 r_hi = r_lo while r_hi < r_n and that[r_hi][0] < this[l_lo][0] + tol: r_hi += 1 for a in this[l_lo:l_hi]: m_left = a[-2]<<n for b in that[r_lo:r_hi]: if (m := m_left | b[-2]) not in seen: if np.abs(a[1] + b[2]) < tol: record(m) record(int(f'{m:b}'[::-1], base=2)) yield(a[-1] + b[-1]) l_lo, r_lo = l_hi, r_hi def track_combo(left, right): n = (left + right)//2 n1 = left + right - n alphas = np.exp(1j*ANG*np.arange(ANGDIV)) def half_track(m, n): turns = tuple(1 - 2*(m>>i & 1) for i in range(n)) rcnt = np.cumsum(turns)%ANGDIV asum = np.sum(alphas[rcnt]) want = asum/alphas[rcnt[-1]] return np.abs(asum), asum, want, m, turns res = [[] for _ in range(right + 1)] for i in range(1<<n): b = i.bit_count() if b <= right: res[b].append(half_track(i, n)) for v in res: v.sort() if n1 == n: return res, res res1 = [[] for _ in range(right + 1)] for i in range(1<<n1): b = i.bit_count() if b <= right: res1[b].append(half_track(i, n1)) for v in res: v.sort() return res, res1 def railway(n): seen = {} for l in range(n//2, n + 1): r = n - l if not l >= r: continue if (l - r)%ANGDIV == 0: res_l, res_r = track_combo(l, r) for i, this in enumerate(res_l): if 2*i < r: continue that = res_r[r - i] for s in match_up(this, that, l == r, seen): yield s sols = [] for i, s in enumerate(railway(30)): print(i + 1, s) sols.append(s) draw_all(sols[:40])
package main import "fmt" const ( right = 1 left = -1 straight = 0 ) func normalize(tracks []int) string { size := len(tracks) a := make([]byte, size) for i := 0; i < size; i++ { a[i] = "abc"[tracks[i]+1] } norm := string(a) for i := 0; i < size; i++ { s := string(a) if s < norm { norm = s } tmp := a[0] copy(a, a[1:]) a[size-1] = tmp } return norm } func fullCircleStraight(tracks []int, nStraight int) bool { if nStraight == 0 { return true } count := 0 for _, track := range tracks { if track == straight { count++ } } if count != nStraight { return false } var straightTracks [12]int for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ { if tracks[i] == straight { straightTracks[idx%12]++ } idx += tracks[i] } any1, any2 := false, false for i := 0; i <= 5; i++ { if straightTracks[i] != straightTracks[i+6] { any1 = true break } } for i := 0; i <= 7; i++ { if straightTracks[i] != straightTracks[i+4] { any2 = true break } } return !any1 || !any2 } func fullCircleRight(tracks []int) bool { sum := 0 for _, track := range tracks { sum += track * 30 } if sum%360 != 0 { return false } var rTurns [12]int for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ { if tracks[i] == right { rTurns[idx%12]++ } idx += tracks[i] } any1, any2 := false, false for i := 0; i <= 5; i++ { if rTurns[i] != rTurns[i+6] { any1 = true break } } for i := 0; i <= 7; i++ { if rTurns[i] != rTurns[i+4] { any2 = true break } } return !any1 || !any2 } func circuits(nCurved, nStraight int) { solutions := make(map[string][]int) gen := getPermutationsGen(nCurved, nStraight) for gen.hasNext() { tracks := gen.next() if !fullCircleStraight(tracks, nStraight) { continue } if !fullCircleRight(tracks) { continue } tracks2 := make([]int, len(tracks)) copy(tracks2, tracks) solutions[normalize(tracks)] = tracks2 } report(solutions, nCurved, nStraight) } func getPermutationsGen(nCurved, nStraight int) PermutationsGen { if (nCurved+nStraight-12)%4 != 0 { panic("input must be 12 + k * 4") } var trackTypes []int switch nStraight { case 0: trackTypes = []int{right, left} case 12: trackTypes = []int{right, straight} default: trackTypes = []int{right, left, straight} } return NewPermutationsGen(nCurved+nStraight, trackTypes) } func report(sol map[string][]int, numC, numS int) { size := len(sol) fmt.Printf("\n%d solution(s) for C%d,%d \n", size, numC, numS) if numC <= 20 { for _, tracks := range sol { for _, track := range tracks { fmt.Printf("%2d ", track) } fmt.Println() } } } type PermutationsGen struct { NumPositions int choices []int indices []int sequence []int carry int } func NewPermutationsGen(numPositions int, choices []int) PermutationsGen { indices := make([]int, numPositions) sequence := make([]int, numPositions) carry := 0 return PermutationsGen{numPositions, choices, indices, sequence, carry} } func (p *PermutationsGen) next() []int { p.carry = 1 for i := 1; i < len(p.indices) && p.carry > 0; i++ { p.indices[i] += p.carry p.carry = 0 if p.indices[i] == len(p.choices) { p.carry = 1 p.indices[i] = 0 } } for j := 0; j < len(p.indices); j++ { p.sequence[j] = p.choices[p.indices[j]] } return p.sequence } func (p *PermutationsGen) hasNext() bool { return p.carry != 1 } func main() { for n := 12; n <= 28; n += 4 { circuits(n, 0) } circuits(12, 4) }
Ensure the translated Go code behaves exactly like the original Python snippet.
from itertools import imap, imap, groupby, chain, imap from operator import itemgetter from sys import argv from array import array def concat_map(func, it): return list(chain.from_iterable(imap(func, it))) def minima(poly): return (min(pt[0] for pt in poly), min(pt[1] for pt in poly)) def translate_to_origin(poly): (minx, miny) = minima(poly) return [(x - minx, y - miny) for (x, y) in poly] rotate90 = lambda (x, y): ( y, -x) rotate180 = lambda (x, y): (-x, -y) rotate270 = lambda (x, y): (-y, x) reflect = lambda (x, y): (-x, y) def rotations_and_reflections(poly): return (poly, map(rotate90, poly), map(rotate180, poly), map(rotate270, poly), map(reflect, poly), [reflect(rotate90(pt)) for pt in poly], [reflect(rotate180(pt)) for pt in poly], [reflect(rotate270(pt)) for pt in poly]) def canonical(poly): return min(sorted(translate_to_origin(pl)) for pl in rotations_and_reflections(poly)) def unique(lst): lst.sort() return map(next, imap(itemgetter(1), groupby(lst))) contiguous = lambda (x, y): [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)] def new_points(poly): return unique([pt for pt in concat_map(contiguous, poly) if pt not in poly]) def new_polys(poly): return unique([canonical(poly + [pt]) for pt in new_points(poly)]) monomino = [(0, 0)] monominoes = [monomino] def rank(n): assert n >= 0 if n == 0: return [] if n == 1: return monominoes return unique(concat_map(new_polys, rank(n - 1))) def text_representation(poly): min_pt = minima(poly) max_pt = (max(p[0] for p in poly), max(p[1] for p in poly)) table = [array('c', ' ') * (max_pt[1] - min_pt[1] + 1) for _ in xrange(max_pt[0] - min_pt[0] + 1)] for pt in poly: table[pt[0] - min_pt[0]][pt[1] - min_pt[1]] = ' return "\n".join(row.tostring() for row in table) def main(): print [len(rank(n)) for n in xrange(1, 11)] n = int(argv[1]) if (len(argv) == 2) else 5 print "\nAll free polyominoes of rank %d:" % n for poly in rank(n): print text_representation(poly), "\n" main()
package main import ( "fmt" "sort" ) type point struct{ x, y int } type polyomino []point type pointset map[point]bool func (p point) rotate90() point { return point{p.y, -p.x} } func (p point) rotate180() point { return point{-p.x, -p.y} } func (p point) rotate270() point { return point{-p.y, p.x} } func (p point) reflect() point { return point{-p.x, p.y} } func (p point) String() string { return fmt.Sprintf("(%d, %d)", p.x, p.y) } func (p point) contiguous() polyomino { return polyomino{point{p.x - 1, p.y}, point{p.x + 1, p.y}, point{p.x, p.y - 1}, point{p.x, p.y + 1}} } func (po polyomino) minima() (int, int) { minx := po[0].x miny := po[0].y for i := 1; i < len(po); i++ { if po[i].x < minx { minx = po[i].x } if po[i].y < miny { miny = po[i].y } } return minx, miny } func (po polyomino) translateToOrigin() polyomino { minx, miny := po.minima() res := make(polyomino, len(po)) for i, p := range po { res[i] = point{p.x - minx, p.y - miny} } sort.Slice(res, func(i, j int) bool { return res[i].x < res[j].x || (res[i].x == res[j].x && res[i].y < res[j].y) }) return res } func (po polyomino) rotationsAndReflections() []polyomino { rr := make([]polyomino, 8) for i := 0; i < 8; i++ { rr[i] = make(polyomino, len(po)) } copy(rr[0], po) for j := 0; j < len(po); j++ { rr[1][j] = po[j].rotate90() rr[2][j] = po[j].rotate180() rr[3][j] = po[j].rotate270() rr[4][j] = po[j].reflect() rr[5][j] = po[j].rotate90().reflect() rr[6][j] = po[j].rotate180().reflect() rr[7][j] = po[j].rotate270().reflect() } return rr } func (po polyomino) canonical() polyomino { rr := po.rotationsAndReflections() minr := rr[0].translateToOrigin() mins := minr.String() for i := 1; i < 8; i++ { r := rr[i].translateToOrigin() s := r.String() if s < mins { minr = r mins = s } } return minr } func (po polyomino) String() string { return fmt.Sprintf("%v", []point(po)) } func (po polyomino) toPointset() pointset { pset := make(pointset, len(po)) for _, p := range po { pset[p] = true } return pset } func (po polyomino) newPoints() polyomino { pset := po.toPointset() m := make(pointset) for _, p := range po { pts := p.contiguous() for _, pt := range pts { if !pset[pt] { m[pt] = true } } } poly := make(polyomino, 0, len(m)) for k := range m { poly = append(poly, k) } return poly } func (po polyomino) newPolys() []polyomino { pts := po.newPoints() res := make([]polyomino, len(pts)) for i, pt := range pts { poly := make(polyomino, len(po)) copy(poly, po) poly = append(poly, pt) res[i] = poly.canonical() } return res } var monomino = polyomino{point{0, 0}} var monominoes = []polyomino{monomino} func rank(n int) []polyomino { switch { case n < 0: panic("n cannot be negative. Program terminated.") case n == 0: return []polyomino{} case n == 1: return monominoes default: r := rank(n - 1) m := make(map[string]bool) var polys []polyomino for _, po := range r { for _, po2 := range po.newPolys() { if s := po2.String(); !m[s] { polys = append(polys, po2) m[s] = true } } } sort.Slice(polys, func(i, j int) bool { return polys[i].String() < polys[j].String() }) return polys } } func main() { const n = 5 fmt.Printf("All free polyominoes of rank %d:\n\n", n) for _, poly := range rank(n) { for _, pt := range poly { fmt.Printf("%s ", pt) } fmt.Println() } const k = 10 fmt.Printf("\nNumber of free polyominoes of ranks 1 to %d:\n", k) for i := 1; i <= k; i++ { fmt.Printf("%d ", len(rank(i))) } fmt.Println() }
Transform the following Python implementation into Go, maintaining the same output and logic.
import requests import json city = None topic = None def getEvent(url_path, key) : responseString = "" params = {'city':city, 'key':key,'topic':topic} r = requests.get(url_path, params = params) print(r.url) responseString = r.text return responseString def getApiKey(key_path): key = "" f = open(key_path, 'r') key = f.read() return key def submitEvent(url_path,params): r = requests.post(url_path, data=json.dumps(params)) print(r.text+" : Event Submitted")
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "net/url" "os" "strings" "time" ) var key string func init() { const keyFile = "api_key.txt" f, err := os.Open(keyFile) if err != nil { log.Fatal(err) } keydata, err := ioutil.ReadAll(f) if err != nil { log.Fatal(err) } key = strings.TrimSpace(string(keydata)) } type EventResponse struct { Results []Result } type Result struct { ID string Status string Name string EventURL string `json:"event_url"` Description string Time EventTime } type EventTime struct{ time.Time } func (et *EventTime) UnmarshalJSON(data []byte) error { var msec int64 if err := json.Unmarshal(data, &msec); err != nil { return err } et.Time = time.Unix(0, msec*int64(time.Millisecond)) return nil } func (et EventTime) MarshalJSON() ([]byte, error) { msec := et.UnixNano() / int64(time.Millisecond) return json.Marshal(msec) } func (r *Result) String() string { var b bytes.Buffer fmt.Fprintln(&b, "ID:", r.ID) fmt.Fprintln(&b, "URL:", r.EventURL) fmt.Fprintln(&b, "Time:", r.Time.Format(time.UnixDate)) d := r.Description const limit = 65 if len(d) > limit { d = d[:limit-1] + "…" } fmt.Fprintln(&b, "Description:", d) return b.String() } func main() { v := url.Values{ "topic": []string{"photo"}, "time": []string{",1w"}, "key": []string{key}, } u := url.URL{ Scheme: "http", Host: "api.meetup.com", Path: "2/open_events.json", RawQuery: v.Encode(), } resp, err := http.Get(u.String()) if err != nil { log.Fatal(err) } defer resp.Body.Close() log.Println("HTTP Status:", resp.Status) body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } var buf bytes.Buffer if err = json.Indent(&buf, body, "", " "); err != nil { log.Fatal(err) } var evresp EventResponse json.Unmarshal(body, &evresp) fmt.Println("Got", len(evresp.Results), "events") if len(evresp.Results) > 0 { fmt.Println("First event:\n", &evresp.Results[0]) } }
Produce a functionally identical Go code for the snippet given in Python.
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), ) def printer(st, matches): if False in matches: print('Missed by one statement: %i, %s' % docs[matches.index(False)]) else: print('Full match:') print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) funcs, docs = zip(*constraintinfo) full, partial = [], [] for st in product( *([(False, True)] * 12) ): truths = [bool(func(st)) for func in funcs] matches = [s == t for s,t in zip(st, truths)] mcount = sum(matches) if mcount == 12: full.append((st, matches)) elif mcount == 11: partial.append((st, matches)) for stm in full + partial: printer(*stm)
package main import "fmt" var solution = make(chan int) var nearMiss = make(chan int) var done = make(chan bool) func main() { for i := 0; i < 4096; i++ { go checkPerm(i) } var ms []int for i := 0; i < 4096; { select { case <-done: i++ case s := <-solution: print12("solution", s) case m := <-nearMiss: ms = append(ms, m) } } for _, m := range ms { print12("near miss", m) } } func print12(label string, bits int) { fmt.Print(label, ":") for i := 1; i <= 12; i++ { if bits&1 == 1 { fmt.Print(" ", i) } bits >>= 1 } fmt.Println() } func checkPerm(tz int) { ts := func(n uint) bool { return tz>>(n-1)&1 == 1 } ntrue := func(xs ...uint) int { nt := 0 for _, x := range xs { if ts(x) { nt++ } } return nt } var con bool test := func(statement uint, b bool) { switch { case ts(statement) == b: case con: panic("bail") default: con = true } } defer func() { if x := recover(); x != nil { if msg, ok := x.(string); !ok && msg != "bail" { panic(x) } } done <- true }() test(1, true) test(2, ntrue(7, 8, 9, 10, 11, 12) == 3) test(3, ntrue(2, 4, 6, 8, 10, 12) == 2) test(4, !ts(5) || ts(6) && ts(7)) test(5, !ts(4) && !ts(3) && !ts(2)) test(6, ntrue(1, 3, 5, 7, 9, 11) == 4) test(7, ts(2) != ts(3)) test(8, !ts(7) || ts(5) && ts(6)) test(9, ntrue(1, 2, 3, 4, 5, 6) == 3) test(10, ts(11) && ts(12)) test(11, ntrue(7, 8, 9) == 1) test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4) if con { nearMiss <- tz } else { solution <- tz } }
Maintain the same structure and functionality when rewriting this code in Go.
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), ) def printer(st, matches): if False in matches: print('Missed by one statement: %i, %s' % docs[matches.index(False)]) else: print('Full match:') print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) funcs, docs = zip(*constraintinfo) full, partial = [], [] for st in product( *([(False, True)] * 12) ): truths = [bool(func(st)) for func in funcs] matches = [s == t for s,t in zip(st, truths)] mcount = sum(matches) if mcount == 12: full.append((st, matches)) elif mcount == 11: partial.append((st, matches)) for stm in full + partial: printer(*stm)
package main import "fmt" var solution = make(chan int) var nearMiss = make(chan int) var done = make(chan bool) func main() { for i := 0; i < 4096; i++ { go checkPerm(i) } var ms []int for i := 0; i < 4096; { select { case <-done: i++ case s := <-solution: print12("solution", s) case m := <-nearMiss: ms = append(ms, m) } } for _, m := range ms { print12("near miss", m) } } func print12(label string, bits int) { fmt.Print(label, ":") for i := 1; i <= 12; i++ { if bits&1 == 1 { fmt.Print(" ", i) } bits >>= 1 } fmt.Println() } func checkPerm(tz int) { ts := func(n uint) bool { return tz>>(n-1)&1 == 1 } ntrue := func(xs ...uint) int { nt := 0 for _, x := range xs { if ts(x) { nt++ } } return nt } var con bool test := func(statement uint, b bool) { switch { case ts(statement) == b: case con: panic("bail") default: con = true } } defer func() { if x := recover(); x != nil { if msg, ok := x.(string); !ok && msg != "bail" { panic(x) } } done <- true }() test(1, true) test(2, ntrue(7, 8, 9, 10, 11, 12) == 3) test(3, ntrue(2, 4, 6, 8, 10, 12) == 2) test(4, !ts(5) || ts(6) && ts(7)) test(5, !ts(4) && !ts(3) && !ts(2)) test(6, ntrue(1, 3, 5, 7, 9, 11) == 4) test(7, ts(2) != ts(3)) test(8, !ts(7) || ts(5) && ts(6)) test(9, ntrue(1, 2, 3, 4, 5, 6) == 3) test(10, ts(11) && ts(12)) test(11, ntrue(7, 8, 9) == 1) test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4) if con { nearMiss <- tz } else { solution <- tz } }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
import math dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087] dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032] def funnel(dxs, rule): x, rxs = 0, [] for dx in dxs: rxs.append(x + dx) x = rule(x, dx) return rxs def mean(xs): return sum(xs) / len(xs) def stddev(xs): m = mean(xs) return math.sqrt(sum((x-m)**2 for x in xs) / len(xs)) def experiment(label, rule): rxs, rys = funnel(dxs, rule), funnel(dys, rule) print label print 'Mean x, y  : %.4f, %.4f' % (mean(rxs), mean(rys)) print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys)) print experiment('Rule 1:', lambda z, dz: 0) experiment('Rule 2:', lambda z, dz: -dz) experiment('Rule 3:', lambda z, dz: -(z+dz)) experiment('Rule 4:', lambda z, dz: z+dz)
package main import ( "fmt" "math" ) type rule func(float64, float64) float64 var dxs = []float64{ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087, } var dys = []float64{ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032, } func funnel(fa []float64, r rule) []float64 { x := 0.0 result := make([]float64, len(fa)) for i, f := range fa { result[i] = x + f x = r(x, f) } return result } func mean(fa []float64) float64 { sum := 0.0 for _, f := range fa { sum += f } return sum / float64(len(fa)) } func stdDev(fa []float64) float64 { m := mean(fa) sum := 0.0 for _, f := range fa { sum += (f - m) * (f - m) } return math.Sqrt(sum / float64(len(fa))) } func experiment(label string, r rule) { rxs := funnel(dxs, r) rys := funnel(dys, r) fmt.Println(label, " : x y") fmt.Printf("Mean  : %7.4f, %7.4f\n", mean(rxs), mean(rys)) fmt.Printf("Std Dev : %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys)) fmt.Println() } func main() { experiment("Rule 1", func(_, _ float64) float64 { return 0.0 }) experiment("Rule 2", func(_, dz float64) float64 { return -dz }) experiment("Rule 3", func(z, dz float64) float64 { return -(z + dz) }) experiment("Rule 4", func(z, dz float64) float64 { return z + dz }) }
Translate this program into Go but keep the logic exactly as in Python.
import math dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087] dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032] def funnel(dxs, rule): x, rxs = 0, [] for dx in dxs: rxs.append(x + dx) x = rule(x, dx) return rxs def mean(xs): return sum(xs) / len(xs) def stddev(xs): m = mean(xs) return math.sqrt(sum((x-m)**2 for x in xs) / len(xs)) def experiment(label, rule): rxs, rys = funnel(dxs, rule), funnel(dys, rule) print label print 'Mean x, y  : %.4f, %.4f' % (mean(rxs), mean(rys)) print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys)) print experiment('Rule 1:', lambda z, dz: 0) experiment('Rule 2:', lambda z, dz: -dz) experiment('Rule 3:', lambda z, dz: -(z+dz)) experiment('Rule 4:', lambda z, dz: z+dz)
package main import ( "fmt" "math" ) type rule func(float64, float64) float64 var dxs = []float64{ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087, } var dys = []float64{ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032, } func funnel(fa []float64, r rule) []float64 { x := 0.0 result := make([]float64, len(fa)) for i, f := range fa { result[i] = x + f x = r(x, f) } return result } func mean(fa []float64) float64 { sum := 0.0 for _, f := range fa { sum += f } return sum / float64(len(fa)) } func stdDev(fa []float64) float64 { m := mean(fa) sum := 0.0 for _, f := range fa { sum += (f - m) * (f - m) } return math.Sqrt(sum / float64(len(fa))) } func experiment(label string, r rule) { rxs := funnel(dxs, r) rys := funnel(dys, r) fmt.Println(label, " : x y") fmt.Printf("Mean  : %7.4f, %7.4f\n", mean(rxs), mean(rys)) fmt.Printf("Std Dev : %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys)) fmt.Println() } func main() { experiment("Rule 1", func(_, _ float64) float64 { return 0.0 }) experiment("Rule 2", func(_, dz float64) float64 { return -dz }) experiment("Rule 3", func(z, dz float64) float64 { return -(z + dz) }) experiment("Rule 4", func(z, dz float64) float64 { return z + dz }) }
Ensure the translated Go code behaves exactly like the original Python snippet.
from re import sub testtexts = [ , , ] for txt in testtexts: text2 = sub(r'<lang\s+\"?([\w\d\s]+)\"?\s?>', r'<syntaxhighlight lang=\1>', txt) text2 = sub(r'<lang\s*>', r'<syntaxhighlight lang=text>', text2) text2 = sub(r'</lang\s*>', r'
package main import "fmt" import "io/ioutil" import "log" import "os" import "regexp" import "strings" func main() { err := fix() if err != nil { log.Fatalln(err) } } func fix() (err error) { buf, err := ioutil.ReadAll(os.Stdin) if err != nil { return err } out, err := Lang(string(buf)) if err != nil { return err } fmt.Println(out) return nil } func Lang(in string) (out string, err error) { reg := regexp.MustCompile("<[^>]+>") out = reg.ReplaceAllStringFunc(in, repl) return out, nil } func repl(in string) (out string) { if in == "</code>" { return "</"+"lang>" } mid := in[1 : len(in)-1] var langs = []string{ "abap", "actionscript", "actionscript3", "ada", "apache", "applescript", "apt_sources", "asm", "asp", "autoit", "avisynth", "bash", "basic4gl", "bf", "blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg", "cfm", "cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css", "d", "delphi", "diff", "_div", "dos", "dot", "eiffel", "email", "fortran", "freebasic", "genero", "gettext", "glsl", "gml", "gnuplot", "go", "groovy", "haskell", "hq9plus", "html4strict", "idl", "ini", "inno", "intercal", "io", "java", "java5", "javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp", "lolcode", "lotusformulas", "lotusscript", "lscript", "lua", "m68k", "make", "matlab", "mirc", "modula3", "mpasm", "mxml", "mysql", "nsis", "objc", "ocaml", "ocaml-brief", "oobas", "oracle11", "oracle8", "pascal", "per", "perl", "php", "php-brief", "pic16", "pixelbender", "plsql", "povray", "powershell", "progress", "prolog", "providex", "python", "qbasic", "rails", "reg", "robots", "ruby", "sas", "scala", "scheme", "scilab", "sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm", "text", "thinbasic", "tsql", "typoscript", "vb", "vbnet", "verilog", "vhdl", "vim", "visualfoxpro", "visualprolog", "whitespace", "winbatch", "xml", "xorg_conf", "xpp", "z80", } for _, lang := range langs { if mid == lang { return fmt.Sprintf("<lang %s>", lang) } if strings.HasPrefix(mid, "/") { if mid[len("/"):] == lang { return "</"+"lang>" } } if strings.HasPrefix(mid, "code ") { if mid[len("code "):] == lang { return fmt.Sprintf("<lang %s>", lang) } } } return in }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ + ':\n')(repr)(showList)( replicateM(2) )([[1, 2, 3], 'abc']) ) def liftA2List(f): return lambda xs: lambda ys: [ f(*xy) for xy in product(xs, ys) ] def fTable(s): def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) def showList(xs): return '[' + ','.join( showList(x) if isinstance(x, list) else repr(x) for x in xs ) + ']' if __name__ == '__main__': main()
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { p[i] = values[x] } fmt.Println(p) if decide(p) { return } for i := 0; ; { pn[i]++ if pn[i] < k { break } pn[i] = 0 i++ if i == n { return } } } }
Rewrite the snippet below in Go so it works the same as the original Python code.
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ + ':\n')(repr)(showList)( replicateM(2) )([[1, 2, 3], 'abc']) ) def liftA2List(f): return lambda xs: lambda ys: [ f(*xy) for xy in product(xs, ys) ] def fTable(s): def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) def showList(xs): return '[' + ','.join( showList(x) if isinstance(x, list) else repr(x) for x in xs ) + ']' if __name__ == '__main__': main()
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { p[i] = values[x] } fmt.Println(p) if decide(p) { return } for i := 0; ; { pn[i]++ if pn[i] < k { break } pn[i] = 0 i++ if i == n { return } } } }
Transform the following Python implementation into Go, maintaining the same output and logic.
def ownCalcPass (password, nonce, test=False) : start = True num1 = 0 num2 = 0 password = int(password) if test: print("password: %08x" % (password)) for c in nonce : if c != "0": if start: num2 = password start = False if test: print("c: %s num1: %08x num2: %08x" % (c, num1, num2)) if c == '1': num1 = (num2 & 0xFFFFFF80) >> 7 num2 = num2 << 25 elif c == '2': num1 = (num2 & 0xFFFFFFF0) >> 4 num2 = num2 << 28 elif c == '3': num1 = (num2 & 0xFFFFFFF8) >> 3 num2 = num2 << 29 elif c == '4': num1 = num2 << 1 num2 = num2 >> 31 elif c == '5': num1 = num2 << 5 num2 = num2 >> 27 elif c == '6': num1 = num2 << 12 num2 = num2 >> 20 elif c == '7': num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 ) num2 = ( num2 & 0xFF000000 ) >> 8 elif c == '8': num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 ) num2 = (num2 & 0x00FF0000) >> 8 elif c == '9': num1 = ~num2 else : num1 = num2 num1 &= 0xFFFFFFFF num2 &= 0xFFFFFFFF if (c not in "09"): num1 |= num2 if test: print(" num1: %08x num2: %08x" % (num1, num2)) num2 = num1 return num1 def test_passwd_calc(passwd, nonce, expected): res = ownCalcPass(passwd, nonce, False) m = passwd+' '+nonce+' '+str(res)+' '+str(expected) if res == int(expected) : print('PASS '+m) else : print('FAIL '+m) if __name__ == '__main__': test_passwd_calc('12345','603356072','25280520') test_passwd_calc('12345','410501656','119537670') test_passwd_calc('12345','630292165','4269684735')
package main import ( "fmt" "strconv" ) func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd } start = false } switch c { case '1': num1 = (num2 & 0xFFFFFF80) >> 7 num2 = num2 << 25 case '2': num1 = (num2 & 0xFFFFFFF0) >> 4 num2 = num2 << 28 case '3': num1 = (num2 & 0xFFFFFFF8) >> 3 num2 = num2 << 29 case '4': num1 = num2 << 1 num2 = num2 >> 31 case '5': num1 = num2 << 5 num2 = num2 >> 27 case '6': num1 = num2 << 12 num2 = num2 >> 20 case '7': num3 := num2 & 0x0000FF00 num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16) num1 = num3 | num4 num2 = (num2 & 0xFF000000) >> 8 case '8': num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24) num2 = (num2 & 0x00FF0000) >> 8 case '9': num1 = ^num2 default: num1 = num2 } num1 &= 0xFFFFFFFF num2 &= 0xFFFFFFFF if c != '0' && c != '9' { num1 |= num2 } num2 = num1 } return num1 } func testPasswordCalc(password, nonce string, expected uint32) { res := ownCalcPass(password, nonce) m := fmt.Sprintf("%s %s  %-10d  %-10d", password, nonce, res, expected) if res == expected { fmt.Println("PASS", m) } else { fmt.Println("FAIL", m) } } func main() { testPasswordCalc("12345", "603356072", 25280520) testPasswordCalc("12345", "410501656", 119537670) testPasswordCalc("12345", "630292165", 4269684735) }
Write a version of this Python function in Go with identical behavior.
from random import shuffle, choice from itertools import product, accumulate from numpy import floor, sqrt class ADFGVX: def __init__(self, spoly, k, alph='ADFGVX'): self.polybius = list(spoly.upper()) self.pdim = int(floor(sqrt(len(self.polybius)))) self.key = list(k.upper()) self.keylen = len(self.key) self.alphabet = list(alph) pairs = [p[0] + p[1] for p in product(self.alphabet, self.alphabet)] self.encode = dict(zip(self.polybius, pairs)) self.decode = dict((v, k) for (k, v) in self.encode.items()) def encrypt(self, msg): chars = list(''.join([self.encode[c] for c in msg.upper() if c in self.polybius])) colvecs = [(lett, chars[i:len(chars):self.keylen]) \ for (i, lett) in enumerate(self.key)] colvecs.sort(key=lambda x: x[0]) return ''.join([''.join(a[1]) for a in colvecs]) def decrypt(self, cod): chars = [c for c in cod if c in self.alphabet] sortedkey = sorted(self.key) order = [self.key.index(ch) for ch in sortedkey] originalorder = [sortedkey.index(ch) for ch in self.key] base, extra = divmod(len(chars), self.keylen) strides = [base + (1 if extra > i else 0) for i in order] starts = list(accumulate(strides[:-1], lambda x, y: x + y)) starts = [0] + starts ends = [starts[i] + strides[i] for i in range(self.keylen)] cols = [chars[starts[i]:ends[i]] for i in originalorder] pairs = [] for i in range((len(chars) - 1) // self.keylen + 1): for j in range(self.keylen): if i * self.keylen + j < len(chars): pairs.append(cols[j][i]) return ''.join([self.decode[pairs[i] + pairs[i + 1]] for i in range(0, len(pairs), 2)]) if __name__ == '__main__': PCHARS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') shuffle(PCHARS) POLYBIUS = ''.join(PCHARS) with open('unixdict.txt') as fh: WORDS = [w for w in (fh.read()).split() \ if len(w) == 9 and len(w) == len(set(list(w)))] KEY = choice(WORDS) SECRET, MESSAGE = ADFGVX(POLYBIUS, KEY), 'ATTACKAT1200AM' print(f'Polybius: {POLYBIUS}, key: {KEY}') print('Message: ', MESSAGE) ENCODED = SECRET.encrypt(MESSAGE) DECODED = SECRET.decrypt(ENCODED) print('Encoded: ', ENCODED) print('Decoded: ', DECODED)
package main import ( "bytes" "fmt" "io/ioutil" "log" "math/rand" "sort" "strings" "time" ) var adfgvx = "ADFGVX" var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func distinct(bs []byte) []byte { var u []byte for _, b := range bs { if !bytes.Contains(u, []byte{b}) { u = append(u, b) } } return u } func allAsciiAlphaNum(word []byte) bool { for _, b := range word { if !((b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122)) { return false } } return true } func orderKey(key string) []int { temp := make([][2]byte, len(key)) for i := 0; i < len(key); i++ { temp[i] = [2]byte{key[i], byte(i)} } sort.Slice(temp, func(i, j int) bool { return temp[i][0] < temp[j][0] }) res := make([]int, len(key)) for i := 0; i < len(key); i++ { res[i] = int(temp[i][1]) } return res } func createPolybius() []string { temp := []byte(alphabet) rand.Shuffle(36, func(i, j int) { temp[i], temp[j] = temp[j], temp[i] }) alphabet = string(temp) fmt.Println("6 x 6 Polybius square:\n") fmt.Println(" | A D F G V X") fmt.Println("---------------") p := make([]string, 6) for i := 0; i < 6; i++ { fmt.Printf("%c | ", adfgvx[i]) p[i] = alphabet[6*i : 6*(i+1)] for _, c := range p[i] { fmt.Printf("%c ", c) } fmt.Println() } return p } func createKey(n int) string { if n < 7 || n > 12 { log.Fatal("Key should be within 7 and 12 letters long.") } bs, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } words := bytes.Split(bs, []byte{'\n'}) var candidates [][]byte for _, word := range words { if len(word) == n && len(distinct(word)) == n && allAsciiAlphaNum(word) { candidates = append(candidates, word) } } k := string(bytes.ToUpper(candidates[rand.Intn(len(candidates))])) fmt.Println("\nThe key is", k) return k } func encrypt(polybius []string, key, plainText string) string { temp := "" outer: for _, ch := range []byte(plainText) { for r := 0; r <= 5; r++ { for c := 0; c <= 5; c++ { if polybius[r][c] == ch { temp += fmt.Sprintf("%c%c", adfgvx[r], adfgvx[c]) continue outer } } } } colLen := len(temp) / len(key) if len(temp)%len(key) > 0 { colLen++ } table := make([][]string, colLen) for i := 0; i < colLen; i++ { table[i] = make([]string, len(key)) } for i := 0; i < len(temp); i++ { table[i/len(key)][i%len(key)] = string(temp[i]) } order := orderKey(key) cols := make([][]string, len(key)) for i := 0; i < len(key); i++ { cols[i] = make([]string, colLen) for j := 0; j < colLen; j++ { cols[i][j] = table[j][order[i]] } } res := make([]string, len(cols)) for i := 0; i < len(cols); i++ { res[i] = strings.Join(cols[i], "") } return strings.Join(res, " ") } func decrypt(polybius []string, key, cipherText string) string { colStrs := strings.Split(cipherText, " ") maxColLen := 0 for _, s := range colStrs { if len(s) > maxColLen { maxColLen = len(s) } } cols := make([][]string, len(colStrs)) for i, s := range colStrs { var ls []string for _, c := range s { ls = append(ls, string(c)) } if len(s) < maxColLen { cols[i] = make([]string, maxColLen) copy(cols[i], ls) } else { cols[i] = ls } } table := make([][]string, maxColLen) order := orderKey(key) for i := 0; i < maxColLen; i++ { table[i] = make([]string, len(key)) for j := 0; j < len(key); j++ { table[i][order[j]] = cols[j][i] } } temp := "" for i := 0; i < len(table); i++ { temp += strings.Join(table[i], "") } plainText := "" for i := 0; i < len(temp); i += 2 { r := strings.IndexByte(adfgvx, temp[i]) c := strings.IndexByte(adfgvx, temp[i+1]) plainText = plainText + string(polybius[r][c]) } return plainText } func main() { rand.Seed(time.Now().UnixNano()) plainText := "ATTACKAT1200AM" polybius := createPolybius() key := createKey(9) fmt.Println("\nPlaintext :", plainText) cipherText := encrypt(polybius, key, plainText) fmt.Println("\nEncrypted :", cipherText) plainText2 := decrypt(polybius, key, cipherText) fmt.Println("\nDecrypted :", plainText2) }
Translate the given Python code snippet into Go without altering its behavior.
from random import shuffle, choice from itertools import product, accumulate from numpy import floor, sqrt class ADFGVX: def __init__(self, spoly, k, alph='ADFGVX'): self.polybius = list(spoly.upper()) self.pdim = int(floor(sqrt(len(self.polybius)))) self.key = list(k.upper()) self.keylen = len(self.key) self.alphabet = list(alph) pairs = [p[0] + p[1] for p in product(self.alphabet, self.alphabet)] self.encode = dict(zip(self.polybius, pairs)) self.decode = dict((v, k) for (k, v) in self.encode.items()) def encrypt(self, msg): chars = list(''.join([self.encode[c] for c in msg.upper() if c in self.polybius])) colvecs = [(lett, chars[i:len(chars):self.keylen]) \ for (i, lett) in enumerate(self.key)] colvecs.sort(key=lambda x: x[0]) return ''.join([''.join(a[1]) for a in colvecs]) def decrypt(self, cod): chars = [c for c in cod if c in self.alphabet] sortedkey = sorted(self.key) order = [self.key.index(ch) for ch in sortedkey] originalorder = [sortedkey.index(ch) for ch in self.key] base, extra = divmod(len(chars), self.keylen) strides = [base + (1 if extra > i else 0) for i in order] starts = list(accumulate(strides[:-1], lambda x, y: x + y)) starts = [0] + starts ends = [starts[i] + strides[i] for i in range(self.keylen)] cols = [chars[starts[i]:ends[i]] for i in originalorder] pairs = [] for i in range((len(chars) - 1) // self.keylen + 1): for j in range(self.keylen): if i * self.keylen + j < len(chars): pairs.append(cols[j][i]) return ''.join([self.decode[pairs[i] + pairs[i + 1]] for i in range(0, len(pairs), 2)]) if __name__ == '__main__': PCHARS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') shuffle(PCHARS) POLYBIUS = ''.join(PCHARS) with open('unixdict.txt') as fh: WORDS = [w for w in (fh.read()).split() \ if len(w) == 9 and len(w) == len(set(list(w)))] KEY = choice(WORDS) SECRET, MESSAGE = ADFGVX(POLYBIUS, KEY), 'ATTACKAT1200AM' print(f'Polybius: {POLYBIUS}, key: {KEY}') print('Message: ', MESSAGE) ENCODED = SECRET.encrypt(MESSAGE) DECODED = SECRET.decrypt(ENCODED) print('Encoded: ', ENCODED) print('Decoded: ', DECODED)
package main import ( "bytes" "fmt" "io/ioutil" "log" "math/rand" "sort" "strings" "time" ) var adfgvx = "ADFGVX" var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func distinct(bs []byte) []byte { var u []byte for _, b := range bs { if !bytes.Contains(u, []byte{b}) { u = append(u, b) } } return u } func allAsciiAlphaNum(word []byte) bool { for _, b := range word { if !((b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122)) { return false } } return true } func orderKey(key string) []int { temp := make([][2]byte, len(key)) for i := 0; i < len(key); i++ { temp[i] = [2]byte{key[i], byte(i)} } sort.Slice(temp, func(i, j int) bool { return temp[i][0] < temp[j][0] }) res := make([]int, len(key)) for i := 0; i < len(key); i++ { res[i] = int(temp[i][1]) } return res } func createPolybius() []string { temp := []byte(alphabet) rand.Shuffle(36, func(i, j int) { temp[i], temp[j] = temp[j], temp[i] }) alphabet = string(temp) fmt.Println("6 x 6 Polybius square:\n") fmt.Println(" | A D F G V X") fmt.Println("---------------") p := make([]string, 6) for i := 0; i < 6; i++ { fmt.Printf("%c | ", adfgvx[i]) p[i] = alphabet[6*i : 6*(i+1)] for _, c := range p[i] { fmt.Printf("%c ", c) } fmt.Println() } return p } func createKey(n int) string { if n < 7 || n > 12 { log.Fatal("Key should be within 7 and 12 letters long.") } bs, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } words := bytes.Split(bs, []byte{'\n'}) var candidates [][]byte for _, word := range words { if len(word) == n && len(distinct(word)) == n && allAsciiAlphaNum(word) { candidates = append(candidates, word) } } k := string(bytes.ToUpper(candidates[rand.Intn(len(candidates))])) fmt.Println("\nThe key is", k) return k } func encrypt(polybius []string, key, plainText string) string { temp := "" outer: for _, ch := range []byte(plainText) { for r := 0; r <= 5; r++ { for c := 0; c <= 5; c++ { if polybius[r][c] == ch { temp += fmt.Sprintf("%c%c", adfgvx[r], adfgvx[c]) continue outer } } } } colLen := len(temp) / len(key) if len(temp)%len(key) > 0 { colLen++ } table := make([][]string, colLen) for i := 0; i < colLen; i++ { table[i] = make([]string, len(key)) } for i := 0; i < len(temp); i++ { table[i/len(key)][i%len(key)] = string(temp[i]) } order := orderKey(key) cols := make([][]string, len(key)) for i := 0; i < len(key); i++ { cols[i] = make([]string, colLen) for j := 0; j < colLen; j++ { cols[i][j] = table[j][order[i]] } } res := make([]string, len(cols)) for i := 0; i < len(cols); i++ { res[i] = strings.Join(cols[i], "") } return strings.Join(res, " ") } func decrypt(polybius []string, key, cipherText string) string { colStrs := strings.Split(cipherText, " ") maxColLen := 0 for _, s := range colStrs { if len(s) > maxColLen { maxColLen = len(s) } } cols := make([][]string, len(colStrs)) for i, s := range colStrs { var ls []string for _, c := range s { ls = append(ls, string(c)) } if len(s) < maxColLen { cols[i] = make([]string, maxColLen) copy(cols[i], ls) } else { cols[i] = ls } } table := make([][]string, maxColLen) order := orderKey(key) for i := 0; i < maxColLen; i++ { table[i] = make([]string, len(key)) for j := 0; j < len(key); j++ { table[i][order[j]] = cols[j][i] } } temp := "" for i := 0; i < len(table); i++ { temp += strings.Join(table[i], "") } plainText := "" for i := 0; i < len(temp); i += 2 { r := strings.IndexByte(adfgvx, temp[i]) c := strings.IndexByte(adfgvx, temp[i+1]) plainText = plainText + string(polybius[r][c]) } return plainText } func main() { rand.Seed(time.Now().UnixNano()) plainText := "ATTACKAT1200AM" polybius := createPolybius() key := createKey(9) fmt.Println("\nPlaintext :", plainText) cipherText := encrypt(polybius, key, plainText) fmt.Println("\nEncrypted :", cipherText) plainText2 := decrypt(polybius, key, cipherText) fmt.Println("\nDecrypted :", plainText2) }
Keep all operations the same but rewrite the snippet in Go.
from itertools import product xx = '-5 +5'.split() pp = '2 3'.split() texts = '-x**p -(x)**p (-x)**p -(x**p)'.split() print('Integer variable exponentiation') for x, p in product(xx, pp): print(f' x,p = {x:2},{p}; ', end=' ') x, p = int(x), int(p) print('; '.join(f"{t} =={eval(t):4}" for t in texts)) print('\nBonus integer literal exponentiation') X, P = 'xp' xx.insert(0, ' 5') texts.insert(0, 'x**p') for x, p in product(xx, pp): texts2 = [t.replace(X, x).replace(P, p) for t in texts] print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))
package main import ( "fmt" "math" ) type float float64 func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) } func main() { ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"} for _, x := range []float{float(-5), float(5)} { for _, e := range []float{float(2), float(3)} { fmt.Printf("x = %2.0f e = %0.0f | ", x, e) fmt.Printf("%s = %4.0f | ", ops[0], -x.p(e)) fmt.Printf("%s = %4.0f | ", ops[1], -(x).p(e)) fmt.Printf("%s = %4.0f | ", ops[2], (-x).p(e)) fmt.Printf("%s = %4.0f\n", ops[3], -(x.p(e))) } } }
Translate this program into Go but keep the logic exactly as in Python.
from itertools import product xx = '-5 +5'.split() pp = '2 3'.split() texts = '-x**p -(x)**p (-x)**p -(x**p)'.split() print('Integer variable exponentiation') for x, p in product(xx, pp): print(f' x,p = {x:2},{p}; ', end=' ') x, p = int(x), int(p) print('; '.join(f"{t} =={eval(t):4}" for t in texts)) print('\nBonus integer literal exponentiation') X, P = 'xp' xx.insert(0, ' 5') texts.insert(0, 'x**p') for x, p in product(xx, pp): texts2 = [t.replace(X, x).replace(P, p) for t in texts] print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))
package main import ( "fmt" "math" ) type float float64 func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) } func main() { ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"} for _, x := range []float{float(-5), float(5)} { for _, e := range []float{float(2), float(3)} { fmt.Printf("x = %2.0f e = %0.0f | ", x, e) fmt.Printf("%s = %4.0f | ", ops[0], -x.p(e)) fmt.Printf("%s = %4.0f | ", ops[1], -(x).p(e)) fmt.Printf("%s = %4.0f | ", ops[2], (-x).p(e)) fmt.Printf("%s = %4.0f\n", ops[3], -(x.p(e))) } } }
Convert this Python block to Go, preserving its control flow and logic.
Plataanstraat 5 split as (Plataanstraat, 5) Straat 12 split as (Straat, 12) Straat 12 II split as (Straat, 12 II) Dr. J. Straat 12 split as (Dr. J. Straat , 12) Dr. J. Straat 12 a split as (Dr. J. Straat, 12 a) Dr. J. Straat 12-14 split as (Dr. J. Straat, 12-14) Laan 1940 – 1945 37 split as (Laan 1940 – 1945, 37) Plein 1940 2 split as (Plein 1940, 2) 1213-laan 11 split as (1213-laan, 11) 16 april 1944 Pad 1 split as (16 april 1944 Pad, 1) 1e Kruisweg 36 split as (1e Kruisweg, 36) Laan 1940-’45 66 split as (Laan 1940-’45, 66) Laan ’40-’45 split as (Laan ’40-’45,) Langeloërduinen 3 46 split as (Langeloërduinen, 3 46) Marienwaerdt 2e Dreef 2 split as (Marienwaerdt 2e Dreef, 2) Provincialeweg N205 1 split as (Provincialeweg N205, 1) Rivium 2e Straat 59. split as (Rivium 2e Straat, 59.) Nieuwe gracht 20rd split as (Nieuwe gracht, 20rd) Nieuwe gracht 20rd 2 split as (Nieuwe gracht, 20rd 2) Nieuwe gracht 20zw /2 split as (Nieuwe gracht, 20zw /2) Nieuwe gracht 20zw/3 split as (Nieuwe gracht, 20zw/3) Nieuwe gracht 20 zw/4 split as (Nieuwe gracht, 20 zw/4) Bahnhofstr. 4 split as (Bahnhofstr., 4) Wertstr. 10 split as (Wertstr., 10) Lindenhof 1 split as (Lindenhof, 1) Nordesch 20 split as (Nordesch, 20) Weilstr. 6 split as (Weilstr., 6) Harthauer Weg 2 split as (Harthauer Weg, 2) Mainaustr. 49 split as (Mainaustr., 49) August-Horch-Str. 3 split as (August-Horch-Str., 3) Marktplatz 31 split as (Marktplatz, 31) Schmidener Weg 3 split as (Schmidener Weg, 3) Karl-Weysser-Str. 6 split as (Karl-Weysser-Str., 6)''')
package main import ( "fmt" "strings" ) func isDigit(b byte) bool { return '0' <= b && b <= '9' } func separateHouseNumber(address string) (street string, house string) { length := len(address) fields := strings.Fields(address) size := len(fields) last := fields[size-1] penult := fields[size-2] if isDigit(last[0]) { isdig := isDigit(penult[0]) if size > 2 && isdig && !strings.HasPrefix(penult, "194") { house = fmt.Sprintf("%s %s", penult, last) } else { house = last } } else if size > 2 { house = fmt.Sprintf("%s %s", penult, last) } street = strings.TrimRight(address[:length-len(house)], " ") return } func main() { addresses := [...]string{ "Plataanstraat 5", "Straat 12", "Straat 12 II", "Dr. J. Straat 12", "Dr. J. Straat 12 a", "Dr. J. Straat 12-14", "Laan 1940 - 1945 37", "Plein 1940 2", "1213-laan 11", "16 april 1944 Pad 1", "1e Kruisweg 36", "Laan 1940-'45 66", "Laan '40-'45", "Langeloërduinen 3 46", "Marienwaerdt 2e Dreef 2", "Provincialeweg N205 1", "Rivium 2e Straat 59.", "Nieuwe gracht 20rd", "Nieuwe gracht 20rd 2", "Nieuwe gracht 20zw /2", "Nieuwe gracht 20zw/3", "Nieuwe gracht 20 zw/4", "Bahnhofstr. 4", "Wertstr. 10", "Lindenhof 1", "Nordesch 20", "Weilstr. 6", "Harthauer Weg 2", "Mainaustr. 49", "August-Horch-Str. 3", "Marktplatz 31", "Schmidener Weg 3", "Karl-Weysser-Str. 6", } fmt.Println("Street House Number") fmt.Println("--------------------- ------------") for _, address := range addresses { street, house := separateHouseNumber(address) if house == "" { house = "(none)" } fmt.Printf("%-22s %s\n", street, house) } }
Generate a Go translation of this Python snippet without changing its computational steps.
import itertools import re import sys from collections import deque from typing import NamedTuple RE_OUTLINE = re.compile(r"^((?: |\t)*)(.+)$", re.M) COLORS = itertools.cycle( [ " " " " " ] ) class Node: def __init__(self, indent, value, parent, children=None): self.indent = indent self.value = value self.parent = parent self.children = children or [] self.color = None def depth(self): if self.parent: return self.parent.depth() + 1 return -1 def height(self): if not self.children: return 0 return max(child.height() for child in self.children) + 1 def colspan(self): if self.leaf: return 1 return sum(child.colspan() for child in self.children) @property def leaf(self): return not bool(self.children) def __iter__(self): q = deque() q.append(self) while q: node = q.popleft() yield node q.extend(node.children) class Token(NamedTuple): indent: int value: str def tokenize(outline): for match in RE_OUTLINE.finditer(outline): indent, value = match.groups() yield Token(len(indent), value) def parse(outline): tokens = list(tokenize(outline)) temp_root = Node(-1, "", None) _parse(tokens, 0, temp_root) root = temp_root.children[0] pad_tree(root, root.height()) return root def _parse(tokens, index, node): if index >= len(tokens): return token = tokens[index] if token.indent == node.indent: current = Node(token.indent, token.value, node.parent) node.parent.children.append(current) _parse(tokens, index + 1, current) elif token.indent > node.indent: current = Node(token.indent, token.value, node) node.children.append(current) _parse(tokens, index + 1, current) elif token.indent < node.indent: _parse(tokens, index, node.parent) def pad_tree(node, height): if node.leaf and node.depth() < height: pad_node = Node(node.indent + 1, "", node) node.children.append(pad_node) for child in node.children: pad_tree(child, height) def color_tree(node): if not node.value: node.color = " elif node.depth() <= 1: node.color = next(COLORS) else: node.color = node.parent.color for child in node.children: color_tree(child) def table_data(node): indent = " " if node.colspan() > 1: colspan = f'colspan="{node.colspan()}"' else: colspan = "" if node.color: style = f'style="background-color: {node.color};"' else: style = "" attrs = " ".join([colspan, style]) return f"{indent}<td{attrs}>{node.value}</td>" def html_table(tree): table_cols = tree.colspan() row_cols = 0 buf = ["<table style='text-align: center;'>"] for node in tree: if row_cols == 0: buf.append(" <tr>") buf.append(table_data(node)) row_cols += node.colspan() if row_cols == table_cols: buf.append(" </tr>") row_cols = 0 buf.append("</table>") return "\n".join(buf) def wiki_table_data(node): if not node.value: return "| |" if node.colspan() > 1: colspan = f"colspan={node.colspan()}" else: colspan = "" if node.color: style = f'style="background: {node.color};"' else: style = "" attrs = " ".join([colspan, style]) return f"| {attrs} | {node.value}" def wiki_table(tree): table_cols = tree.colspan() row_cols = 0 buf = ['{| class="wikitable" style="text-align: center;"'] for node in tree: if row_cols == 0: buf.append("|-") buf.append(wiki_table_data(node)) row_cols += node.colspan() if row_cols == table_cols: row_cols = 0 buf.append("|}") return "\n".join(buf) def example(table_format="wiki"): outline = ( "Display an outline as a nested table.\n" " Parse the outline to a tree,\n" " measuring the indent of each line,\n" " translating the indentation to a nested structure,\n" " and padding the tree to even depth.\n" " count the leaves descending from each node,\n" " defining the width of a leaf as 1,\n" " and the width of a parent node as a sum.\n" " (The sum of the widths of its children)\n" " and write out a table with 'colspan' values\n" " either as a wiki table,\n" " or as HTML." ) tree = parse(outline) color_tree(tree) if table_format == "wiki": print(wiki_table(tree)) else: print(html_table(tree)) if __name__ == "__main__": args = sys.argv[1:] if len(args) == 1: table_format = args[0] else: table_format = "wiki" example(table_format)
package main import ( "fmt" "strings" ) type nNode struct { name string children []nNode } type iNode struct { level int name string } func toNest(iNodes []iNode, start, level int, n *nNode) { if level == 0 { n.name = iNodes[0].name } for i := start + 1; i < len(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 makeIndent(outline string, tab int) []iNode { lines := strings.Split(outline, "\n") iNodes := make([]iNode, len(lines)) for i, line := range lines { line2 := strings.TrimLeft(line, " ") le, le2 := len(line), len(line2) level := (le - le2) / tab iNodes[i] = iNode{level, line2} } return iNodes } func toMarkup(n nNode, cols []string, depth int) string { var span int var colSpan func(nn nNode) colSpan = func(nn nNode) { for i, c := range nn.children { if i > 0 { span++ } colSpan(c) } } for _, c := range n.children { span = 1 colSpan(c) } var lines []string lines = append(lines, `{| class="wikitable" style="text-align: center;"`) const l1, l2 = "|-", "| |" lines = append(lines, l1) span = 1 colSpan(n) s := fmt.Sprintf(`| style="background: %s " colSpan=%d | %s`, cols[0], span, n.name) lines = append(lines, s, l1) var nestedFor func(nn nNode, level, maxLevel, col int) nestedFor = func(nn nNode, level, maxLevel, col int) { if level == 1 && maxLevel > level { for i, c := range nn.children { nestedFor(c, 2, maxLevel, i) } } else if level < maxLevel { for _, c := range nn.children { nestedFor(c, level+1, maxLevel, col) } } else { if len(nn.children) > 0 { for i, c := range nn.children { span = 1 colSpan(c) cn := col + 1 if maxLevel == 1 { cn = i + 1 } s := fmt.Sprintf(`| style="background: %s " colspan=%d | %s`, cols[cn], span, c.name) lines = append(lines, s) } } else { lines = append(lines, l2) } } } for maxLevel := 1; maxLevel < depth; maxLevel++ { nestedFor(n, 1, maxLevel, 0) if maxLevel < depth-1 { lines = append(lines, l1) } } lines = append(lines, "|}") return strings.Join(lines, "\n") } func main() { const outline = `Display an outline as a nested table. Parse the outline to a tree, measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. count the leaves descending from each node, defining the width of a leaf as 1, and the width of a parent node as a sum. (The sum of the widths of its children) and write out a table with 'colspan' values either as a wiki table, or as HTML.` const ( yellow = "#ffffe6;" orange = "#ffebd2;" green = "#f0fff0;" blue = "#e6ffff;" pink = "#ffeeff;" ) cols := []string{yellow, orange, green, blue, pink} iNodes := makeIndent(outline, 4) var n nNode toNest(iNodes, 0, 0, &n) fmt.Println(toMarkup(n, cols, 4)) fmt.Println("\n") const outline2 = `Display an outline as a nested table. Parse the outline to a tree, measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. count the leaves descending from each node, defining the width of a leaf as 1, and the width of a parent node as a sum. (The sum of the widths of its children) Propagating the sums upward as necessary. and write out a table with 'colspan' values either as a wiki table, or as HTML. Optionally add color to the nodes.` cols2 := []string{blue, yellow, orange, green, pink} var n2 nNode iNodes2 := makeIndent(outline2, 4) toNest(iNodes2, 0, 0, &n2) fmt.Println(toMarkup(n2, cols2, 4)) }
Translate this program into Go but keep the logic exactly as in Python.
def common_list_elements(*lists): return list(set.intersection(*(set(list_) for list_ in lists))) if __name__ == "__main__": test_cases = [ ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]), ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]), ] for case in test_cases: result = common_list_elements(*case) print(f"Intersection of {case} is {result}")
package main import "fmt" func indexOf(l []int, n int) int { for i := 0; i < len(l); i++ { if l[i] == n { return i } } return -1 } func common2(l1, l2 []int) []int { c1, c2 := len(l1), len(l2) shortest, longest := l1, l2 if c1 > c2 { shortest, longest = l2, l1 } longest2 := make([]int, len(longest)) copy(longest2, longest) var res []int for _, e := range shortest { ix := indexOf(longest2, e) if ix >= 0 { res = append(res, e) longest2 = append(longest2[:ix], longest2[ix+1:]...) } } return res } func commonN(ll [][]int) []int { n := len(ll) if n == 0 { return []int{} } if n == 1 { return ll[0] } res := common2(ll[0], ll[1]) if n == 2 { return res } for _, l := range ll[2:] { res = common2(res, l) } return res } func main() { lls := [][][]int{ {{2, 5, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 9, 8, 4}, {1, 3, 7, 6, 9}}, {{2, 2, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 2, 2, 4}, {2, 3, 7, 6, 2}}, } for _, ll := range lls { fmt.Println("Intersection of", ll, "is:") fmt.Println(commonN(ll)) fmt.Println() } }
Write a version of this Python function in Go with identical behavior.
def common_list_elements(*lists): return list(set.intersection(*(set(list_) for list_ in lists))) if __name__ == "__main__": test_cases = [ ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]), ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]), ] for case in test_cases: result = common_list_elements(*case) print(f"Intersection of {case} is {result}")
package main import "fmt" func indexOf(l []int, n int) int { for i := 0; i < len(l); i++ { if l[i] == n { return i } } return -1 } func common2(l1, l2 []int) []int { c1, c2 := len(l1), len(l2) shortest, longest := l1, l2 if c1 > c2 { shortest, longest = l2, l1 } longest2 := make([]int, len(longest)) copy(longest2, longest) var res []int for _, e := range shortest { ix := indexOf(longest2, e) if ix >= 0 { res = append(res, e) longest2 = append(longest2[:ix], longest2[ix+1:]...) } } return res } func commonN(ll [][]int) []int { n := len(ll) if n == 0 { return []int{} } if n == 1 { return ll[0] } res := common2(ll[0], ll[1]) if n == 2 { return res } for _, l := range ll[2:] { res = common2(res, l) } return res } func main() { lls := [][][]int{ {{2, 5, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 9, 8, 4}, {1, 3, 7, 6, 9}}, {{2, 2, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 2, 2, 4}, {2, 3, 7, 6, 2}}, } for _, ll := range lls { fmt.Println("Intersection of", ll, "is:") fmt.Println(commonN(ll)) fmt.Println() } }
Produce a language-to-language conversion: from Python to Go, same semantics.
from __future__ import annotations import functools import math import os from typing import Any from typing import Callable from typing import Generic from typing import List from typing import TypeVar from typing import Union T = TypeVar("T") class Writer(Generic[T]): def __init__(self, value: Union[T, Writer[T]], *msgs: str): if isinstance(value, Writer): self.value: T = value.value self.msgs: List[str] = value.msgs + list(msgs) else: self.value = value self.msgs = list(f"{msg}: {self.value}" for msg in msgs) def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]: writer = func(self.value) return Writer(writer, *self.msgs) def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]: return self.bind(func) def __str__(self): return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}" def __repr__(self): return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")" def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]: @functools.wraps(func) def wrapped(value): return Writer(func(value), msg) return wrapped if __name__ == "__main__": square_root = lift(math.sqrt, "square root") add_one = lift(lambda x: x + 1, "add one") half = lift(lambda x: x / 2, "div two") print(Writer(5, "initial") >> square_root >> add_one >> half)
package main import ( "fmt" "math" ) type mwriter struct { value float64 log string } func (m mwriter) bind(f func(v float64) mwriter) mwriter { n := f(m.value) n.log = m.log + n.log return n } func unit(v float64, s string) mwriter { return mwriter{v, fmt.Sprintf("  %-17s: %g\n", s, v)} } func root(v float64) mwriter { return unit(math.Sqrt(v), "Took square root") } func addOne(v float64) mwriter { return unit(v+1, "Added one") } func half(v float64) mwriter { return unit(v/2, "Divided by two") } func main() { mw1 := unit(5, "Initial value") mw2 := mw1.bind(root).bind(addOne).bind(half) fmt.Println("The Golden Ratio is", mw2.value) fmt.Println("\nThis was derived as follows:-") fmt.Println(mw2.log) }
Transform the following Python implementation into Go, maintaining the same output and logic.
from mip import Model, BINARY, xsum, minimize def n_queens_min(N): if N < 4: brd = [[0 for i in range(N)] for j in range(N)] brd[0 if N < 2 else 1][0 if N < 2 else 1] = 1 return 1, brd model = Model() board = [[model.add_var(var_type=BINARY) for j in range(N)] for i in range(N)] for k in range(N): model += xsum(board[k][j] for j in range(N)) <= 1 model += xsum(board[i][k] for i in range(N)) <= 1 for k in range(1, 2 * N - 2): model += xsum(board[k - j][j] for j in range(max(0, k - N + 1), min(k + 1, N))) <= 1 for k in range(2 - N, N - 1): model += xsum(board[k + j][j] for j in range(max(0, -k), min(N - k, N))) <= 1 for i in range(N): for j in range(N): model += xsum([xsum(board[i][k] for k in range(N)), xsum(board[k][j] for k in range(N)), xsum(board[i + k][j + k] for k in range(-N, N) if 0 <= i + k < N and 0 <= j + k < N), xsum(board[i - k][j + k] for k in range(-N, N) if 0 <= i - k < N and 0 <= j + k < N)]) >= 1 model.objective = minimize(xsum(board[i][j] for i in range(N) for j in range(N))) model.optimize() return model.objective_value, [[board[i][j].x for i in range(N)] for j in range(N)] def n_bishops_min(N): model = Model() board = [[model.add_var(var_type=BINARY) for j in range(N)] for i in range(N)] for i in range(N): for j in range(N): model += xsum([ xsum(board[i + k][j + k] for k in range(-N, N) if 0 <= i + k < N and 0 <= j + k < N), xsum(board[i - k][j + k] for k in range(-N, N) if 0 <= i - k < N and 0 <= j + k < N)]) >= 1 model.objective = minimize(xsum(board[i][j] for i in range(N) for j in range(N))) model.optimize() return model.objective_value, [[board[i][j].x for i in range(N)] for j in range(N)] def n_knights_min(N): if N < 2: return 1, "N" knightdeltas = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)] model = Model() board = [[model.add_var(var_type=BINARY) for j in range(N + 4)] for i in range(N + 4)] for i in range(N + 4): model += xsum(board[i][j] for j in [0, 1, N + 2, N + 3]) == 0 for j in range(N + 4): model += xsum(board[i][j] for i in [0, 1, N + 2, N + 3]) == 0 for i in range(2, N + 2): for j in range(2, N + 2): model += xsum([board[i][j]] + [board[i + d[0]][j + d[1]] for d in knightdeltas]) >= 1 model += xsum([board[i + d[0]][j + d[1]] for d in knightdeltas] + [100 * board[i][j]]) <= 100 model.objective = minimize(xsum(board[i][j] for i in range(2, N + 2) for j in range(2, N + 2))) model.optimize() minresult = model.objective_value return minresult, [[board[i][j].x for i in range(2, N + 2)] for j in range(2, N + 2)] if __name__ == '__main__': examples, pieces, chars = [[], [], []], ["Queens", "Bishops", "Knights"], ['Q', 'B', 'N'] print(" Squares Queens Bishops Knights") for nrows in range(1, 11): print(str(nrows * nrows).rjust(10), end='') minval, examples[0] = n_queens_min(nrows) print(str(int(minval)).rjust(10), end='') minval, examples[1] = n_bishops_min(nrows) print(str(int(minval)).rjust(10), end='') minval, examples[2] = n_knights_min(nrows) print(str(int(minval)).rjust(10)) if nrows == 10: print("\nExamples for N = 10:") for idx, piece in enumerate(chars): print(f"\n{pieces[idx]}:") for row in examples[idx]: for sqr in row: print(chars[idx] if sqr == 1 else '.', '', end = '') print() print()
package main import ( "fmt" "math" "strings" "time" ) var board [][]bool var diag1, diag2 [][]int var diag1Lookup, diag2Lookup []bool var n, minCount int var layout string func isAttacked(piece string, row, col int) bool { if piece == "Q" { for i := 0; i < n; i++ { if board[i][col] || board[row][i] { return true } } if diag1Lookup[diag1[row][col]] || diag2Lookup[diag2[row][col]] { return true } } else if piece == "B" { if diag1Lookup[diag1[row][col]] || diag2Lookup[diag2[row][col]] { return true } } else { if board[row][col] { return true } if row+2 < n && col-1 >= 0 && board[row+2][col-1] { return true } if row-2 >= 0 && col-1 >= 0 && board[row-2][col-1] { return true } if row+2 < n && col+1 < n && board[row+2][col+1] { return true } if row-2 >= 0 && col+1 < n && board[row-2][col+1] { return true } if row+1 < n && col+2 < n && board[row+1][col+2] { return true } if row-1 >= 0 && col+2 < n && board[row-1][col+2] { return true } if row+1 < n && col-2 >= 0 && board[row+1][col-2] { return true } if row-1 >= 0 && col-2 >= 0 && board[row-1][col-2] { return true } } return false } func abs(i int) int { if i < 0 { i = -i } return i } func attacks(piece string, row, col, trow, tcol int) bool { if piece == "Q" { return row == trow || col == tcol || abs(row-trow) == abs(col-tcol) } else if piece == "B" { return abs(row-trow) == abs(col-tcol) } else { rd := abs(trow - row) cd := abs(tcol - col) return (rd == 1 && cd == 2) || (rd == 2 && cd == 1) } } func storeLayout(piece string) { var sb strings.Builder for _, row := range board { for _, cell := range row { if cell { sb.WriteString(piece + " ") } else { sb.WriteString(". ") } } sb.WriteString("\n") } layout = sb.String() } func placePiece(piece string, countSoFar, maxCount int) { if countSoFar >= minCount { return } allAttacked := true ti := 0 tj := 0 for i := 0; i < n; i++ { for j := 0; j < n; j++ { if !isAttacked(piece, i, j) { allAttacked = false ti = i tj = j break } } if !allAttacked { break } } if allAttacked { minCount = countSoFar storeLayout(piece) return } if countSoFar <= maxCount { si := ti sj := tj if piece == "K" { si = si - 2 sj = sj - 2 if si < 0 { si = 0 } if sj < 0 { sj = 0 } } for i := si; i < n; i++ { for j := sj; j < n; j++ { if !isAttacked(piece, i, j) { if (i == ti && j == tj) || attacks(piece, i, j, ti, tj) { board[i][j] = true if piece != "K" { diag1Lookup[diag1[i][j]] = true diag2Lookup[diag2[i][j]] = true } placePiece(piece, countSoFar+1, maxCount) board[i][j] = false if piece != "K" { diag1Lookup[diag1[i][j]] = false diag2Lookup[diag2[i][j]] = false } } } } } } } func main() { start := time.Now() pieces := []string{"Q", "B", "K"} limits := map[string]int{"Q": 10, "B": 10, "K": 10} names := map[string]string{"Q": "Queens", "B": "Bishops", "K": "Knights"} for _, piece := range pieces { fmt.Println(names[piece]) fmt.Println("=======\n") for n = 1; ; n++ { board = make([][]bool, n) for i := 0; i < n; i++ { board[i] = make([]bool, n) } if piece != "K" { diag1 = make([][]int, n) for i := 0; i < n; i++ { diag1[i] = make([]int, n) for j := 0; j < n; j++ { diag1[i][j] = i + j } } diag2 = make([][]int, n) for i := 0; i < n; i++ { diag2[i] = make([]int, n) for j := 0; j < n; j++ { diag2[i][j] = i - j + n - 1 } } diag1Lookup = make([]bool, 2*n-1) diag2Lookup = make([]bool, 2*n-1) } minCount = math.MaxInt32 layout = "" for maxCount := 1; maxCount <= n*n; maxCount++ { placePiece(piece, 0, maxCount) if minCount <= n*n { break } } fmt.Printf("%2d x %-2d : %d\n", n, n, minCount) if n == limits[piece] { fmt.Printf("\n%s on a %d x %d board:\n", names[piece], n, n) fmt.Println("\n" + layout) break } } } elapsed := time.Now().Sub(start) fmt.Printf("Took %s\n", elapsed) }
Translate the given Python code snippet into Go without altering its behavior.
from functools import reduce from operator import add def wordleScore(target, guess): return mapAccumL(amber)( *first(charCounts)( mapAccumL(green)( [], zip(target, guess) ) ) )[1] def green(residue, tg): t, g = tg return (residue, (g, 2)) if t == g else ( [t] + residue, (g, 0) ) def amber(tally, cn): c, n = cn return (tally, 2) if 2 == n else ( adjust( lambda x: x - 1, c, tally ), 1 ) if 0 < tally.get(c, 0) else (tally, 0) def main(): print(' -> '.join(['Target', 'Guess', 'Scores'])) print() print( '\n'.join([ wordleReport(*tg) for tg in [ ("ALLOW", "LOLLY"), ("CHANT", "LATTE"), ("ROBIN", "ALERT"), ("ROBIN", "SONIC"), ("ROBIN", "ROBIN"), ("BULLY", "LOLLY"), ("ADAPT", "SÅLÅD"), ("Ukraine", "Ukraíne"), ("BBAAB", "BBBBBAA"), ("BBAABBB", "AABBBAA") ] ]) ) def wordleReport(target, guess): scoreName = {2: 'green', 1: 'amber', 0: 'gray'} if 5 != len(target): return f'{target}: Expected 5 character target.' elif 5 != len(guess): return f'{guess}: Expected 5 character guess.' else: scores = wordleScore(target, guess) return ' -> '.join([ target, guess, repr(scores), ' '.join([ scoreName[n] for n in scores ]) ]) def adjust(f, k, dct): return dict( dct, **{k: f(dct[k]) if k in dct else None} ) def charCounts(s): return reduce( lambda a, c: insertWith(add)(c)(1)(a), list(s), {} ) def first(f): return lambda xy: (f(xy[0]), xy[1]) def insertWith(f): return lambda k: lambda x: lambda dct: dict( dct, **{k: f(dct[k], x) if k in dct else x} ) def mapAccumL(f): def nxt(a, x): return second(lambda v: a[1] + [v])( f(a[0], x) ) return lambda acc, xs: reduce( nxt, xs, (acc, []) ) def second(f): return lambda xy: (xy[0], f(xy[1])) if __name__ == '__main__': main()
package main import ( "bytes" "fmt" "log" ) func wordle(answer, guess string) []int { n := len(guess) if n != len(answer) { log.Fatal("The words must be of the same length.") } answerBytes := []byte(answer) result := make([]int, n) for i := 0; i < n; i++ { if guess[i] == answerBytes[i] { answerBytes[i] = '\000' result[i] = 2 } } for i := 0; i < n; i++ { ix := bytes.IndexByte(answerBytes, guess[i]) if ix >= 0 { answerBytes[ix] = '\000' result[i] = 1 } } return result } func main() { colors := []string{"grey", "yellow", "green"} pairs := [][]string{ {"ALLOW", "LOLLY"}, {"BULLY", "LOLLY"}, {"ROBIN", "ALERT"}, {"ROBIN", "SONIC"}, {"ROBIN", "ROBIN"}, } for _, pair := range pairs { res := wordle(pair[0], pair[1]) res2 := make([]string, len(res)) for i := 0; i < len(res); i++ { res2[i] = colors[res[i]] } fmt.Printf("%s v %s => %v => %v\n", pair[0], pair[1], res, res2) } }
Preserve the algorithm and functionality while converting the code from Python to Go.
from math import prod def maxproduct(mat, length): nrow, ncol = len(mat), len(mat[0]) maxprod, maxrow, maxcol, arr = 0, [0, 0], [0, 0], [0] for row in range(nrow): for col in range(ncol): row2, col2 = row + length, col + length if row < nrow - length: array = [r[col] for r in mat[row:row2]] pro = prod(array) if pro > maxprod: maxprod, maxrow, maxcol, arr = pro, [row, row2], col, array if col < ncol - length: pro = prod(mat[row][col:col2]) if pro > maxprod: maxprod, maxrow, maxcol, arr = pro, row, [col, col2], mat[row][col:col2] print(f"The max {length}-product is {maxprod}, product of {arr} at row {maxrow}, col {maxcol}.") MATRIX = [ [ 8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8], [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0], [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65], [52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91], [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80], [24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50], [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70], [67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21], [24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72], [21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95], [78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92], [16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57], [86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58], [19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40], [ 4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66], [88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69], [ 4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36], [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16], [20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54], [ 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48] ] for n in range(2, 6): maxproduct(MATRIX, n)
package main import ( "fmt" "rcu" "strings" ) var grid = [][]int { { 8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8}, {49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0}, {81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65}, {52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91}, {22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80}, {24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50}, {32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70}, {67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21}, {24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72}, {21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95}, {78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92}, {16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57}, {86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58}, {19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40}, { 4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66}, {88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69}, { 4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36}, {20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16}, {20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54}, { 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48}, } func main() { maxProd, maxR1, maxR2, maxC1, maxC2 := 0, 0, 0, 0, 0 var maxNums [4]int h, w := len(grid), len(grid[0]) for r := 0; r < h; r++ { for c := 0; c < w-4; c++ { prod := 1 for i := c; i < c+4; i++ { prod *= grid[r][i] } if prod > maxProd { maxProd = prod for n := 0; n < 4; n++ { maxNums[n] = grid[r][c+n] } maxR1, maxR2 = r, r maxC1, maxC2 = c, c+3 } } } for c := 0; c < w; c++ { for r := 0; r < h-4; r++ { prod := 1 for i := r; i < r+4; i++ { prod *= grid[i][c] } if prod > maxProd { maxProd = prod for n := 0; n < 4; n++ { maxNums[n] = grid[r+n][c] } maxR1, maxR2 = r, r+3 maxC1, maxC2 = c, c } } } fmt.Println("The greatest product of four adjacent numbers in the same direction (down or right) in the grid is:") var maxNumStrs [4]string for i := 0; i < 4; i++ { maxNumStrs[i] = fmt.Sprintf("%d", maxNums[i]) } fmt.Printf(" %s = %s\n", strings.Join(maxNumStrs[:], " x "), rcu.Commatize(maxProd)) fmt.Print(" at indices (one based): ") for r := maxR1; r <= maxR2; r++ { for c := maxC1; c <= maxC2; c++ { fmt.Printf("(%d, %d) ", r+1, c+1) } } fmt.Println() }
Transform the following Python implementation into Go, maintaining the same output and logic.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': print("p q pq+2") print("-----------------------") for p in range(2, 499): if not isPrime(p): continue q = p + 1 while not isPrime(q): q += 1 if not isPrime(2 + p*q): continue print(p, "\t", q, "\t", 2+p*q)
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(504) var nprimes []int fmt.Println("Neighbour primes < 500:") for i := 0; i < len(primes)-1; i++ { p := primes[i]*primes[i+1] + 2 if rcu.IsPrime(p) { nprimes = append(nprimes, primes[i]) } } rcu.PrintTable(nprimes, 10, 3, false) fmt.Println("\nFound", len(nprimes), "such primes.") }
Rewrite the snippet below in Go so it works the same as the original Python code.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': print("p q pq+2") print("-----------------------") for p in range(2, 499): if not isPrime(p): continue q = p + 1 while not isPrime(q): q += 1 if not isPrime(2 + p*q): continue print(p, "\t", q, "\t", 2+p*q)
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(504) var nprimes []int fmt.Println("Neighbour primes < 500:") for i := 0; i < len(primes)-1; i++ { p := primes[i]*primes[i+1] + 2 if rcu.IsPrime(p) { nprimes = append(nprimes, primes[i]) } } rcu.PrintTable(nprimes, 10, 3, false) fmt.Println("\nFound", len(nprimes), "such primes.") }
Produce a functionally identical Go code for the snippet given in Python.
import strutils, strformat type Node = ref object kind: char resistance: float voltage: float a: Node b: Node proc res(node: Node): float = if node.kind == '+': return node.a.res + node.b.res if node.kind == '*': return 1 / (1 / node.a.res + 1 / node.b.res) node.resistance proc current(node: Node): float = node.voltage / node.res proc effect (node: Node): float = node.current * node.voltage proc report(node: Node, level: string = "") = echo fmt"{node.res:8.3f} {node.voltage:8.3f} {node.current:8.3f} {node.effect:8.3f} {level}{node.kind}" if node.kind in "+*": node.a.report level & "| " node.b.report level & "| " proc setVoltage(node: Node, voltage: float) = node.voltage = voltage if node.kind == '+': let ra = node.a.res let rb = node.b.res node.a.setVoltage ra / (ra+rb) * voltage node.b.setVoltage rb / (ra+rb) * voltage if node.kind == '*': node.a.setVoltage voltage node.b.setVoltage voltage proc build(tokens: seq[string]): Node = var stack: seq[Node] for token in tokens: stack.add if token == "+": Node(kind: '+', a: stack.pop, b: stack.pop) elif token == "*": Node(kind: '*', a: stack.pop, b: stack.pop) else: Node(kind: 'r', resistance: parseFloat(token)) stack.pop proc calculate(voltage: float, tokens: seq[string]): Node = echo "" echo " Ohm Volt Ampere Watt Network tree" let node = build tokens node.setVoltage voltage node.report node
package main import "fmt" type Resistor struct { symbol rune resistance, voltage float64 a, b *Resistor } func (r *Resistor) res() float64 { switch r.symbol { case '+': return r.a.res() + r.b.res() case '*': return 1 / (1/r.a.res() + 1/r.b.res()) default: return r.resistance } } func (r *Resistor) setVoltage(voltage float64) { switch r.symbol { case '+': ra := r.a.res() rb := r.b.res() r.a.setVoltage(ra / (ra + rb) * voltage) r.b.setVoltage(rb / (ra + rb) * voltage) case '*': r.a.setVoltage(voltage) r.b.setVoltage(voltage) } r.voltage = voltage } func (r *Resistor) current() float64 { return r.voltage / r.res() } func (r *Resistor) effect() float64 { return r.current() * r.voltage } func (r *Resistor) report(level string) { fmt.Printf("%8.3f %8.3f %8.3f %8.3f %s%c\n", r.res(), r.voltage, r.current(), r.effect(), level, r.symbol) if r.a != nil { r.a.report(level + "| ") } if r.b != nil { r.b.report(level + "| ") } } func (r *Resistor) add(other *Resistor) *Resistor { return &Resistor{'+', 0, 0, r, other} } func (r *Resistor) mul(other *Resistor) *Resistor { return &Resistor{'*', 0, 0, r, other} } func main() { var r [10]*Resistor resistances := []float64{6, 8, 4, 8, 4, 6, 8, 10, 6, 2} for i := 0; i < 10; i++ { r[i] = &Resistor{'r', resistances[i], 0, nil, nil} } node := r[7].add(r[9]).mul(r[8]).add(r[6]).mul(r[5]).add(r[4]).mul(r[3]).add(r[2]).mul(r[1]).add(r[0]) node.setVoltage(18) fmt.Println(" Ohm Volt Ampere Watt Network tree") node.report("") }
Port the provided Python code into Go while preserving the original functionality.
def gen_upside_down_number(): wrappings = [[1, 9], [2, 8], [3, 7], [4, 6], [5, 5], [6, 4], [7, 3], [8, 2], [9, 1]] evens = [19, 28, 37, 46, 55, 64, 73, 82, 91] odds = [5] odd_index, even_index = 0, 0 ndigits = 1 while True: if ndigits % 2 == 1: if len(odds) > odd_index: yield odds[odd_index] odd_index += 1 else: odds = sorted([hi * 10**(ndigits + 1) + 10 * i + lo for i in odds for hi, lo in wrappings]) ndigits += 1 odd_index = 0 else: if len(evens) > even_index: yield evens[even_index] even_index += 1 else: evens = sorted([hi * 10**(ndigits + 1) + 10 * i + lo for i in evens for hi, lo in wrappings]) ndigits += 1 even_index = 0 print('First fifty upside-downs:') for (udcount, udnumber) in enumerate(gen_upside_down_number()): if udcount < 50: print(f'{udnumber : 5}', end='\n' if (udcount + 1) % 10 == 0 else '') elif udcount == 499: print(f'\nFive hundredth: {udnumber: ,}') elif udcount == 4999: print(f'\nFive thousandth: {udnumber: ,}') elif udcount == 49_999: print(f'\nFifty thousandth: {udnumber: ,}') elif udcount == 499_999: print(f'\nFive hundred thousandth: {udnumber: ,}') elif udcount == 4_999_999: print(f'\nFive millionth: {udnumber: ,}') break
package main import ( "fmt" "rcu" ) func genUpsideDown(limit int) chan int { ch := make(chan int) wrappings := [][2]int{ {1, 9}, {2, 8}, {3, 7}, {4, 6}, {5, 5}, {6, 4}, {7, 3}, {8, 2}, {9, 1}, } evens := []int{19, 28, 37, 46, 55, 64, 73, 82, 91} odds := []int{5} oddIndex := 0 evenIndex := 0 ndigits := 1 pow := 100 count := 0 go func() { for count < limit { if ndigits%2 == 1 { if len(odds) > oddIndex { ch <- odds[oddIndex] count++ oddIndex++ } else { var nextOdds []int for _, w := range wrappings { for _, i := range odds { nextOdds = append(nextOdds, w[0]*pow+i*10+w[1]) } } odds = nextOdds ndigits++ pow *= 10 oddIndex = 0 } } else { if len(evens) > evenIndex { ch <- evens[evenIndex] count++ evenIndex++ } else { var nextEvens []int for _, w := range wrappings { for _, i := range evens { nextEvens = append(nextEvens, w[0]*pow+i*10+w[1]) } } evens = nextEvens ndigits++ pow *= 10 evenIndex = 0 } } } close(ch) }() return ch } func main() { const limit = 50_000_000 count := 0 var ud50s []int pow := 50 for n := range genUpsideDown(limit) { count++ if count < 50 { ud50s = append(ud50s, n) } else if count == 50 { ud50s = append(ud50s, n) fmt.Println("First 50 upside down numbers:") rcu.PrintTable(ud50s, 10, 5, true) fmt.Println() pow = 500 } else if count == pow { fmt.Printf("%sth : %s\n", rcu.Commatize(pow), rcu.Commatize(n)) pow *= 10 } } }
Please provide an equivalent version of this Python code in Go.
print( "{:19.16f} {:19.16f}".format( minkowski(minkowski_inv(4.04145188432738056)), minkowski_inv(minkowski(4.04145188432738056)), ) )
package main import ( "fmt" "math" ) const MAXITER = 151 func minkowski(x float64) float64 { if x > 1 || x < 0 { return math.Floor(x) + minkowski(x-math.Floor(x)) } p := uint64(x) q := uint64(1) r := p + 1 s := uint64(1) d := 1.0 y := float64(p) for { d = d / 2 if y+d == y { break } m := p + r if m < 0 || p < 0 { break } n := q + s if n < 0 { break } if x < float64(m)/float64(n) { r = m s = n } else { y = y + d p = m q = n } } return y + d } func minkowskiInv(x float64) float64 { if x > 1 || x < 0 { return math.Floor(x) + minkowskiInv(x-math.Floor(x)) } if x == 1 || x == 0 { return x } contFrac := []uint32{0} curr := uint32(0) count := uint32(1) i := 0 for { x *= 2 if curr == 0 { if x < 1 { count++ } else { i++ t := contFrac contFrac = make([]uint32, i+1) copy(contFrac, t) contFrac[i-1] = count count = 1 curr = 1 x-- } } else { if x > 1 { count++ x-- } else { i++ t := contFrac contFrac = make([]uint32, i+1) copy(contFrac, t) contFrac[i-1] = count count = 1 curr = 0 } } if x == math.Floor(x) { contFrac[i] = count break } if i == MAXITER { break } } ret := 1.0 / float64(contFrac[i]) for j := i - 1; j >= 0; j-- { ret = float64(contFrac[j]) + 1.0/ret } return 1.0 / ret } func main() { fmt.Printf("%19.16f %19.16f\n", minkowski(0.5*(1+math.Sqrt(5))), 5.0/3.0) fmt.Printf("%19.16f %19.16f\n", minkowskiInv(-5.0/9.0), (math.Sqrt(13)-7)/6) fmt.Printf("%19.16f %19.16f\n", minkowski(minkowskiInv(0.718281828)), minkowskiInv(minkowski(0.1213141516171819))) }
Write the same algorithm in Go as shown in this Python implementation.
import numpy as np from scipy.ndimage.filters import convolve, gaussian_filter from scipy.misc import imread, imshow def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31): im = np.array(im, dtype=float) im2 = gaussian_filter(im, blur) im3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) im3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]]) grad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5) theta = np.arctan2(im3v, im3h) thetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 gradSup = grad.copy() for r in range(im.shape[0]): for c in range(im.shape[1]): if r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1: gradSup[r, c] = 0 continue tq = thetaQ[r, c] % 4 if tq == 0: if grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]: gradSup[r, c] = 0 if tq == 1: if grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]: gradSup[r, c] = 0 if tq == 2: if grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]: gradSup[r, c] = 0 if tq == 3: if grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]: gradSup[r, c] = 0 strongEdges = (gradSup > highThreshold) thresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold) finalEdges = strongEdges.copy() currentPixels = [] for r in range(1, im.shape[0]-1): for c in range(1, im.shape[1]-1): if thresholdedEdges[r, c] != 1: continue localPatch = thresholdedEdges[r-1:r+2,c-1:c+2] patchMax = localPatch.max() if patchMax == 2: currentPixels.append((r, c)) finalEdges[r, c] = 1 while len(currentPixels) > 0: newPix = [] for r, c in currentPixels: for dr in range(-1, 2): for dc in range(-1, 2): if dr == 0 and dc == 0: continue r2 = r+dr c2 = c+dc if thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0: newPix.append((r2, c2)) finalEdges[r2, c2] = 1 currentPixels = newPix return finalEdges if __name__=="__main__": im = imread("test.jpg", mode="L") finalEdges = CannyEdgeDetector(im) imshow(finalEdges)
package main import ( ed "github.com/Ernyoke/Imger/edgedetection" "github.com/Ernyoke/Imger/imgio" "log" ) func main() { img, err := imgio.ImreadRGBA("Valve_original_(1).png") if err != nil { log.Fatal("Could not read image", err) } cny, err := ed.CannyRGBA(img, 15, 45, 5) if err != nil { log.Fatal("Could not perform Canny Edge detection") } err = imgio.Imwrite(cny, "Valve_canny_(1).png") if err != nil { log.Fatal("Could not write Canny image to disk") } }
Maintain the same structure and functionality when rewriting this code in Go.
from numpy.random import shuffle SUITS = ['♣', '♦', '♥', '♠'] FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] DECK = [f + s for f in FACES for s in SUITS] CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK))) class WarCardGame: def __init__(self): deck = DECK.copy() shuffle(deck) self.deck1, self.deck2 = deck[:26], deck[26:] self.pending = [] def turn(self): if len(self.deck1) == 0 or len(self.deck2) == 0: return self.gameover() card1, card2 = self.deck1.pop(0), self.deck2.pop(0) rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2] print("{:10}{:10}".format(card1, card2), end='') if rank1 > rank2: print('Player 1 takes the cards.') self.deck1.extend([card1, card2]) self.deck1.extend(self.pending) self.pending = [] elif rank1 < rank2: print('Player 2 takes the cards.') self.deck2.extend([card2, card1]) self.deck2.extend(self.pending) self.pending = [] else: print('Tie!') if len(self.deck1) == 0 or len(self.deck2) == 0: return self.gameover() card3, card4 = self.deck1.pop(0), self.deck2.pop(0) self.pending.extend([card1, card2, card3, card4]) print("{:10}{:10}".format("?", "?"), 'Cards are face down.', sep='') return self.turn() return True def gameover(self): if len(self.deck2) == 0: if len(self.deck1) == 0: print('\nGame ends as a tie.') else: print('\nPlayer 1 wins the game.') else: print('\nPlayer 2 wins the game.') return False if __name__ == '__main__': WG = WarCardGame() while WG.turn(): continue
package main import ( "fmt" "math/rand" "time" ) var suits = []string{"♣", "♦", "♥", "♠"} var faces = []string{"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"} var cards = make([]string, 52) var ranks = make([]int, 52) func init() { for i := 0; i < 52; i++ { cards[i] = fmt.Sprintf("%s%s", faces[i%13], suits[i/13]) ranks[i] = i % 13 } } func war() { deck := make([]int, 52) for i := 0; i < 52; i++ { deck[i] = i } rand.Shuffle(52, func(i, j int) { deck[i], deck[j] = deck[j], deck[i] }) hand1 := make([]int, 26, 52) hand2 := make([]int, 26, 52) for i := 0; i < 26; i++ { hand1[25-i] = deck[2*i] hand2[25-i] = deck[2*i+1] } for len(hand1) > 0 && len(hand2) > 0 { card1 := hand1[0] copy(hand1[0:], hand1[1:]) hand1[len(hand1)-1] = 0 hand1 = hand1[0 : len(hand1)-1] card2 := hand2[0] copy(hand2[0:], hand2[1:]) hand2[len(hand2)-1] = 0 hand2 = hand2[0 : len(hand2)-1] played1 := []int{card1} played2 := []int{card2} numPlayed := 2 for { fmt.Printf("%s\t%s\t", cards[card1], cards[card2]) if ranks[card1] > ranks[card2] { hand1 = append(hand1, played1...) hand1 = append(hand1, played2...) fmt.Printf("Player 1 takes the %d cards. Now has %d.\n", numPlayed, len(hand1)) break } else if ranks[card1] < ranks[card2] { hand2 = append(hand2, played2...) hand2 = append(hand2, played1...) fmt.Printf("Player 2 takes the %d cards. Now has %d.\n", numPlayed, len(hand2)) break } else { fmt.Println("War!") if len(hand1) < 2 { fmt.Println("Player 1 has insufficient cards left.") hand2 = append(hand2, played2...) hand2 = append(hand2, played1...) hand2 = append(hand2, hand1...) hand1 = hand1[0:0] break } if len(hand2) < 2 { fmt.Println("Player 2 has insufficient cards left.") hand1 = append(hand1, played1...) hand1 = append(hand1, played2...) hand1 = append(hand1, hand2...) hand2 = hand2[0:0] break } fdCard1 := hand1[0] card1 = hand1[1] copy(hand1[0:], hand1[2:]) hand1[len(hand1)-1] = 0 hand1[len(hand1)-2] = 0 hand1 = hand1[0 : len(hand1)-2] played1 = append(played1, fdCard1, card1) fdCard2 := hand2[0] card2 = hand2[1] copy(hand2[0:], hand2[2:]) hand2[len(hand2)-1] = 0 hand2[len(hand2)-2] = 0 hand2 = hand2[0 : len(hand2)-2] played2 = append(played2, fdCard2, card2) numPlayed += 4 fmt.Println("? \t? \tFace down cards.") } } } if len(hand1) == 52 { fmt.Println("Player 1 wins the game!") } else { fmt.Println("Player 2 wins the game!") } } func main() { rand.Seed(time.Now().UnixNano()) war() }
Change the programming language of this snippet from Python to Go without modifying what it does.
from numpy.random import shuffle SUITS = ['♣', '♦', '♥', '♠'] FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] DECK = [f + s for f in FACES for s in SUITS] CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK))) class WarCardGame: def __init__(self): deck = DECK.copy() shuffle(deck) self.deck1, self.deck2 = deck[:26], deck[26:] self.pending = [] def turn(self): if len(self.deck1) == 0 or len(self.deck2) == 0: return self.gameover() card1, card2 = self.deck1.pop(0), self.deck2.pop(0) rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2] print("{:10}{:10}".format(card1, card2), end='') if rank1 > rank2: print('Player 1 takes the cards.') self.deck1.extend([card1, card2]) self.deck1.extend(self.pending) self.pending = [] elif rank1 < rank2: print('Player 2 takes the cards.') self.deck2.extend([card2, card1]) self.deck2.extend(self.pending) self.pending = [] else: print('Tie!') if len(self.deck1) == 0 or len(self.deck2) == 0: return self.gameover() card3, card4 = self.deck1.pop(0), self.deck2.pop(0) self.pending.extend([card1, card2, card3, card4]) print("{:10}{:10}".format("?", "?"), 'Cards are face down.', sep='') return self.turn() return True def gameover(self): if len(self.deck2) == 0: if len(self.deck1) == 0: print('\nGame ends as a tie.') else: print('\nPlayer 1 wins the game.') else: print('\nPlayer 2 wins the game.') return False if __name__ == '__main__': WG = WarCardGame() while WG.turn(): continue
package main import ( "fmt" "math/rand" "time" ) var suits = []string{"♣", "♦", "♥", "♠"} var faces = []string{"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"} var cards = make([]string, 52) var ranks = make([]int, 52) func init() { for i := 0; i < 52; i++ { cards[i] = fmt.Sprintf("%s%s", faces[i%13], suits[i/13]) ranks[i] = i % 13 } } func war() { deck := make([]int, 52) for i := 0; i < 52; i++ { deck[i] = i } rand.Shuffle(52, func(i, j int) { deck[i], deck[j] = deck[j], deck[i] }) hand1 := make([]int, 26, 52) hand2 := make([]int, 26, 52) for i := 0; i < 26; i++ { hand1[25-i] = deck[2*i] hand2[25-i] = deck[2*i+1] } for len(hand1) > 0 && len(hand2) > 0 { card1 := hand1[0] copy(hand1[0:], hand1[1:]) hand1[len(hand1)-1] = 0 hand1 = hand1[0 : len(hand1)-1] card2 := hand2[0] copy(hand2[0:], hand2[1:]) hand2[len(hand2)-1] = 0 hand2 = hand2[0 : len(hand2)-1] played1 := []int{card1} played2 := []int{card2} numPlayed := 2 for { fmt.Printf("%s\t%s\t", cards[card1], cards[card2]) if ranks[card1] > ranks[card2] { hand1 = append(hand1, played1...) hand1 = append(hand1, played2...) fmt.Printf("Player 1 takes the %d cards. Now has %d.\n", numPlayed, len(hand1)) break } else if ranks[card1] < ranks[card2] { hand2 = append(hand2, played2...) hand2 = append(hand2, played1...) fmt.Printf("Player 2 takes the %d cards. Now has %d.\n", numPlayed, len(hand2)) break } else { fmt.Println("War!") if len(hand1) < 2 { fmt.Println("Player 1 has insufficient cards left.") hand2 = append(hand2, played2...) hand2 = append(hand2, played1...) hand2 = append(hand2, hand1...) hand1 = hand1[0:0] break } if len(hand2) < 2 { fmt.Println("Player 2 has insufficient cards left.") hand1 = append(hand1, played1...) hand1 = append(hand1, played2...) hand1 = append(hand1, hand2...) hand2 = hand2[0:0] break } fdCard1 := hand1[0] card1 = hand1[1] copy(hand1[0:], hand1[2:]) hand1[len(hand1)-1] = 0 hand1[len(hand1)-2] = 0 hand1 = hand1[0 : len(hand1)-2] played1 = append(played1, fdCard1, card1) fdCard2 := hand2[0] card2 = hand2[1] copy(hand2[0:], hand2[2:]) hand2[len(hand2)-1] = 0 hand2[len(hand2)-2] = 0 hand2 = hand2[0 : len(hand2)-2] played2 = append(played2, fdCard2, card2) numPlayed += 4 fmt.Println("? \t? \tFace down cards.") } } } if len(hand1) == 52 { fmt.Println("Player 1 wins the game!") } else { fmt.Println("Player 2 wins the game!") } } func main() { rand.Seed(time.Now().UnixNano()) war() }
Change the following Python code into Go without altering its purpose.
from PIL import Image if __name__=="__main__": im = Image.open("frog.png") im2 = im.quantize(16) im2.show()
package main import ( "container/heap" "image" "image/color" "image/png" "log" "math" "os" "sort" ) func main() { f, err := os.Open("Quantum_frog.png") if err != nil { log.Fatal(err) } img, err := png.Decode(f) if ec := f.Close(); err != nil { log.Fatal(err) } else if ec != nil { log.Fatal(ec) } fq, err := os.Create("frog16.png") if err != nil { log.Fatal(err) } if err = png.Encode(fq, quant(img, 16)); err != nil { log.Fatal(err) } } func quant(img image.Image, nq int) image.Image { qz := newQuantizer(img, nq) qz.cluster() return qz.Paletted() } type quantizer struct { img image.Image cs []cluster px []point ch chValues eq []point } type cluster struct { px []point widestCh int chRange uint32 } type point struct{ x, y int } type chValues []uint32 type queue []*cluster const ( rx = iota gx bx ) func newQuantizer(img image.Image, nq int) *quantizer { b := img.Bounds() npx := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y) qz := &quantizer{ img: img, ch: make(chValues, npx), cs: make([]cluster, nq), } c := &qz.cs[0] px := make([]point, npx) c.px = px i := 0 for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { px[i].x = x px[i].y = y i++ } } return qz } func (qz *quantizer) cluster() { pq := new(queue) c := &qz.cs[0] for i := 1; ; { qz.setColorRange(c) if c.chRange > 0 { heap.Push(pq, c) } if len(*pq) == 0 { qz.cs = qz.cs[:i] break } s := heap.Pop(pq).(*cluster) c = &qz.cs[i] i++ m := qz.Median(s) qz.Split(s, c, m) if i == len(qz.cs) { break } qz.setColorRange(s) if s.chRange > 0 { heap.Push(pq, s) } } } func (q *quantizer) setColorRange(c *cluster) { var maxR, maxG, maxB uint32 minR := uint32(math.MaxUint32) minG := uint32(math.MaxUint32) minB := uint32(math.MaxUint32) for _, p := range c.px { r, g, b, _ := q.img.At(p.x, p.y).RGBA() if r < minR { minR = r } if r > maxR { maxR = r } if g < minG { minG = g } if g > maxG { maxG = g } if b < minB { minB = b } if b > maxB { maxB = b } } s := gx min := minG max := maxG if maxR-minR > max-min { s = rx min = minR max = maxR } if maxB-minB > max-min { s = bx min = minB max = maxB } c.widestCh = s c.chRange = max - min } func (q *quantizer) Median(c *cluster) uint32 { px := c.px ch := q.ch[:len(px)] switch c.widestCh { case rx: for i, p := range c.px { ch[i], _, _, _ = q.img.At(p.x, p.y).RGBA() } case gx: for i, p := range c.px { _, ch[i], _, _ = q.img.At(p.x, p.y).RGBA() } case bx: for i, p := range c.px { _, _, ch[i], _ = q.img.At(p.x, p.y).RGBA() } } sort.Sort(ch) half := len(ch) / 2 m := ch[half] if len(ch)%2 == 0 { m = (m + ch[half-1]) / 2 } return m } func (q *quantizer) Split(s, c *cluster, m uint32) { px := s.px var v uint32 i := 0 lt := 0 gt := len(px) - 1 eq := q.eq[:0] for i <= gt { r, g, b, _ := q.img.At(px[i].x, px[i].y).RGBA() switch s.widestCh { case rx: v = r case gx: v = g case bx: v = b } switch { case v < m: px[lt] = px[i] lt++ i++ case v > m: px[gt], px[i] = px[i], px[gt] gt-- default: eq = append(eq, px[i]) i++ } } if len(eq) > 0 { copy(px[lt:], eq) if len(px)-i < lt { i = lt } q.eq = eq } s.px = px[:i] c.px = px[i:] } func (qz *quantizer) Paletted() *image.Paletted { cp := make(color.Palette, len(qz.cs)) pi := image.NewPaletted(qz.img.Bounds(), cp) for i := range qz.cs { px := qz.cs[i].px var rsum, gsum, bsum int64 for _, p := range px { r, g, b, _ := qz.img.At(p.x, p.y).RGBA() rsum += int64(r) gsum += int64(g) bsum += int64(b) } n64 := int64(len(px)) cp[i] = color.NRGBA64{ uint16(rsum / n64), uint16(gsum / n64), uint16(bsum / n64), 0xffff, } for _, p := range px { pi.SetColorIndex(p.x, p.y, uint8(i)) } } return pi } func (c chValues) Len() int { return len(c) } func (c chValues) Less(i, j int) bool { return c[i] < c[j] } func (c chValues) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (q queue) Len() int { return len(q) } func (q queue) Less(i, j int) bool { return len(q[j].px) < len(q[i].px) } func (q queue) Swap(i, j int) { q[i], q[j] = q[j], q[i] } func (pq *queue) Push(x interface{}) { c := x.(*cluster) *pq = append(*pq, c) } func (pq *queue) Pop() interface{} { q := *pq n := len(q) - 1 c := q[n] *pq = q[:n] return c }
Keep all operations the same but rewrite the snippet in Go.
import random from typing import List, Callable, Optional def modifier(x: float) -> float: return 2*(.5 - x) if x < 0.5 else 2*(x - .5) def modified_random_distribution(modifier: Callable[[float], float], n: int) -> List[float]: d: List[float] = [] while len(d) < n: r1 = prob = random.random() if random.random() < modifier(prob): d.append(r1) return d if __name__ == '__main__': from collections import Counter data = modified_random_distribution(modifier, 50_000) bins = 15 counts = Counter(d // (1 / bins) for d in data) mx = max(counts.values()) print(" BIN, COUNTS, DELTA: HISTOGRAM\n") last: Optional[float] = None for b, count in sorted(counts.items()): delta = 'N/A' if last is None else str(count - last) print(f" {b / bins:5.2f}, {count:4}, {delta:>4}: " f"{' last = count
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } func commatize(n int) string { s := 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() { rand.Seed(time.Now().UnixNano()) modifier := func(x float64) float64 { if x < 0.5 { return 2 * (0.5 - x) } return 2 * (x - 0.5) } const ( N = 100000 NUM_BINS = 20 HIST_CHAR = "■" HIST_CHAR_SIZE = 125 ) bins := make([]int, NUM_BINS) binSize := 1.0 / NUM_BINS for i := 0; i < N; i++ { rn := rng(modifier) bn := int(math.Floor(rn / binSize)) bins[bn]++ } fmt.Println("Modified random distribution with", commatize(N), "samples in range [0, 1):\n") fmt.Println(" Range Number of samples within that range") for i := 0; i < NUM_BINS; i++ { hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE))) fi := float64(i) fmt.Printf("%4.2f ..< %4.2f %s %s\n", binSize*fi, binSize*(fi+1), hist, commatize(bins[i])) } }
Convert the following code from Python to Go, ensuring the logic remains intact.
import random from typing import List, Callable, Optional def modifier(x: float) -> float: return 2*(.5 - x) if x < 0.5 else 2*(x - .5) def modified_random_distribution(modifier: Callable[[float], float], n: int) -> List[float]: d: List[float] = [] while len(d) < n: r1 = prob = random.random() if random.random() < modifier(prob): d.append(r1) return d if __name__ == '__main__': from collections import Counter data = modified_random_distribution(modifier, 50_000) bins = 15 counts = Counter(d // (1 / bins) for d in data) mx = max(counts.values()) print(" BIN, COUNTS, DELTA: HISTOGRAM\n") last: Optional[float] = None for b, count in sorted(counts.items()): delta = 'N/A' if last is None else str(count - last) print(f" {b / bins:5.2f}, {count:4}, {delta:>4}: " f"{' last = count
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } func commatize(n int) string { s := 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() { rand.Seed(time.Now().UnixNano()) modifier := func(x float64) float64 { if x < 0.5 { return 2 * (0.5 - x) } return 2 * (x - 0.5) } const ( N = 100000 NUM_BINS = 20 HIST_CHAR = "■" HIST_CHAR_SIZE = 125 ) bins := make([]int, NUM_BINS) binSize := 1.0 / NUM_BINS for i := 0; i < N; i++ { rn := rng(modifier) bn := int(math.Floor(rn / binSize)) bins[bn]++ } fmt.Println("Modified random distribution with", commatize(N), "samples in range [0, 1):\n") fmt.Println(" Range Number of samples within that range") for i := 0; i < NUM_BINS; i++ { hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE))) fi := float64(i) fmt.Printf("%4.2f ..< %4.2f %s %s\n", binSize*fi, binSize*(fi+1), hist, commatize(bins[i])) } }
Produce a language-to-language conversion: from Python to Go, same semantics.
import random from typing import List, Callable, Optional def modifier(x: float) -> float: return 2*(.5 - x) if x < 0.5 else 2*(x - .5) def modified_random_distribution(modifier: Callable[[float], float], n: int) -> List[float]: d: List[float] = [] while len(d) < n: r1 = prob = random.random() if random.random() < modifier(prob): d.append(r1) return d if __name__ == '__main__': from collections import Counter data = modified_random_distribution(modifier, 50_000) bins = 15 counts = Counter(d // (1 / bins) for d in data) mx = max(counts.values()) print(" BIN, COUNTS, DELTA: HISTOGRAM\n") last: Optional[float] = None for b, count in sorted(counts.items()): delta = 'N/A' if last is None else str(count - last) print(f" {b / bins:5.2f}, {count:4}, {delta:>4}: " f"{' last = count
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } func commatize(n int) string { s := 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() { rand.Seed(time.Now().UnixNano()) modifier := func(x float64) float64 { if x < 0.5 { return 2 * (0.5 - x) } return 2 * (x - 0.5) } const ( N = 100000 NUM_BINS = 20 HIST_CHAR = "■" HIST_CHAR_SIZE = 125 ) bins := make([]int, NUM_BINS) binSize := 1.0 / NUM_BINS for i := 0; i < N; i++ { rn := rng(modifier) bn := int(math.Floor(rn / binSize)) bins[bn]++ } fmt.Println("Modified random distribution with", commatize(N), "samples in range [0, 1):\n") fmt.Println(" Range Number of samples within that range") for i := 0; i < NUM_BINS; i++ { hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE))) fi := float64(i) fmt.Printf("%4.2f ..< %4.2f %s %s\n", binSize*fi, binSize*(fi+1), hist, commatize(bins[i])) } }
Maintain the same structure and functionality when rewriting this code in Go.
import math print("working...") list = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)] Squares = [] def issquare(x): for p in range(x): if x == p*p: return 1 for n in range(3): for m in range(len(list[n])): if issquare(list[n][m]): Squares.append(list[n][m]) Squares.sort() print(Squares) print("done...")
package main import ( "fmt" "math" "sort" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { lists := [][]int{ {3, 4, 34, 25, 9, 12, 36, 56, 36}, {2, 8, 81, 169, 34, 55, 76, 49, 7}, {75, 121, 75, 144, 35, 16, 46, 35}, } var squares []int for _, list := range lists { for _, e := range list { if isSquare(e) { squares = append(squares, e) } } } sort.Ints(squares) fmt.Println(squares) }
Ensure the translated Go code behaves exactly like the original Python snippet.
import math print("working...") list = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)] Squares = [] def issquare(x): for p in range(x): if x == p*p: return 1 for n in range(3): for m in range(len(list[n])): if issquare(list[n][m]): Squares.append(list[n][m]) Squares.sort() print(Squares) print("done...")
package main import ( "fmt" "math" "sort" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { lists := [][]int{ {3, 4, 34, 25, 9, 12, 36, 56, 36}, {2, 8, 81, 169, 34, 55, 76, 49, 7}, {75, 121, 75, 144, 35, 16, 46, 35}, } var squares []int for _, list := range lists { for _, e := range list { if isSquare(e) { squares = append(squares, e) } } } sort.Ints(squares) fmt.Println(squares) }
Write the same algorithm in Go as shown in this Python implementation.
import math import os def suffize(num, digits=None, base=10): suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol'] exponent_distance = 10 if base == 2 else 3 num = num.strip().replace(',', '') num_sign = num[0] if num[0] in '+-' else '' num = abs(float(num)) if base == 10 and num >= 1e100: suffix_index = 13 num /= 1e100 elif num > 1: magnitude = math.floor(math.log(num, base)) suffix_index = min(math.floor(magnitude / exponent_distance), 12) num /= base ** (exponent_distance * suffix_index) else: suffix_index = 0 if digits is not None: num_str = f'{num:.{digits}f}' else: num_str = f'{num:.3f}'.strip('0').strip('.') return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '') tests = [('87,654,321',), ('-998,877,665,544,332,211,000', 3), ('+112,233', 0), ('16,777,216', 1), ('456,789,100,000,000', 2), ('456,789,100,000,000', 2, 10), ('456,789,100,000,000', 5, 2), ('456,789,100,000.000e+00', 0, 10), ('+16777216', None, 2), ('1.2e101',)] for test in tests: print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))
package main import ( "fmt" "math/big" "strconv" "strings" ) var suffixes = " KMGTPEZYXWVU" var ggl = googol() func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } return g } func suffize(arg string) { fields := strings.Fields(arg) a := fields[0] if a == "" { a = "0" } var places, base int var frac, radix string switch len(fields) { case 1: places = -1 base = 10 case 2: places, _ = strconv.Atoi(fields[1]) base = 10 frac = strconv.Itoa(places) case 3: if fields[1] == "," { places = 0 frac = "," } else { places, _ = strconv.Atoi(fields[1]) frac = strconv.Itoa(places) } base, _ = strconv.Atoi(fields[2]) if base != 2 && base != 10 { base = 10 } radix = strconv.Itoa(base) } a = strings.Replace(a, ",", "", -1) sign := "" if a[0] == '+' || a[0] == '-' { sign = string(a[0]) a = a[1:] } b := new(big.Float).SetPrec(500) d := new(big.Float).SetPrec(500) b.SetString(a) g := false if b.Cmp(ggl) >= 0 { g = true } if !g && base == 2 { d.SetUint64(1024) } else if !g && base == 10 { d.SetUint64(1000) } else { d.Set(ggl) } c := 0 for b.Cmp(d) >= 0 && c < 12 { b.Quo(b, d) c++ } var suffix string if !g { suffix = string(suffixes[c]) } else { suffix = "googol" } if base == 2 { suffix += "i" } fmt.Println(" input number =", fields[0]) fmt.Println(" fraction digs =", frac) fmt.Println("specified radix =", radix) fmt.Print(" new number = ") if places >= 0 { fmt.Printf("%s%.*f%s\n", sign, places, b, suffix) } else { fmt.Printf("%s%s%s\n", sign, b.Text('g', 50), suffix) } fmt.Println() } func main() { tests := []string{ "87,654,321", "-998,877,665,544,332,211,000 3", "+112,233 0", "16,777,216 1", "456,789,100,000,000", "456,789,100,000,000 2 10", "456,789,100,000,000 5 2", "456,789,100,000.000e+00 0 10", "+16777216 , 2", "1.2e101", "446,835,273,728 1", "1e36", "1e39", } for _, test := range tests { suffize(test) } }
Translate the given Python code snippet into Go without altering its behavior.
import math import os def suffize(num, digits=None, base=10): suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol'] exponent_distance = 10 if base == 2 else 3 num = num.strip().replace(',', '') num_sign = num[0] if num[0] in '+-' else '' num = abs(float(num)) if base == 10 and num >= 1e100: suffix_index = 13 num /= 1e100 elif num > 1: magnitude = math.floor(math.log(num, base)) suffix_index = min(math.floor(magnitude / exponent_distance), 12) num /= base ** (exponent_distance * suffix_index) else: suffix_index = 0 if digits is not None: num_str = f'{num:.{digits}f}' else: num_str = f'{num:.3f}'.strip('0').strip('.') return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '') tests = [('87,654,321',), ('-998,877,665,544,332,211,000', 3), ('+112,233', 0), ('16,777,216', 1), ('456,789,100,000,000', 2), ('456,789,100,000,000', 2, 10), ('456,789,100,000,000', 5, 2), ('456,789,100,000.000e+00', 0, 10), ('+16777216', None, 2), ('1.2e101',)] for test in tests: print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))
package main import ( "fmt" "math/big" "strconv" "strings" ) var suffixes = " KMGTPEZYXWVU" var ggl = googol() func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } return g } func suffize(arg string) { fields := strings.Fields(arg) a := fields[0] if a == "" { a = "0" } var places, base int var frac, radix string switch len(fields) { case 1: places = -1 base = 10 case 2: places, _ = strconv.Atoi(fields[1]) base = 10 frac = strconv.Itoa(places) case 3: if fields[1] == "," { places = 0 frac = "," } else { places, _ = strconv.Atoi(fields[1]) frac = strconv.Itoa(places) } base, _ = strconv.Atoi(fields[2]) if base != 2 && base != 10 { base = 10 } radix = strconv.Itoa(base) } a = strings.Replace(a, ",", "", -1) sign := "" if a[0] == '+' || a[0] == '-' { sign = string(a[0]) a = a[1:] } b := new(big.Float).SetPrec(500) d := new(big.Float).SetPrec(500) b.SetString(a) g := false if b.Cmp(ggl) >= 0 { g = true } if !g && base == 2 { d.SetUint64(1024) } else if !g && base == 10 { d.SetUint64(1000) } else { d.Set(ggl) } c := 0 for b.Cmp(d) >= 0 && c < 12 { b.Quo(b, d) c++ } var suffix string if !g { suffix = string(suffixes[c]) } else { suffix = "googol" } if base == 2 { suffix += "i" } fmt.Println(" input number =", fields[0]) fmt.Println(" fraction digs =", frac) fmt.Println("specified radix =", radix) fmt.Print(" new number = ") if places >= 0 { fmt.Printf("%s%.*f%s\n", sign, places, b, suffix) } else { fmt.Printf("%s%s%s\n", sign, b.Text('g', 50), suffix) } fmt.Println() } func main() { tests := []string{ "87,654,321", "-998,877,665,544,332,211,000 3", "+112,233 0", "16,777,216 1", "456,789,100,000,000", "456,789,100,000,000 2 10", "456,789,100,000,000 5 2", "456,789,100,000.000e+00 0 10", "+16777216 , 2", "1.2e101", "446,835,273,728 1", "1e36", "1e39", } for _, test := range tests { suffize(test) } }
Write a version of this Python function in Go with identical behavior.
def longestPalindromes(s): k = s.lower() palindromes = [ palExpansion(k)(ab) for ab in palindromicNuclei(k) ] maxLength = max([ len(x) for x in palindromes ]) if palindromes else 1 return ( [ x for x in palindromes if maxLength == len(x) ] if palindromes else list(s), maxLength ) if s else ([], 0) def palindromicNuclei(s): cs = list(s) return [ (i, 1 + i) for (i, (a, b)) in enumerate(zip(cs, cs[1:])) if a == b ] + [ (i, 2 + i) for (i, (a, b, c)) in enumerate(zip(cs, cs[1:], cs[2:])) if a == c ] def palExpansion(s): iEnd = len(s) - 1 def limit(ij): i, j = ij return 0 == i or iEnd == j or s[i-1] != s[j+1] def expansion(ij): i, j = ij return (i - 1, 1 + j) def go(ij): ab = until(limit)(expansion)(ij) return s[ab[0]:ab[1] + 1] return go def main(): print( fTable(main.__doc__ + ':\n')(repr)(repr)( longestPalindromes )([ 'three old rotators', 'never reverse', 'stable was I ere I saw elbatrosses', 'abracadabra', 'drome', 'the abbatial palace', '' ]) ) def until(p): def go(f): def g(x): v = x while not p(v): v = f(v) return v return g return go def fTable(s): def gox(xShow): def gofx(fxShow): def gof(f): def goxs(xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) def arrowed(x, y): return y.rjust(w, ' ') + ' -> ' + ( fxShow(f(x)) ) return s + '\n' + '\n'.join( map(arrowed, xs, ys) ) return goxs return gof return gofx return gox if __name__ == '__main__': main()
package main import ( "fmt" "sort" ) func reverse(s string) string { var r = []rune(s) for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func longestPalSubstring(s string) []string { var le = len(s) if le <= 1 { return []string{s} } targetLen := le var longest []string i := 0 for { j := i + targetLen - 1 if j < le { ss := s[i : j+1] if reverse(ss) == ss { longest = append(longest, ss) } i++ } else { if len(longest) > 0 { return longest } i = 0 targetLen-- } } return longest } func distinct(sa []string) []string { sort.Strings(sa) duplicated := make([]bool, len(sa)) for i := 1; i < len(sa); i++ { if sa[i] == sa[i-1] { duplicated[i] = true } } var res []string for i := 0; i < len(sa); i++ { if !duplicated[i] { res = append(res, sa[i]) } } return res } func main() { strings := []string{"babaccd", "rotator", "reverse", "forever", "several", "palindrome", "abaracadaraba"} fmt.Println("The palindromic substrings having the longest length are:") for _, s := range strings { longest := distinct(longestPalSubstring(s)) fmt.Printf("  %-13s Length %d -> %v\n", s, len(longest[0]), longest) } }
Write the same code in Go as shown below in Python.
import random class WumpusGame(object): def __init__(self, edges=[]): if edges: cave = {} N = max([edges[i][0] for i in range(len(edges))]) for i in range(N): exits = [edge[1] for edge in edges if edge[0] == i] cave[i] = exits else: cave = {1: [2,3,4], 2: [1,5,6], 3: [1,7,8], 4: [1,9,10], 5:[2,9,11], 6: [2,7,12], 7: [3,6,13], 8: [3,10,14], 9: [4,5,15], 10: [4,8,16], 11: [5,12,17], 12: [6,11,18], 13: [7,14,18], 14: [8,13,19], 15: [9,16,17], 16: [10,15,19], 17: [11,20,15], 18: [12,13,20], 19: [14,16,20], 20: [17,18,19]} self.cave = cave self.threats = {} self.arrows = 5 self.arrow_travel_distance = 5 self.player_pos = -1 def get_safe_rooms(self): return list(set(self.cave.keys()).difference(self.threats.keys())) def populate_cave(self): for threat in ['bat', 'bat', 'pit', 'pit', 'wumpus']: pos = random.choice(self.get_safe_rooms()) self.threats[pos] = threat self.player_pos = random.choice(self.get_safe_rooms()) def breadth_first_search(self, source, target, max_depth=5): graph = self.cave depth = 0 def search(stack, visited, target, depth): if stack == []: return False, -1 if target in stack: return True, depth visited = visited + stack stack = list(set([graph[v][i] for v in stack for i in range(len(graph[v]))]).difference(visited)) depth += 1 if depth > max_depth: return False, depth else: return search(stack, visited, target, depth) return search([source], [], target, depth) def print_warning(self, threat): if threat == 'bat': print("You hear a rustling.") elif threat == 'pit': print("You feel a cold wind blowing from a nearby cavern.") elif threat == 'wumpus': print("You smell something terrible nearby.") def get_players_input(self): while 1: inpt = input("Shoot or move (S-M)? ") try: mode = str(inpt).lower() assert mode in ['s', 'm', 'q'] break except (ValueError, AssertionError): print("This is not a valid action: pick 'S' to shoot and 'M' to move.") if mode == 'q': return 'q', 0 while 1: inpt = input("Where to? ") try: target = int(inpt) except ValueError: print("This is not even a real number.") continue if mode == 'm': try: assert target in self.cave[self.player_pos] break except AssertionError: print("You cannot walk that far. Please use one of the tunnels.") elif mode == 's': try: bfs = self.breadth_first_search(self.player_pos, target) assert bfs[0] == True break except AssertionError: if bfs[1] == -1: print("There is no room with this number in the cave. Your arrow travels randomly.") target = random.choice(self.cave.keys()) if bfs[1] > self.arrow_travel_distance: print("Arrows aren't that croocked.") return mode, target def enter_room(self, room_number): print("Entering room {}...".format(room_number)) if self.threats.get(room_number) == 'bat': print("You encounter a bat, it transports you to a random empty room.") new_pos = random.choice(self.get_safe_rooms()) return self.enter_room(new_pos) elif self.threats.get(room_number) == 'wumpus': print("Wumpus eats you.") return -1 elif self.threats.get(room_number) == 'pit': print("You fall into a pit.") return -1 for i in self.cave[room_number]: self.print_warning(self.threats.get(i)) return room_number def shoot_room(self, room_number): print("Shooting an arrow into room {}...".format(room_number)) self.arrows -= 1 threat = self.threats.get(room_number) if threat in ['bat', 'wumpus']: del self.threats[room_number] if threat == 'wumpus': print("Hurra, you killed the wumpus!") return -1 elif threat == 'bat': print("You killed a bat.") elif threat in ['pit', None]: print("This arrow is lost.") if self.arrows < 1: print("Your quiver is empty.") return -1 if random.random() < 0.75: for room_number, threat in self.threats.items(): if threat == 'wumpus': wumpus_pos = room_number new_pos = random.choice(list(set(self.cave[wumpus_pos]).difference(self.threats.keys()))) del self.threats[room_number] self.threats[new_pos] = 'wumpus' if new_pos == self.player_pos: print("Wumpus enters your room and eats you!") return -1 return self.player_pos def gameloop(self): print("HUNT THE WUMPUS") print("===============") print() self.populate_cave() self.enter_room(self.player_pos) while 1: print("You are in room {}.".format(self.player_pos), end=" ") print("Tunnels lead to: {0} {1} {2}".format(*self.cave[self.player_pos])) inpt = self.get_players_input() print() if inpt[0] == 'm': target = inpt[1] self.player_pos = self.enter_room(target) elif inpt[0] == 's': target = inpt[1] self.player_pos = self.shoot_room(target) elif inpt[0] == 'q': self.player_pos = -1 if self.player_pos == -1: break print() print("Game over!") if __name__ == '__main__': WG = WumpusGame() WG.gameloop()
package main import ( "bufio" "fmt" "log" "math/rand" "os" "strconv" "strings" "time" ) var cave = map[int][3]int{ 1: {2, 3, 4}, 2: {1, 5, 6}, 3: {1, 7, 8}, 4: {1, 9, 10}, 5: {2, 9, 11}, 6: {2, 7, 12}, 7: {3, 6, 13}, 8: {3, 10, 14}, 9: {4, 5, 15}, 10: {4, 8, 16}, 11: {5, 12, 17}, 12: {6, 11, 18}, 13: {7, 14, 18}, 14: {8, 13, 19}, 15: {9, 16, 17}, 16: {10, 15, 19}, 17: {11, 20, 15}, 18: {12, 13, 20}, 19: {14, 16, 20}, 20: {17, 18, 19}, } var player, wumpus, bat1, bat2, pit1, pit2 int var arrows = 5 func isEmpty(r int) bool { if r != player && r != wumpus && r != bat1 && r != bat2 && r != pit1 && r != pit2 { return true } return false } func sense(adj [3]int) { bat := false pit := false for _, ar := range adj { if ar == wumpus { fmt.Println("You smell something terrible nearby.") } switch ar { case bat1, bat2: if !bat { fmt.Println("You hear a rustling.") bat = true } case pit1, pit2: if !pit { fmt.Println("You feel a cold wind blowing from a nearby cavern.") pit = true } } } fmt.Println() } func check(err error) { if err != nil { log.Fatal(err) } } func plural(n int) string { if n != 1 { return "s" } return "" } func main() { rand.Seed(time.Now().UnixNano()) player = 1 wumpus = rand.Intn(19) + 2 bat1 = rand.Intn(19) + 2 for { bat2 = rand.Intn(19) + 2 if bat2 != bat1 { break } } for { pit1 = rand.Intn(19) + 2 if pit1 != bat1 && pit1 != bat2 { break } } for { pit2 = rand.Intn(19) + 2 if pit2 != bat1 && pit2 != bat2 && pit2 != pit1 { break } } scanner := bufio.NewScanner(os.Stdin) for { fmt.Printf("\nYou are in room %d with %d arrow%s left\n", player, arrows, plural(arrows)) adj := cave[player] fmt.Printf("The adjacent rooms are %v\n", adj) sense(adj) var room int for { fmt.Print("Choose an adjacent room : ") scanner.Scan() room, _ = strconv.Atoi(scanner.Text()) if room != adj[0] && room != adj[1] && room != adj[2] { fmt.Println("Invalid response, try again") } else { break } } check(scanner.Err()) var action byte for { fmt.Print("Walk or shoot w/s : ") scanner.Scan() reply := strings.ToLower(scanner.Text()) if len(reply) != 1 || (len(reply) == 1 && reply[0] != 'w' && reply[0] != 's') { fmt.Println("Invalid response, try again") } else { action = reply[0] break } } check(scanner.Err()) if action == 'w' { player = room switch player { case wumpus: fmt.Println("You have been eaten by the Wumpus and lost the game!") return case pit1, pit2: fmt.Println("You have fallen down a bottomless pit and lost the game!") return case bat1, bat2: for { room = rand.Intn(19) + 2 if isEmpty(room) { fmt.Println("A bat has transported you to a random empty room") player = room break } } } } else { if room == wumpus { fmt.Println("You have killed the Wumpus and won the game!!") return } else { chance := rand.Intn(4) if chance > 0 { wumpus = cave[wumpus][rand.Intn(3)] if player == wumpus { fmt.Println("You have been eaten by the Wumpus and lost the game!") return } } } arrows-- if arrows == 0 { fmt.Println("You have run out of arrows and lost the game!") return } } } }
Translate this program into Go but keep the logic exactly as in Python.
import sys if len(sys.argv)!=2: print("Usage : python " + sys.argv[0] + " <filename>") exit() dataFile = open(sys.argv[1],"r") fileData = dataFile.read().split('\n') dataFile.close() [print(i) for i in fileData[::-1]]
package main import ( "bytes" "fmt" "io/ioutil" "log" "runtime" ) func main() { fileName1 := "rodgers.txt" fileName2 := "rodgers_reversed.txt" lineBreak := "\n" if runtime.GOOS == "windows" { lineBreak = "\r\n" } b, err := ioutil.ReadFile(fileName1) if err != nil { log.Fatal(err) } lines := bytes.Split(b, []byte(lineBreak)) if len(lines[len(lines)-1]) == 0 { lines = lines[:len(lines)-1] } for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 { lines[i], lines[j] = lines[j], lines[i] } b = bytes.Join(lines, []byte(lineBreak)) if err = ioutil.WriteFile(fileName2, b, 0o666); err != nil { log.Fatal(err) } b, err = ioutil.ReadFile(fileName2) if err != nil { log.Fatal(err) } fmt.Println(string(b)) }
Maintain the same structure and functionality when rewriting this code in Go.
def hourglass_puzzle(): t4 = 0 while t4 < 10_000: t7_left = 7 - t4 % 7 if t7_left == 9 - 4: break t4 += 4 else: print('Not found') return print(f) hourglass_puzzle()
package main import ( "fmt" "log" ) func minimum(a []int) int { min := a[0] for i := 1; i < len(a); i++ { if a[i] < min { min = a[i] } } return min } func sum(a []int) int { s := 0 for _, i := range a { s = s + i } return s } func hourglassFlipper(hourglasses []int, target int) (int, []int) { flippers := make([]int, len(hourglasses)) copy(flippers, hourglasses) var series []int for iter := 0; iter < 10000; iter++ { n := minimum(flippers) series = append(series, n) for i := 0; i < len(flippers); i++ { flippers[i] -= n } for i, flipper := range flippers { if flipper == 0 { flippers[i] = hourglasses[i] } } for start := len(series) - 1; start >= 0; start-- { if sum(series[start:]) == target { return start, series } } } log.Fatal("Unable to find an answer within 10,000 iterations.") return 0, nil } func main() { fmt.Print("Flip an hourglass every time it runs out of grains, ") fmt.Println("and note the interval in time.") hgs := [][]int{{4, 7}, {5, 7, 31}} ts := []int{9, 36} for i := 0; i < len(hgs); i++ { start, series := hourglassFlipper(hgs[i], ts[i]) end := len(series) - 1 fmt.Println("\nSeries:", series) fmt.Printf("Use hourglasses from indices %d to %d (inclusive) to sum ", start, end) fmt.Println(ts[i], "using", hgs[i]) } }
Ensure the translated Go code behaves exactly like the original Python snippet.
def hourglass_puzzle(): t4 = 0 while t4 < 10_000: t7_left = 7 - t4 % 7 if t7_left == 9 - 4: break t4 += 4 else: print('Not found') return print(f) hourglass_puzzle()
package main import ( "fmt" "log" ) func minimum(a []int) int { min := a[0] for i := 1; i < len(a); i++ { if a[i] < min { min = a[i] } } return min } func sum(a []int) int { s := 0 for _, i := range a { s = s + i } return s } func hourglassFlipper(hourglasses []int, target int) (int, []int) { flippers := make([]int, len(hourglasses)) copy(flippers, hourglasses) var series []int for iter := 0; iter < 10000; iter++ { n := minimum(flippers) series = append(series, n) for i := 0; i < len(flippers); i++ { flippers[i] -= n } for i, flipper := range flippers { if flipper == 0 { flippers[i] = hourglasses[i] } } for start := len(series) - 1; start >= 0; start-- { if sum(series[start:]) == target { return start, series } } } log.Fatal("Unable to find an answer within 10,000 iterations.") return 0, nil } func main() { fmt.Print("Flip an hourglass every time it runs out of grains, ") fmt.Println("and note the interval in time.") hgs := [][]int{{4, 7}, {5, 7, 31}} ts := []int{9, 36} for i := 0; i < len(hgs); i++ { start, series := hourglassFlipper(hgs[i], ts[i]) end := len(series) - 1 fmt.Println("\nSeries:", series) fmt.Printf("Use hourglasses from indices %d to %d (inclusive) to sum ", start, end) fmt.Println(ts[i], "using", hgs[i]) } }
Please provide an equivalent version of this Python code in Go.
LIST = ["1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"] print(sorted([ch for ch in set([c for c in ''.join(LIST)]) if all(w.count(ch) == 1 for w in LIST)]))
package main import ( "fmt" "sort" ) func main() { strings := []string{"1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"} u := make(map[rune]int) for _, s := range strings { m := make(map[rune]int) for _, c := range s { m[c]++ } for k, v := range m { if v == 1 { u[k]++ } } } var chars []rune for k, v := range u { if v == 3 { chars = append(chars, k) } } sort.Slice(chars, func(i, j int) bool { return chars[i] < chars[j] }) fmt.Println(string(chars)) }
Translate the given Python code snippet into Go without altering its behavior.
class FibonacciHeap: class Node: def __init__(self, data): self.data = data self.parent = self.child = self.left = self.right = None self.degree = 0 self.mark = False def iterate(self, head): node = stop = head flag = False while True: if node == stop and flag is True: break elif node == stop: flag = True yield node node = node.right root_list, min_node = None, None total_nodes = 0 def find_min(self): return self.min_node def extract_min(self): z = self.min_node if z is not None: if z.child is not None: children = [x for x in self.iterate(z.child)] for i in xrange(0, len(children)): self.merge_with_root_list(children[i]) children[i].parent = None self.remove_from_root_list(z) if z == z.right: self.min_node = self.root_list = None else: self.min_node = z.right self.consolidate() self.total_nodes -= 1 return z def insert(self, data): n = self.Node(data) n.left = n.right = n self.merge_with_root_list(n) if self.min_node is None or n.data < self.min_node.data: self.min_node = n self.total_nodes += 1 def decrease_key(self, x, k): if k > x.data: return None x.data = k y = x.parent if y is not None and x.data < y.data: self.cut(x, y) self.cascading_cut(y) if x.data < self.min_node.data: self.min_node = x def merge(self, h2): H = FibonacciHeap() H.root_list, H.min_node = self.root_list, self.min_node last = h2.root_list.left h2.root_list.left = H.root_list.left H.root_list.left.right = h2.root_list H.root_list.left = last H.root_list.left.right = H.root_list if h2.min_node.data < H.min_node.data: H.min_node = h2.min_node H.total_nodes = self.total_nodes + h2.total_nodes return H def cut(self, x, y): self.remove_from_child_list(y, x) y.degree -= 1 self.merge_with_root_list(x) x.parent = None x.mark = False def cascading_cut(self, y): z = y.parent if z is not None: if y.mark is False: y.mark = True else: self.cut(y, z) self.cascading_cut(z) def consolidate(self): A = [None] * self.total_nodes nodes = [w for w in self.iterate(self.root_list)] for w in xrange(0, len(nodes)): x = nodes[w] d = x.degree while A[d] != None: y = A[d] if x.data > y.data: temp = x x, y = y, temp self.heap_link(y, x) A[d] = None d += 1 A[d] = x for i in xrange(0, len(A)): if A[i] is not None: if A[i].data < self.min_node.data: self.min_node = A[i] def heap_link(self, y, x): self.remove_from_root_list(y) y.left = y.right = y self.merge_with_child_list(x, y) x.degree += 1 y.parent = x y.mark = False def merge_with_root_list(self, node): if self.root_list is None: self.root_list = node else: node.right = self.root_list.right node.left = self.root_list self.root_list.right.left = node self.root_list.right = node def merge_with_child_list(self, parent, node): if parent.child is None: parent.child = node else: node.right = parent.child.right node.left = parent.child parent.child.right.left = node parent.child.right = node def remove_from_root_list(self, node): if node == self.root_list: self.root_list = node.right node.left.right = node.right node.right.left = node.left def remove_from_child_list(self, parent, node): if parent.child == parent.child.right: parent.child = None elif parent.child == node: parent.child = node.right node.right.parent = parent node.left.right = node.right node.right.left = node.left
package fib import "fmt" type Value interface { LT(Value) bool } type Node struct { value Value parent *Node child *Node prev, next *Node rank int mark bool } func (n Node) Value() Value { return n.value } type Heap struct{ *Node } func MakeHeap() *Heap { return &Heap{} } func (h *Heap) Insert(v Value) *Node { x := &Node{value: v} if h.Node == nil { x.next = x x.prev = x h.Node = x } else { meld1(h.Node, x) if x.value.LT(h.value) { h.Node = x } } return x } func meld1(list, single *Node) { list.prev.next = single single.prev = list.prev single.next = list list.prev = single } func (h *Heap) Union(h2 *Heap) { switch { case h.Node == nil: *h = *h2 case h2.Node != nil: meld2(h.Node, h2.Node) if h2.value.LT(h.value) { *h = *h2 } } h2.Node = nil } func meld2(a, b *Node) { a.prev.next = b b.prev.next = a a.prev, b.prev = b.prev, a.prev } func (h Heap) Minimum() (min Value, ok bool) { if h.Node == nil { return } return h.value, true } func (h *Heap) ExtractMin() (min Value, ok bool) { if h.Node == nil { return } min = h.value roots := map[int]*Node{} add := func(r *Node) { r.prev = r r.next = r for { x, ok := roots[r.rank] if !ok { break } delete(roots, r.rank) if x.value.LT(r.value) { r, x = x, r } x.parent = r x.mark = false if r.child == nil { x.next = x x.prev = x r.child = x } else { meld1(r.child, x) } r.rank++ } roots[r.rank] = r } for r := h.next; r != h.Node; { n := r.next add(r) r = n } if c := h.child; c != nil { c.parent = nil r := c.next add(c) for r != c { n := r.next r.parent = nil add(r) r = n } } if len(roots) == 0 { h.Node = nil return min, true } var mv *Node var d int for d, mv = range roots { break } delete(roots, d) mv.next = mv mv.prev = mv for _, r := range roots { r.prev = mv r.next = mv.next mv.next.prev = r mv.next = r if r.value.LT(mv.value) { mv = r } } h.Node = mv return min, true } func (h *Heap) DecreaseKey(n *Node, v Value) error { if n.value.LT(v) { return fmt.Errorf("DecreaseKey new value greater than existing value") } n.value = v if n == h.Node { return nil } p := n.parent if p == nil { if v.LT(h.value) { h.Node = n } return nil } h.cutAndMeld(n) return nil } func (h Heap) cut(x *Node) { p := x.parent p.rank-- if p.rank == 0 { p.child = nil } else { p.child = x.next x.prev.next = x.next x.next.prev = x.prev } if p.parent == nil { return } if !p.mark { p.mark = true return } h.cutAndMeld(p) } func (h Heap) cutAndMeld(x *Node) { h.cut(x) x.parent = nil meld1(h.Node, x) } func (h *Heap) Delete(n *Node) { p := n.parent if p == nil { if n == h.Node { h.ExtractMin() return } n.prev.next = n.next n.next.prev = n.prev } else { h.cut(n) } c := n.child if c == nil { return } for { c.parent = nil c = c.next if c == n.child { break } } meld2(h.Node, c) } func (h Heap) Vis() { if h.Node == nil { fmt.Println("<empty>") return } var f func(*Node, string) f = func(n *Node, pre string) { pc := "│ " for x := n; ; x = x.next { if x.next != n { fmt.Print(pre, "├─") } else { fmt.Print(pre, "└─") pc = " " } if x.child == nil { fmt.Println("╴", x.value) } else { fmt.Println("┐", x.value) f(x.child, pre+pc) } if x.next == n { break } } } f(h.Node, "") }
Preserve the algorithm and functionality while converting the code from Python to Go.
import datetime def g2m(date, gtm_correlation=True): correlation = 584283 if gtm_correlation else 584285 long_count_days = [144000, 7200, 360, 20, 1] tzolkin_months = ['Imix’', 'Ik’', 'Ak’bal', 'K’an', 'Chikchan', 'Kimi', 'Manik’', 'Lamat', 'Muluk', 'Ok', 'Chuwen', 'Eb', 'Ben', 'Hix', 'Men', 'K’ib’', 'Kaban', 'Etz’nab’', 'Kawak', 'Ajaw'] haad_months = ['Pop', 'Wo’', 'Sip', 'Sotz’', 'Sek', 'Xul', 'Yaxk’in', 'Mol', 'Ch’en', 'Yax', 'Sak’', 'Keh', 'Mak', 'K’ank’in', 'Muwan', 'Pax', 'K’ayab', 'Kumk’u', 'Wayeb’'] gregorian_days = datetime.datetime.strptime(date, '%Y-%m-%d').toordinal() julian_days = gregorian_days + 1721425 long_date = list() remainder = julian_days - correlation for days in long_count_days: result, remainder = divmod(remainder, days) long_date.append(int(result)) long_date = '.'.join(['{:02d}'.format(d) for d in long_date]) tzolkin_month = (julian_days + 16) % 20 tzolkin_day = ((julian_days + 5) % 13) + 1 haab_month = int(((julian_days + 65) % 365) / 20) haab_day = ((julian_days + 65) % 365) % 20 haab_day = haab_day if haab_day else 'Chum' lord_number = (julian_days - correlation) % 9 lord_number = lord_number if lord_number else 9 round_date = f'{tzolkin_day} {tzolkin_months[tzolkin_month]} {haab_day} {haad_months[haab_month]} G{lord_number}' return long_date, round_date if __name__ == '__main__': dates = ['2004-06-19', '2012-12-18', '2012-12-21', '2019-01-19', '2019-03-27', '2020-02-29', '2020-03-01'] for date in dates: long, round = g2m(date) print(date, long, round)
package main import ( "fmt" "strconv" "strings" "time" ) var sacred = strings.Fields("Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw") var civil = strings.Fields("Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muwan’ Pax K’ayab Kumk’u Wayeb’") var ( date1 = time.Date(2012, time.December, 21, 0, 0, 0, 0, time.UTC) date2 = time.Date(2019, time.April, 2, 0, 0, 0, 0, time.UTC) ) func tzolkin(date time.Time) (int, string) { diff := int(date.Sub(date1).Hours()) / 24 rem := diff % 13 if rem < 0 { rem = 13 + rem } var num int if rem <= 9 { num = rem + 4 } else { num = rem - 9 } rem = diff % 20 if rem <= 0 { rem = 20 + rem } return num, sacred[rem-1] } func haab(date time.Time) (string, string) { diff := int(date.Sub(date2).Hours()) / 24 rem := diff % 365 if rem < 0 { rem = 365 + rem } month := civil[(rem+1)/20] last := 20 if month == "Wayeb’" { last = 5 } d := rem%20 + 1 if d < last { return strconv.Itoa(d), month } return "Chum", month } func longCount(date time.Time) string { diff := int(date.Sub(date1).Hours()) / 24 diff += 13 * 400 * 360 baktun := diff / (400 * 360) diff %= 400 * 360 katun := diff / (20 * 360) diff %= 20 * 360 tun := diff / 360 diff %= 360 winal := diff / 20 kin := diff % 20 return fmt.Sprintf("%d.%d.%d.%d.%d", baktun, katun, tun, winal, kin) } func lord(date time.Time) string { diff := int(date.Sub(date1).Hours()) / 24 rem := diff % 9 if rem <= 0 { rem = 9 + rem } return fmt.Sprintf("G%d", rem) } func main() { const shortForm = "2006-01-02" dates := []string{ "2004-06-19", "2012-12-18", "2012-12-21", "2019-01-19", "2019-03-27", "2020-02-29", "2020-03-01", "2071-05-16", } fmt.Println(" Gregorian Tzolk’in Haab’ Long Lord of") fmt.Println(" Date # Name Day Month Count the Night") fmt.Println("---------- -------- ------------- -------------- ---------") for _, dt := range dates { date, _ := time.Parse(shortForm, dt) n, s := tzolkin(date) d, m := haab(date) lc := longCount(date) l := lord(date) fmt.Printf("%s %2d %-8s %4s %-9s  %-14s %s\n", dt, n, s, d, m, lc, l) } }
Write a version of this Python function in Go with identical behavior.
import sys if len(sys.argv)!=2: print("Usage : python " + sys.argv[0] + " <whole number>") exit() numLimit = int(sys.argv[1]) resultSet = {} base = 1 while len(resultSet)!=numLimit: result = base**base for i in range(0,numLimit): if str(i) in str(result) and i not in resultSet: resultSet[i] = base base+=1 [print(resultSet[i], end=' ') for i in sorted(resultSet)]
package main import ( "fmt" "math/big" "strconv" "strings" ) func main() { var res []int64 for n := 0; n <= 50; n++ { ns := strconv.Itoa(n) k := int64(1) for { bk := big.NewInt(k) s := bk.Exp(bk, bk, nil).String() if strings.Contains(s, ns) { res = append(res, k) break } k++ } } fmt.Println("The smallest positive integers K where K ^ K contains N (0..50) are:") for i, n := range res { fmt.Printf("%2d ", n) if (i+1)%17 == 0 { fmt.Println() } } }
Please provide an equivalent version of this Python code in Go.
print("working...") row = 0 limit = 1500 Sophie = [] def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True for n in range(2,limit): p = 2*n + 1 if isPrime(n) and isPrime(p): Sophie.append(n) print("Found ",end = "") print(len(Sophie),end = "") print(" Safe and Sophie primes.") print(Sophie) print("done...")
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 } } fmt.Println("The first 50 Sophie Germain primes are:") for i := 0; i < len(sgp); i++ { fmt.Printf("%5s ", rcu.Commatize(sgp[i])) if (i+1)%10 == 0 { fmt.Println() } } }
Translate this program into Go but keep the logic exactly as in Python.
print("working...") row = 0 limit = 1500 Sophie = [] def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True for n in range(2,limit): p = 2*n + 1 if isPrime(n) and isPrime(p): Sophie.append(n) print("Found ",end = "") print(len(Sophie),end = "") print(" Safe and Sophie primes.") print(Sophie) print("done...")
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 } } fmt.Println("The first 50 Sophie Germain primes are:") for i := 0; i < len(sgp); i++ { fmt.Printf("%5s ", rcu.Commatize(sgp[i])) if (i+1)%10 == 0 { fmt.Println() } } }
Produce a functionally identical Go code for the snippet given in Python.
from __future__ import unicode_literals import argparse import fileinput import os import sys from functools import partial from itertools import count from itertools import takewhile ANSI_RESET = "\u001b[0m" RED = (255, 0, 0) GREEN = (0, 255, 0) YELLOW = (255, 255, 0) BLUE = (0, 0, 255) MAGENTA = (255, 0, 255) CYAN = (0, 255, 255) ANSI_PALETTE = { RED: "\u001b[31m", GREEN: "\u001b[32m", YELLOW: "\u001b[33m", BLUE: "\u001b[34m", MAGENTA: "\u001b[35m", CYAN: "\u001b[36m", } _8BIT_PALETTE = { (0xAF, 0x00, 0x00): "\u001b[38;5;124m", (0xAF, 0x00, 0x5F): "\u001b[38;5;125m", (0xAF, 0x00, 0x87): "\u001b[38;5;126m", (0xAF, 0x00, 0xAF): "\u001b[38;5;127m", (0xAF, 0x00, 0xD7): "\u001b[38;5;128m", (0xAF, 0x00, 0xFF): "\u001b[38;5;129m", (0xAF, 0x5F, 0x00): "\u001b[38;5;130m", (0xAF, 0x5F, 0x5F): "\u001b[38;5;131m", (0xAF, 0x5F, 0x87): "\u001b[38;5;132m", (0xAF, 0x5F, 0xAF): "\u001b[38;5;133m", (0xAF, 0x5F, 0xD7): "\u001b[38;5;134m", (0xAF, 0x5F, 0xFF): "\u001b[38;5;135m", (0xAF, 0x87, 0x00): "\u001b[38;5;136m", (0xAF, 0x87, 0x5F): "\u001b[38;5;137m", (0xAF, 0x87, 0x87): "\u001b[38;5;138m", (0xAF, 0x87, 0xAF): "\u001b[38;5;139m", (0xAF, 0x87, 0xD7): "\u001b[38;5;140m", (0xAF, 0x87, 0xFF): "\u001b[38;5;141m", (0xAF, 0xAF, 0x00): "\u001b[38;5;142m", (0xAF, 0xAF, 0x5F): "\u001b[38;5;143m", (0xAF, 0xAF, 0x87): "\u001b[38;5;144m", (0xAF, 0xAF, 0xAF): "\u001b[38;5;145m", (0xAF, 0xAF, 0xD7): "\u001b[38;5;146m", (0xAF, 0xAF, 0xFF): "\u001b[38;5;147m", (0xAF, 0xD7, 0x00): "\u001b[38;5;148m", (0xAF, 0xD7, 0x5F): "\u001b[38;5;149m", (0xAF, 0xD7, 0x87): "\u001b[38;5;150m", (0xAF, 0xD7, 0xAF): "\u001b[38;5;151m", (0xAF, 0xD7, 0xD7): "\u001b[38;5;152m", (0xAF, 0xD7, 0xFF): "\u001b[38;5;153m", (0xAF, 0xFF, 0x00): "\u001b[38;5;154m", (0xAF, 0xFF, 0x5F): "\u001b[38;5;155m", (0xAF, 0xFF, 0x87): "\u001b[38;5;156m", (0xAF, 0xFF, 0xAF): "\u001b[38;5;157m", (0xAF, 0xFF, 0xD7): "\u001b[38;5;158m", (0xAF, 0xFF, 0xFF): "\u001b[38;5;159m", } def error(msg): sys.stderr.write(msg) sys.stderr.write(os.linesep) sys.exit(1) def rgb(group): nibbles_per_channel = len(group) // 3 max_val = 16 ** nibbles_per_channel - 1 nibbles = chunked(group, nibbles_per_channel) return tuple((int(n, 16) * 255) // max_val for n in nibbles) def distance(color, other): return sum((o - s) ** 2 for s, o in zip(color, other)) def chunked(seq, n): return takewhile(len, (seq[i : i + n] for i in count(0, n))) def escape(group, palette): key = partial(distance, other=rgb(group.ljust(3, "0"))) ansi_color = min(palette, key=key) return "".join([palette[ansi_color], group, ANSI_RESET]) def colorize(line, group_size=3, palette=ANSI_PALETTE): checksum, filename = line.split(None, 1) escaped = [escape(group, palette) for group in chunked(checksum, group_size)] sys.stdout.write(" ".join(["".join(escaped), filename])) def html_colorize(checksum, group_size=3, palette=ANSI_PALETTE): def span(group): key = partial(distance, other=rgb(group.ljust(3, "0"))) ansi_color = min(palette, key=key) int_val = int.from_bytes(ansi_color, byteorder="big") hex_val = hex(int_val)[2:].rjust(6, "0") return '<span style="color: checksum, filename = line.split(None, 1) escaped = [span(group) for group in chunked(checksum, group_size)] sys.stdout.write(" ".join(["".join(escaped), filename])) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Color checksum.") parser.add_argument( "-n", type=int, default=3, help="Color the checksum in groups of size N. Defaults to 3.", ) parser.add_argument( "-e", "--extended-palette", action="store_true", help="Use the extended 8-bit palette. Defaults to False.", ) parser.add_argument( "--html", action="store_true", help="Output checksum groups wrapped with 'span' tags instead of ANSI escape sequences.", ) parser.add_argument("files", nargs="*", default="-", metavar="FILE") args = parser.parse_args() if sys.stdout.isatty(): palette = ANSI_PALETTE if args.extended_palette: palette = _8BIT_PALETTE colorize_func = colorize if args.html: colorize_func = html_colorize for line in fileinput.input(files=args.files): colorize_func(line, group_size=args.n, palette=palette) else: for line in fileinput.input(files=args.files): sys.stdout.write(line)
package main import ( "bufio" "fmt" "golang.org/x/crypto/ssh/terminal" "log" "os" "regexp" "strconv" ) type Color struct{ r, g, b int } type ColorEx struct { color Color code string } var colors = []ColorEx{ {Color{15, 0, 0}, "31"}, {Color{0, 15, 0}, "32"}, {Color{15, 15, 0}, "33"}, {Color{0, 0, 15}, "34"}, {Color{15, 0, 15}, "35"}, {Color{0, 15, 15}, "36"}, } func squareDist(c1, c2 Color) int { xd := c2.r - c1.r yd := c2.g - c1.g zd := c2.b - c1.b return xd*xd + yd*yd + zd*zd } func printColor(s string) { n := len(s) k := 0 for i := 0; i < n/3; i++ { j := i * 3 c1 := s[j] c2 := s[j+1] c3 := s[j+2] k = j + 3 r, err := strconv.ParseInt(fmt.Sprintf("0x%c", c1), 0, 64) check(err) g, err := strconv.ParseInt(fmt.Sprintf("0x%c", c2), 0, 64) check(err) b, err := strconv.ParseInt(fmt.Sprintf("0x%c", c3), 0, 64) check(err) rgb := Color{int(r), int(g), int(b)} m := 676 colorCode := "" for _, cex := range colors { sqd := squareDist(cex.color, rgb) if sqd < m { colorCode = cex.code m = sqd } } fmt.Printf("\033[%s;1m%c%c%c\033[00m", colorCode, c1, c2, c3) } for j := k; j < n; j++ { c := s[j] fmt.Printf("\033[0;1m%c\033[00m", c) } } var ( r = regexp.MustCompile("^([A-Fa-f0-9]+)([ \t]+.+)$") scanner = bufio.NewScanner(os.Stdin) err error ) func colorChecksum() { for scanner.Scan() { line := scanner.Text() if r.MatchString(line) { submatches := r.FindStringSubmatch(line) s1 := submatches[1] s2 := submatches[2] printColor(s1) fmt.Println(s2) } else { fmt.Println(line) } } check(scanner.Err()) } func cat() { for scanner.Scan() { line := scanner.Text() fmt.Println(line) } check(scanner.Err()) } func check(err error) { if err != nil { log.Fatal(err) } } func main() { if terminal.IsTerminal(int(os.Stdout.Fd())) { colorChecksum() } else { cat() } }
Write the same code in Go as shown below in Python.
import sqlite3 import string import random from http import HTTPStatus from flask import Flask from flask import Blueprint from flask import abort from flask import current_app from flask import g from flask import jsonify from flask import redirect from flask import request from flask import url_for CHARS = frozenset(string.ascii_letters + string.digits) MIN_URL_SIZE = 8 RANDOM_ATTEMPTS = 3 def create_app(*, db=None, server_name=None) -> Flask: app = Flask(__name__) app.config.from_mapping( DATABASE=db or "shorten.sqlite", SERVER_NAME=server_name, ) with app.app_context(): init_db() app.teardown_appcontext(close_db) app.register_blueprint(shortener) return app def get_db(): if "db" not in g: g.db = sqlite3.connect(current_app.config["DATABASE"]) g.db.row_factory = sqlite3.Row return g.db def close_db(_): db = g.pop("db", None) if db is not None: db.close() def init_db(): db = get_db() with db: db.execute( "CREATE TABLE IF NOT EXISTS shorten (" "url TEXT PRIMARY KEY, " "short TEXT NOT NULL UNIQUE ON CONFLICT FAIL)" ) shortener = Blueprint("shorten", "short") def random_short(size=MIN_URL_SIZE): return "".join(random.sample(CHARS, size)) @shortener.errorhandler(HTTPStatus.NOT_FOUND) def short_url_not_found(_): return "short url not found", HTTPStatus.NOT_FOUND @shortener.route("/<path:key>", methods=("GET",)) def short(key): db = get_db() cursor = db.execute("SELECT url FROM shorten WHERE short = ?", (key,)) row = cursor.fetchone() if row is None: abort(HTTPStatus.NOT_FOUND) return redirect(row["url"], code=HTTPStatus.FOUND) class URLExistsError(Exception): class ShortCollisionError(Exception): def _insert_short(long_url, short): db = get_db() if ( db.execute("SELECT * FROM shorten WHERE url = ?", (long_url,)).fetchone() is not None ): raise URLExistsError(long_url) if ( db.execute("SELECT * FROM shorten WHERE short = ?", (short,)).fetchone() is not None ): raise ShortCollisionError(short) with db: db.execute("INSERT INTO shorten VALUES (?, ?)", (long_url, short)) def make_short(long_url): size = MIN_URL_SIZE attempts = 1 short = random_short(size=size) while True: try: _insert_short(long_url, short) except ShortCollisionError: if not attempts % RANDOM_ATTEMPTS: size += 1 attempts += 1 short = random_short(size=size) else: break return short @shortener.route("/", methods=("POST",)) def shorten(): data = request.get_json() if data is None: abort(HTTPStatus.BAD_REQUEST) long_url = data.get("long") if long_url is None: abort(HTTPStatus.BAD_REQUEST) db = get_db() cursor = db.execute("SELECT short FROM shorten WHERE url = ?", (long_url,)) row = cursor.fetchone() if row is not None: short_url = url_for("shorten.short", _external=True, key=row["short"]) status_code = HTTPStatus.OK else: short_url = url_for("shorten.short", _external=True, key=make_short(long_url)) status_code = HTTPStatus.CREATED mimetype = request.accept_mimetypes.best_match( matches=["text/plain", "application/json"], default="text/plain" ) if mimetype == "application/json": return jsonify(long=long_url, short=short_url), status_code else: return short_url, status_code if __name__ == "__main__": app = create_app() app.env = "development" app.run(debug=True)
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "time" ) const ( chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" host = "localhost:8000" ) type database map[string]string type shortener struct { Long string `json:"long"` } func (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) { switch req.Method { case http.MethodPost: body, err := ioutil.ReadAll(req.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) return } var sh shortener err = json.Unmarshal(body, &sh) if err != nil { w.WriteHeader(http.StatusUnprocessableEntity) return } short := generateKey(8) db[short] = sh.Long fmt.Fprintf(w, "The shortened URL: http: case http.MethodGet: path := req.URL.Path[1:] if v, ok := db[path]; ok { http.Redirect(w, req, v, http.StatusFound) } else { w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "No such shortened url: http: } default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Unsupprted method: %s\n", req.Method) } } func generateKey(size int) string { key := make([]byte, size) le := len(chars) for i := 0; i < size; i++ { key[i] = chars[rand.Intn(le)] } return string(key) } func main() { rand.Seed(time.Now().UnixNano()) db := make(database) log.Fatal(http.ListenAndServe(host, db)) }
Maintain the same structure and functionality when rewriting this code in Go.
import sqlite3 import string import random from http import HTTPStatus from flask import Flask from flask import Blueprint from flask import abort from flask import current_app from flask import g from flask import jsonify from flask import redirect from flask import request from flask import url_for CHARS = frozenset(string.ascii_letters + string.digits) MIN_URL_SIZE = 8 RANDOM_ATTEMPTS = 3 def create_app(*, db=None, server_name=None) -> Flask: app = Flask(__name__) app.config.from_mapping( DATABASE=db or "shorten.sqlite", SERVER_NAME=server_name, ) with app.app_context(): init_db() app.teardown_appcontext(close_db) app.register_blueprint(shortener) return app def get_db(): if "db" not in g: g.db = sqlite3.connect(current_app.config["DATABASE"]) g.db.row_factory = sqlite3.Row return g.db def close_db(_): db = g.pop("db", None) if db is not None: db.close() def init_db(): db = get_db() with db: db.execute( "CREATE TABLE IF NOT EXISTS shorten (" "url TEXT PRIMARY KEY, " "short TEXT NOT NULL UNIQUE ON CONFLICT FAIL)" ) shortener = Blueprint("shorten", "short") def random_short(size=MIN_URL_SIZE): return "".join(random.sample(CHARS, size)) @shortener.errorhandler(HTTPStatus.NOT_FOUND) def short_url_not_found(_): return "short url not found", HTTPStatus.NOT_FOUND @shortener.route("/<path:key>", methods=("GET",)) def short(key): db = get_db() cursor = db.execute("SELECT url FROM shorten WHERE short = ?", (key,)) row = cursor.fetchone() if row is None: abort(HTTPStatus.NOT_FOUND) return redirect(row["url"], code=HTTPStatus.FOUND) class URLExistsError(Exception): class ShortCollisionError(Exception): def _insert_short(long_url, short): db = get_db() if ( db.execute("SELECT * FROM shorten WHERE url = ?", (long_url,)).fetchone() is not None ): raise URLExistsError(long_url) if ( db.execute("SELECT * FROM shorten WHERE short = ?", (short,)).fetchone() is not None ): raise ShortCollisionError(short) with db: db.execute("INSERT INTO shorten VALUES (?, ?)", (long_url, short)) def make_short(long_url): size = MIN_URL_SIZE attempts = 1 short = random_short(size=size) while True: try: _insert_short(long_url, short) except ShortCollisionError: if not attempts % RANDOM_ATTEMPTS: size += 1 attempts += 1 short = random_short(size=size) else: break return short @shortener.route("/", methods=("POST",)) def shorten(): data = request.get_json() if data is None: abort(HTTPStatus.BAD_REQUEST) long_url = data.get("long") if long_url is None: abort(HTTPStatus.BAD_REQUEST) db = get_db() cursor = db.execute("SELECT short FROM shorten WHERE url = ?", (long_url,)) row = cursor.fetchone() if row is not None: short_url = url_for("shorten.short", _external=True, key=row["short"]) status_code = HTTPStatus.OK else: short_url = url_for("shorten.short", _external=True, key=make_short(long_url)) status_code = HTTPStatus.CREATED mimetype = request.accept_mimetypes.best_match( matches=["text/plain", "application/json"], default="text/plain" ) if mimetype == "application/json": return jsonify(long=long_url, short=short_url), status_code else: return short_url, status_code if __name__ == "__main__": app = create_app() app.env = "development" app.run(debug=True)
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "time" ) const ( chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" host = "localhost:8000" ) type database map[string]string type shortener struct { Long string `json:"long"` } func (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) { switch req.Method { case http.MethodPost: body, err := ioutil.ReadAll(req.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) return } var sh shortener err = json.Unmarshal(body, &sh) if err != nil { w.WriteHeader(http.StatusUnprocessableEntity) return } short := generateKey(8) db[short] = sh.Long fmt.Fprintf(w, "The shortened URL: http: case http.MethodGet: path := req.URL.Path[1:] if v, ok := db[path]; ok { http.Redirect(w, req, v, http.StatusFound) } else { w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "No such shortened url: http: } default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Unsupprted method: %s\n", req.Method) } } func generateKey(size int) string { key := make([]byte, size) le := len(chars) for i := 0; i < size; i++ { key[i] = chars[rand.Intn(le)] } return string(key) } func main() { rand.Seed(time.Now().UnixNano()) db := make(database) log.Fatal(http.ListenAndServe(host, db)) }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
import sys black_pawn = " \u265f " white_pawn = " \u2659 " empty_square = " " def draw_board(board_data): bg_black = "\u001b[48;5;237m" bg_white = "\u001b[48;5;245m" clear_to_eol = "\u001b[0m\u001b[K\n" board = ["1 ", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black, board_data[0][2], clear_to_eol, "2 ", bg_white, board_data[1][0], bg_black, board_data[1][1], bg_white, board_data[1][2], clear_to_eol, "3 ", bg_black, board_data[2][0], bg_white, board_data[2][1], bg_black, board_data[2][2], clear_to_eol, " A B C\n"]; sys.stdout.write("".join(board)) def get_movement_direction(colour): direction = -1 if colour == black_pawn: direction = 1 elif colour == white_pawn: direction = -1 else: raise ValueError("Invalid piece colour") return direction def get_other_colour(colour): if colour == black_pawn: return white_pawn elif colour == white_pawn: return black_pawn else: raise ValueError("Invalid piece colour") def get_allowed_moves(board_data, row, col): if board_data[row][col] == empty_square: return set() colour = board_data[row][col] other_colour = get_other_colour(colour) direction = get_movement_direction(colour) if (row + direction < 0 or row + direction > 2): return set() allowed_moves = set() if board_data[row + direction][col] == empty_square: allowed_moves.add('f') if col > 0 and board_data[row + direction][col - 1] == other_colour: allowed_moves.add('dl') if col < 2 and board_data[row + direction][col + 1] == other_colour: allowed_moves.add('dr') return allowed_moves def get_human_move(board_data, colour): direction = get_movement_direction(colour) while True: piece_posn = input(f'What {colour} do you want to move? ') valid_inputs = {'a1': (0,0), 'b1': (0,1), 'c1': (0,2), 'a2': (1,0), 'b2': (1,1), 'c2': (1,2), 'a3': (2,0), 'b3': (2,1), 'c3': (2,2)} if piece_posn not in valid_inputs: print("LOL that's not a valid position! Try again.") continue (row, col) = valid_inputs[piece_posn] piece = board_data[row][col] if piece == empty_square: print("What are you trying to pull, there's no piece in that space!") continue if piece != colour: print("LOL that's not your piece, try again!") continue allowed_moves = get_allowed_moves(board_data, row, col) if len(allowed_moves) == 0: print('LOL nice try. That piece has no valid moves.') continue move = list(allowed_moves)[0] if len(allowed_moves) > 1: move = input(f'What move do you want to make ({",".join(list(allowed_moves))})? ') if move not in allowed_moves: print('LOL that move is not allowed. Try again.') continue if move == 'f': board_data[row + direction][col] = board_data[row][col] elif move == 'dl': board_data[row + direction][col - 1] = board_data[row][col] elif move == 'dr': board_data[row + direction][col + 1] = board_data[row][col] board_data[row][col] = empty_square return board_data def is_game_over(board_data): if board_data[0][0] == white_pawn or board_data[0][1] == white_pawn or board_data[0][2] == white_pawn: return white_pawn if board_data[2][0] == black_pawn or board_data[2][1] == black_pawn or board_data[2][2] == black_pawn: return black_pawn white_count = 0 black_count = 0 black_allowed_moves = [] white_allowed_moves = [] for i in range(3): for j in range(3): moves = get_allowed_moves(board_data, i, j) if board_data[i][j] == white_pawn: white_count += 1 if len(moves) > 0: white_allowed_moves.append((i,j,moves)) if board_data[i][j] == black_pawn: black_count += 1 if len(moves) > 0: black_allowed_moves.append((i,j,moves)) if white_count == 0 or len(white_allowed_moves) == 0: return black_pawn if black_count == 0 or len(black_allowed_moves) == 0: return white_pawn return "LOL NOPE" def play_game(black_move, white_move): board_data = [[black_pawn, black_pawn, black_pawn], [empty_square, empty_square, empty_square], [white_pawn, white_pawn, white_pawn]] last_player = black_pawn next_player = white_pawn while is_game_over(board_data) == "LOL NOPE": draw_board(board_data) if (next_player == black_pawn): board_data = black_move(board_data, next_player) else: board_data = white_move(board_data, next_player) temp = last_player last_player = next_player next_player = temp winner = is_game_over(board_data) print(f'Congratulations {winner}!') play_game(get_human_move, get_human_move)
package main import ( "bytes" "errors" "flag" "fmt" "io" "io/ioutil" "log" "math/rand" "os" "time" ) const ( Rows = 3 Cols = 3 ) var vlog *log.Logger func main() { verbose := flag.Bool("v", false, "verbose") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } logOutput := ioutil.Discard if *verbose { logOutput = os.Stderr } vlog = log.New(logOutput, "hexapawn: ", 0) rand.Seed(time.Now().UnixNano()) wins := make(map[spot]int, 2) for { h := New() var s herGameState for c := false; h[stateIdx] == empty; c = !c { if c { h = s.Move(h) } else { h = h.HumanMove() } } fmt.Printf("Board:\n%v is a win for %v\n", h, h[stateIdx]) s.Result(h[stateIdx]) wins[h[stateIdx]]++ fmt.Printf("Wins: Black=%d, White=%d\n", wins[black], wins[white]) fmt.Println() } } func (h Hexapawn) HumanMove() Hexapawn { fmt.Print("Board:\n", h, "\n") var from, to int for { fmt.Print("Your move: ") _, err := fmt.Scanln(&from, &to) if err != nil { fmt.Println(err) if err == io.EOF { os.Exit(0) } continue } if err := h.doMove(white, from-1, to-1); err != nil { fmt.Println(err) continue } return h } } var herNextMove = make(map[Hexapawn][]move) type herGameState struct { h Hexapawn i int } func (s *herGameState) Move(h Hexapawn) Hexapawn { known := false moves := herNextMove[h] if moves == nil { moves = possibleMoves(black, h) herNextMove[h] = moves } else if len(moves) == 0 { vlog.Println("no good moves left to black, picking a random looser") known = true moves = possibleMoves(black, h) } vlog.Println("considering", moves) i := rand.Intn(len(moves)) if !known { s.h = h s.i = i } fmt.Println("Computer moves", moves[i]) if err := h.doMove(black, moves[i].from, moves[i].to); err != nil { panic(err) } return h } func (s herGameState) Result(winner spot) { if winner == black { return } moves := herNextMove[s.h] vlog.Printf("Training:\n%v will no longer do %v\n", s.h, moves[s.i]) herNextMove[s.h] = append(moves[:s.i], moves[s.i+1:]...) vlog.Println("will instead do one of:", herNextMove[s.h]) } type move struct{ from, to int } func (m move) String() string { return fmt.Sprintf("%d→%d", m.from+1, m.to+1) } var cachedMoves = []map[Hexapawn][]move{ black: make(map[Hexapawn][]move), white: make(map[Hexapawn][]move), } func possibleMoves(s spot, h Hexapawn) []move { m := cachedMoves[s][h] if m != nil { return m } m = make([]move, 0) for from := 0; from < Rows*Cols; from++ { for to := 0; to < Rows*Cols; to++ { if err := h.checkMove(s, from, to); err == nil { m = append(m, move{from, to}) } } } cachedMoves[s][h] = m vlog.Printf("caclulated possible moves for %v\n%v as %v\n", s, h, m) return m } func (h *Hexapawn) doMove(p spot, from, to int) error { if err := h.checkMove(p, from, to); err != nil { return err } h[from] = empty h[to] = p if (p == white && to/Rows == Rows-1) || (p == black && to/Rows == 0) { h[stateIdx] = p } else if len(possibleMoves(p.Other(), *h)) == 0 { h[stateIdx] = p } return nil } func (h *Hexapawn) checkMove(p spot, from, to int) error { if h[from] != p { return fmt.Errorf("No %v located at spot %v", p, from+1) } if h[to] == p { return fmt.Errorf("%v already occupies spot %v", p, to+1) } Δr := from/Rows - to/Rows if (p == white && Δr != -1) || (p == black && Δr != 1) { return errors.New("must move forward one row") } Δc := from%Rows - to%Rows capture := h[to] != empty if (capture || Δc != 0) && (!capture || (Δc != 1 && Δc != -1)) { return errors.New("ilegal move") } return nil } type Hexapawn [Rows*Cols + 1]spot func New() Hexapawn { return Hexapawn{ white, white, white, empty, empty, empty, black, black, black, } } func idx(r, c int) int { return r*Cols + c } const stateIdx = Rows * Cols func (h Hexapawn) String() string { var b bytes.Buffer for r := Rows - 1; r >= 0; r-- { for c := 0; c < Cols; c++ { b.WriteByte(h[idx(r, c)].Byte()) } b.WriteByte('\n') } return string(b.Next(Rows*(Cols+1) - 1)) } type spot uint8 const ( empty spot = iota black white ) func (s spot) String() string { switch s { case black: return "Black" case white: return "White" } panic(s) } func (s spot) Byte() byte { switch s { case empty: return '.' case black: return 'B' case white: return 'W' } panic(s) } func (s spot) Other() spot { if s == black { return white } return black }
Maintain the same structure and functionality when rewriting this code in Go.
import sys black_pawn = " \u265f " white_pawn = " \u2659 " empty_square = " " def draw_board(board_data): bg_black = "\u001b[48;5;237m" bg_white = "\u001b[48;5;245m" clear_to_eol = "\u001b[0m\u001b[K\n" board = ["1 ", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black, board_data[0][2], clear_to_eol, "2 ", bg_white, board_data[1][0], bg_black, board_data[1][1], bg_white, board_data[1][2], clear_to_eol, "3 ", bg_black, board_data[2][0], bg_white, board_data[2][1], bg_black, board_data[2][2], clear_to_eol, " A B C\n"]; sys.stdout.write("".join(board)) def get_movement_direction(colour): direction = -1 if colour == black_pawn: direction = 1 elif colour == white_pawn: direction = -1 else: raise ValueError("Invalid piece colour") return direction def get_other_colour(colour): if colour == black_pawn: return white_pawn elif colour == white_pawn: return black_pawn else: raise ValueError("Invalid piece colour") def get_allowed_moves(board_data, row, col): if board_data[row][col] == empty_square: return set() colour = board_data[row][col] other_colour = get_other_colour(colour) direction = get_movement_direction(colour) if (row + direction < 0 or row + direction > 2): return set() allowed_moves = set() if board_data[row + direction][col] == empty_square: allowed_moves.add('f') if col > 0 and board_data[row + direction][col - 1] == other_colour: allowed_moves.add('dl') if col < 2 and board_data[row + direction][col + 1] == other_colour: allowed_moves.add('dr') return allowed_moves def get_human_move(board_data, colour): direction = get_movement_direction(colour) while True: piece_posn = input(f'What {colour} do you want to move? ') valid_inputs = {'a1': (0,0), 'b1': (0,1), 'c1': (0,2), 'a2': (1,0), 'b2': (1,1), 'c2': (1,2), 'a3': (2,0), 'b3': (2,1), 'c3': (2,2)} if piece_posn not in valid_inputs: print("LOL that's not a valid position! Try again.") continue (row, col) = valid_inputs[piece_posn] piece = board_data[row][col] if piece == empty_square: print("What are you trying to pull, there's no piece in that space!") continue if piece != colour: print("LOL that's not your piece, try again!") continue allowed_moves = get_allowed_moves(board_data, row, col) if len(allowed_moves) == 0: print('LOL nice try. That piece has no valid moves.') continue move = list(allowed_moves)[0] if len(allowed_moves) > 1: move = input(f'What move do you want to make ({",".join(list(allowed_moves))})? ') if move not in allowed_moves: print('LOL that move is not allowed. Try again.') continue if move == 'f': board_data[row + direction][col] = board_data[row][col] elif move == 'dl': board_data[row + direction][col - 1] = board_data[row][col] elif move == 'dr': board_data[row + direction][col + 1] = board_data[row][col] board_data[row][col] = empty_square return board_data def is_game_over(board_data): if board_data[0][0] == white_pawn or board_data[0][1] == white_pawn or board_data[0][2] == white_pawn: return white_pawn if board_data[2][0] == black_pawn or board_data[2][1] == black_pawn or board_data[2][2] == black_pawn: return black_pawn white_count = 0 black_count = 0 black_allowed_moves = [] white_allowed_moves = [] for i in range(3): for j in range(3): moves = get_allowed_moves(board_data, i, j) if board_data[i][j] == white_pawn: white_count += 1 if len(moves) > 0: white_allowed_moves.append((i,j,moves)) if board_data[i][j] == black_pawn: black_count += 1 if len(moves) > 0: black_allowed_moves.append((i,j,moves)) if white_count == 0 or len(white_allowed_moves) == 0: return black_pawn if black_count == 0 or len(black_allowed_moves) == 0: return white_pawn return "LOL NOPE" def play_game(black_move, white_move): board_data = [[black_pawn, black_pawn, black_pawn], [empty_square, empty_square, empty_square], [white_pawn, white_pawn, white_pawn]] last_player = black_pawn next_player = white_pawn while is_game_over(board_data) == "LOL NOPE": draw_board(board_data) if (next_player == black_pawn): board_data = black_move(board_data, next_player) else: board_data = white_move(board_data, next_player) temp = last_player last_player = next_player next_player = temp winner = is_game_over(board_data) print(f'Congratulations {winner}!') play_game(get_human_move, get_human_move)
package main import ( "bytes" "errors" "flag" "fmt" "io" "io/ioutil" "log" "math/rand" "os" "time" ) const ( Rows = 3 Cols = 3 ) var vlog *log.Logger func main() { verbose := flag.Bool("v", false, "verbose") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } logOutput := ioutil.Discard if *verbose { logOutput = os.Stderr } vlog = log.New(logOutput, "hexapawn: ", 0) rand.Seed(time.Now().UnixNano()) wins := make(map[spot]int, 2) for { h := New() var s herGameState for c := false; h[stateIdx] == empty; c = !c { if c { h = s.Move(h) } else { h = h.HumanMove() } } fmt.Printf("Board:\n%v is a win for %v\n", h, h[stateIdx]) s.Result(h[stateIdx]) wins[h[stateIdx]]++ fmt.Printf("Wins: Black=%d, White=%d\n", wins[black], wins[white]) fmt.Println() } } func (h Hexapawn) HumanMove() Hexapawn { fmt.Print("Board:\n", h, "\n") var from, to int for { fmt.Print("Your move: ") _, err := fmt.Scanln(&from, &to) if err != nil { fmt.Println(err) if err == io.EOF { os.Exit(0) } continue } if err := h.doMove(white, from-1, to-1); err != nil { fmt.Println(err) continue } return h } } var herNextMove = make(map[Hexapawn][]move) type herGameState struct { h Hexapawn i int } func (s *herGameState) Move(h Hexapawn) Hexapawn { known := false moves := herNextMove[h] if moves == nil { moves = possibleMoves(black, h) herNextMove[h] = moves } else if len(moves) == 0 { vlog.Println("no good moves left to black, picking a random looser") known = true moves = possibleMoves(black, h) } vlog.Println("considering", moves) i := rand.Intn(len(moves)) if !known { s.h = h s.i = i } fmt.Println("Computer moves", moves[i]) if err := h.doMove(black, moves[i].from, moves[i].to); err != nil { panic(err) } return h } func (s herGameState) Result(winner spot) { if winner == black { return } moves := herNextMove[s.h] vlog.Printf("Training:\n%v will no longer do %v\n", s.h, moves[s.i]) herNextMove[s.h] = append(moves[:s.i], moves[s.i+1:]...) vlog.Println("will instead do one of:", herNextMove[s.h]) } type move struct{ from, to int } func (m move) String() string { return fmt.Sprintf("%d→%d", m.from+1, m.to+1) } var cachedMoves = []map[Hexapawn][]move{ black: make(map[Hexapawn][]move), white: make(map[Hexapawn][]move), } func possibleMoves(s spot, h Hexapawn) []move { m := cachedMoves[s][h] if m != nil { return m } m = make([]move, 0) for from := 0; from < Rows*Cols; from++ { for to := 0; to < Rows*Cols; to++ { if err := h.checkMove(s, from, to); err == nil { m = append(m, move{from, to}) } } } cachedMoves[s][h] = m vlog.Printf("caclulated possible moves for %v\n%v as %v\n", s, h, m) return m } func (h *Hexapawn) doMove(p spot, from, to int) error { if err := h.checkMove(p, from, to); err != nil { return err } h[from] = empty h[to] = p if (p == white && to/Rows == Rows-1) || (p == black && to/Rows == 0) { h[stateIdx] = p } else if len(possibleMoves(p.Other(), *h)) == 0 { h[stateIdx] = p } return nil } func (h *Hexapawn) checkMove(p spot, from, to int) error { if h[from] != p { return fmt.Errorf("No %v located at spot %v", p, from+1) } if h[to] == p { return fmt.Errorf("%v already occupies spot %v", p, to+1) } Δr := from/Rows - to/Rows if (p == white && Δr != -1) || (p == black && Δr != 1) { return errors.New("must move forward one row") } Δc := from%Rows - to%Rows capture := h[to] != empty if (capture || Δc != 0) && (!capture || (Δc != 1 && Δc != -1)) { return errors.New("ilegal move") } return nil } type Hexapawn [Rows*Cols + 1]spot func New() Hexapawn { return Hexapawn{ white, white, white, empty, empty, empty, black, black, black, } } func idx(r, c int) int { return r*Cols + c } const stateIdx = Rows * Cols func (h Hexapawn) String() string { var b bytes.Buffer for r := Rows - 1; r >= 0; r-- { for c := 0; c < Cols; c++ { b.WriteByte(h[idx(r, c)].Byte()) } b.WriteByte('\n') } return string(b.Next(Rows*(Cols+1) - 1)) } type spot uint8 const ( empty spot = iota black white ) func (s spot) String() string { switch s { case black: return "Black" case white: return "White" } panic(s) } func (s spot) Byte() byte { switch s { case empty: return '.' case black: return 'B' case white: return 'W' } panic(s) } func (s spot) Other() spot { if s == black { return white } return black }
Translate this program into Go but keep the logic exactly as in Python.
import re from collections import defaultdict from itertools import count connection_re = r class Graph: def __init__(self, name, connections): self.name = name self.connections = connections g = self.graph = defaultdict(list) matches = re.finditer(connection_re, connections, re.MULTILINE | re.VERBOSE) for match in matches: n1, n2, n = match.groups() if n: g[n] += [] else: g[n1].append(n2) g[n2].append(n1) def greedy_colour(self, order=None): "Greedy colourisation algo." if order is None: order = self.graph colour = self.colour = {} neighbours = self.graph for node in order: used_neighbour_colours = (colour[nbr] for nbr in neighbours[node] if nbr in colour) colour[node] = first_avail_int(used_neighbour_colours) self.pp_colours() return colour def pp_colours(self): print(f"\n{self.name}") c = self.colour e = canonical_edges = set() for n1, neighbours in sorted(self.graph.items()): if neighbours: for n2 in neighbours: edge = tuple(sorted([n1, n2])) if edge not in canonical_edges: print(f" {n1}-{n2}: Colour: {c[n1]}, {c[n2]}") canonical_edges.add(edge) else: print(f" {n1}: Colour: {c[n1]}") lc = len(set(c.values())) print(f" def first_avail_int(data): "return lowest int 0... not in data" d = set(data) for i in count(): if i not in d: return i if __name__ == '__main__': for name, connections in [ ('Ex1', "0-1 1-2 2-0 3"), ('Ex2', "1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7"), ('Ex3', "1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6"), ('Ex4', "1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7"), ]: g = Graph(name, connections) g.greedy_colour()
package main import ( "fmt" "sort" ) type graph struct { nn int st int nbr [][]int } type nodeval struct { n int v int } func contains(s []int, n int) bool { for _, e := range s { if e == n { return true } } return false } func newGraph(nn, st int) graph { nbr := make([][]int, nn) return graph{nn, st, nbr} } func (g graph) addEdge(n1, n2 int) { n1, n2 = n1-g.st, n2-g.st g.nbr[n1] = append(g.nbr[n1], n2) if n1 != n2 { g.nbr[n2] = append(g.nbr[n2], n1) } } func (g graph) greedyColoring() []int { cols := make([]int, g.nn) for i := 1; i < g.nn; i++ { cols[i] = -1 } available := make([]bool, g.nn) for i := 1; i < g.nn; i++ { for _, j := range g.nbr[i] { if cols[j] != -1 { available[cols[j]] = true } } c := 0 for ; c < g.nn; c++ { if !available[c] { break } } cols[i] = c for _, j := range g.nbr[i] { if cols[j] != -1 { available[cols[j]] = false } } } return cols } func (g graph) wpColoring() []int { nvs := make([]nodeval, g.nn) for i := 0; i < g.nn; i++ { v := len(g.nbr[i]) if v == 1 && g.nbr[i][0] == i { v = 0 } nvs[i] = nodeval{i, v} } sort.Slice(nvs, func(i, j int) bool { return nvs[i].v > nvs[j].v }) cols := make([]int, g.nn) for i := range cols { cols[i] = -1 } currCol := 0 for f := 0; f < g.nn-1; f++ { h := nvs[f].n if cols[h] != -1 { continue } cols[h] = currCol outer: for i := f + 1; i < g.nn; i++ { j := nvs[i].n if cols[j] != -1 { continue } for k := f; k < i; k++ { l := nvs[k].n if cols[l] == -1 { continue } if contains(g.nbr[j], l) { continue outer } } cols[j] = currCol } currCol++ } return cols } func main() { fns := [](func(graph) []int){graph.greedyColoring, graph.wpColoring} titles := []string{"'Greedy'", "Welsh-Powell"} nns := []int{4, 8, 8, 8} starts := []int{0, 1, 1, 1} edges1 := [][2]int{{0, 1}, {1, 2}, {2, 0}, {3, 3}} edges2 := [][2]int{{1, 6}, {1, 7}, {1, 8}, {2, 5}, {2, 7}, {2, 8}, {3, 5}, {3, 6}, {3, 8}, {4, 5}, {4, 6}, {4, 7}} edges3 := [][2]int{{1, 4}, {1, 6}, {1, 8}, {3, 2}, {3, 6}, {3, 8}, {5, 2}, {5, 4}, {5, 8}, {7, 2}, {7, 4}, {7, 6}} edges4 := [][2]int{{1, 6}, {7, 1}, {8, 1}, {5, 2}, {2, 7}, {2, 8}, {3, 5}, {6, 3}, {3, 8}, {4, 5}, {4, 6}, {4, 7}} for j, fn := range fns { fmt.Println("Using the", titles[j], "algorithm:\n") for i, edges := range [][][2]int{edges1, edges2, edges3, edges4} { fmt.Println(" Example", i+1) g := newGraph(nns[i], starts[i]) for _, e := range edges { g.addEdge(e[0], e[1]) } cols := fn(g) ecount := 0 for _, e := range edges { if e[0] != e[1] { fmt.Printf(" Edge %d-%d -> Color %d, %d\n", e[0], e[1], cols[e[0]-g.st], cols[e[1]-g.st]) ecount++ } else { fmt.Printf(" Node %d -> Color %d\n", e[0], cols[e[0]-g.st]) } } maxCol := 0 for _, col := range cols { if col > maxCol { maxCol = col } } fmt.Println(" Number of nodes  :", nns[i]) fmt.Println(" Number of edges  :", ecount) fmt.Println(" Number of colors :", maxCol+1) fmt.Println() } } }
Write a version of this Python function in Go with identical behavior.
print("working...") print("Primes are:") def isprime(m): for i in range(2,int(m**0.5)+1): if m%i==0: return False return True Primes = [2,43,81,122,63,13,7,95,103] Temp = [] for n in range(len(Primes)): if isprime(Primes[n]): Temp.append(Primes[n]) Temp.sort() print(Temp) print("done...")
package main import ( "fmt" "rcu" "sort" ) func main() { list := []int{2, 43, 81, 122, 63, 13, 7, 95, 103} var primes []int for _, e := range list { if rcu.IsPrime(e) { primes = append(primes, e) } } sort.Ints(primes) fmt.Println(primes) }
Rewrite the snippet below in Go so it works the same as the original Python code.
from itertools import product, compress fact = lambda n: n and n*fact(n - 1) or 1 combo_count = lambda total, coins, perm:\ sum(perm and fact(len(x)) or 1 for x in (list(compress(coins, c)) for c in product(*([(0, 1)]*len(coins)))) if sum(x) == total) cases = [(6, [1, 2, 3, 4, 5]), (6, [1, 1, 2, 3, 3, 4, 5]), (40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100])] for perm in [False, True]: print(f'Order matters: {perm}') for s, c in cases: print(f'{combo_count(s, c, perm):7d} ways for {s:2d} total from coins {c}') print()
package main import "fmt" var cnt = 0 var cnt2 = 0 var wdth = 0 func factorial(n int) int { prod := 1 for i := 2; i <= n; i++ { prod *= i } return prod } func count(want int, used []int, sum int, have, uindices, rindices []int) { if sum == want { cnt++ cnt2 += factorial(len(used)) if cnt < 11 { uindicesStr := fmt.Sprintf("%v", uindices) fmt.Printf(" indices %*s => used %v\n", wdth, uindicesStr, used) } } else if sum < want && len(have) != 0 { thisCoin := have[0] index := rindices[0] rest := have[1:] rindices := rindices[1:] count(want, append(used, thisCoin), sum+thisCoin, rest, append(uindices, index), rindices) count(want, used, sum, rest, uindices, rindices) } } func countCoins(want int, coins []int, width int) { fmt.Printf("Sum %d from coins %v\n", want, coins) cnt = 0 cnt2 = 0 wdth = -width rindices := make([]int, len(coins)) for i := range rindices { rindices[i] = i } count(want, []int{}, 0, coins, []int{}, rindices) if cnt > 10 { fmt.Println(" .......") fmt.Println(" (only the first 10 ways generated are shown)") } fmt.Println("Number of ways - order unimportant :", cnt, "(as above)") fmt.Println("Number of ways - order important  :", cnt2, "(all perms of above indices)\n") } func main() { countCoins(6, []int{1, 2, 3, 4, 5}, 7) countCoins(6, []int{1, 1, 2, 3, 3, 4, 5}, 9) countCoins(40, []int{1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100}, 20) }
Rewrite the snippet below in Go so it works the same as the original Python code.
from itertools import product, compress fact = lambda n: n and n*fact(n - 1) or 1 combo_count = lambda total, coins, perm:\ sum(perm and fact(len(x)) or 1 for x in (list(compress(coins, c)) for c in product(*([(0, 1)]*len(coins)))) if sum(x) == total) cases = [(6, [1, 2, 3, 4, 5]), (6, [1, 1, 2, 3, 3, 4, 5]), (40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100])] for perm in [False, True]: print(f'Order matters: {perm}') for s, c in cases: print(f'{combo_count(s, c, perm):7d} ways for {s:2d} total from coins {c}') print()
package main import "fmt" var cnt = 0 var cnt2 = 0 var wdth = 0 func factorial(n int) int { prod := 1 for i := 2; i <= n; i++ { prod *= i } return prod } func count(want int, used []int, sum int, have, uindices, rindices []int) { if sum == want { cnt++ cnt2 += factorial(len(used)) if cnt < 11 { uindicesStr := fmt.Sprintf("%v", uindices) fmt.Printf(" indices %*s => used %v\n", wdth, uindicesStr, used) } } else if sum < want && len(have) != 0 { thisCoin := have[0] index := rindices[0] rest := have[1:] rindices := rindices[1:] count(want, append(used, thisCoin), sum+thisCoin, rest, append(uindices, index), rindices) count(want, used, sum, rest, uindices, rindices) } } func countCoins(want int, coins []int, width int) { fmt.Printf("Sum %d from coins %v\n", want, coins) cnt = 0 cnt2 = 0 wdth = -width rindices := make([]int, len(coins)) for i := range rindices { rindices[i] = i } count(want, []int{}, 0, coins, []int{}, rindices) if cnt > 10 { fmt.Println(" .......") fmt.Println(" (only the first 10 ways generated are shown)") } fmt.Println("Number of ways - order unimportant :", cnt, "(as above)") fmt.Println("Number of ways - order important  :", cnt2, "(all perms of above indices)\n") } func main() { countCoins(6, []int{1, 2, 3, 4, 5}, 7) countCoins(6, []int{1, 1, 2, 3, 3, 4, 5}, 9) countCoins(40, []int{1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100}, 20) }
Produce a language-to-language conversion: from Python to Go, same semantics.
from functools import reduce from operator import mul from decimal import * getcontext().prec = MAX_PREC def expand(num): suffixes = [ ('greatgross', 7, 12, 3), ('gross', 2, 12, 2), ('dozens', 3, 12, 1), ('pairs', 4, 2, 1), ('scores', 3, 20, 1), ('googols', 6, 10, 100), ('ki', 2, 2, 10), ('mi', 2, 2, 20), ('gi', 2, 2, 30), ('ti', 2, 2, 40), ('pi', 2, 2, 50), ('ei', 2, 2, 60), ('zi', 2, 2, 70), ('yi', 2, 2, 80), ('xi', 2, 2, 90), ('wi', 2, 2, 100), ('vi', 2, 2, 110), ('ui', 2, 2, 120), ('k', 1, 10, 3), ('m', 1, 10, 6), ('g', 1, 10, 9), ('t', 1, 10, 12), ('p', 1, 10, 15), ('e', 1, 10, 18), ('z', 1, 10, 21), ('y', 1, 10, 24), ('x', 1, 10, 27), ('w', 1, 10, 30) ] num = num.replace(',', '').strip().lower() if num[-1].isdigit(): return float(num) for i, char in enumerate(reversed(num)): if char.isdigit(): input_suffix = num[-i:] num = Decimal(num[:-i]) break if input_suffix[0] == '!': return reduce(mul, range(int(num), 0, -len(input_suffix))) while len(input_suffix) > 0: for suffix, min_abbrev, base, power in suffixes: if input_suffix[:min_abbrev] == suffix[:min_abbrev]: for i in range(min_abbrev, len(input_suffix) + 1): if input_suffix[:i+1] != suffix[:i+1]: num *= base ** power input_suffix = input_suffix[i:] break break return num test = "2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre\n\ 1,567 +1.567k 0.1567e-2m\n\ 25.123kK 25.123m 2.5123e-00002G\n\ 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei\n\ -.25123e-34Vikki 2e-77gooGols\n\ 9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!" for test_line in test.split("\n"): test_cases = test_line.split() print("Input:", ' '.join(test_cases)) print("Output:", ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) type minmult struct { min int mult float64 } var abbrevs = map[string]minmult{ "PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12}, "GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100}, } var metric = map[string]float64{ "K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15, "E": 1e18, "Z": 1e21, "Y": 1e24, "X": 1e27, "W": 1e30, "V": 1e33, "U": 1e36, } var binary = map[string]float64{ "Ki": b(10), "Mi": b(20), "Gi": b(30), "Ti": b(40), "Pi": b(50), "Ei": b(60), "Zi": b(70), "Yi": b(80), "Xi": b(90), "Wi": b(100), "Vi": b(110), "Ui": b(120), } func b(e float64) float64 { return math.Pow(2, e) } func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } return g } func fact(num string, d int) int { prod := 1 n, _ := strconv.Atoi(num) for i := n; i > 0; i -= d { prod *= i } return prod } func parse(number string) *big.Float { bf := new(big.Float).SetPrec(500) t1 := new(big.Float).SetPrec(500) t2 := new(big.Float).SetPrec(500) var i int for i = len(number) - 1; i >= 0; i-- { if '0' <= number[i] && number[i] <= '9' { break } } num := number[:i+1] num = strings.Replace(num, ",", "", -1) suf := strings.ToUpper(number[i+1:]) if suf == "" { bf.SetString(num) return bf } if suf[0] == '!' { prod := fact(num, len(suf)) bf.SetInt64(int64(prod)) return bf } for k, v := range abbrevs { kk := strings.ToUpper(k) if strings.HasPrefix(kk, suf) && len(suf) >= v.min { t1.SetString(num) if k != "GOOGOLs" { t2.SetFloat64(v.mult) } else { t2 = googol() } bf.Mul(t1, t2) return bf } } bf.SetString(num) for k, v := range metric { for j := 0; j < len(suf); j++ { if k == suf[j:j+1] { if j < len(suf)-1 && suf[j+1] == 'I' { t1.SetFloat64(binary[k+"i"]) bf.Mul(bf, t1) j++ } else { t1.SetFloat64(v) bf.Mul(bf, t1) } } } } return bf } func commatize(s string) string { if len(s) == 0 { return "" } neg := s[0] == '-' if neg { s = s[1:] } frac := "" if ix := strings.Index(s, "."); ix >= 0 { frac = s[ix:] s = s[:ix] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if !neg { return s + frac } return "-" + s + frac } func process(numbers []string) { fmt.Print("numbers = ") for _, number := range numbers { fmt.Printf("%s ", number) } fmt.Print("\nresults = ") for _, number := range numbers { res := parse(number) t := res.Text('g', 50) fmt.Printf("%s ", commatize(t)) } fmt.Println("\n") } func main() { numbers := []string{"2greatGRo", "24Gros", "288Doz", "1,728pairs", "172.8SCOre"} process(numbers) numbers = []string{"1,567", "+1.567k", "0.1567e-2m"} process(numbers) numbers = []string{"25.123kK", "25.123m", "2.5123e-00002G"} process(numbers) numbers = []string{"25.123kiKI", "25.123Mi", "2.5123e-00002Gi", "+.25123E-7Ei"} process(numbers) numbers = []string{"-.25123e-34Vikki", "2e-77gooGols"} process(numbers) numbers = []string{"9!", "9!!", "9!!!", "9!!!!", "9!!!!!", "9!!!!!!", "9!!!!!!!", "9!!!!!!!!", "9!!!!!!!!!"} process(numbers) }
Preserve the algorithm and functionality while converting the code from Python to Go.
from functools import reduce from operator import mul from decimal import * getcontext().prec = MAX_PREC def expand(num): suffixes = [ ('greatgross', 7, 12, 3), ('gross', 2, 12, 2), ('dozens', 3, 12, 1), ('pairs', 4, 2, 1), ('scores', 3, 20, 1), ('googols', 6, 10, 100), ('ki', 2, 2, 10), ('mi', 2, 2, 20), ('gi', 2, 2, 30), ('ti', 2, 2, 40), ('pi', 2, 2, 50), ('ei', 2, 2, 60), ('zi', 2, 2, 70), ('yi', 2, 2, 80), ('xi', 2, 2, 90), ('wi', 2, 2, 100), ('vi', 2, 2, 110), ('ui', 2, 2, 120), ('k', 1, 10, 3), ('m', 1, 10, 6), ('g', 1, 10, 9), ('t', 1, 10, 12), ('p', 1, 10, 15), ('e', 1, 10, 18), ('z', 1, 10, 21), ('y', 1, 10, 24), ('x', 1, 10, 27), ('w', 1, 10, 30) ] num = num.replace(',', '').strip().lower() if num[-1].isdigit(): return float(num) for i, char in enumerate(reversed(num)): if char.isdigit(): input_suffix = num[-i:] num = Decimal(num[:-i]) break if input_suffix[0] == '!': return reduce(mul, range(int(num), 0, -len(input_suffix))) while len(input_suffix) > 0: for suffix, min_abbrev, base, power in suffixes: if input_suffix[:min_abbrev] == suffix[:min_abbrev]: for i in range(min_abbrev, len(input_suffix) + 1): if input_suffix[:i+1] != suffix[:i+1]: num *= base ** power input_suffix = input_suffix[i:] break break return num test = "2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre\n\ 1,567 +1.567k 0.1567e-2m\n\ 25.123kK 25.123m 2.5123e-00002G\n\ 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei\n\ -.25123e-34Vikki 2e-77gooGols\n\ 9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!" for test_line in test.split("\n"): test_cases = test_line.split() print("Input:", ' '.join(test_cases)) print("Output:", ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) type minmult struct { min int mult float64 } var abbrevs = map[string]minmult{ "PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12}, "GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100}, } var metric = map[string]float64{ "K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15, "E": 1e18, "Z": 1e21, "Y": 1e24, "X": 1e27, "W": 1e30, "V": 1e33, "U": 1e36, } var binary = map[string]float64{ "Ki": b(10), "Mi": b(20), "Gi": b(30), "Ti": b(40), "Pi": b(50), "Ei": b(60), "Zi": b(70), "Yi": b(80), "Xi": b(90), "Wi": b(100), "Vi": b(110), "Ui": b(120), } func b(e float64) float64 { return math.Pow(2, e) } func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } return g } func fact(num string, d int) int { prod := 1 n, _ := strconv.Atoi(num) for i := n; i > 0; i -= d { prod *= i } return prod } func parse(number string) *big.Float { bf := new(big.Float).SetPrec(500) t1 := new(big.Float).SetPrec(500) t2 := new(big.Float).SetPrec(500) var i int for i = len(number) - 1; i >= 0; i-- { if '0' <= number[i] && number[i] <= '9' { break } } num := number[:i+1] num = strings.Replace(num, ",", "", -1) suf := strings.ToUpper(number[i+1:]) if suf == "" { bf.SetString(num) return bf } if suf[0] == '!' { prod := fact(num, len(suf)) bf.SetInt64(int64(prod)) return bf } for k, v := range abbrevs { kk := strings.ToUpper(k) if strings.HasPrefix(kk, suf) && len(suf) >= v.min { t1.SetString(num) if k != "GOOGOLs" { t2.SetFloat64(v.mult) } else { t2 = googol() } bf.Mul(t1, t2) return bf } } bf.SetString(num) for k, v := range metric { for j := 0; j < len(suf); j++ { if k == suf[j:j+1] { if j < len(suf)-1 && suf[j+1] == 'I' { t1.SetFloat64(binary[k+"i"]) bf.Mul(bf, t1) j++ } else { t1.SetFloat64(v) bf.Mul(bf, t1) } } } } return bf } func commatize(s string) string { if len(s) == 0 { return "" } neg := s[0] == '-' if neg { s = s[1:] } frac := "" if ix := strings.Index(s, "."); ix >= 0 { frac = s[ix:] s = s[:ix] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if !neg { return s + frac } return "-" + s + frac } func process(numbers []string) { fmt.Print("numbers = ") for _, number := range numbers { fmt.Printf("%s ", number) } fmt.Print("\nresults = ") for _, number := range numbers { res := parse(number) t := res.Text('g', 50) fmt.Printf("%s ", commatize(t)) } fmt.Println("\n") } func main() { numbers := []string{"2greatGRo", "24Gros", "288Doz", "1,728pairs", "172.8SCOre"} process(numbers) numbers = []string{"1,567", "+1.567k", "0.1567e-2m"} process(numbers) numbers = []string{"25.123kK", "25.123m", "2.5123e-00002G"} process(numbers) numbers = []string{"25.123kiKI", "25.123Mi", "2.5123e-00002Gi", "+.25123E-7Ei"} process(numbers) numbers = []string{"-.25123e-34Vikki", "2e-77gooGols"} process(numbers) numbers = []string{"9!", "9!!", "9!!!", "9!!!!", "9!!!!!", "9!!!!!!", "9!!!!!!!", "9!!!!!!!!", "9!!!!!!!!!"} process(numbers) }
Transform the following Python implementation into Go, maintaining the same output and logic.
import math def apply_perm(omega,fbn): for m in range(len(fbn)): g = fbn[m] if g > 0: new_first = omega[m+g] omega[m+1:m+g+1] = omega[m:m+g] omega[m] = new_first return omega def int_to_fbn(i): current = i divisor = 2 new_fbn = [] while current > 0: remainder = current % divisor current = current // divisor new_fbn.append(remainder) divisor += 1 return list(reversed(new_fbn)) def leading_zeros(l,n): if len(l) < n: return(([0] * (n - len(l))) + l) else: return l def get_fbn(n): max = math.factorial(n) for i in range(max): current = i divisor = 1 new_fbn = int_to_fbn(i) yield leading_zeros(new_fbn,n-1) def print_write(f, line): print(line) f.write(str(line)+'\n') def dot_format(l): if len(l) < 1: return "" dot_string = str(l[0]) for e in l[1:]: dot_string += "."+str(e) return dot_string def str_format(l): if len(l) < 1: return "" new_string = "" for e in l: new_string += str(e) return new_string with open("output.html", "w", encoding="utf-8") as f: f.write("<pre>\n") omega=[0,1,2,3] four_list = get_fbn(4) for l in four_list: print_write(f,dot_format(l)+' -> '+str_format(apply_perm(omega[:],l))) print_write(f," ") num_permutations = 0 for p in get_fbn(11): num_permutations += 1 if num_permutations % 1000000 == 0: print_write(f,"permutations so far = "+str(num_permutations)) print_write(f," ") print_write(f,"Permutations generated = "+str(num_permutations)) print_write(f,"compared to 11! which = "+str(math.factorial(11))) print_write(f," ") shoe = [] for suit in [u"\u2660",u"\u2665",u"\u2666",u"\u2663"]: for value in ['A','K','Q','J','10','9','8','7','6','5','4','3','2']: shoe.append(value+suit) print_write(f,str_format(shoe)) p1 = [39,49,7,47,29,30,2,12,10,3,29,37,33,17,12,31,29,34,17,25,2,4,25,4,1,14,20,6,21,18,1,1,1,4,0,5,15,12,4,3,10,10,9,1,6,5,5,3,0,0,0] p2 = [51,48,16,22,3,0,19,34,29,1,36,30,12,32,12,29,30,26,14,21,8,12,1,3,10,4,7,17,6,21,8,12,15,15,13,15,7,3,12,11,9,5,5,6,6,3,4,0,3,2,1] print_write(f," ") print_write(f,dot_format(p1)) print_write(f," ") print_write(f,str_format(apply_perm(shoe[:],p1))) print_write(f," ") print_write(f,dot_format(p2)) print_write(f," ") print_write(f,str_format(apply_perm(shoe[:],p2))) import random max = math.factorial(52) random_int = random.randint(0, max-1) myperm = leading_zeros(int_to_fbn(random_int),51) print(len(myperm)) print_write(f," ") print_write(f,dot_format(myperm)) print_write(f," ") print_write(f,str_format(apply_perm(shoe[:],myperm))) f.write("</pre>\n")
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func genFactBaseNums(size int, countOnly bool) ([][]int, int) { var results [][]int count := 0 for n := 0; ; n++ { radix := 2 var res []int = nil if !countOnly { res = make([]int, size) } k := n for k > 0 { div := k / radix rem := k % radix if !countOnly { if radix <= size+1 { res[size-radix+1] = rem } } k = div radix++ } if radix > size+2 { break } count++ if !countOnly { results = append(results, res) } } return results, count } func mapToPerms(factNums [][]int) [][]int { var perms [][]int psize := len(factNums[0]) + 1 start := make([]int, psize) for i := 0; i < psize; i++ { start[i] = i } for _, fn := range factNums { perm := make([]int, psize) copy(perm, start) for m := 0; m < len(fn); m++ { g := fn[m] if g == 0 { continue } first := m last := m + g for i := 1; i <= g; i++ { temp := perm[first] for j := first + 1; j <= last; j++ { perm[j-1] = perm[j] } perm[last] = temp } } perms = append(perms, perm) } return perms } func join(is []int, sep string) string { ss := make([]string, len(is)) for i := 0; i < len(is); i++ { ss[i] = strconv.Itoa(is[i]) } return strings.Join(ss, sep) } func undot(s string) []int { ss := strings.Split(s, ".") is := make([]int, len(ss)) for i := 0; i < len(ss); i++ { is[i], _ = strconv.Atoi(ss[i]) } return is } func main() { rand.Seed(time.Now().UnixNano()) factNums, _ := genFactBaseNums(3, false) perms := mapToPerms(factNums) for i, fn := range factNums { fmt.Printf("%v -> %v\n", join(fn, "."), join(perms[i], "")) } _, count := genFactBaseNums(10, true) fmt.Println("\nPermutations generated =", count) fmt.Println("compared to 11! which =", factorial(11)) fmt.Println() fbn51s := []string{ "39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0", "51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1", } factNums = [][]int{undot(fbn51s[0]), undot(fbn51s[1])} perms = mapToPerms(factNums) shoe := []rune("A♠K♠Q♠J♠T♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥T♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦T♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣T♣9♣8♣7♣6♣5♣4♣3♣2♣") cards := make([]string, 52) for i := 0; i < 52; i++ { cards[i] = string(shoe[2*i : 2*i+2]) if cards[i][0] == 'T' { cards[i] = "10" + cards[i][1:] } } for i, fbn51 := range fbn51s { fmt.Println(fbn51) for _, d := range perms[i] { fmt.Print(cards[d]) } fmt.Println("\n") } fbn51 := make([]int, 51) for i := 0; i < 51; i++ { fbn51[i] = rand.Intn(52 - i) } fmt.Println(join(fbn51, ".")) perms = mapToPerms([][]int{fbn51}) for _, d := range perms[0] { fmt.Print(cards[d]) } fmt.Println() }