Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
import matplotlib.pyplot as plt from math import sin, cos, pi def sgn(x): return ((x>0)-(x<0))*1 a,b,n=200,200,2.5 na=2/n step=100 piece=(pi*2)/step xp=[];yp=[] t=0 for t1 in range(step+1): x=(abs((cos(t)))**na)*a*sgn(cos(t)) y=(abs((sin(t)))**na)*b*sgn(sin(t)) xp.append(x);yp.append(y) t+=piece plt.plot(xp,yp) plt.title("Superellipse with parameter "+str(n)) plt.show()
package main import ( "github.com/fogleman/gg" "math" ) func superEllipse(dc *gg.Context, n float64, a int) { hw := float64(dc.Width() / 2) hh := float64(dc.Height() / 2) y := make([]float64, a+1) for x := 0; x <= a; x++ { aa := math.Pow(float64(a), n) xx := math.Pow(float64(x), n) y[x] = math.Pow(aa-xx, 1.0/n) } for x := a; x >= 0; x-- { dc.LineTo(hw+float64(x), hh-y[x]) } for x := 0; x <= a; x++ { dc.LineTo(hw+float64(x), hh+y[x]) } for x := a; x >= 0; x-- { dc.LineTo(hw-float64(x), hh+y[x]) } for x := 0; x <= a; x++ { dc.LineTo(hw-float64(x), hh-y[x]) } dc.SetRGB(1, 1, 1) dc.Fill() } func main() { dc := gg.NewContext(500, 500) dc.SetRGB(0, 0, 0) dc.Clear() superEllipse(dc, 2.5, 200) dc.SavePNG("superellipse.png") }
Please provide an equivalent version of this Python code in Go.
from math import factorial as fact from random import randrange from textwrap import wrap def identity_perm(n): return list(range(n)) def unranker1(n, r, pi): while n > 0: n1, (rdivn, rmodn) = n-1, divmod(r, n) pi[n1], pi[rmodn] = pi[rmodn], pi[n1] n = n1 r = rdivn return pi def init_pi1(n, pi): pi1 = [-1] * n for i in range(n): pi1[pi[i]] = i return pi1 def ranker1(n, pi, pi1): if n == 1: return 0 n1 = n-1 s = pi[n1] pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1] pi1[s], pi1[n1] = pi1[n1], pi1[s] return s + n * ranker1(n1, pi, pi1) def unranker2(n, r, pi): while n > 0: n1 = n-1 s, rmodf = divmod(r, fact(n1)) pi[n1], pi[s] = pi[s], pi[n1] n = n1 r = rmodf return pi def ranker2(n, pi, pi1): if n == 1: return 0 n1 = n-1 s = pi[n1] pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1] pi1[s], pi1[n1] = pi1[n1], pi1[s] return s * fact(n1) + ranker2(n1, pi, pi1) def get_random_ranks(permsize, samplesize): perms = fact(permsize) ranks = set() while len(ranks) < samplesize: ranks |= set( randrange(perms) for r in range(samplesize - len(ranks)) ) return ranks def test1(comment, unranker, ranker): n, samplesize, n2 = 3, 4, 12 print(comment) perms = [] for r in range(fact(n)): pi = identity_perm(n) perm = unranker(n, r, pi) perms.append((r, perm)) for r, pi in perms: pi1 = init_pi1(n, pi) print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1))) print('\n %i random individual samples of %i items:' % (samplesize, n2)) for r in get_random_ranks(n2, samplesize): pi = identity_perm(n2) print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi))) print('') def test2(comment, unranker): samplesize, n2 = 4, 144 print(comment) print(' %i random individual samples of %i items:' % (samplesize, n2)) for r in get_random_ranks(n2, samplesize): pi = identity_perm(n2) print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi))))) print('') if __name__ == '__main__': test1('First ordering:', unranker1, ranker1) test1('Second ordering:', unranker2, ranker2) test2('First ordering, large number of perms:', unranker1)
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } return p } func MRRank(p []int) (r int) { p = append([]int{}, p...) inv := inverse(p) for i := len(p) - 1; i > 0; i-- { s := p[i] p[inv[i]] = s inv[s] = inv[i] } for i := 1; i < len(p); i++ { r = r*(i+1) + p[i] } return } func inverse(p []int) []int { r := make([]int, len(p)) for i, x := range p { r[x] = i } return r } func fact(n int) (f int) { for f = n; n > 2; { n-- f *= n } return } func main() { n := 3 fmt.Println("permutations of", n, "items") f := fact(n) for i := 0; i < f; i++ { p := MRPerm(i, n) fmt.Println(i, p, MRRank(p)) } n = 12 fmt.Println("permutations of", n, "items") f = fact(n) m := map[int]bool{} for len(m) < 4 { r := rand.Intn(f) if m[r] { continue } m[r] = true fmt.Println(r, MRPerm(r, n)) } }
Translate this program into Go but keep the logic exactly as in Python.
from math import factorial as fact from random import randrange from textwrap import wrap def identity_perm(n): return list(range(n)) def unranker1(n, r, pi): while n > 0: n1, (rdivn, rmodn) = n-1, divmod(r, n) pi[n1], pi[rmodn] = pi[rmodn], pi[n1] n = n1 r = rdivn return pi def init_pi1(n, pi): pi1 = [-1] * n for i in range(n): pi1[pi[i]] = i return pi1 def ranker1(n, pi, pi1): if n == 1: return 0 n1 = n-1 s = pi[n1] pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1] pi1[s], pi1[n1] = pi1[n1], pi1[s] return s + n * ranker1(n1, pi, pi1) def unranker2(n, r, pi): while n > 0: n1 = n-1 s, rmodf = divmod(r, fact(n1)) pi[n1], pi[s] = pi[s], pi[n1] n = n1 r = rmodf return pi def ranker2(n, pi, pi1): if n == 1: return 0 n1 = n-1 s = pi[n1] pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1] pi1[s], pi1[n1] = pi1[n1], pi1[s] return s * fact(n1) + ranker2(n1, pi, pi1) def get_random_ranks(permsize, samplesize): perms = fact(permsize) ranks = set() while len(ranks) < samplesize: ranks |= set( randrange(perms) for r in range(samplesize - len(ranks)) ) return ranks def test1(comment, unranker, ranker): n, samplesize, n2 = 3, 4, 12 print(comment) perms = [] for r in range(fact(n)): pi = identity_perm(n) perm = unranker(n, r, pi) perms.append((r, perm)) for r, pi in perms: pi1 = init_pi1(n, pi) print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1))) print('\n %i random individual samples of %i items:' % (samplesize, n2)) for r in get_random_ranks(n2, samplesize): pi = identity_perm(n2) print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi))) print('') def test2(comment, unranker): samplesize, n2 = 4, 144 print(comment) print(' %i random individual samples of %i items:' % (samplesize, n2)) for r in get_random_ranks(n2, samplesize): pi = identity_perm(n2) print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi))))) print('') if __name__ == '__main__': test1('First ordering:', unranker1, ranker1) test1('Second ordering:', unranker2, ranker2) test2('First ordering, large number of perms:', unranker1)
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } return p } func MRRank(p []int) (r int) { p = append([]int{}, p...) inv := inverse(p) for i := len(p) - 1; i > 0; i-- { s := p[i] p[inv[i]] = s inv[s] = inv[i] } for i := 1; i < len(p); i++ { r = r*(i+1) + p[i] } return } func inverse(p []int) []int { r := make([]int, len(p)) for i, x := range p { r[x] = i } return r } func fact(n int) (f int) { for f = n; n > 2; { n-- f *= n } return } func main() { n := 3 fmt.Println("permutations of", n, "items") f := fact(n) for i := 0; i < f; i++ { p := MRPerm(i, n) fmt.Println(i, p, MRRank(p)) } n = 12 fmt.Println("permutations of", n, "items") f = fact(n) m := map[int]bool{} for len(m) < 4 { r := rand.Intn(f) if m[r] { continue } m[r] = true fmt.Println(r, MRPerm(r, n)) } }
Keep all operations the same but rewrite the snippet in Go.
def main(): resources = int(input("Cantidad de recursos: ")) processes = int(input("Cantidad de procesos: ")) max_resources = [int(i) for i in input("Recursos máximos: ").split()] print("\n-- recursos asignados para cada proceso --") currently_allocated = [[int(i) for i in input(f"proceso {j + 1}: ").split()] for j in range(processes)] print("\n--- recursos máximos para cada proceso ---") max_need = [[int(i) for i in input(f"proceso {j + 1}: ").split()] for j in range(processes)] allocated = [0] * resources for i in range(processes): for j in range(resources): allocated[j] += currently_allocated[i][j] print(f"\nRecursos totales asignados  : {allocated}") available = [max_resources[i] - allocated[i] for i in range(resources)] print(f"Recursos totales disponibles: {available}\n") running = [True] * processes count = processes while count != 0: safe = False for i in range(processes): if running[i]: executing = True for j in range(resources): if max_need[i][j] - currently_allocated[i][j] > available[j]: executing = False break if executing: print(f"proceso {i + 1} ejecutándose") running[i] = False count -= 1 safe = True for j in range(resources): available[j] += currently_allocated[i][j] break if not safe: print("El proceso está en un estado inseguro.") break print(f"El proceso está en un estado seguro.\nRecursos disponibles: {available}\n") if __name__ == '__main__': main()
package bank import ( "bytes" "errors" "fmt" "log" "sort" "sync" ) type PID string type RID string type RMap map[RID]int func (m RMap) String() string { rs := make([]string, len(m)) i := 0 for r := range m { rs[i] = string(r) i++ } sort.Strings(rs) var b bytes.Buffer b.WriteString("{") for _, r := range rs { fmt.Fprintf(&b, "%q: %d, ", r, m[RID(r)]) } bb := b.Bytes() if len(bb) > 1 { bb[len(bb)-2] = '}' } return string(bb) } type Bank struct { available RMap max map[PID]RMap allocation map[PID]RMap sync.Mutex } func (b *Bank) need(p PID, r RID) int { return b.max[p][r] - b.allocation[p][r] } func New(available RMap) (b *Bank, err error) { for r, a := range available { if a < 0 { return nil, fmt.Errorf("negative resource %s: %d", r, a) } } return &Bank{ available: available, max: map[PID]RMap{}, allocation: map[PID]RMap{}, }, nil } func (b *Bank) NewProcess(p PID, max RMap) (err error) { b.Lock() defer b.Unlock() if _, ok := b.max[p]; ok { return fmt.Errorf("process %s already registered", p) } for r, m := range max { switch a, ok := b.available[r]; { case !ok: return fmt.Errorf("resource %s unknown", r) case m > a: return fmt.Errorf("resource %s: process %s max %d > available %d", r, p, m, a) } } b.max[p] = max b.allocation[p] = RMap{} return } func (b *Bank) Request(pid PID, change RMap) (err error) { b.Lock() defer b.Unlock() if _, ok := b.max[pid]; !ok { return fmt.Errorf("process %s unknown", pid) } for r, c := range change { if c < 0 { return errors.New("decrease not allowed") } if _, ok := b.available[r]; !ok { return fmt.Errorf("resource %s unknown", r) } if c > b.need(pid, r) { return errors.New("increase exceeds declared max") } } for r, c := range change { b.allocation[pid][r] += c } defer func() { if err != nil { for r, c := range change { b.allocation[pid][r] -= c } } }() cash := RMap{} for r, a := range b.available { cash[r] = a } perm := make([]PID, len(b.allocation)) i := 1 for pr, a := range b.allocation { if pr == pid { perm[0] = pr } else { perm[i] = pr i++ } for r, a := range a { cash[r] -= a } } ret := RMap{} m := len(perm) for { h := 0 h: for ; ; h++ { if h == m { return errors.New("request would make deadlock possible") } for r := range b.available { if b.need(perm[h], r) > cash[r]+ret[r] { continue h } } log.Println(" ", perm[h], "could terminate") break } if h == 0 { return nil } for r, a := range b.allocation[perm[h]] { ret[r] += a } m-- perm[h] = perm[m] } }
Write a version of this Python function in Go with identical behavior.
def range_extract(lst): 'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints' lenlst = len(lst) i = 0 while i< lenlst: low = lst[i] while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1 hi = lst[i] if hi - low >= 2: yield (low, hi) elif hi - low == 1: yield (low,) yield (hi,) else: yield (low,) i += 1 def printr(ranges): print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r) for r in ranges ) ) if __name__ == '__main__': for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20], [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]: printr(range_extract(lst))
package main import ( "errors" "fmt" "strconv" "strings" ) func main() { rf, err := rangeFormat([]int{ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, }) if err != nil { fmt.Println(err) return } fmt.Println("range format:", rf) } func rangeFormat(a []int) (string, error) { if len(a) == 0 { return "", nil } var parts []string for n1 := 0; ; { n2 := n1 + 1 for n2 < len(a) && a[n2] == a[n2-1]+1 { n2++ } s := strconv.Itoa(a[n1]) if n2 == n1+2 { s += "," + strconv.Itoa(a[n2-1]) } else if n2 > n1+2 { s += "-" + strconv.Itoa(a[n2-1]) } parts = append(parts, s) if n2 == len(a) { break } if a[n2] == a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence repeats value %d", a[n2])) } if a[n2] < a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence not ordered: %d < %d", a[n2], a[n2-1])) } n1 = n2 } return strings.Join(parts, ","), nil }
Generate a Go translation of this Python snippet without changing its computational steps.
import ctypes import os from ctypes import c_ubyte, c_int code = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3]) code_size = len(code) if (os.name == 'posix'): import mmap executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC) executable_map.write(code) func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map)) elif (os.name == 'nt'): code_buffer = ctypes.create_string_buffer(code) PAGE_EXECUTE_READWRITE = 0x40 MEM_COMMIT = 0x1000 executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE) if (executable_buffer_address == 0): print('Warning: Failed to enable code execution, call will likely cause a protection fault.') func_address = ctypes.addressof(code_buffer) else: ctypes.memmove(executable_buffer_address, code_buffer, code_size) func_address = executable_buffer_address else: code_buffer = ctypes.create_string_buffer(code) func_address = ctypes.addressof(code_buffer) prototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte) func = prototype(func_address) res = func(7,12) print(res)
package main import "fmt" import "C" func main() { code := []byte{ 0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d, 0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75, 0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75, 0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3, } le := len(code) buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC, C.MAP_PRIVATE|C.MAP_ANON, -1, 0) codePtr := C.CBytes(code) C.memcpy(buf, codePtr, C.size_t(le)) var a, b byte = 7, 12 fmt.Printf("%d + %d = ", a, b) C.runMachineCode(buf, C.byte(a), C.byte(b)) C.munmap(buf, C.size_t(le)) C.free(codePtr) }
Please provide an equivalent version of this Python code in Go.
fun maxpathsum(t): let a = val t for i in a.length-1..-1..1, c in linearindices a[r]: a[r, c] += max(a[r+1, c], a[r=1, c+1]) return a[1, 1] let test = [ [55], [94, 48], [95, 30, 96], [77, 71, 26, 67], [97, 13, 76, 38, 45], [07, 36, 79, 16, 37, 68], [48, 07, 09, 18, 70, 26, 06], [18, 72, 79, 46, 59, 79, 29, 90], [20, 76, 87, 11, 32, 07, 07, 49, 18], [27, 83, 58, 35, 71, 11, 25, 57, 29, 85], [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55], [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23], [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42], [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72], [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36], [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52], [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15], [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93] ] @print maxpathsum test
package main import ( "fmt" "strconv" "strings" ) const t = ` 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93` func main() { lines := strings.Split(t, "\n") f := strings.Fields(lines[len(lines)-1]) d := make([]int, len(f)) var err error for i, s := range f { if d[i], err = strconv.Atoi(s); err != nil { panic(err) } } d1 := d[1:] var l, r, u int for row := len(lines) - 2; row >= 0; row-- { l = d[0] for i, s := range strings.Fields(lines[row]) { if u, err = strconv.Atoi(s); err != nil { panic(err) } if r = d1[i]; l > r { d[i] = u + l } else { d[i] = u + r } l = r } } fmt.Println(d[0]) }
Please provide an equivalent version of this Python code in Go.
beforeTxt = smallrc01 = rc01 = def intarray(binstring): return [[1 if ch == '1' else 0 for ch in line] for line in binstring.strip().split()] def chararray(intmatrix): return '\n'.join(''.join(str(p) for p in row) for row in intmatrix) def toTxt(intmatrix): Return 8-neighbours of point p1 of picture, in order''' i = image x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1 return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1], i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]] def transitions(neighbours): n = neighbours + neighbours[0:1] return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:])) def zhangSuen(image): changing1 = changing2 = [(-1, -1)] while changing1 or changing2: changing1 = [] for y in range(1, len(image) - 1): for x in range(1, len(image[0]) - 1): P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image) if (image[y][x] == 1 and P4 * P6 * P8 == 0 and P2 * P4 * P6 == 0 and transitions(n) == 1 and 2 <= sum(n) <= 6): changing1.append((x,y)) for x, y in changing1: image[y][x] = 0 changing2 = [] for y in range(1, len(image) - 1): for x in range(1, len(image[0]) - 1): P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image) if (image[y][x] == 1 and P2 * P6 * P8 == 0 and P2 * P4 * P8 == 0 and transitions(n) == 1 and 2 <= sum(n) <= 6): changing2.append((x,y)) for x, y in changing2: image[y][x] = 0 return image if __name__ == '__main__': for picture in (beforeTxt, smallrc01, rc01): image = intarray(picture) print('\nFrom:\n%s' % toTxt(image)) after = zhangSuen(image) print('\nTo thinned:\n%s' % toTxt(after))
package main import ( "bytes" "fmt" "strings" ) var in = ` 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000` func main() { b := wbFromString(in, '1') b.zhangSuen() fmt.Println(b) } const ( white = 0 black = 1 ) type wbArray [][]byte func wbFromString(s string, blk byte) wbArray { lines := strings.Split(s, "\n")[1:] b := make(wbArray, len(lines)) for i, sl := range lines { bl := make([]byte, len(sl)) for j := 0; j < len(sl); j++ { bl[j] = sl[j] & 1 } b[i] = bl } return b } var sym = [2]byte{ white: ' ', black: '#', } func (b wbArray) String() string { b2 := bytes.Join(b, []byte{'\n'}) for i, b1 := range b2 { if b1 > 1 { continue } b2[i] = sym[b1] } return string(b2) } var nb = [...][2]int{ 2: {-1, 0}, 3: {-1, 1}, 4: {0, 1}, 5: {1, 1}, 6: {1, 0}, 7: {1, -1}, 8: {0, -1}, 9: {-1, -1}, } func (b wbArray) reset(en []int) (rs bool) { var r, c int var p [10]byte readP := func() { for nx := 1; nx <= 9; nx++ { n := nb[nx] p[nx] = b[r+n[0]][c+n[1]] } } shiftRead := func() { n := nb[3] p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]] n = nb[4] p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]] n = nb[5] p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]] } countA := func() (ct byte) { bit := p[9] for nx := 2; nx <= 9; nx++ { last := bit bit = p[nx] if last == white { ct += bit } } return ct } countB := func() (ct byte) { for nx := 2; nx <= 9; nx++ { ct += p[nx] } return ct } lastRow := len(b) - 1 lastCol := len(b[0]) - 1 mark := make([][]bool, lastRow) for r = range mark { mark[r] = make([]bool, lastCol) } for r = 1; r < lastRow; r++ { c = 1 readP() for { m := false if !(p[1] == black) { goto markDone } if b1 := countB(); !(2 <= b1 && b1 <= 6) { goto markDone } if !(countA() == 1) { goto markDone } { e1, e2 := p[en[1]], p[en[2]] if !(p[en[0]]&e1&e2 == 0) { goto markDone } if !(e1&e2&p[en[3]] == 0) { goto markDone } } m = true rs = true markDone: mark[r][c] = m c++ if c == lastCol { break } shiftRead() } } if rs { for r = 1; r < lastRow; r++ { for c = 1; c < lastCol; c++ { if mark[r][c] { b[r][c] = white } } } } return rs } var step1 = []int{2, 4, 6, 8} var step2 = []int{4, 2, 8, 6} func (b wbArray) zhangSuen() { for { rs1 := b.reset(step1) rs2 := b.reset(step2) if !rs1 && !rs2 { break } } }
Write the same algorithm in Go as shown in this Python implementation.
import Image, ImageFilter im = Image.open('image.ppm') median = im.filter(ImageFilter.MedianFilter(3)) median.save('image2.ppm')
package main import ( "fmt" "raster" ) var g0, g1 *raster.Grmap var ko [][]int var kc []uint16 var mid int func init() { ko = [][]int{ {-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {0, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}} kc = make([]uint16, len(ko)) mid = len(ko) / 2 } func main() { b, err := raster.ReadPpmFile("Lenna50.ppm") if err != nil { fmt.Println(err) return } g0 = b.Grmap() w, h := g0.Extent() g1 = raster.NewGrmap(w, h) for y := 0; y < h; y++ { for x := 0; x < w; x++ { g1.SetPx(x, y, median(x, y)) } } err = g1.Bitmap().WritePpmFile("median.ppm") if err != nil { fmt.Println(err) } } func median(x, y int) uint16 { var n int for _, o := range ko { c, ok := g0.GetPx(x+o[0], y+o[1]) if !ok { continue } var i int for ; i < n; i++ { if c < kc[i] { for j := n; j > i; j-- { kc[j] = kc[j-1] } break } } kc[i] = c n++ } switch { case n == len(kc): return kc[mid] case n%2 == 1: return kc[n/2] } m := n / 2 return (kc[m-1] + kc[m]) / 2 }
Write the same algorithm in Go as shown in this Python implementation.
import Image, ImageFilter im = Image.open('image.ppm') median = im.filter(ImageFilter.MedianFilter(3)) median.save('image2.ppm')
package main import ( "fmt" "raster" ) var g0, g1 *raster.Grmap var ko [][]int var kc []uint16 var mid int func init() { ko = [][]int{ {-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {0, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}} kc = make([]uint16, len(ko)) mid = len(ko) / 2 } func main() { b, err := raster.ReadPpmFile("Lenna50.ppm") if err != nil { fmt.Println(err) return } g0 = b.Grmap() w, h := g0.Extent() g1 = raster.NewGrmap(w, h) for y := 0; y < h; y++ { for x := 0; x < w; x++ { g1.SetPx(x, y, median(x, y)) } } err = g1.Bitmap().WritePpmFile("median.ppm") if err != nil { fmt.Println(err) } } func median(x, y int) uint16 { var n int for _, o := range ko { c, ok := g0.GetPx(x+o[0], y+o[1]) if !ok { continue } var i int for ; i < n; i++ { if c < kc[i] { for j := n; j > i; j-- { kc[j] = kc[j-1] } break } } kc[i] = c n++ } switch { case n == len(kc): return kc[mid] case n%2 == 1: return kc[n/2] } m := n / 2 return (kc[m-1] + kc[m]) / 2 }
Translate this program into Go but keep the logic exactly as in Python.
import posix import os import sys pid = posix.fork() if pid != 0: print("Child process detached with pid %s" % pid) sys.exit(0) old_stdin = sys.stdin old_stdout = sys.stdout old_stderr = sys.stderr sys.stdin = open('/dev/null', 'rt') sys.stdout = open('/tmp/dmn.log', 'wt') sys.stderr = sys.stdout old_stdin.close() old_stdout.close() old_stderr.close() posix.setsid() import time t = time.time() while time.time() < t + 10: print("timer running, %s seconds" % str(time.time() - t)) time.sleep(1)
package main import ( "fmt" "github.com/sevlyar/go-daemon" "log" "os" "time" ) func work() { f, err := os.Create("daemon_output.txt") if err != nil { log.Fatal(err) } defer f.Close() ticker := time.NewTicker(time.Second) go func() { for t := range ticker.C { fmt.Fprintln(f, t) } }() time.Sleep(60 * time.Second) ticker.Stop() log.Print("ticker stopped") } func main() { cntxt := &daemon.Context{ PidFileName: "pid", PidFilePerm: 0644, LogFileName: "log", LogFilePerm: 0640, WorkDir: "./", Umask: 027, Args: []string{"[Rosetta Code daemon example]"}, } d, err := cntxt.Reborn() if err != nil { log.Fatal("Unable to run: ", err) } if d != nil { return } defer cntxt.Release() log.Print("- - - - - - - - - - - - - - -") log.Print("daemon started") work() }
Rewrite the snippet below in Go so it works the same as the original Python code.
import posix import os import sys pid = posix.fork() if pid != 0: print("Child process detached with pid %s" % pid) sys.exit(0) old_stdin = sys.stdin old_stdout = sys.stdout old_stderr = sys.stderr sys.stdin = open('/dev/null', 'rt') sys.stdout = open('/tmp/dmn.log', 'wt') sys.stderr = sys.stdout old_stdin.close() old_stdout.close() old_stderr.close() posix.setsid() import time t = time.time() while time.time() < t + 10: print("timer running, %s seconds" % str(time.time() - t)) time.sleep(1)
package main import ( "fmt" "github.com/sevlyar/go-daemon" "log" "os" "time" ) func work() { f, err := os.Create("daemon_output.txt") if err != nil { log.Fatal(err) } defer f.Close() ticker := time.NewTicker(time.Second) go func() { for t := range ticker.C { fmt.Fprintln(f, t) } }() time.Sleep(60 * time.Second) ticker.Stop() log.Print("ticker stopped") } func main() { cntxt := &daemon.Context{ PidFileName: "pid", PidFilePerm: 0644, LogFileName: "log", LogFilePerm: 0640, WorkDir: "./", Umask: 027, Args: []string{"[Rosetta Code daemon example]"}, } d, err := cntxt.Reborn() if err != nil { log.Fatal("Unable to run: ", err) } if d != nil { return } defer cntxt.Release() log.Print("- - - - - - - - - - - - - - -") log.Print("daemon started") work() }
Change the programming language of this snippet from Python to Go without modifying what it does.
def Gcd(v1, v2): a, b = v1, v2 if (a < b): a, b = v2, v1 r = 1 while (r != 0): r = a % b if (r != 0): a = b b = r return b a = [1, 2] n = 3 while (n < 50): gcd1 = Gcd(n, a[-1]) gcd2 = Gcd(n, a[-2]) if (gcd1 == 1 and gcd2 == 1 and not(n in a)): a.append(n) n = 3 else: n += 1 for i in range(0, len(a)): if (i % 10 == 0): print('') print("%4d" % a[i], end = ''); print("\n\nNumber of elements in coprime triplets = " + str(len(a)), end = "\n")
package main import ( "fmt" "rcu" ) func contains(a []int, v int) bool { for _, e := range a { if e == v { return true } } return false } func main() { const limit = 50 cpt := []int{1, 2} for { m := 1 l := len(cpt) for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 { m++ } if m >= limit { break } cpt = append(cpt, m) } fmt.Printf("Coprime triplets under %d:\n", limit) for i, t := range cpt { fmt.Printf("%2d ", t) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n\nFound %d such numbers\n", len(cpt)) }
Maintain the same structure and functionality when rewriting this code in Go.
def Gcd(v1, v2): a, b = v1, v2 if (a < b): a, b = v2, v1 r = 1 while (r != 0): r = a % b if (r != 0): a = b b = r return b a = [1, 2] n = 3 while (n < 50): gcd1 = Gcd(n, a[-1]) gcd2 = Gcd(n, a[-2]) if (gcd1 == 1 and gcd2 == 1 and not(n in a)): a.append(n) n = 3 else: n += 1 for i in range(0, len(a)): if (i % 10 == 0): print('') print("%4d" % a[i], end = ''); print("\n\nNumber of elements in coprime triplets = " + str(len(a)), end = "\n")
package main import ( "fmt" "rcu" ) func contains(a []int, v int) bool { for _, e := range a { if e == v { return true } } return false } func main() { const limit = 50 cpt := []int{1, 2} for { m := 1 l := len(cpt) for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 { m++ } if m >= limit { break } cpt = append(cpt, m) } fmt.Printf("Coprime triplets under %d:\n", limit) for i, t := range cpt { fmt.Printf("%2d ", t) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n\nFound %d such numbers\n", len(cpt)) }
Change the programming language of this snippet from Python to Go without modifying what it does.
s = [1, 2, 2, 3, 4, 4, 5] for i in range(len(s)): curr = s[i] if i > 0 and curr == prev: print(i) prev = curr
package main import "fmt" func main() { s := []int{1, 2, 2, 3, 4, 4, 5} for i := 0; i < len(s); i++ { curr := s[i] var prev int if i > 0 && curr == prev { fmt.Println(i) } prev = curr } var prev int for i := 0; i < len(s); i++ { curr := s[i] if i > 0 && curr == prev { fmt.Println(i) } prev = curr } }
Write the same algorithm in Go as shown in this Python implementation.
from SOAPpy import WSDL proxy = WSDL.Proxy("http://example.com/soap/wsdl") result = proxy.soapFunc("hello") result = proxy.anotherSoapFunc(34234)
package main import ( "fmt" "github.com/tiaguinho/gosoap" "log" ) type CheckVatResponse struct { CountryCode string `xml:"countryCode"` VatNumber string `xml:"vatNumber"` RequestDate string `xml:"requestDate"` Valid string `xml:"valid"` Name string `xml:"name"` Address string `xml:"address"` } var ( rv CheckVatResponse ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { soap, err := gosoap.SoapClient("http: params := gosoap.Params{ "vatNumber": "6388047V", "countryCode": "IE", } err = soap.Call("checkVat", params) check(err) err = soap.Unmarshal(&rv) check(err) fmt.Println("Country Code  : ", rv.CountryCode) fmt.Println("Vat Number  : ", rv.VatNumber) fmt.Println("Request Date  : ", rv.RequestDate) fmt.Println("Valid  : ", rv.Valid) fmt.Println("Name  : ", rv.Name) fmt.Println("Address  : ", rv.Address) }
Change the following Python code into Go without altering its purpose.
Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import __future__ >>> __future__.all_feature_names ['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL'] >>>
Port the provided Python code into Go while preserving the original functionality.
def msb(x): return x.bit_length() - 1 def lsb(x): return msb(x & -x) for i in range(6): x = 42 ** i print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x))) for i in range(6): x = 1302 ** i print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
package main import ( "fmt" "math/big" ) const ( mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota mask1, bit1 mask2, bit2 mask3, bit3 mask4, bit4 mask5, bit5 ) func rupb(x uint64) (out int) { if x == 0 { return -1 } if x&^mask5 != 0 { x >>= bit5 out |= bit5 } if x&^mask4 != 0 { x >>= bit4 out |= bit4 } if x&^mask3 != 0 { x >>= bit3 out |= bit3 } if x&^mask2 != 0 { x >>= bit2 out |= bit2 } if x&^mask1 != 0 { x >>= bit1 out |= bit1 } if x&^mask0 != 0 { out |= bit0 } return } func rlwb(x uint64) (out int) { if x == 0 { return 0 } if x&mask5 == 0 { x >>= bit5 out |= bit5 } if x&mask4 == 0 { x >>= bit4 out |= bit4 } if x&mask3 == 0 { x >>= bit3 out |= bit3 } if x&mask2 == 0 { x >>= bit2 out |= bit2 } if x&mask1 == 0 { x >>= bit1 out |= bit1 } if x&mask0 == 0 { out |= bit0 } return } func rupbBig(x *big.Int) int { return x.BitLen() - 1 } func rlwbBig(x *big.Int) int { if x.BitLen() < 2 { return 0 } bit := uint(1) mask := big.NewInt(1) var ms []*big.Int var y, z big.Int for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 { ms = append(ms, mask) mask = new(big.Int).Or(mask, &z) bit <<= 1 } out := bit for i := len(ms) - 1; i >= 0; i-- { bit >>= 1 if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 { out |= bit } } return int(out) } func main() { show() showBig() } func show() { fmt.Println("uint64:") fmt.Println("power number rupb rlwb") const base = 42 n := uint64(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %19d %5d %5d\n", base, i, n, rupb(n), rlwb(n)) n *= base } } func showBig() { fmt.Println("\nbig numbers:") fmt.Println(" power number rupb rlwb") base := big.NewInt(1302) n := big.NewInt(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %36d %5d %5d\n", base, i, n, rupbBig(n), rlwbBig(n)) n.Mul(n, base) } }
Translate the given Python code snippet into Go without altering its behavior.
def msb(x): return x.bit_length() - 1 def lsb(x): return msb(x & -x) for i in range(6): x = 42 ** i print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x))) for i in range(6): x = 1302 ** i print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
package main import ( "fmt" "math/big" ) const ( mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota mask1, bit1 mask2, bit2 mask3, bit3 mask4, bit4 mask5, bit5 ) func rupb(x uint64) (out int) { if x == 0 { return -1 } if x&^mask5 != 0 { x >>= bit5 out |= bit5 } if x&^mask4 != 0 { x >>= bit4 out |= bit4 } if x&^mask3 != 0 { x >>= bit3 out |= bit3 } if x&^mask2 != 0 { x >>= bit2 out |= bit2 } if x&^mask1 != 0 { x >>= bit1 out |= bit1 } if x&^mask0 != 0 { out |= bit0 } return } func rlwb(x uint64) (out int) { if x == 0 { return 0 } if x&mask5 == 0 { x >>= bit5 out |= bit5 } if x&mask4 == 0 { x >>= bit4 out |= bit4 } if x&mask3 == 0 { x >>= bit3 out |= bit3 } if x&mask2 == 0 { x >>= bit2 out |= bit2 } if x&mask1 == 0 { x >>= bit1 out |= bit1 } if x&mask0 == 0 { out |= bit0 } return } func rupbBig(x *big.Int) int { return x.BitLen() - 1 } func rlwbBig(x *big.Int) int { if x.BitLen() < 2 { return 0 } bit := uint(1) mask := big.NewInt(1) var ms []*big.Int var y, z big.Int for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 { ms = append(ms, mask) mask = new(big.Int).Or(mask, &z) bit <<= 1 } out := bit for i := len(ms) - 1; i >= 0; i-- { bit >>= 1 if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 { out |= bit } } return int(out) } func main() { show() showBig() } func show() { fmt.Println("uint64:") fmt.Println("power number rupb rlwb") const base = 42 n := uint64(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %19d %5d %5d\n", base, i, n, rupb(n), rlwb(n)) n *= base } } func showBig() { fmt.Println("\nbig numbers:") fmt.Println(" power number rupb rlwb") base := big.NewInt(1302) n := big.NewInt(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %36d %5d %5d\n", base, i, n, rupbBig(n), rlwbBig(n)) n.Mul(n, base) } }
Produce a language-to-language conversion: from Python to Go, same semantics.
import itertools def riseEqFall(num): height = 0 d1 = num % 10 num //= 10 while num: d2 = num % 10 height += (d1<d2) - (d1>d2) d1 = d2 num //= 10 return height == 0 def sequence(start, fn): num=start-1 while True: num += 1 while not fn(num): num += 1 yield num a296712 = sequence(1, riseEqFall) print("The first 200 numbers are:") print(*itertools.islice(a296712, 200)) print("The 10,000,000th number is:") print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))
package main import "fmt" func risesEqualsFalls(n int) bool { if n < 10 { return true } rises := 0 falls := 0 prev := -1 for n > 0 { d := n % 10 if prev >= 0 { if d < prev { rises = rises + 1 } else if d > prev { falls = falls + 1 } } prev = d n /= 10 } return rises == falls } func main() { fmt.Println("The first 200 numbers in the sequence are:") count := 0 n := 1 for { if risesEqualsFalls(n) { count++ if count <= 200 { fmt.Printf("%3d ", n) if count%20 == 0 { fmt.Println() } } if count == 1e7 { fmt.Println("\nThe 10 millionth number in the sequence is ", n) break } } n++ } }
Convert this Python snippet to Go and keep its semantics consistent.
import curses scr = curses.initscr() def move_left(): y,x = curses.getyx() curses.move(y,x-1) def move_right(): y,x = curses.getyx() curses.move(y,x+1) def move_up(): y,x = curses.getyx() curses.move(y-1,x) def move_down(): y,x = curses.getyx() curses.move(y+1,x) def move_line_home() y,x = curses.getyx() curses.move(y,0) def move_line_end() y,x = curses.getyx() maxy,maxx = scr.getmaxyx() curses.move(y,maxx) def move_page_home(): curses.move(0,0) def move_page_end(): y,x = scr.getmaxyx() curses.move(y,x)
package main import ( "fmt" "time" "os" "os/exec" "strconv" ) func main() { tput("clear") tput("cup", "6", "3") time.Sleep(1 * time.Second) tput("cub1") time.Sleep(1 * time.Second) tput("cuf1") time.Sleep(1 * time.Second) tput("cuu1") time.Sleep(1 * time.Second) tput("cud", "1") time.Sleep(1 * time.Second) tput("cr") time.Sleep(1 * time.Second) var h, w int cmd := exec.Command("stty", "size") cmd.Stdin = os.Stdin d, _ := cmd.Output() fmt.Sscan(string(d), &h, &w) tput("hpa", strconv.Itoa(w-1)) time.Sleep(2 * time.Second) tput("home") time.Sleep(2 * time.Second) tput("cup", strconv.Itoa(h-1), strconv.Itoa(w-1)) time.Sleep(3 * time.Second) } func tput(args ...string) error { cmd := exec.Command("tput", args...) cmd.Stdout = os.Stdout return cmd.Run() }
Rewrite the snippet below in Go so it works the same as the original Python code.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': suma = 2 n = 1 for i in range(3, 2000000, 2): if isPrime(i): suma += i n+=1 print(suma)
package main import ( "fmt" "rcu" ) func main() { sum := 0 for _, p := range rcu.Primes(2e6 - 1) { sum += p } fmt.Printf("The sum of all primes below 2 million is %s.\n", rcu.Commatize(sum)) }
Port the provided Python code into Go while preserving the original functionality.
l = 300 def setup(): size(400, 400) background(0, 0, 255) stroke(255) translate(width / 2.0, height / 2.0) translate(-l / 2.0, l * sqrt(3) / 6.0) for i in range(4): kcurve(0, l) rotate(radians(120)) translate(-l, 0) def kcurve(x1, x2): s = (x2 - x1) / 3.0 if s < 5: pushMatrix() translate(x1, 0) line(0, 0, s, 0) line(2 * s, 0, 3 * s, 0) translate(s, 0) rotate(radians(60)) line(0, 0, s, 0) translate(s, 0) rotate(radians(-120)) line(0, 0, s, 0) popMatrix() return pushMatrix() translate(x1, 0) kcurve(0, s) kcurve(2 * s, 3 * s) translate(s, 0) rotate(radians(60)) kcurve(0, s) translate(s, 0) rotate(radians(-120)) kcurve(0, s) popMatrix()
package main import ( "github.com/fogleman/gg" "math" ) var dc = gg.NewContext(512, 512) func koch(x1, y1, x2, y2 float64, iter int) { angle := math.Pi / 3 x3 := (x1*2 + x2) / 3 y3 := (y1*2 + y2) / 3 x4 := (x1 + x2*2) / 3 y4 := (y1 + y2*2) / 3 x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle) y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle) if iter > 0 { iter-- koch(x1, y1, x3, y3, iter) koch(x3, y3, x5, y5, iter) koch(x5, y5, x4, y4, iter) koch(x4, y4, x2, y2, iter) } else { dc.LineTo(x1, y1) dc.LineTo(x3, y3) dc.LineTo(x5, y5) dc.LineTo(x4, y4) dc.LineTo(x2, y2) } } func main() { dc.SetRGB(1, 1, 1) dc.Clear() koch(100, 100, 400, 400, 4) dc.SetRGB(0, 0, 1) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("koch.png") }
Port the following code from Python to Go with equivalent syntax and logic.
import Tkinter,random def draw_pixel_2 ( sizex=640,sizey=480 ): pos = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 ) root = Tkinter.Tk() can = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' ) can.create_rectangle( pos*2,outline='yellow' ) can.pack() root.title('press ESCAPE to quit') root.bind('<Escape>',lambda e : root.quit()) root.mainloop() draw_pixel_2()
package main import ( "fmt" "image" "image/color" "image/draw" "math/rand" "time" ) func main() { rect := image.Rect(0, 0, 640, 480) img := image.NewRGBA(rect) blue := color.RGBA{0, 0, 255, 255} draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src) yellow := color.RGBA{255, 255, 0, 255} width := img.Bounds().Dx() height := img.Bounds().Dy() rand.Seed(time.Now().UnixNano()) x := rand.Intn(width) y := rand.Intn(height) img.Set(x, y, yellow) cmap := map[color.Color]string{blue: "blue", yellow: "yellow"} for i := 0; i < width; i++ { for j := 0; j < height; j++ { c := img.At(i, j) if cmap[c] == "yellow" { fmt.Printf("The color of the pixel at (%d, %d) is yellow\n", i, j) } } } }
Transform the following Python implementation into Go, maintaining the same output and logic.
def isvowel(c): return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', "I", 'O', 'U'] def isletter(c): return 'a' <= c <= 'z' or 'A' <= c <= 'Z' def isconsonant(c): return not isvowel(c) and isletter(c) def vccounts(s): a = list(s.lower()) au = set(a) return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \ sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au]) def testvccount(): teststrings = [ "Forever Python programming language", "Now is the time for all good men to come to the aid of their country."] for s in teststrings: vcnt, ccnt, vu, cu = vccounts(s) print(f"String: {s}\n Vowels: {vcnt} (distinct {vu})\n Consonants: {ccnt} (distinct {cu})\n") testvccount()
package main import ( "fmt" "strings" ) func main() { const ( vowels = "aeiou" consonants = "bcdfghjklmnpqrstvwxyz" ) strs := []string{ "Forever Go programming language", "Now is the time for all good men to come to the aid of their country.", } for _, str := range strs { fmt.Println(str) str = strings.ToLower(str) vc, cc := 0, 0 vmap := make(map[rune]bool) cmap := make(map[rune]bool) for _, c := range str { if strings.ContainsRune(vowels, c) { vc++ vmap[c] = true } else if strings.ContainsRune(consonants, c) { cc++ cmap[c] = true } } fmt.Printf("contains (total) %d vowels and %d consonants.\n", vc, cc) fmt.Printf("contains (distinct %d vowels and %d consonants.\n\n", len(vmap), len(cmap)) } }
Convert this Python block to Go, preserving its control flow and logic.
def isvowel(c): return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', "I", 'O', 'U'] def isletter(c): return 'a' <= c <= 'z' or 'A' <= c <= 'Z' def isconsonant(c): return not isvowel(c) and isletter(c) def vccounts(s): a = list(s.lower()) au = set(a) return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \ sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au]) def testvccount(): teststrings = [ "Forever Python programming language", "Now is the time for all good men to come to the aid of their country."] for s in teststrings: vcnt, ccnt, vu, cu = vccounts(s) print(f"String: {s}\n Vowels: {vcnt} (distinct {vu})\n Consonants: {ccnt} (distinct {cu})\n") testvccount()
package main import ( "fmt" "strings" ) func main() { const ( vowels = "aeiou" consonants = "bcdfghjklmnpqrstvwxyz" ) strs := []string{ "Forever Go programming language", "Now is the time for all good men to come to the aid of their country.", } for _, str := range strs { fmt.Println(str) str = strings.ToLower(str) vc, cc := 0, 0 vmap := make(map[rune]bool) cmap := make(map[rune]bool) for _, c := range str { if strings.ContainsRune(vowels, c) { vc++ vmap[c] = true } else if strings.ContainsRune(consonants, c) { cc++ cmap[c] = true } } fmt.Printf("contains (total) %d vowels and %d consonants.\n", vc, cc) fmt.Printf("contains (distinct %d vowels and %d consonants.\n\n", len(vmap), len(cmap)) } }
Preserve the algorithm and functionality while converting the code from Python to Go.
def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error() while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q)) return x def paren_expr() expect("(") x = expr(0) expect(")") return x def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0)) t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type TokenType int const ( tkEOI TokenType = iota tkMul tkDiv tkMod tkAdd tkSub tkNegate tkNot tkLss tkLeq tkGtr tkGeq tkEql tkNeq tkAssign tkAnd tkOr tkIf tkElse tkWhile tkPrint tkPutc tkLparen tkRparen tkLbrace tkRbrace tkSemi tkComma tkIdent tkInteger tkString ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type tokS struct { tok TokenType errLn int errCol int text string } type Tree struct { nodeType NodeType left *Tree right *Tree value string } type atr struct { text string enumText string tok TokenType rightAssociative bool isBinary bool isUnary bool precedence int nodeType NodeType } var atrs = []atr{ {"EOI", "End_of_input", tkEOI, false, false, false, -1, -1}, {"*", "Op_multiply", tkMul, false, true, false, 13, ndMul}, {"/", "Op_divide", tkDiv, false, true, false, 13, ndDiv}, {"%", "Op_mod", tkMod, false, true, false, 13, ndMod}, {"+", "Op_add", tkAdd, false, true, false, 12, ndAdd}, {"-", "Op_subtract", tkSub, false, true, false, 12, ndSub}, {"-", "Op_negate", tkNegate, false, false, true, 14, ndNegate}, {"!", "Op_not", tkNot, false, false, true, 14, ndNot}, {"<", "Op_less", tkLss, false, true, false, 10, ndLss}, {"<=", "Op_lessequal", tkLeq, false, true, false, 10, ndLeq}, {">", "Op_greater", tkGtr, false, true, false, 10, ndGtr}, {">=", "Op_greaterequal", tkGeq, false, true, false, 10, ndGeq}, {"==", "Op_equal", tkEql, false, true, false, 9, ndEql}, {"!=", "Op_notequal", tkNeq, false, true, false, 9, ndNeq}, {"=", "Op_assign", tkAssign, false, false, false, -1, ndAssign}, {"&&", "Op_and", tkAnd, false, true, false, 5, ndAnd}, {"||", "Op_or", tkOr, false, true, false, 4, ndOr}, {"if", "Keyword_if", tkIf, false, false, false, -1, ndIf}, {"else", "Keyword_else", tkElse, false, false, false, -1, -1}, {"while", "Keyword_while", tkWhile, false, false, false, -1, ndWhile}, {"print", "Keyword_print", tkPrint, false, false, false, -1, -1}, {"putc", "Keyword_putc", tkPutc, false, false, false, -1, -1}, {"(", "LeftParen", tkLparen, false, false, false, -1, -1}, {")", "RightParen", tkRparen, false, false, false, -1, -1}, {"{", "LeftBrace", tkLbrace, false, false, false, -1, -1}, {"}", "RightBrace", tkRbrace, false, false, false, -1, -1}, {";", "Semicolon", tkSemi, false, false, false, -1, -1}, {",", "Comma", tkComma, false, false, false, -1, -1}, {"Ident", "Identifier", tkIdent, false, false, false, -1, ndIdent}, {"Integer literal", "Integer", tkInteger, false, false, false, -1, ndInteger}, {"String literal", "String", tkString, false, false, false, -1, ndString}, } var displayNodes = []string{ "Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add", "Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal", "NotEqual", "And", "Or", } var ( err error token tokS scanner *bufio.Scanner ) func reportError(errLine, errCol int, msg string) { log.Fatalf("(%d, %d) error : %s\n", errLine, errCol, msg) } func check(err error) { if err != nil { log.Fatal(err) } } func getEum(name string) TokenType { for _, atr := range atrs { if atr.enumText == name { return atr.tok } } reportError(0, 0, fmt.Sprintf("Unknown token %s\n", name)) return tkEOI } func getTok() tokS { tok := tokS{} if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") fields := strings.Fields(line) tok.errLn, err = strconv.Atoi(fields[0]) check(err) tok.errCol, err = strconv.Atoi(fields[1]) check(err) tok.tok = getEum(fields[2]) le := len(fields) if le == 4 { tok.text = fields[3] } else if le > 4 { idx := strings.Index(line, `"`) tok.text = line[idx:] } } check(scanner.Err()) return tok } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, ""} } func makeLeaf(nodeType NodeType, value string) *Tree { return &Tree{nodeType, nil, nil, value} } func expect(msg string, s TokenType) { if token.tok == s { token = getTok() return } reportError(token.errLn, token.errCol, fmt.Sprintf("%s: Expecting '%s', found '%s'\n", msg, atrs[s].text, atrs[token.tok].text)) } func expr(p int) *Tree { var x, node *Tree switch token.tok { case tkLparen: x = parenExpr() case tkSub, tkAdd: op := token.tok token = getTok() node = expr(atrs[tkNegate].precedence) if op == tkSub { x = makeNode(ndNegate, node, nil) } else { x = node } case tkNot: token = getTok() x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil) case tkIdent: x = makeLeaf(ndIdent, token.text) token = getTok() case tkInteger: x = makeLeaf(ndInteger, token.text) token = getTok() default: reportError(token.errLn, token.errCol, fmt.Sprintf("Expecting a primary, found: %s\n", atrs[token.tok].text)) } for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p { op := token.tok token = getTok() q := atrs[op].precedence if !atrs[op].rightAssociative { q++ } node = expr(q) x = makeNode(atrs[op].nodeType, x, node) } return x } func parenExpr() *Tree { expect("parenExpr", tkLparen) t := expr(0) expect("parenExpr", tkRparen) return t } func stmt() *Tree { var t, v, e, s, s2 *Tree switch token.tok { case tkIf: token = getTok() e = parenExpr() s = stmt() s2 = nil if token.tok == tkElse { token = getTok() s2 = stmt() } t = makeNode(ndIf, e, makeNode(ndIf, s, s2)) case tkPutc: token = getTok() e = parenExpr() t = makeNode(ndPrtc, e, nil) expect("Putc", tkSemi) case tkPrint: token = getTok() for expect("Print", tkLparen); ; expect("Print", tkComma) { if token.tok == tkString { e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil) token = getTok() } else { e = makeNode(ndPrti, expr(0), nil) } t = makeNode(ndSequence, t, e) if token.tok != tkComma { break } } expect("Print", tkRparen) expect("Print", tkSemi) case tkSemi: token = getTok() case tkIdent: v = makeLeaf(ndIdent, token.text) token = getTok() expect("assign", tkAssign) e = expr(0) t = makeNode(ndAssign, v, e) expect("assign", tkSemi) case tkWhile: token = getTok() e = parenExpr() s = stmt() t = makeNode(ndWhile, e, s) case tkLbrace: for expect("Lbrace", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; { t = makeNode(ndSequence, t, stmt()) } expect("Lbrace", tkRbrace) case tkEOI: default: reportError(token.errLn, token.errCol, fmt.Sprintf("expecting start of statement, found '%s'\n", atrs[token.tok].text)) } return t } func parse() *Tree { var t *Tree token = getTok() for { t = makeNode(ndSequence, t, stmt()) if t == nil || token.tok == tkEOI { break } } return t } func prtAst(t *Tree) { if t == nil { fmt.Print(";\n") } else { fmt.Printf("%-14s ", displayNodes[t.nodeType]) if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString { fmt.Printf("%s\n", t.value) } else { fmt.Println() prtAst(t.left) prtAst(t.right) } } } func main() { source, err := os.Open("source.txt") check(err) defer source.Close() scanner = bufio.NewScanner(source) prtAst(parse()) }
Write the same code in Go as shown below in Python.
def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error() while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q)) return x def paren_expr() expect("(") x = expr(0) expect(")") return x def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0)) t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type TokenType int const ( tkEOI TokenType = iota tkMul tkDiv tkMod tkAdd tkSub tkNegate tkNot tkLss tkLeq tkGtr tkGeq tkEql tkNeq tkAssign tkAnd tkOr tkIf tkElse tkWhile tkPrint tkPutc tkLparen tkRparen tkLbrace tkRbrace tkSemi tkComma tkIdent tkInteger tkString ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type tokS struct { tok TokenType errLn int errCol int text string } type Tree struct { nodeType NodeType left *Tree right *Tree value string } type atr struct { text string enumText string tok TokenType rightAssociative bool isBinary bool isUnary bool precedence int nodeType NodeType } var atrs = []atr{ {"EOI", "End_of_input", tkEOI, false, false, false, -1, -1}, {"*", "Op_multiply", tkMul, false, true, false, 13, ndMul}, {"/", "Op_divide", tkDiv, false, true, false, 13, ndDiv}, {"%", "Op_mod", tkMod, false, true, false, 13, ndMod}, {"+", "Op_add", tkAdd, false, true, false, 12, ndAdd}, {"-", "Op_subtract", tkSub, false, true, false, 12, ndSub}, {"-", "Op_negate", tkNegate, false, false, true, 14, ndNegate}, {"!", "Op_not", tkNot, false, false, true, 14, ndNot}, {"<", "Op_less", tkLss, false, true, false, 10, ndLss}, {"<=", "Op_lessequal", tkLeq, false, true, false, 10, ndLeq}, {">", "Op_greater", tkGtr, false, true, false, 10, ndGtr}, {">=", "Op_greaterequal", tkGeq, false, true, false, 10, ndGeq}, {"==", "Op_equal", tkEql, false, true, false, 9, ndEql}, {"!=", "Op_notequal", tkNeq, false, true, false, 9, ndNeq}, {"=", "Op_assign", tkAssign, false, false, false, -1, ndAssign}, {"&&", "Op_and", tkAnd, false, true, false, 5, ndAnd}, {"||", "Op_or", tkOr, false, true, false, 4, ndOr}, {"if", "Keyword_if", tkIf, false, false, false, -1, ndIf}, {"else", "Keyword_else", tkElse, false, false, false, -1, -1}, {"while", "Keyword_while", tkWhile, false, false, false, -1, ndWhile}, {"print", "Keyword_print", tkPrint, false, false, false, -1, -1}, {"putc", "Keyword_putc", tkPutc, false, false, false, -1, -1}, {"(", "LeftParen", tkLparen, false, false, false, -1, -1}, {")", "RightParen", tkRparen, false, false, false, -1, -1}, {"{", "LeftBrace", tkLbrace, false, false, false, -1, -1}, {"}", "RightBrace", tkRbrace, false, false, false, -1, -1}, {";", "Semicolon", tkSemi, false, false, false, -1, -1}, {",", "Comma", tkComma, false, false, false, -1, -1}, {"Ident", "Identifier", tkIdent, false, false, false, -1, ndIdent}, {"Integer literal", "Integer", tkInteger, false, false, false, -1, ndInteger}, {"String literal", "String", tkString, false, false, false, -1, ndString}, } var displayNodes = []string{ "Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add", "Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal", "NotEqual", "And", "Or", } var ( err error token tokS scanner *bufio.Scanner ) func reportError(errLine, errCol int, msg string) { log.Fatalf("(%d, %d) error : %s\n", errLine, errCol, msg) } func check(err error) { if err != nil { log.Fatal(err) } } func getEum(name string) TokenType { for _, atr := range atrs { if atr.enumText == name { return atr.tok } } reportError(0, 0, fmt.Sprintf("Unknown token %s\n", name)) return tkEOI } func getTok() tokS { tok := tokS{} if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") fields := strings.Fields(line) tok.errLn, err = strconv.Atoi(fields[0]) check(err) tok.errCol, err = strconv.Atoi(fields[1]) check(err) tok.tok = getEum(fields[2]) le := len(fields) if le == 4 { tok.text = fields[3] } else if le > 4 { idx := strings.Index(line, `"`) tok.text = line[idx:] } } check(scanner.Err()) return tok } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, ""} } func makeLeaf(nodeType NodeType, value string) *Tree { return &Tree{nodeType, nil, nil, value} } func expect(msg string, s TokenType) { if token.tok == s { token = getTok() return } reportError(token.errLn, token.errCol, fmt.Sprintf("%s: Expecting '%s', found '%s'\n", msg, atrs[s].text, atrs[token.tok].text)) } func expr(p int) *Tree { var x, node *Tree switch token.tok { case tkLparen: x = parenExpr() case tkSub, tkAdd: op := token.tok token = getTok() node = expr(atrs[tkNegate].precedence) if op == tkSub { x = makeNode(ndNegate, node, nil) } else { x = node } case tkNot: token = getTok() x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil) case tkIdent: x = makeLeaf(ndIdent, token.text) token = getTok() case tkInteger: x = makeLeaf(ndInteger, token.text) token = getTok() default: reportError(token.errLn, token.errCol, fmt.Sprintf("Expecting a primary, found: %s\n", atrs[token.tok].text)) } for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p { op := token.tok token = getTok() q := atrs[op].precedence if !atrs[op].rightAssociative { q++ } node = expr(q) x = makeNode(atrs[op].nodeType, x, node) } return x } func parenExpr() *Tree { expect("parenExpr", tkLparen) t := expr(0) expect("parenExpr", tkRparen) return t } func stmt() *Tree { var t, v, e, s, s2 *Tree switch token.tok { case tkIf: token = getTok() e = parenExpr() s = stmt() s2 = nil if token.tok == tkElse { token = getTok() s2 = stmt() } t = makeNode(ndIf, e, makeNode(ndIf, s, s2)) case tkPutc: token = getTok() e = parenExpr() t = makeNode(ndPrtc, e, nil) expect("Putc", tkSemi) case tkPrint: token = getTok() for expect("Print", tkLparen); ; expect("Print", tkComma) { if token.tok == tkString { e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil) token = getTok() } else { e = makeNode(ndPrti, expr(0), nil) } t = makeNode(ndSequence, t, e) if token.tok != tkComma { break } } expect("Print", tkRparen) expect("Print", tkSemi) case tkSemi: token = getTok() case tkIdent: v = makeLeaf(ndIdent, token.text) token = getTok() expect("assign", tkAssign) e = expr(0) t = makeNode(ndAssign, v, e) expect("assign", tkSemi) case tkWhile: token = getTok() e = parenExpr() s = stmt() t = makeNode(ndWhile, e, s) case tkLbrace: for expect("Lbrace", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; { t = makeNode(ndSequence, t, stmt()) } expect("Lbrace", tkRbrace) case tkEOI: default: reportError(token.errLn, token.errCol, fmt.Sprintf("expecting start of statement, found '%s'\n", atrs[token.tok].text)) } return t } func parse() *Tree { var t *Tree token = getTok() for { t = makeNode(ndSequence, t, stmt()) if t == nil || token.tok == tkEOI { break } } return t } func prtAst(t *Tree) { if t == nil { fmt.Print(";\n") } else { fmt.Printf("%-14s ", displayNodes[t.nodeType]) if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString { fmt.Printf("%s\n", t.value) } else { fmt.Println() prtAst(t.left) prtAst(t.right) } } } func main() { source, err := os.Open("source.txt") check(err) defer source.Close() scanner = bufio.NewScanner(source) prtAst(parse()) }
Generate a Go translation of this Python snippet without changing its computational steps.
from PIL import Image img = Image.new('RGB', (320, 240)) pixels = img.load() pixels[100,100] = (255,0,0) img.show()
package main import ( "fmt" "image" "image/color" "image/draw" ) func main() { rect := image.Rect(0, 0, 320, 240) img := image.NewRGBA(rect) green := color.RGBA{0, 255, 0, 255} draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src) red := color.RGBA{255, 0, 0, 255} img.Set(100, 100, red) cmap := map[color.Color]string{green: "green", red: "red"} c1 := img.At(0, 0) c2 := img.At(100, 100) fmt.Println("The color of the pixel at ( 0, 0) is", cmap[c1], "\b.") fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.") }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
def digitSumsPrime(n): def go(bases): return all( isPrime(digitSum(b)(n)) for b in bases ) return go def digitSum(base): def go(n): q, r = divmod(n, base) return go(q) + r if n else 0 return go def main(): xs = [ str(n) for n in range(1, 200) if digitSumsPrime(n)([2, 3]) ] print(f'{len(xs)} matches in [1..199]\n') print(table(10)(xs)) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
package main import ( "fmt" "rcu" ) func main() { var numbers []int for i := 2; i < 200; i++ { bds := rcu.DigitSum(i, 2) if rcu.IsPrime(bds) { tds := rcu.DigitSum(i, 3) if rcu.IsPrime(tds) { numbers = append(numbers, i) } } } fmt.Println("Numbers < 200 whose binary and ternary digit sums are prime:") for i, n := range numbers { fmt.Printf("%4d", n) if (i+1)%14 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such numbers found\n", len(numbers)) }
Rewrite the snippet below in Go so it works the same as the original Python code.
def digitSumsPrime(n): def go(bases): return all( isPrime(digitSum(b)(n)) for b in bases ) return go def digitSum(base): def go(n): q, r = divmod(n, base) return go(q) + r if n else 0 return go def main(): xs = [ str(n) for n in range(1, 200) if digitSumsPrime(n)([2, 3]) ] print(f'{len(xs)} matches in [1..199]\n') print(table(10)(xs)) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
package main import ( "fmt" "rcu" ) func main() { var numbers []int for i := 2; i < 200; i++ { bds := rcu.DigitSum(i, 2) if rcu.IsPrime(bds) { tds := rcu.DigitSum(i, 3) if rcu.IsPrime(tds) { numbers = append(numbers, i) } } } fmt.Println("Numbers < 200 whose binary and ternary digit sums are prime:") for i, n := range numbers { fmt.Printf("%4d", n) if (i+1)%14 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such numbers found\n", len(numbers)) }
Translate the given Python code snippet into Go without altering its behavior.
import urllib.request from collections import Counter urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() filteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9] for word in filteredWords[:-9]: position = filteredWords.index(word) newWord = "".join([filteredWords[position+i][i] for i in range(0,9)]) if newWord in filteredWords: print(newWord)
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) >= 9 { words = append(words, s) } } count := 0 var alreadyFound []string le := len(words) var sb strings.Builder for i := 0; i < le-9; i++ { sb.Reset() for j := i; j < i+9; j++ { sb.WriteByte(words[j][j-i]) } word := sb.String() ix := sort.SearchStrings(words, word) if ix < le && word == words[ix] { ix2 := sort.SearchStrings(alreadyFound, word) if ix2 == len(alreadyFound) { count++ fmt.Printf("%2d: %s\n", count, word) alreadyFound = append(alreadyFound, word) } } } }
Transform the following Python implementation into Go, maintaining the same output and logic.
from functools import reduce from operator import mul def p(n): digits = [int(c) for c in str(n)] return not 0 in digits and ( 0 != (n % reduce(mul, digits, 1)) ) and all(0 == n % d for d in digits) def main(): xs = [ str(n) for n in range(1, 1000) if p(n) ] w = len(xs[-1]) print(f'{len(xs)} matching numbers:\n') print('\n'.join( ' '.join(cell.rjust(w, ' ') for cell in row) for row in chunksOf(10)(xs) )) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go if __name__ == '__main__': main()
package main import ( "fmt" "rcu" ) func main() { var res []int for n := 1; n < 1000; n++ { digits := rcu.Digits(n, 10) var all = true for _, d := range digits { if d == 0 || n%d != 0 { all = false break } } if all { prod := 1 for _, d := range digits { prod *= d } if prod > 0 && n%prod != 0 { res = append(res, n) } } } fmt.Println("Numbers < 1000 divisible by their digits, but not by the product thereof:") for i, n := range res { fmt.Printf("%4d", n) if (i+1)%9 == 0 { fmt.Println() } } fmt.Printf("\n%d such numbers found\n", len(res)) }
Write a version of this Python function in Go with identical behavior.
from myhdl import * @block def NOTgate( a, q ): @always_comb def NOTgateLogic(): q.next = not a return NOTgateLogic @block def ANDgate( a, b, q ): @always_comb def ANDgateLogic(): q.next = a and b return ANDgateLogic @block def ORgate( a, b, q ): @always_comb def ORgateLogic(): q.next = a or b return ORgateLogic @block def XORgate( a, b, q ): nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)] inv0 = NOTgate( a, nota ) inv1 = NOTgate( b, notb ) and2a = ANDgate( a, notb, annotb ) and2b = ANDgate( b, nota, bnnota ) or2a = ORgate( annotb, bnnota, q ) return inv0, inv1, and2a, and2b, or2a @block def HalfAdder( in_a, in_b, summ, carry ): and2a = ANDgate(in_a, in_b, carry) xor2a = XORgate(in_a, in_b, summ) return and2a, xor2a @block def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ): ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)] HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 ) HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 ) or2a = ORgate(ha1_c1, ha2_c1, fa_c1) return HalfAdder01, HalfAdder02, or2a @block def Adder4b( ina, inb, cOut, sum4): cl = [Signal(bool()) for i in range(0,4)] sl = [Signal(bool()) for i in range(4)] HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] ) FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] ) FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] ) FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut ) sc = ConcatSignal(*reversed(sl)) @always_comb def list2intbv(): sum4.next = sc return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)] ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)] from random import randrange @block def Test_Adder4b(): dut = Adder4b( ina4, inb4, t_co, sum4 ) @instance def check(): print( "\n b a | c1 s \n -------------------" ) for i in range(15): ina4.next, inb4.next = randrange(2**4), randrange(2**4) yield delay(5) print( " %2d %2d | %2d %2d " \ % (ina4,inb4, t_co,sum4) ) assert t_co * 16 + sum4 == ina4 + inb4 print() return dut, check def main(): simInst = Test_Adder4b() simInst.name = "mySimInst" simInst.config_sim(trace=True) simInst.run_sim(duration=None) inst = Adder4b( ina4, inb4, t_co, sum4 ) inst.convert(hdl='VHDL') inst.convert(hdl='Verilog') if __name__ == '__main__': main()
package main import "fmt" func xor(a, b byte) byte { return a&(^b) | b&(^a) } func ha(a, b byte) (s, c byte) { return xor(a, b), a & b } func fa(a, b, c0 byte) (s, c1 byte) { sa, ca := ha(a, c0) s, cb := ha(sa, b) c1 = ca | cb return } func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) { s0, c0 := fa(a0, b0, 0) s1, c1 := fa(a1, b1, c0) s2, c2 := fa(a2, b2, c1) s3, v = fa(a3, b3, c2) return } func main() { fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1)) }
Port the provided Python code into Go while preserving the original functionality.
from myhdl import * @block def NOTgate( a, q ): @always_comb def NOTgateLogic(): q.next = not a return NOTgateLogic @block def ANDgate( a, b, q ): @always_comb def ANDgateLogic(): q.next = a and b return ANDgateLogic @block def ORgate( a, b, q ): @always_comb def ORgateLogic(): q.next = a or b return ORgateLogic @block def XORgate( a, b, q ): nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)] inv0 = NOTgate( a, nota ) inv1 = NOTgate( b, notb ) and2a = ANDgate( a, notb, annotb ) and2b = ANDgate( b, nota, bnnota ) or2a = ORgate( annotb, bnnota, q ) return inv0, inv1, and2a, and2b, or2a @block def HalfAdder( in_a, in_b, summ, carry ): and2a = ANDgate(in_a, in_b, carry) xor2a = XORgate(in_a, in_b, summ) return and2a, xor2a @block def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ): ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)] HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 ) HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 ) or2a = ORgate(ha1_c1, ha2_c1, fa_c1) return HalfAdder01, HalfAdder02, or2a @block def Adder4b( ina, inb, cOut, sum4): cl = [Signal(bool()) for i in range(0,4)] sl = [Signal(bool()) for i in range(4)] HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] ) FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] ) FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] ) FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut ) sc = ConcatSignal(*reversed(sl)) @always_comb def list2intbv(): sum4.next = sc return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)] ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)] from random import randrange @block def Test_Adder4b(): dut = Adder4b( ina4, inb4, t_co, sum4 ) @instance def check(): print( "\n b a | c1 s \n -------------------" ) for i in range(15): ina4.next, inb4.next = randrange(2**4), randrange(2**4) yield delay(5) print( " %2d %2d | %2d %2d " \ % (ina4,inb4, t_co,sum4) ) assert t_co * 16 + sum4 == ina4 + inb4 print() return dut, check def main(): simInst = Test_Adder4b() simInst.name = "mySimInst" simInst.config_sim(trace=True) simInst.run_sim(duration=None) inst = Adder4b( ina4, inb4, t_co, sum4 ) inst.convert(hdl='VHDL') inst.convert(hdl='Verilog') if __name__ == '__main__': main()
package main import "fmt" func xor(a, b byte) byte { return a&(^b) | b&(^a) } func ha(a, b byte) (s, c byte) { return xor(a, b), a & b } func fa(a, b, c0 byte) (s, c1 byte) { sa, ca := ha(a, c0) s, cb := ha(sa, b) c1 = ca | cb return } func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) { s0, c0 := fa(a0, b0, 0) s1, c1 := fa(a1, b1, c0) s2, c2 := fa(a2, b2, c1) s3, v = fa(a3, b3, c2) return } func main() { fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1)) }
Please provide an equivalent version of this Python code in Go.
import math from sys import stdout LOG_10 = 2.302585092994 def build_oms(s): if s % 2 == 0: s += 1 q = [[0 for j in range(s)] for i in range(s)] p = 1 i = s // 2 j = 0 while p <= (s * s): q[i][j] = p ti = i + 1 if ti >= s: ti = 0 tj = j - 1 if tj < 0: tj = s - 1 if q[ti][tj] != 0: ti = i tj = j + 1 i = ti j = tj p = p + 1 return q, s def build_sems(s): if s % 2 == 1: s += 1 while s % 4 == 0: s += 2 q = [[0 for j in range(s)] for i in range(s)] z = s // 2 b = z * z c = 2 * b d = 3 * b o = build_oms(z) for j in range(0, z): for i in range(0, z): a = o[0][i][j] q[i][j] = a q[i + z][j + z] = a + b q[i + z][j] = a + c q[i][j + z] = a + d lc = z // 2 rc = lc for j in range(0, z): for i in range(0, s): if i < lc or i > s - rc or (i == lc and j == lc): if not (i == 0 and j == lc): t = q[i][j] q[i][j] = q[i][j + z] q[i][j + z] = t return q, s def format_sqr(s, l): for i in range(0, l - len(s)): s = "0" + s return s + " " def display(q): s = q[1] print(" - {0} x {1}\n".format(s, s)) k = 1 + math.floor(math.log(s * s) / LOG_10) for j in range(0, s): for i in range(0, s): stdout.write(format_sqr("{0}".format(q[0][i][j]), k)) print() print("Magic sum: {0}\n".format(s * ((s * s) + 1) // 2)) stdout.write("Singly Even Magic Square") display(build_sems(6))
package main import ( "fmt" "log" ) func magicSquareOdd(n int) ([][]int, error) { if n < 3 || n%2 == 0 { return nil, fmt.Errorf("base must be odd and > 2") } value := 1 gridSize := n * n c, r := n/2, 0 result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for value <= gridSize { result[r][c] = value if r == 0 { if c == n-1 { r++ } else { r = n - 1 c++ } } else if c == n-1 { r-- c = 0 } else if result[r-1][c+1] == 0 { r-- c++ } else { r++ } value++ } return result, nil } func magicSquareSinglyEven(n int) ([][]int, error) { if n < 6 || (n-2)%4 != 0 { return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2") } size := n * n halfN := n / 2 subSquareSize := size / 4 subSquare, err := magicSquareOdd(halfN) if err != nil { return nil, err } quadrantFactors := [4]int{0, 2, 3, 1} result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for r := 0; r < n; r++ { for c := 0; c < n; c++ { quadrant := r/halfN*2 + c/halfN result[r][c] = subSquare[r%halfN][c%halfN] result[r][c] += quadrantFactors[quadrant] * subSquareSize } } nColsLeft := halfN / 2 nColsRight := nColsLeft - 1 for r := 0; r < halfN; r++ { for c := 0; c < n; c++ { if c < nColsLeft || c >= n-nColsRight || (c == nColsLeft && r == nColsLeft) { if c == 0 && r == nColsLeft { continue } tmp := result[r][c] result[r][c] = result[r+halfN][c] result[r+halfN][c] = tmp } } } return result, nil } func main() { const n = 6 msse, err := magicSquareSinglyEven(n) if err != nil { log.Fatal(err) } for _, row := range msse { for _, x := range row { fmt.Printf("%2d ", x) } fmt.Println() } fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2) }
Write the same algorithm in Go as shown in this Python implementation.
>>> from itertools import permutations >>> pieces = 'KQRrBbNN' >>> starts = {''.join(p).upper() for p in permutations(pieces) if p.index('B') % 2 != p.index('b') % 2 and ( p.index('r') < p.index('K') < p.index('R') or p.index('R') < p.index('K') < p.index('r') ) } >>> len(starts) 960 >>> starts.pop() 'QNBRNKRB' >>>
package main import ( "fmt" "math/rand" ) type symbols struct{ k, q, r, b, n rune } var A = symbols{'K', 'Q', 'R', 'B', 'N'} var W = symbols{'♔', '♕', '♖', '♗', '♘'} var B = symbols{'♚', '♛', '♜', '♝', '♞'} var krn = []string{ "nnrkr", "nrnkr", "nrknr", "nrkrn", "rnnkr", "rnknr", "rnkrn", "rknnr", "rknrn", "rkrnn"} func (sym symbols) chess960(id int) string { var pos [8]rune q, r := id/4, id%4 pos[r*2+1] = sym.b q, r = q/4, q%4 pos[r*2] = sym.b q, r = q/6, q%6 for i := 0; ; i++ { if pos[i] != 0 { continue } if r == 0 { pos[i] = sym.q break } r-- } i := 0 for _, f := range krn[q] { for pos[i] != 0 { i++ } switch f { case 'k': pos[i] = sym.k case 'r': pos[i] = sym.r case 'n': pos[i] = sym.n } } return string(pos[:]) } func main() { fmt.Println(" ID Start position") for _, id := range []int{0, 518, 959} { fmt.Printf("%3d %s\n", id, A.chess960(id)) } fmt.Println("\nRandom") for i := 0; i < 5; i++ { fmt.Println(W.chess960(rand.Intn(960))) } }
Change the programming language of this snippet from Python to Go without modifying what it does.
>>> from itertools import permutations >>> pieces = 'KQRrBbNN' >>> starts = {''.join(p).upper() for p in permutations(pieces) if p.index('B') % 2 != p.index('b') % 2 and ( p.index('r') < p.index('K') < p.index('R') or p.index('R') < p.index('K') < p.index('r') ) } >>> len(starts) 960 >>> starts.pop() 'QNBRNKRB' >>>
package main import ( "fmt" "math/rand" ) type symbols struct{ k, q, r, b, n rune } var A = symbols{'K', 'Q', 'R', 'B', 'N'} var W = symbols{'♔', '♕', '♖', '♗', '♘'} var B = symbols{'♚', '♛', '♜', '♝', '♞'} var krn = []string{ "nnrkr", "nrnkr", "nrknr", "nrkrn", "rnnkr", "rnknr", "rnkrn", "rknnr", "rknrn", "rkrnn"} func (sym symbols) chess960(id int) string { var pos [8]rune q, r := id/4, id%4 pos[r*2+1] = sym.b q, r = q/4, q%4 pos[r*2] = sym.b q, r = q/6, q%6 for i := 0; ; i++ { if pos[i] != 0 { continue } if r == 0 { pos[i] = sym.q break } r-- } i := 0 for _, f := range krn[q] { for pos[i] != 0 { i++ } switch f { case 'k': pos[i] = sym.k case 'r': pos[i] = sym.r case 'n': pos[i] = sym.n } } return string(pos[:]) } func main() { fmt.Println(" ID Start position") for _, id := range []int{0, 518, 959} { fmt.Printf("%3d %s\n", id, A.chess960(id)) } fmt.Println("\nRandom") for i := 0; i < 5; i++ { fmt.Println(W.chess960(rand.Intn(960))) } }
Port the provided Python code into Go while preserving the original functionality.
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
Preserve the algorithm and functionality while converting the code from Python to Go.
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
Produce a functionally identical Go code for the snippet given in Python.
import math def perlin_noise(x, y, z): X = math.floor(x) & 255 Y = math.floor(y) & 255 Z = math.floor(z) & 255 x -= math.floor(x) y -= math.floor(y) z -= math.floor(z) u = fade(x) v = fade(y) w = fade(z) A = p[X ]+Y; AA = p[A]+Z; AB = p[A+1]+Z B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))) def fade(t): return t ** 3 * (t * (t * 6 - 15) + 10) def lerp(t, a, b): return a + t * (b - a) def grad(hash, x, y, z): h = hash & 15 u = x if h<8 else y v = y if h<4 else (x if h in (12, 14) else z) return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v) p = [None] * 512 permutation = [151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180] for i in range(256): p[256+i] = p[i] = permutation[i] if __name__ == '__main__': print("%1.17f" % perlin_noise(3.14, 42, 7))
package main import ( "fmt" "math" ) func main() { fmt.Println(noise(3.14, 42, 7)) } func noise(x, y, z float64) float64 { X := int(math.Floor(x)) & 255 Y := int(math.Floor(y)) & 255 Z := int(math.Floor(z)) & 255 x -= math.Floor(x) y -= math.Floor(y) z -= math.Floor(z) u := fade(x) v := fade(y) w := fade(z) A := p[X] + Y AA := p[A] + Z AB := p[A+1] + Z B := p[X+1] + Y BA := p[B] + Z BB := p[B+1] + Z return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x-1, y, z)), lerp(u, grad(p[AB], x, y-1, z), grad(p[BB], x-1, y-1, z))), lerp(v, lerp(u, grad(p[AA+1], x, y, z-1), grad(p[BA+1], x-1, y, z-1)), lerp(u, grad(p[AB+1], x, y-1, z-1), grad(p[BB+1], x-1, y-1, z-1)))) } func fade(t float64) float64 { return t * t * t * (t*(t*6-15) + 10) } func lerp(t, a, b float64) float64 { return a + t*(b-a) } func grad(hash int, x, y, z float64) float64 { switch hash & 15 { case 0, 12: return x + y case 1, 14: return y - x case 2: return x - y case 3: return -x - y case 4: return x + z case 5: return z - x case 6: return x - z case 7: return -x - z case 8: return y + z case 9, 13: return z - y case 10: return y - z } return -y - z } var permutation = []int{ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, } var p = append(permutation, permutation...)
Change the following Python code into Go without altering its purpose.
import sys, os from collections import Counter def dodir(path): global h for name in os.listdir(path): p = os.path.join(path, name) if os.path.islink(p): pass elif os.path.isfile(p): h[os.stat(p).st_size] += 1 elif os.path.isdir(p): dodir(p) else: pass def main(arg): global h h = Counter() for dir in arg: dodir(dir) s = n = 0 for k, v in sorted(h.items()): print("Size %d -> %d file(s)" % (k, v)) n += v s += k * v print("Total %d bytes for %d files" % (s, n)) main(sys.argv[1:])
package main import ( "fmt" "log" "math" "os" "path/filepath" ) func commatize(n int64) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func fileSizeDistribution(root string) { var sizes [12]int files := 0 directories := 0 totalSize := int64(0) walkFunc := func(path string, info os.FileInfo, err error) error { if err != nil { return err } files++ if info.IsDir() { directories++ } size := info.Size() if size == 0 { sizes[0]++ return nil } totalSize += size logSize := math.Log10(float64(size)) index := int(math.Floor(logSize)) sizes[index+1]++ return nil } err := filepath.Walk(root, walkFunc) if err != nil { log.Fatal(err) } fmt.Printf("File size distribution for '%s' :-\n\n", root) for i := 0; i < len(sizes); i++ { if i == 0 { fmt.Print(" ") } else { fmt.Print("+ ") } fmt.Printf("Files less than 10 ^ %-2d bytes : %5d\n", i, sizes[i]) } fmt.Println(" -----") fmt.Printf("= Total number of files  : %5d\n", files) fmt.Printf(" including directories  : %5d\n", directories) c := commatize(totalSize) fmt.Println("\n Total size of files  :", c, "bytes") } func main() { fileSizeDistribution("./") }
Preserve the algorithm and functionality while converting the code from Python to Go.
>>> import os >>> print('\n'.join(sorted(os.listdir('.')))) DLLs Doc LICENSE.txt Lib NEWS.txt README.txt Scripts Tools include libs python.exe pythonw.exe tcl >>>
package main import ( "fmt" "log" "os" "sort" ) func main() { f, err := os.Open(".") if err != nil { log.Fatal(err) } files, err := f.Readdirnames(0) f.Close() if err != nil { log.Fatal(err) } sort.Strings(files) for _, n := range files { fmt.Println(n) } }
Port the following code from Python to Go with equivalent syntax and logic.
from __future__ import annotations import asyncio import sys from typing import Optional from typing import TextIO class OutOfInkError(Exception): class Printer: def __init__(self, name: str, backup: Optional[Printer]): self.name = name self.backup = backup self.ink_level: int = 5 self.output_stream: TextIO = sys.stdout async def print(self, msg): if self.ink_level <= 0: if self.backup: await self.backup.print(msg) else: raise OutOfInkError(self.name) else: self.ink_level -= 1 self.output_stream.write(f"({self.name}): {msg}\n") async def main(): reserve = Printer("reserve", None) main = Printer("main", reserve) humpty_lines = [ "Humpty Dumpty sat on a wall.", "Humpty Dumpty had a great fall.", "All the king's horses and all the king's men,", "Couldn't put Humpty together again.", ] goose_lines = [ "Old Mother Goose,", "When she wanted to wander,", "Would ride through the air,", "On a very fine gander.", "Jack's mother came in,", "And caught the goose soon,", "And mounting its back,", "Flew up to the moon.", ] async def print_humpty(): for line in humpty_lines: try: task = asyncio.Task(main.print(line)) await task except OutOfInkError: print("\t Humpty Dumpty out of ink!") break async def print_goose(): for line in goose_lines: try: task = asyncio.Task(main.print(line)) await task except OutOfInkError: print("\t Mother Goose out of ink!") break await asyncio.gather(print_goose(), print_humpty()) if __name__ == "__main__": asyncio.run(main(), debug=True)
package main import ( "errors" "fmt" "strings" "sync" ) var hdText = `Humpty Dumpty sat on a wall. Humpty Dumpty had a great fall. All the king's horses and all the king's men, Couldn't put Humpty together again.` var mgText = `Old Mother Goose, When she wanted to wander, Would ride through the air, On a very fine gander. Jack's mother came in, And caught the goose soon, And mounting its back, Flew up to the moon.` func main() { reservePrinter := startMonitor(newPrinter(5), nil) mainPrinter := startMonitor(newPrinter(5), reservePrinter) var busy sync.WaitGroup busy.Add(2) go writer(mainPrinter, "hd", hdText, &busy) go writer(mainPrinter, "mg", mgText, &busy) busy.Wait() } type printer func(string) error func newPrinter(ink int) printer { return func(line string) error { if ink == 0 { return eOutOfInk } for _, c := range line { fmt.Printf("%c", c) } fmt.Println() ink-- return nil } } var eOutOfInk = errors.New("out of ink") type rSync struct { call chan string response chan error } func (r *rSync) print(data string) error { r.call <- data return <-r.response } func monitor(hardPrint printer, entry, reserve *rSync) { for { data := <-entry.call switch err := hardPrint(data); { case err == nil: entry.response <- nil case err == eOutOfInk && reserve != nil: entry.response <- reserve.print(data) default: entry.response <- err } } } func startMonitor(p printer, reservePrinter *rSync) *rSync { entry := &rSync{make(chan string), make(chan error)} go monitor(p, entry, reservePrinter) return entry } func writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) { for _, line := range strings.Split(text, "\n") { if err := printMonitor.print(line); err != nil { fmt.Printf("**** writer task %q terminated: %v ****\n", id, err) break } } busy.Done() }
Write a version of this Python function in Go with identical behavior.
from __future__ import annotations import asyncio import sys from typing import Optional from typing import TextIO class OutOfInkError(Exception): class Printer: def __init__(self, name: str, backup: Optional[Printer]): self.name = name self.backup = backup self.ink_level: int = 5 self.output_stream: TextIO = sys.stdout async def print(self, msg): if self.ink_level <= 0: if self.backup: await self.backup.print(msg) else: raise OutOfInkError(self.name) else: self.ink_level -= 1 self.output_stream.write(f"({self.name}): {msg}\n") async def main(): reserve = Printer("reserve", None) main = Printer("main", reserve) humpty_lines = [ "Humpty Dumpty sat on a wall.", "Humpty Dumpty had a great fall.", "All the king's horses and all the king's men,", "Couldn't put Humpty together again.", ] goose_lines = [ "Old Mother Goose,", "When she wanted to wander,", "Would ride through the air,", "On a very fine gander.", "Jack's mother came in,", "And caught the goose soon,", "And mounting its back,", "Flew up to the moon.", ] async def print_humpty(): for line in humpty_lines: try: task = asyncio.Task(main.print(line)) await task except OutOfInkError: print("\t Humpty Dumpty out of ink!") break async def print_goose(): for line in goose_lines: try: task = asyncio.Task(main.print(line)) await task except OutOfInkError: print("\t Mother Goose out of ink!") break await asyncio.gather(print_goose(), print_humpty()) if __name__ == "__main__": asyncio.run(main(), debug=True)
package main import ( "errors" "fmt" "strings" "sync" ) var hdText = `Humpty Dumpty sat on a wall. Humpty Dumpty had a great fall. All the king's horses and all the king's men, Couldn't put Humpty together again.` var mgText = `Old Mother Goose, When she wanted to wander, Would ride through the air, On a very fine gander. Jack's mother came in, And caught the goose soon, And mounting its back, Flew up to the moon.` func main() { reservePrinter := startMonitor(newPrinter(5), nil) mainPrinter := startMonitor(newPrinter(5), reservePrinter) var busy sync.WaitGroup busy.Add(2) go writer(mainPrinter, "hd", hdText, &busy) go writer(mainPrinter, "mg", mgText, &busy) busy.Wait() } type printer func(string) error func newPrinter(ink int) printer { return func(line string) error { if ink == 0 { return eOutOfInk } for _, c := range line { fmt.Printf("%c", c) } fmt.Println() ink-- return nil } } var eOutOfInk = errors.New("out of ink") type rSync struct { call chan string response chan error } func (r *rSync) print(data string) error { r.call <- data return <-r.response } func monitor(hardPrint printer, entry, reserve *rSync) { for { data := <-entry.call switch err := hardPrint(data); { case err == nil: entry.response <- nil case err == eOutOfInk && reserve != nil: entry.response <- reserve.print(data) default: entry.response <- err } } } func startMonitor(p printer, reservePrinter *rSync) *rSync { entry := &rSync{make(chan string), make(chan error)} go monitor(p, entry, reservePrinter) return entry } func writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) { for _, line := range strings.Split(text, "\n") { if err := printMonitor.print(line); err != nil { fmt.Printf("**** writer task %q terminated: %v ****\n", id, err) break } } busy.Done() }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
environments = [{'cnt':0, 'seq':i+1} for i in range(12)] code = while any(env['seq'] > 1 for env in environments): for env in environments: exec(code, globals(), env) print() print('Counts') for env in environments: print('% 4d' % env['cnt'], end='') print()
package main import "fmt" const jobs = 12 type environment struct{ seq, cnt int } var ( env [jobs]environment seq, cnt *int ) func hail() { fmt.Printf("% 4d", *seq) if *seq == 1 { return } (*cnt)++ if *seq&1 != 0 { *seq = 3*(*seq) + 1 } else { *seq /= 2 } } func switchTo(id int) { seq = &env[id].seq cnt = &env[id].cnt } func main() { for i := 0; i < jobs; i++ { switchTo(i) env[i].seq = i + 1 } again: for i := 0; i < jobs; i++ { switchTo(i) hail() } fmt.Println() for j := 0; j < jobs; j++ { switchTo(j) if *seq != 1 { goto again } } fmt.Println() fmt.Println("COUNTS:") for i := 0; i < jobs; i++ { switchTo(i) fmt.Printf("% 4d", *cnt) } fmt.Println() }
Rewrite the snippet below in Go so it works the same as the original Python code.
from unicodedata import name def unicode_code(ch): return 'U+{:04x}'.format(ord(ch)) def utf8hex(ch): return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper() if __name__ == "__main__": print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)')) chars = ['A', 'ö', 'Ж', '€', '𝄞'] for char in chars: print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
package main import ( "bytes" "encoding/hex" "fmt" "log" "strings" ) var testCases = []struct { rune string }{ {'A', "41"}, {'ö', "C3 B6"}, {'Ж', "D0 96"}, {'€', "E2 82 AC"}, {'𝄞', "F0 9D 84 9E"}, } func main() { for _, tc := range testCases { u := fmt.Sprintf("U+%04X", tc.rune) b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1)) if err != nil { log.Fatal("bad test data") } e := encodeUTF8(tc.rune) d := decodeUTF8(b) fmt.Printf("%c  %-7s %X\n", d, u, e) if !bytes.Equal(e, b) { log.Fatal("encodeUTF8 wrong") } if d != tc.rune { log.Fatal("decodeUTF8 wrong") } } } const ( b2Lead = 0xC0 b2Mask = 0x1F b3Lead = 0xE0 b3Mask = 0x0F b4Lead = 0xF0 b4Mask = 0x07 mbLead = 0x80 mbMask = 0x3F ) func encodeUTF8(r rune) []byte { switch i := uint32(r); { case i <= 1<<7-1: return []byte{byte(r)} case i <= 1<<11-1: return []byte{ b2Lead | byte(r>>6), mbLead | byte(r)&mbMask} case i <= 1<<16-1: return []byte{ b3Lead | byte(r>>12), mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} default: return []byte{ b4Lead | byte(r>>18), mbLead | byte(r>>12)&mbMask, mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} } } func decodeUTF8(b []byte) rune { switch b0 := b[0]; { case b0 < 0x80: return rune(b0) case b0 < 0xE0: return rune(b0&b2Mask)<<6 | rune(b[1]&mbMask) case b0 < 0xF0: return rune(b0&b3Mask)<<12 | rune(b[1]&mbMask)<<6 | rune(b[2]&mbMask) default: return rune(b0&b4Mask)<<18 | rune(b[1]&mbMask)<<12 | rune(b[2]&mbMask)<<6 | rune(b[3]&mbMask) } }
Please provide an equivalent version of this Python code in Go.
from unicodedata import name def unicode_code(ch): return 'U+{:04x}'.format(ord(ch)) def utf8hex(ch): return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper() if __name__ == "__main__": print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)')) chars = ['A', 'ö', 'Ж', '€', '𝄞'] for char in chars: print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
package main import ( "bytes" "encoding/hex" "fmt" "log" "strings" ) var testCases = []struct { rune string }{ {'A', "41"}, {'ö', "C3 B6"}, {'Ж', "D0 96"}, {'€', "E2 82 AC"}, {'𝄞', "F0 9D 84 9E"}, } func main() { for _, tc := range testCases { u := fmt.Sprintf("U+%04X", tc.rune) b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1)) if err != nil { log.Fatal("bad test data") } e := encodeUTF8(tc.rune) d := decodeUTF8(b) fmt.Printf("%c  %-7s %X\n", d, u, e) if !bytes.Equal(e, b) { log.Fatal("encodeUTF8 wrong") } if d != tc.rune { log.Fatal("decodeUTF8 wrong") } } } const ( b2Lead = 0xC0 b2Mask = 0x1F b3Lead = 0xE0 b3Mask = 0x0F b4Lead = 0xF0 b4Mask = 0x07 mbLead = 0x80 mbMask = 0x3F ) func encodeUTF8(r rune) []byte { switch i := uint32(r); { case i <= 1<<7-1: return []byte{byte(r)} case i <= 1<<11-1: return []byte{ b2Lead | byte(r>>6), mbLead | byte(r)&mbMask} case i <= 1<<16-1: return []byte{ b3Lead | byte(r>>12), mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} default: return []byte{ b4Lead | byte(r>>18), mbLead | byte(r>>12)&mbMask, mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} } } func decodeUTF8(b []byte) rune { switch b0 := b[0]; { case b0 < 0x80: return rune(b0) case b0 < 0xE0: return rune(b0&b2Mask)<<6 | rune(b[1]&mbMask) case b0 < 0xF0: return rune(b0&b3Mask)<<12 | rune(b[1]&mbMask)<<6 | rune(b[2]&mbMask) default: return rune(b0&b4Mask)<<18 | rune(b[1]&mbMask)<<12 | rune(b[2]&mbMask)<<6 | rune(b[3]&mbMask) } }
Ensure the translated Go code behaves exactly like the original Python snippet.
from __future__ import division import sys from PIL import Image def _fpart(x): return x - int(x) def _rfpart(x): return 1 - _fpart(x) def putpixel(img, xy, color, alpha=1): compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg)) c = compose_color(img.getpixel(xy), color) img.putpixel(xy, c) def draw_line(img, p1, p2, color): x1, y1 = p1 x2, y2 = p2 dx, dy = x2-x1, y2-y1 steep = abs(dx) < abs(dy) p = lambda px, py: ((px,py), (py,px))[steep] if steep: x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx if x2 < x1: x1, x2, y1, y2 = x2, x1, y2, y1 grad = dy/dx intery = y1 + _rfpart(x1) * grad def draw_endpoint(pt): x, y = pt xend = round(x) yend = y + grad * (xend - x) xgap = _rfpart(x + 0.5) px, py = int(xend), int(yend) putpixel(img, p(px, py), color, _rfpart(yend) * xgap) putpixel(img, p(px, py+1), color, _fpart(yend) * xgap) return px xstart = draw_endpoint(p(*p1)) + 1 xend = draw_endpoint(p(*p2)) for x in range(xstart, xend): y = int(intery) putpixel(img, p(x, y), color, _rfpart(intery)) putpixel(img, p(x, y+1), color, _fpart(intery)) intery += grad if __name__ == '__main__': if len(sys.argv) != 2: print 'usage: python xiaolinwu.py [output-file]' sys.exit(-1) blue = (0, 0, 255) yellow = (255, 255, 0) img = Image.new("RGB", (500,500), blue) for a in range(10, 431, 60): draw_line(img, (10, 10), (490, a), yellow) draw_line(img, (10, 10), (a, 490), yellow) draw_line(img, (10, 10), (490, 490), yellow) filename = sys.argv[1] img.save(filename) print 'image saved to', filename
package raster import "math" func ipart(x float64) float64 { return math.Floor(x) } func round(x float64) float64 { return ipart(x + .5) } func fpart(x float64) float64 { return x - ipart(x) } func rfpart(x float64) float64 { return 1 - fpart(x) } func (g *Grmap) AaLine(x1, y1, x2, y2 float64) { dx := x2 - x1 dy := y2 - y1 ax := dx if ax < 0 { ax = -ax } ay := dy if ay < 0 { ay = -ay } var plot func(int, int, float64) if ax < ay { x1, y1 = y1, x1 x2, y2 = y2, x2 dx, dy = dy, dx plot = func(x, y int, c float64) { g.SetPx(y, x, uint16(c*math.MaxUint16)) } } else { plot = func(x, y int, c float64) { g.SetPx(x, y, uint16(c*math.MaxUint16)) } } if x2 < x1 { x1, x2 = x2, x1 y1, y2 = y2, y1 } gradient := dy / dx xend := round(x1) yend := y1 + gradient*(xend-x1) xgap := rfpart(x1 + .5) xpxl1 := int(xend) ypxl1 := int(ipart(yend)) plot(xpxl1, ypxl1, rfpart(yend)*xgap) plot(xpxl1, ypxl1+1, fpart(yend)*xgap) intery := yend + gradient xend = round(x2) yend = y2 + gradient*(xend-x2) xgap = fpart(x2 + 0.5) xpxl2 := int(xend) ypxl2 := int(ipart(yend)) plot(xpxl2, ypxl2, rfpart(yend)*xgap) plot(xpxl2, ypxl2+1, fpart(yend)*xgap) for x := xpxl1 + 1; x <= xpxl2-1; x++ { plot(x, int(ipart(intery)), rfpart(intery)) plot(x, int(ipart(intery))+1, fpart(intery)) intery = intery + gradient } }
Ensure the translated Go code behaves exactly like the original Python snippet.
import curses def print_message(): stdscr.addstr('This is the message.\n') stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) stdscr.addstr('CTRL+P for message or q to quit.\n') while True: c = stdscr.getch() if c == 16: print_message() elif c == ord('q'): break curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin()
package main import "C" import "fmt" import "unsafe" func main() { d := C.XOpenDisplay(nil) f7, f6 := C.CString("F7"), C.CString("F6") defer C.free(unsafe.Pointer(f7)) defer C.free(unsafe.Pointer(f6)) if d != nil { C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync) C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync) var event C.XEvent for { C.XNextEvent(d, &event) if C.getXEvent_type(event) == C.KeyPress { xkeyEvent := C.getXEvent_xkey(event) s := C.XLookupKeysym(&xkeyEvent, 0) if s == C.XK_F7 { fmt.Println("something's happened") } else if s == C.XK_F6 { break } } } C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d)) C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d)) } else { fmt.Println("XOpenDisplay did not succeed") } }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
>>> from itertools import product >>> nuggets = set(range(101)) >>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)): nuggets.discard(6*s + 9*n + 20*t) >>> max(nuggets) 43 >>>
package main import "fmt" func mcnugget(limit int) { sv := make([]bool, limit+1) for s := 0; s <= limit; s += 6 { for n := s; n <= limit; n += 9 { for t := n; t <= limit; t += 20 { sv[t] = true } } } for i := limit; i >= 0; i-- { if !sv[i] { fmt.Println("Maximum non-McNuggets number is", i) return } } } func main() { mcnugget(100) }
Write the same code in Go as shown below in Python.
def MagicSquareDoublyEven(order): sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ] n1 = order/4 for r in range(n1): r1 = sq[r][n1:-n1] r2 = sq[order -r - 1][n1:-n1] r1.reverse() r2.reverse() sq[r][n1:-n1] = r2 sq[order -r - 1][n1:-n1] = r1 for r in range(n1, order-n1): r1 = sq[r][:n1] r2 = sq[order -r - 1][order-n1:] r1.reverse() r2.reverse() sq[r][:n1] = r2 sq[order -r - 1][order-n1:] = r1 return sq def printsq(s): n = len(s) bl = len(str(n**2))+1 for i in range(n): print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] ) print "\nMagic constant = %d"%sum(s[0]) printsq(MagicSquareDoublyEven(8))
package main import ( "fmt" "log" "strings" ) const dimensions int = 8 func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 size := d * d mult := d / 4 for i, r := 0, 0; r < d; r++ { output = append(output, []int{}) for c := 0; c < d; i, c = i+1, c+1 { bitPos := c/mult + (r/mult)*4 if (bits & (1 << uint(bitPos))) != 0 { output[r] = append(output[r], i+1) } else { output[r] = append(output[r], size-i) } } } return output, nil } func arrayItoa(input []int) []string { var output []string for _, i := range input { output = append(output, fmt.Sprintf("%4d", i)) } return output } func main() { data, err := setupMagicSquareData(dimensions) if err != nil { log.Fatal(err) } magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2 for _, row := range data { fmt.Println(strings.Join(arrayItoa(row), " ")) } fmt.Printf("\nMagic Constant: %d\n", magicConstant) }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
>>> >>> inf = 1e234 * 1e234 >>> _inf = 1e234 * -1e234 >>> _zero = 1 / _inf >>> nan = inf + _inf >>> inf, _inf, _zero, nan (inf, -inf, -0.0, nan) >>> >>> for value in (inf, _inf, _zero, nan): print (value) inf -inf -0.0 nan >>> >>> float('nan') nan >>> float('inf') inf >>> float('-inf') -inf >>> -0. -0.0 >>> >>> nan == nan False >>> nan is nan True >>> 0. == -0. True >>> 0. is -0. False >>> inf + _inf nan >>> 0.0 * nan nan >>> nan * 0.0 nan >>> 0.0 * inf nan >>> inf * 0.0 nan
package main import ( "fmt" "math" ) func main() { var zero float64 var negZero, posInf, negInf, nan float64 negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero fmt.Println(negZero, posInf, negInf, nan) fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN()) fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") } func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } } func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } } func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } } func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } } func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
Convert the following code from Python to Go, ensuring the logic remains intact.
>>> >>> inf = 1e234 * 1e234 >>> _inf = 1e234 * -1e234 >>> _zero = 1 / _inf >>> nan = inf + _inf >>> inf, _inf, _zero, nan (inf, -inf, -0.0, nan) >>> >>> for value in (inf, _inf, _zero, nan): print (value) inf -inf -0.0 nan >>> >>> float('nan') nan >>> float('inf') inf >>> float('-inf') -inf >>> -0. -0.0 >>> >>> nan == nan False >>> nan is nan True >>> 0. == -0. True >>> 0. is -0. False >>> inf + _inf nan >>> 0.0 * nan nan >>> nan * 0.0 nan >>> 0.0 * inf nan >>> inf * 0.0 nan
package main import ( "fmt" "math" ) func main() { var zero float64 var negZero, posInf, negInf, nan float64 negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero fmt.Println(negZero, posInf, negInf, nan) fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN()) fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") } func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } } func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } } func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } } func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } } func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
>>> >>> inf = 1e234 * 1e234 >>> _inf = 1e234 * -1e234 >>> _zero = 1 / _inf >>> nan = inf + _inf >>> inf, _inf, _zero, nan (inf, -inf, -0.0, nan) >>> >>> for value in (inf, _inf, _zero, nan): print (value) inf -inf -0.0 nan >>> >>> float('nan') nan >>> float('inf') inf >>> float('-inf') -inf >>> -0. -0.0 >>> >>> nan == nan False >>> nan is nan True >>> 0. == -0. True >>> 0. is -0. False >>> inf + _inf nan >>> 0.0 * nan nan >>> nan * 0.0 nan >>> 0.0 * inf nan >>> inf * 0.0 nan
package main import ( "fmt" "math" ) func main() { var zero float64 var negZero, posInf, negInf, nan float64 negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero fmt.Println(negZero, posInf, negInf, nan) fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN()) fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") } func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } } func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } } func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } } func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } } func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
Rewrite the snippet below in Go so it works the same as the original Python code.
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 const = 0x2545F4914F6CDD1D class Xorshift_star(): def __init__(self, seed=0): self.state = seed & mask64 def seed(self, num): self.state = num & mask64 def next_int(self): "return random int between 0 and 2**32" x = self.state x = (x ^ (x >> 12)) & mask64 x = (x ^ (x << 25)) & mask64 x = (x ^ (x >> 27)) & mask64 self.state = x answer = (((x * const) & mask64) >> 32) & mask32 return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / (1 << 32) if __name__ == '__main__': random_gen = Xorshift_star() random_gen.seed(1234567) for i in range(5): print(random_gen.next_int()) random_gen.seed(987654321) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
package main import ( "fmt" "math" ) const CONST = 0x2545F4914F6CDD1D type XorshiftStar struct{ state uint64 } func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} } func (xor *XorshiftStar) seed(state uint64) { xor.state = state } func (xor *XorshiftStar) nextInt() uint32 { x := xor.state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) xor.state = x return uint32((x * CONST) >> 32) } func (xor *XorshiftStar) nextFloat() float64 { return float64(xor.nextInt()) / (1 << 32) } func main() { randomGen := XorshiftStarNew(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
Please provide an equivalent version of this Python code in Go.
import inflect def count_letters(word): count = 0 for letter in word: if letter != ',' and letter !='-' and letter !=' ': count += 1 return count def split_with_spaces(sentence): sentence_list = [] curr_word = "" for c in sentence: if c == " " and curr_word != "": sentence_list.append(curr_word+" ") curr_word = "" else: curr_word += c if len(curr_word) > 0: sentence_list.append(curr_word) return sentence_list def my_num_to_words(p, my_number): number_string_list = p.number_to_words(my_number, wantlist=True, andword='') number_string = number_string_list[0] for i in range(1,len(number_string_list)): number_string += " " + number_string_list[i] return number_string def build_sentence(p, max_words): sentence_list = split_with_spaces("Four is the number of letters in the first word of this sentence,") num_words = 13 word_number = 2 while num_words < max_words: ordinal_string = my_num_to_words(p, p.ordinal(word_number)) word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1])) new_string = " "+word_number_string+" in the "+ordinal_string+"," new_list = split_with_spaces(new_string) sentence_list += new_list num_words += len(new_list) word_number += 1 return sentence_list, num_words def word_and_counts(word_num): sentence_list, num_words = build_sentence(p, word_num) word_str = sentence_list[word_num - 1].strip(' ,') num_letters = len(word_str) num_characters = 0 for word in sentence_list: num_characters += len(word) print('Word {0:8d} is "{1}", with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters)) p = inflect.engine() sentence_list, num_words = build_sentence(p, 201) print(" ") print("The lengths of the first 201 words are:") print(" ") print('{0:3d}: '.format(1),end='') total_characters = 0 for word_index in range(201): word_length = count_letters(sentence_list[word_index]) total_characters += len(sentence_list[word_index]) print('{0:2d}'.format(word_length),end='') if (word_index+1) % 20 == 0: print(" ") print('{0:3d}: '.format(word_index + 2),end='') else: print(" ",end='') print(" ") print(" ") print("Length of the sentence so far: "+str(total_characters)) print(" ") word_and_counts(1000) word_and_counts(10000) word_and_counts(100000) word_and_counts(1000000) word_and_counts(10000000)
package main import ( "fmt" "strings" "unicode" ) func main() { f := NewFourIsSeq() fmt.Print("The lengths of the first 201 words are:") for i := 1; i <= 201; i++ { if i%25 == 1 { fmt.Printf("\n%3d: ", i) } _, n := f.WordLen(i) fmt.Printf(" %2d", n) } fmt.Println() fmt.Println("Length of sentence so far:", f.TotalLength()) for i := 1000; i <= 1e7; i *= 10 { w, n := f.WordLen(i) fmt.Printf("Word %8d is %q, with %d letters.", i, w, n) fmt.Println(" Length of sentence so far:", f.TotalLength()) } } type FourIsSeq struct { i int words []string } func NewFourIsSeq() *FourIsSeq { return &FourIsSeq{ words: []string{ "Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,", }, } } func (f *FourIsSeq) WordLen(w int) (string, int) { for len(f.words) < w { f.i++ n := countLetters(f.words[f.i]) ns := say(int64(n)) os := sayOrdinal(int64(f.i+1)) + "," f.words = append(f.words, strings.Fields(ns)...) f.words = append(f.words, "in", "the") f.words = append(f.words, strings.Fields(os)...) } word := f.words[w-1] return word, countLetters(word) } func (f FourIsSeq) TotalLength() int { cnt := 0 for _, w := range f.words { cnt += len(w) + 1 } return cnt - 1 } func countLetters(s string) int { cnt := 0 for _, r := range s { if unicode.IsLetter(r) { cnt++ } } return cnt }
Produce a language-to-language conversion: from Python to Go, same semantics.
def validate(diagram): rawlines = diagram.splitlines() lines = [] for line in rawlines: if line != '': lines.append(line) if len(lines) == 0: print('diagram has no non-empty lines!') return None width = len(lines[0]) cols = (width - 1) // 3 if cols not in [8, 16, 32, 64]: print('number of columns should be 8, 16, 32 or 64') return None if len(lines)%2 == 0: print('number of non-empty lines should be odd') return None if lines[0] != (('+--' * cols)+'+'): print('incorrect header line') return None for i in range(len(lines)): line=lines[i] if i == 0: continue elif i%2 == 0: if line != lines[0]: print('incorrect separator line') return None elif len(line) != width: print('inconsistent line widths') return None elif line[0] != '|' or line[width-1] != '|': print("non-separator lines must begin and end with '|'") return None return lines def decode(lines): print("Name Bits Start End") print("======= ==== ===== ===") startbit = 0 results = [] for line in lines: infield=False for c in line: if not infield and c == '|': infield = True spaces = 0 name = '' elif infield: if c == ' ': spaces += 1 elif c != '|': name += c else: bits = (spaces + len(name) + 1) // 3 endbit = startbit + bits - 1 print('{0:7} {1:2d} {2:2d} {3:2d}'.format(name, bits, startbit, endbit)) reslist = [name, bits, startbit, endbit] results.append(reslist) spaces = 0 name = '' startbit += bits return results def unpack(results, hex): print("\nTest string in hex:") print(hex) print("\nTest string in binary:") bin = f'{int(hex, 16):0>{4*len(hex)}b}' print(bin) print("\nUnpacked:\n") print("Name Size Bit pattern") print("======= ==== ================") for r in results: name = r[0] size = r[1] startbit = r[2] endbit = r[3] bitpattern = bin[startbit:endbit+1] print('{0:7} {1:2d} {2:16}'.format(name, size, bitpattern)) diagram = lines = validate(diagram) if lines == None: print("No lines returned") else: print(" ") print("Diagram after trimming whitespace and removal of blank lines:") print(" ") for line in lines: print(line) print(" ") print("Decoded:") print(" ") results = decode(lines) hex = "78477bbf5496e12e1bf169a4" unpack(results, hex)
package main import ( "fmt" "log" "math/big" "strings" ) type result struct { name string size int start int end int } func (r result) String() string { return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end) } func validate(diagram string) []string { var lines []string for _, line := range strings.Split(diagram, "\n") { line = strings.Trim(line, " \t") if line != "" { lines = append(lines, line) } } if len(lines) == 0 { log.Fatal("diagram has no non-empty lines!") } width := len(lines[0]) cols := (width - 1) / 3 if cols != 8 && cols != 16 && cols != 32 && cols != 64 { log.Fatal("number of columns should be 8, 16, 32 or 64") } if len(lines)%2 == 0 { log.Fatal("number of non-empty lines should be odd") } if lines[0] != strings.Repeat("+--", cols)+"+" { log.Fatal("incorrect header line") } for i, line := range lines { if i == 0 { continue } else if i%2 == 0 { if line != lines[0] { log.Fatal("incorrect separator line") } } else if len(line) != width { log.Fatal("inconsistent line widths") } else if line[0] != '|' || line[width-1] != '|' { log.Fatal("non-separator lines must begin and end with '|'") } } return lines } func decode(lines []string) []result { fmt.Println("Name Bits Start End") fmt.Println("======= ==== ===== ===") start := 0 width := len(lines[0]) var results []result for i, line := range lines { if i%2 == 0 { continue } line := line[1 : width-1] for _, name := range strings.Split(line, "|") { size := (len(name) + 1) / 3 name = strings.TrimSpace(name) res := result{name, size, start, start + size - 1} results = append(results, res) fmt.Println(res) start += size } } return results } func unpack(results []result, hex string) { fmt.Println("\nTest string in hex:") fmt.Println(hex) fmt.Println("\nTest string in binary:") bin := hex2bin(hex) fmt.Println(bin) fmt.Println("\nUnpacked:\n") fmt.Println("Name Size Bit pattern") fmt.Println("======= ==== ================") for _, res := range results { fmt.Printf("%-7s %2d %s\n", res.name, res.size, bin[res.start:res.end+1]) } } func hex2bin(hex string) string { z := new(big.Int) z.SetString(hex, 16) return fmt.Sprintf("%0*b", 4*len(hex), z) } func main() { const diagram = ` +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ` lines := validate(diagram) fmt.Println("Diagram after trimming whitespace and removal of blank lines:\n") for _, line := range lines { fmt.Println(line) } fmt.Println("\nDecoded:\n") results := decode(lines) hex := "78477bbf5496e12e1bf169a4" unpack(results, hex) }
Convert this Python snippet to Go and keep its semantics consistent.
from difflib import ndiff def levenshtein(str1, str2): result = "" pos, removed = 0, 0 for x in ndiff(str1, str2): if pos<len(str1) and str1[pos] == x[2]: pos += 1 result += x[2] if x[0] == "-": removed += 1 continue else: if removed > 0: removed -=1 else: result += "-" print(result) levenshtein("place","palace") levenshtein("rosettacode","raisethysword")
package main import ( "fmt" "github.com/biogo/biogo/align" ab "github.com/biogo/biogo/alphabet" "github.com/biogo/biogo/feat" "github.com/biogo/biogo/seq/linear" ) func main() { lc := ab.Must(ab.NewAlphabet("-abcdefghijklmnopqrstuvwxyz", feat.Undefined, '-', 0, true)) nw := make(align.NW, lc.Len()) for i := range nw { r := make([]int, lc.Len()) nw[i] = r for j := range r { if j != i { r[j] = -1 } } } a := &linear.Seq{Seq: ab.BytesToLetters([]byte("rosettacode"))} a.Alpha = lc b := &linear.Seq{Seq: ab.BytesToLetters([]byte("raisethysword"))} b.Alpha = lc aln, err := nw.Align(a, b) if err != nil { fmt.Println(err) return } fa := align.Format(a, b, aln, '-') fmt.Printf("%s\n%s\n", fa[0], fa[1]) aa := fmt.Sprint(fa[0]) ba := fmt.Sprint(fa[1]) ma := make([]byte, len(aa)) for i := range ma { if aa[i] == ba[i] { ma[i] = ' ' } else { ma[i] = '|' } } fmt.Println(string(ma)) }
Generate a Go translation of this Python snippet without changing its computational steps.
def builtinsort(x): x.sort() def partition(seq, pivot): low, middle, up = [], [], [] for x in seq: if x < pivot: low.append(x) elif x == pivot: middle.append(x) else: up.append(x) return low, middle, up import random def qsortranpart(seq): size = len(seq) if size < 2: return seq low, middle, up = partition(seq, random.choice(seq)) return qsortranpart(low) + middle + qsortranpart(up)
package main import ( "log" "math/rand" "testing" "time" "github.com/gonum/plot" "github.com/gonum/plot/plotter" "github.com/gonum/plot/plotutil" "github.com/gonum/plot/vg" ) func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } } func insertionsort(a []int) { for i := 1; i < len(a); i++ { value := a[i] j := i - 1 for j >= 0 && a[j] > value { a[j+1] = a[j] j = j - 1 } a[j+1] = value } } func quicksort(a []int) { var pex func(int, int) pex = func(lower, upper int) { for { switch upper - lower { case -1, 0: return case 1: if a[upper] < a[lower] { a[upper], a[lower] = a[lower], a[upper] } return } bx := (upper + lower) / 2 b := a[bx] lp := lower up := upper outer: for { for lp < upper && !(b < a[lp]) { lp++ } for { if lp > up { break outer } if a[up] < b { break } up-- } a[lp], a[up] = a[up], a[lp] lp++ up-- } if bx < lp { if bx < lp-1 { a[bx], a[lp-1] = a[lp-1], b } up = lp - 2 } else { if bx > lp { a[bx], a[lp] = a[lp], b } up = lp - 1 lp++ } if up-lower < upper-lp { pex(lower, up) lower = lp } else { pex(lp, upper) upper = up } } } pex(0, len(a)-1) } func ones(n int) []int { s := make([]int, n) for i := range s { s[i] = 1 } return s } func ascending(n int) []int { s := make([]int, n) v := 1 for i := 0; i < n; { if rand.Intn(3) == 0 { s[i] = v i++ } v++ } return s } func shuffled(n int) []int { return rand.Perm(n) } const ( nPts = 7 inc = 1000 ) var ( p *plot.Plot sortName = []string{"Bubble sort", "Insertion sort", "Quicksort"} sortFunc = []func([]int){bubblesort, insertionsort, quicksort} dataName = []string{"Ones", "Ascending", "Shuffled"} dataFunc = []func(int) []int{ones, ascending, shuffled} ) func main() { rand.Seed(time.Now().Unix()) var err error p, err = plot.New() if err != nil { log.Fatal(err) } p.X.Label.Text = "Data size" p.Y.Label.Text = "microseconds" p.Y.Scale = plot.LogScale{} p.Y.Tick.Marker = plot.LogTicks{} p.Y.Min = .5 for dx, name := range dataName { s, err := plotter.NewScatter(plotter.XYs{}) if err != nil { log.Fatal(err) } s.Shape = plotutil.DefaultGlyphShapes[dx] p.Legend.Add(name, s) } for sx, name := range sortName { l, err := plotter.NewLine(plotter.XYs{}) if err != nil { log.Fatal(err) } l.Color = plotutil.DarkColors[sx] p.Legend.Add(name, l) } for sx := range sortFunc { bench(sx, 0, 1) bench(sx, 1, 5) bench(sx, 2, 5) } if err := p.Save(5*vg.Inch, 5*vg.Inch, "comp.png"); err != nil { log.Fatal(err) } } func bench(sx, dx, rep int) { log.Println("bench", sortName[sx], dataName[dx], "x", rep) pts := make(plotter.XYs, nPts) sf := sortFunc[sx] for i := range pts { x := (i + 1) * inc s0 := dataFunc[dx](x) s := make([]int, x) var tSort int64 for j := 0; j < rep; j++ { tSort += testing.Benchmark(func(b *testing.B) { for i := 0; i < b.N; i++ { copy(s, s0) sf(s) } }).NsPerOp() } tSort /= int64(rep) log.Println(x, "items", tSort, "ns") pts[i] = struct{ X, Y float64 }{float64(x), float64(tSort) * .001} } pl, ps, err := plotter.NewLinePoints(pts) if err != nil { log.Fatal(err) } pl.Color = plotutil.DarkColors[sx] ps.Color = plotutil.DarkColors[sx] ps.Shape = plotutil.DefaultGlyphShapes[dx] p.Add(pl, ps) }
Maintain the same structure and functionality when rewriting this code in Go.
try: from itertools import zip_longest as izip_longest except: from itertools import izip_longest def fringe(tree): for node1 in tree: if isinstance(node1, tuple): for node2 in fringe(node1): yield node2 else: yield node1 def same_fringe(tree1, tree2): return all(node1 == node2 for node1, node2 in izip_longest(fringe(tree1), fringe(tree2))) if __name__ == '__main__': a = 1, 2, 3, 4, 5, 6, 7, 8 b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8)))) c = (((1, 2), 3), 4), 5, 6, 7, 8 x = 1, 2, 3, 4, 5, 6, 7, 8, 9 y = 0, 2, 3, 4, 5, 6, 7, 8 z = 1, 2, (4, 3), 5, 6, 7, 8 assert same_fringe(a, a) assert same_fringe(a, b) assert same_fringe(a, c) assert not same_fringe(a, x) assert not same_fringe(a, y) assert not same_fringe(a, z)
package main import "fmt" type node struct { int left, right *node } func leaves(t *node) chan int { ch := make(chan int) var f func(*node) f = func(n *node) { if n == nil { return } if n.left == nil && n.right == nil { ch <- n.int } else { f(n.left) f(n.right) } } go func() { f(t) close(ch) }() return ch } func sameFringe(t1, t2 *node) bool { f1 := leaves(t1) f2 := leaves(t2) for l1 := range f1 { if l2, ok := <-f2; !ok || l1 != l2 { return false } } _, ok := <-f2 return !ok } func main() { t1 := &node{3, &node{1, &node{int: 1}, &node{int: 2}}, &node{8, &node{int: 5}, &node{int: 13}}} t2 := &node{-8, &node{-3, &node{-1, &node{int: 1}, &node{int: 2}}, &node{int: 5}}, &node{int: 13}} fmt.Println(sameFringe(t1, t2)) }
Please provide an equivalent version of this Python code in Go.
try: from itertools import zip_longest as izip_longest except: from itertools import izip_longest def fringe(tree): for node1 in tree: if isinstance(node1, tuple): for node2 in fringe(node1): yield node2 else: yield node1 def same_fringe(tree1, tree2): return all(node1 == node2 for node1, node2 in izip_longest(fringe(tree1), fringe(tree2))) if __name__ == '__main__': a = 1, 2, 3, 4, 5, 6, 7, 8 b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8)))) c = (((1, 2), 3), 4), 5, 6, 7, 8 x = 1, 2, 3, 4, 5, 6, 7, 8, 9 y = 0, 2, 3, 4, 5, 6, 7, 8 z = 1, 2, (4, 3), 5, 6, 7, 8 assert same_fringe(a, a) assert same_fringe(a, b) assert same_fringe(a, c) assert not same_fringe(a, x) assert not same_fringe(a, y) assert not same_fringe(a, z)
package main import "fmt" type node struct { int left, right *node } func leaves(t *node) chan int { ch := make(chan int) var f func(*node) f = func(n *node) { if n == nil { return } if n.left == nil && n.right == nil { ch <- n.int } else { f(n.left) f(n.right) } } go func() { f(t) close(ch) }() return ch } func sameFringe(t1, t2 *node) bool { f1 := leaves(t1) f2 := leaves(t2) for l1 := range f1 { if l2, ok := <-f2; !ok || l1 != l2 { return false } } _, ok := <-f2 return !ok } func main() { t1 := &node{3, &node{1, &node{int: 1}, &node{int: 2}}, &node{8, &node{int: 5}, &node{int: 13}}} t2 := &node{-8, &node{-3, &node{-1, &node{int: 1}, &node{int: 2}}, &node{int: 5}}, &node{int: 13}} fmt.Println(sameFringe(t1, t2)) }
Convert the following code from Python to Go, ensuring the logic remains intact.
from optparse import OptionParser [...] parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() example: <yourscript> --file=outfile -q
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
Write the same code in Go as shown below in Python.
from optparse import OptionParser [...] parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() example: <yourscript> --file=outfile -q
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
Write the same algorithm in Go as shown in this Python implementation.
from optparse import OptionParser [...] parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() example: <yourscript> --file=outfile -q
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
Change the programming language of this snippet from Python to Go without modifying what it does.
[print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
package main import ( "fmt" "strconv" "strings" ) func a(n int) { s, _ := strconv.Atoi(strings.Repeat("1", n) + "3") t := s * s fmt.Printf("%d %d\n", s, t) } func main() { for n := 0; n <= 7; n++ { a(n) } }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
[print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
package main import ( "fmt" "strconv" "strings" ) func a(n int) { s, _ := strconv.Atoi(strings.Repeat("1", n) + "3") t := s * s fmt.Printf("%d %d\n", s, t) } func main() { for n := 0; n <= 7; n++ { a(n) } }
Please provide an equivalent version of this Python code in Go.
import autopy autopy.key.type_string("Hello, world!") autopy.key.type_string("Hello, world!", wpm=60) autopy.key.tap(autopy.key.Code.RETURN) autopy.key.tap(autopy.key.Code.F1) autopy.key.tap(autopy.key.Code.LEFT_ARROW)
package main import ( "github.com/micmonay/keybd_event" "log" "runtime" "time" ) func main() { kb, err := keybd_event.NewKeyBonding() if err != nil { log.Fatal(err) } if runtime.GOOS == "linux" { time.Sleep(2 * time.Second) } kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER) err = kb.Launching() if err != nil { log.Fatal(err) } }
Convert this Python block to Go, preserving its control flow and logic.
from itertools import combinations, product, count from functools import lru_cache, reduce _bbullet, _wbullet = '\u2022\u25E6' _or = set.__or__ def place(m, n): "Place m black and white queens, peacefully, on an n-by-n board" board = set(product(range(n), repeat=2)) placements = {frozenset(c) for c in combinations(board, m)} for blacks in placements: black_attacks = reduce(_or, (queen_attacks_from(pos, n) for pos in blacks), set()) for whites in {frozenset(c) for c in combinations(board - black_attacks, m)}: if not black_attacks & whites: return blacks, whites return set(), set() @lru_cache(maxsize=None) def queen_attacks_from(pos, n): x0, y0 = pos a = set([pos]) a.update((x, y0) for x in range(n)) a.update((x0, y) for y in range(n)) for x1 in range(n): y1 = y0 -x0 +x1 if 0 <= y1 < n: a.add((x1, y1)) y1 = y0 +x0 -x1 if 0 <= y1 < n: a.add((x1, y1)) return a def pboard(black_white, n): "Print board" if black_white is None: blk, wht = set(), set() else: blk, wht = black_white print(f" f"on a {n}-by-{n} board:", end='') for x, y in product(range(n), repeat=2): if y == 0: print() xy = (x, y) ch = ('?' if xy in blk and xy in wht else 'B' if xy in blk else 'W' if xy in wht else _bbullet if (x + y)%2 else _wbullet) print('%s' % ch, end='') print() if __name__ == '__main__': n=2 for n in range(2, 7): print() for m in count(1): ans = place(m, n) if ans[0]: pboard(ans, n) else: print (f" break print('\n') m, n = 5, 7 ans = place(m, n) pboard(ans, n)
package main import "fmt" const ( empty = iota black white ) const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' ) type position struct{ i, j int } func iabs(i int) int { if i < 0 { return -i } return i } func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool { if m == 0 { return true } placingBlack := true for i := 0; i < n; i++ { inner: for j := 0; j < n; j++ { pos := position{i, j} for _, queen := range *pBlackQueens { if queen == pos || !placingBlack && isAttacking(queen, pos) { continue inner } } for _, queen := range *pWhiteQueens { if queen == pos || placingBlack && isAttacking(queen, pos) { continue inner } } if placingBlack { *pBlackQueens = append(*pBlackQueens, pos) placingBlack = false } else { *pWhiteQueens = append(*pWhiteQueens, pos) if place(m-1, n, pBlackQueens, pWhiteQueens) { return true } *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1] placingBlack = true } } } if !placingBlack { *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] } return false } func isAttacking(queen, pos position) bool { if queen.i == pos.i { return true } if queen.j == pos.j { return true } if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) { return true } return false } func printBoard(n int, blackQueens, whiteQueens []position) { board := make([]int, n*n) for _, queen := range blackQueens { board[queen.i*n+queen.j] = black } for _, queen := range whiteQueens { board[queen.i*n+queen.j] = white } for i, b := range board { if i != 0 && i%n == 0 { fmt.Println() } switch b { case black: fmt.Printf("%c ", bqueen) case white: fmt.Printf("%c ", wqueen) case empty: if i%2 == 0 { fmt.Printf("%c ", bbullet) } else { fmt.Printf("%c ", wbullet) } } } fmt.Println("\n") } func main() { nms := [][2]int{ {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, } for _, nm := range nms { n, m := nm[0], nm[1] fmt.Printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n) var blackQueens, whiteQueens []position if place(m, n, &blackQueens, &whiteQueens) { printBoard(n, blackQueens, whiteQueens) } else { fmt.Println("No solution exists.\n") } } }
Ensure the translated Go code behaves exactly like the original Python snippet.
while 1: print "SPAM"
package main import "fmt" func main() { for { fmt.Printf("SPAM\n") } }
Produce a functionally identical Go code for the snippet given in Python.
from macropy.core.macros import * from macropy.core.quotes import macros, q, ast, u macros = Macros() @macros.expr def expand(tree, **kw): addition = 10 return q[lambda x: x * ast[tree] + u[addition]]
package main import "fmt" type person struct{ name string age int } func copy(p person) person { return person{p.name, p.age} } func main() { p := person{"Dave", 40} fmt.Println(p) q := copy(p) fmt.Println(q) }
Convert this Python snippet to Go and keep its semantics consistent.
col = 0 for i in range(100000): if set(str(i)) == set(hex(i)[2:]): col += 1 print("{:7}".format(i), end='\n'[:col % 10 == 0]) print()
package main import ( "fmt" "rcu" "strconv" ) func equalSets(s1, s2 map[rune]bool) bool { if len(s1) != len(s2) { return false } for k, _ := range s1 { _, ok := s2[k] if !ok { return false } } return true } func main() { const limit = 100_000 count := 0 fmt.Println("Numbers under 100,000 which use the same digits in decimal or hex:") for n := 0; n < limit; n++ { h := strconv.FormatInt(int64(n), 16) hs := make(map[rune]bool) for _, c := range h { hs[c] = true } ns := make(map[rune]bool) for _, c := range strconv.Itoa(n) { ns[c] = true } if equalSets(hs, ns) { count++ fmt.Printf("%6s ", rcu.Commatize(n)) if count%10 == 0 { fmt.Println() } } } fmt.Printf("\n\n%d such numbers found.\n", count) }
Produce a functionally identical Go code for the snippet given in Python.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': n = 600851475143 j = 3 while not isPrime(n): if n % j == 0: n /= j j += 2 print(n);
package main import "fmt" func largestPrimeFactor(n uint64) uint64 { if n < 2 { return 1 } inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6} max := uint64(1) for n%2 == 0 { max = 2 n /= 2 } for n%3 == 0 { max = 3 n /= 3 } for n%5 == 0 { max = 5 n /= 5 } k := uint64(7) i := 0 for k*k <= n { if n%k == 0 { max = k n /= k } else { k += inc[i] i = (i + 1) % 8 } } if n > 1 { return n } return max } func main() { n := uint64(600851475143) fmt.Println("The largest prime factor of", n, "is", largestPrimeFactor(n), "\b.") }
Generate a Go translation of this Python snippet without changing its computational steps.
def lpd(n): for i in range(n-1,0,-1): if n%i==0: return i return 1 for i in range(1,101): print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
package main import "fmt" func largestProperDivisor(n int) int { for i := 2; i*i <= n; i++ { if n%i == 0 { return n / i } } return 1 } func main() { fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:") fmt.Print(" 1 ") for n := 2; n <= 100; n++ { if n%2 == 0 { fmt.Printf("%2d ", n/2) } else { fmt.Printf("%2d ", largestProperDivisor(n)) } if n%10 == 0 { fmt.Println() } } }
Write the same algorithm in Go as shown in this Python implementation.
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad return sequence def move2front_decode(sequence, symboltable): chars, pad = [], symboltable[::] for indx in sequence: char = pad[indx] chars.append(char) pad = [pad.pop(indx)] + pad return ''.join(chars) if __name__ == '__main__': for s in ['broood', 'bananaaa', 'hiphophiphop']: encode = move2front_encode(s, SYMBOLTABLE) print('%14r encodes to %r' % (s, encode), end=', ') decode = move2front_decode(encode, SYMBOLTABLE) print('which decodes back to %r' % decode) assert s == decode, 'Whoops!'
package main import ( "bytes" "fmt" ) type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq } func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) } func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
Produce a language-to-language conversion: from Python to Go, same semantics.
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad return sequence def move2front_decode(sequence, symboltable): chars, pad = [], symboltable[::] for indx in sequence: char = pad[indx] chars.append(char) pad = [pad.pop(indx)] + pad return ''.join(chars) if __name__ == '__main__': for s in ['broood', 'bananaaa', 'hiphophiphop']: encode = move2front_encode(s, SYMBOLTABLE) print('%14r encodes to %r' % (s, encode), end=', ') decode = move2front_decode(encode, SYMBOLTABLE) print('which decodes back to %r' % decode) assert s == decode, 'Whoops!'
package main import ( "bytes" "fmt" ) type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq } func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) } func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
Translate this program into Go but keep the logic exactly as in Python.
Import-Module ActiveDirectory $searchData = "user name" $searchBase = "DC=example,DC=com" get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, GroupFilter: "(memberUid=%s)", } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } groups, err := client.GetGroupsOfUser("username") if err != nil { log.Fatalf("Error getting groups for user %s: %+v", "username", err) } log.Printf("Groups: %+v", groups) }
Port the following code from Python to Go with equivalent syntax and logic.
from numpy import * A = matrix([[3, 0], [4, 5]]) U, Sigma, VT = linalg.svd(A) print(U) print(Sigma) print(VT)
<package main import ( "fmt" "gonum.org/v1/gonum/mat" "log" ) func matPrint(m mat.Matrix) { fa := mat.Formatted(m, mat.Prefix(""), mat.Squeeze()) fmt.Printf("%13.10f\n", fa) } func main() { var svd mat.SVD a := mat.NewDense(2, 2, []float64{3, 0, 4, 5}) ok := svd.Factorize(a, mat.SVDFull) if !ok { log.Fatal("Something went wrong!") } u := mat.NewDense(2, 2, nil) svd.UTo(u) fmt.Println("U:") matPrint(u) values := svd.Values(nil) sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]}) fmt.Println("\nΣ:") matPrint(sigma) vt := mat.NewDense(2, 2, nil) svd.VTo(vt) fmt.Println("\nVT:") matPrint(vt) }
Rewrite the snippet below in Go so it works the same as the original Python code.
def main(): fila = 0 lenCubos = 51 print("Suma de N cubos para n = [0..49]\n") for n in range(1, lenCubos): sumCubos = 0 for m in range(1, n): sumCubos = sumCubos + (m ** 3) fila += 1 print(f'{sumCubos:7} ', end='') if fila % 5 == 0: print(" ") print(f"\nEncontrados {fila} cubos.") if __name__ == '__main__': main()
package main import ( "fmt" "rcu" ) func main() { fmt.Println("Cumulative sums of the first 50 cubes:") sum := 0 for n := 0; n < 50; n++ { sum += n * n * n fmt.Printf("%9s ", rcu.Commatize(sum)) if n%10 == 9 { fmt.Println() } } fmt.Println()
Convert this Python snippet to Go and keep its semantics consistent.
>>> def isint(f): return complex(f).imag == 0 and complex(f).real.is_integer() >>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))] [True, True, True, False, False, False] >>> ... >>> isint(25.000000) True >>> isint(24.999999) False >>> isint(25.000100) False >>> isint(-2.1e120) True >>> isint(-5e-2) False >>> isint(float('nan')) False >>> isint(float('inf')) False >>> isint(5.0+0.0j) True >>> isint(5-5j) False
package main import ( "fmt" "math" "math/big" "reflect" "strings" "unsafe" ) func Float64IsInt(f float64) bool { _, frac := math.Modf(f) return frac == 0 } func Float32IsInt(f float32) bool { return Float64IsInt(float64(f)) } func Complex128IsInt(c complex128) bool { return imag(c) == 0 && Float64IsInt(real(c)) } func Complex64IsInt(c complex64) bool { return imag(c) == 0 && Float64IsInt(float64(real(c))) } type hasIsInt interface { IsInt() bool } var bigIntT = reflect.TypeOf((*big.Int)(nil)) func IsInt(i interface{}) bool { if ci, ok := i.(hasIsInt); ok { return ci.IsInt() } switch v := reflect.ValueOf(i); v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return true case reflect.Float32, reflect.Float64: return Float64IsInt(v.Float()) case reflect.Complex64, reflect.Complex128: return Complex128IsInt(v.Complex()) case reflect.String: if r, ok := new(big.Rat).SetString(v.String()); ok { return r.IsInt() } case reflect.Ptr: if v.Type() == bigIntT { return true } } return false } type intbased int16 type complexbased complex64 type customIntegerType struct { } func (customIntegerType) IsInt() bool { return true } func (customIntegerType) String() string { return "<…>" } func main() { hdr := fmt.Sprintf("%27s  %-6s %s\n", "Input", "IsInt", "Type") show2 := func(t bool, i interface{}, args ...interface{}) { istr := fmt.Sprint(i) fmt.Printf("%27s  %-6t %T ", istr, t, i) fmt.Println(args...) } show := func(i interface{}, args ...interface{}) { show2(IsInt(i), i, args...) } fmt.Print("Using Float64IsInt with float64:\n", hdr) neg1 := -1. for _, f := range []float64{ 0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3, math.Pi, math.MinInt64, math.MaxUint64, math.SmallestNonzeroFloat64, math.MaxFloat64, math.NaN(), math.Inf(1), math.Inf(-1), } { show2(Float64IsInt(f), f) } fmt.Print("\nUsing Complex128IsInt with complex128:\n", hdr) for _, c := range []complex128{ 3, 1i, 0i, 3.4, } { show2(Complex128IsInt(c), c) } fmt.Println("\nUsing reflection:") fmt.Print(hdr) show("hello") show(math.MaxFloat64) show("9e100") f := new(big.Float) show(f) f.SetString("1e-3000") show(f) show("(4+0i)", "(complex strings not parsed)") show(4 + 0i) show(rune('§'), "or rune") show(byte('A'), "or byte") var t1 intbased = 5200 var t2a, t2b complexbased = 5 + 0i, 5 + 1i show(t1) show(t2a) show(t2b) x := uintptr(unsafe.Pointer(&t2b)) show(x) show(math.MinInt32) show(uint64(math.MaxUint64)) b, _ := new(big.Int).SetString(strings.Repeat("9", 25), 0) show(b) r := new(big.Rat) show(r) r.SetString("2/3") show(r) show(r.SetFrac(b, new(big.Int).SetInt64(9))) show("12345/5") show(new(customIntegerType)) }
Keep all operations the same but rewrite the snippet in Go.
import os exit_code = os.system('ls') output = os.popen('ls').read()
package main import ( "log" "os" "os/exec" ) func main() { cmd := exec.Command("ls", "-l") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }
Port the provided Python code into Go while preserving the original functionality.
from __future__ import print_function import lxml from lxml import etree if __name__=="__main__": parser = etree.XMLParser(dtd_validation=True) schema_root = etree.XML() schema = etree.XMLSchema(schema_root) parser = etree.XMLParser(schema = schema) try: root = etree.fromstring("<a>5</a>", parser) print ("Finished validating good xml") except lxml.etree.XMLSyntaxError as err: print (err) parser = etree.XMLParser(schema = schema) try: root = etree.fromstring("<a>5<b>foobar</b></a>", parser) except lxml.etree.XMLSyntaxError as err: print (err)
package main import ( "fmt" "github.com/lestrrat-go/libxml2" "github.com/lestrrat-go/libxml2/xsd" "io/ioutil" "log" "os" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { xsdfile := "shiporder.xsd" f, err := os.Open(xsdfile) check(err) defer f.Close() buf, err := ioutil.ReadAll(f) check(err) s, err := xsd.Parse(buf) check(err) defer s.Free() xmlfile := "shiporder.xml" f2, err := os.Open(xmlfile) check(err) defer f2.Close() buf2, err := ioutil.ReadAll(f2) check(err) d, err := libxml2.Parse(buf2) check(err) if err := s.Validate(d); err != nil { for _, e := range err.(xsd.SchemaValidationError).Errors() { log.Printf("error: %s", e.Error()) } return } fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!") }
Translate this program into Go but keep the logic exactly as in Python.
def longest_increasing_subsequence(X): N = len(X) P = [0] * N M = [0] * (N+1) L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): lo = mid+1 else: hi = mid-1 newL = lo P[i] = M[newL-1] M[newL] = i if (newL > L): L = newL S = [] k = M[L] for i in range(L-1, -1, -1): S.append(X[k]) k = P[k] return S[::-1] if __name__ == '__main__': for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]: print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
package main import ( "fmt" "sort" ) type Node struct { val int back *Node } func lis (n []int) (result []int) { var pileTops []*Node for _, x := range n { j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) node := &Node{ x, nil } if j != 0 { node.back = pileTops[j-1] } if j != len(pileTops) { pileTops[j] = node } else { pileTops = append(pileTops, node) } } if len(pileTops) == 0 { return []int{} } for node := pileTops[len(pileTops)-1]; node != nil; node = node.back { result = append(result, node.val) } for i := 0; i < len(result)/2; i++ { result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i] } return } func main() { for _, d := range [][]int{{3, 2, 6, 4, 5, 1}, {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} { fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d)) } }
Convert the following code from Python to Go, ensuring the logic remains intact.
import sys, math, collections Sphere = collections.namedtuple("Sphere", "cx cy cz r") V3 = collections.namedtuple("V3", "x y z") def normalize((x, y, z)): len = math.sqrt(x**2 + y**2 + z**2) return V3(x / len, y / len, z / len) def dot(v1, v2): d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z return -d if d < 0 else 0.0 def hit_sphere(sph, x0, y0): x = x0 - sph.cx y = y0 - sph.cy zsq = sph.r ** 2 - (x ** 2 + y ** 2) if zsq < 0: return (False, 0, 0) szsq = math.sqrt(zsq) return (True, sph.cz - szsq, sph.cz + szsq) def draw_sphere(k, ambient, light): shades = ".:!*oe& pos = Sphere(20.0, 20.0, 0.0, 20.0) neg = Sphere(1.0, 1.0, -6.0, 20.0) for i in xrange(int(math.floor(pos.cy - pos.r)), int(math.ceil(pos.cy + pos.r) + 1)): y = i + 0.5 for j in xrange(int(math.floor(pos.cx - 2 * pos.r)), int(math.ceil(pos.cx + 2 * pos.r) + 1)): x = (j - pos.cx) / 2.0 + 0.5 + pos.cx (h, zb1, zb2) = hit_sphere(pos, x, y) if not h: hit_result = 0 else: (h, zs1, zs2) = hit_sphere(neg, x, y) if not h: hit_result = 1 elif zs1 > zb1: hit_result = 1 elif zs2 > zb2: hit_result = 0 elif zs2 > zb1: hit_result = 2 else: hit_result = 1 if hit_result == 0: sys.stdout.write(' ') continue elif hit_result == 1: vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz) elif hit_result == 2: vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2) vec = normalize(vec) b = dot(light, vec) ** k + ambient intensity = int((1 - b) * len(shades)) intensity = min(len(shades), max(0, intensity)) sys.stdout.write(shades[intensity]) print light = normalize(V3(-50, 30, 50)) draw_sphere(2, 0.5, light)
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func (v *vector) normalize() { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } type sphere struct { cx, cy, cz int r int } func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) { x -= s.cx y -= s.cy if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 { zsqrt := math.Sqrt(float64(zsq)) return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true } return 0, 0, false } func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray { w, h := pos.r*4, pos.r*3 bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2) img := image.NewGray(bounds) vec := new(vector) for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ { for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ { zb1, zb2, hit := pos.hit(x, y) if !hit { continue } zs1, zs2, hit := neg.hit(x, y) if hit { if zs1 > zb1 { hit = false } else if zs2 > zb2 { continue } } if hit { vec[0] = float64(neg.cx - x) vec[1] = float64(neg.cy - y) vec[2] = float64(neg.cz) - zs2 } else { vec[0] = float64(x - pos.cx) vec[1] = float64(y - pos.cy) vec[2] = zb1 - float64(pos.cz) } vec.normalize() s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } return img } func main() { dir := &vector{20, -40, -10} dir.normalize() pos := &sphere{0, 0, 0, 120} neg := &sphere{-90, -90, -30, 100} img := deathStar(pos, neg, 1.5, .2, dir) f, err := os.Create("dstar.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Generate a Go translation of this Python snippet without changing its computational steps.
import sys, math, collections Sphere = collections.namedtuple("Sphere", "cx cy cz r") V3 = collections.namedtuple("V3", "x y z") def normalize((x, y, z)): len = math.sqrt(x**2 + y**2 + z**2) return V3(x / len, y / len, z / len) def dot(v1, v2): d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z return -d if d < 0 else 0.0 def hit_sphere(sph, x0, y0): x = x0 - sph.cx y = y0 - sph.cy zsq = sph.r ** 2 - (x ** 2 + y ** 2) if zsq < 0: return (False, 0, 0) szsq = math.sqrt(zsq) return (True, sph.cz - szsq, sph.cz + szsq) def draw_sphere(k, ambient, light): shades = ".:!*oe& pos = Sphere(20.0, 20.0, 0.0, 20.0) neg = Sphere(1.0, 1.0, -6.0, 20.0) for i in xrange(int(math.floor(pos.cy - pos.r)), int(math.ceil(pos.cy + pos.r) + 1)): y = i + 0.5 for j in xrange(int(math.floor(pos.cx - 2 * pos.r)), int(math.ceil(pos.cx + 2 * pos.r) + 1)): x = (j - pos.cx) / 2.0 + 0.5 + pos.cx (h, zb1, zb2) = hit_sphere(pos, x, y) if not h: hit_result = 0 else: (h, zs1, zs2) = hit_sphere(neg, x, y) if not h: hit_result = 1 elif zs1 > zb1: hit_result = 1 elif zs2 > zb2: hit_result = 0 elif zs2 > zb1: hit_result = 2 else: hit_result = 1 if hit_result == 0: sys.stdout.write(' ') continue elif hit_result == 1: vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz) elif hit_result == 2: vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2) vec = normalize(vec) b = dot(light, vec) ** k + ambient intensity = int((1 - b) * len(shades)) intensity = min(len(shades), max(0, intensity)) sys.stdout.write(shades[intensity]) print light = normalize(V3(-50, 30, 50)) draw_sphere(2, 0.5, light)
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func (v *vector) normalize() { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } type sphere struct { cx, cy, cz int r int } func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) { x -= s.cx y -= s.cy if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 { zsqrt := math.Sqrt(float64(zsq)) return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true } return 0, 0, false } func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray { w, h := pos.r*4, pos.r*3 bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2) img := image.NewGray(bounds) vec := new(vector) for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ { for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ { zb1, zb2, hit := pos.hit(x, y) if !hit { continue } zs1, zs2, hit := neg.hit(x, y) if hit { if zs1 > zb1 { hit = false } else if zs2 > zb2 { continue } } if hit { vec[0] = float64(neg.cx - x) vec[1] = float64(neg.cy - y) vec[2] = float64(neg.cz) - zs2 } else { vec[0] = float64(x - pos.cx) vec[1] = float64(y - pos.cy) vec[2] = zb1 - float64(pos.cz) } vec.normalize() s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } return img } func main() { dir := &vector{20, -40, -10} dir.normalize() pos := &sphere{0, 0, 0, 120} neg := &sphere{-90, -90, -30, 100} img := deathStar(pos, neg, 1.5, .2, dir) f, err := os.Create("dstar.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Generate a Go translation of this Python snippet without changing its computational steps.
from __future__ import print_function def lgen(even=False, nmax=1000000): start = 2 if even else 1 n, lst = 1, list(range(start, nmax + 1, 2)) lenlst = len(lst) yield lst[0] while n < lenlst and lst[n] < lenlst: yield lst[n] n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]] lenlst = len(lst) for i in lst[n:]: yield i
package main import ( "fmt" "log" "os" "strconv" "strings" ) const luckySize = 60000 var luckyOdd = make([]int, luckySize) var luckyEven = make([]int, luckySize) func init() { for i := 0; i < luckySize; i++ { luckyOdd[i] = i*2 + 1 luckyEven[i] = i*2 + 2 } } func filterLuckyOdd() { for n := 2; n < len(luckyOdd); n++ { m := luckyOdd[n-1] end := (len(luckyOdd)/m)*m - 1 for j := end; j >= m-1; j -= m { copy(luckyOdd[j:], luckyOdd[j+1:]) luckyOdd = luckyOdd[:len(luckyOdd)-1] } } } func filterLuckyEven() { for n := 2; n < len(luckyEven); n++ { m := luckyEven[n-1] end := (len(luckyEven)/m)*m - 1 for j := end; j >= m-1; j -= m { copy(luckyEven[j:], luckyEven[j+1:]) luckyEven = luckyEven[:len(luckyEven)-1] } } } func printSingle(j int, odd bool) error { if odd { if j >= len(luckyOdd) { return fmt.Errorf("the argument, %d, is too big", j) } fmt.Println("Lucky number", j, "=", luckyOdd[j-1]) } else { if j >= len(luckyEven) { return fmt.Errorf("the argument, %d, is too big", j) } fmt.Println("Lucky even number", j, "=", luckyEven[j-1]) } return nil } func printRange(j, k int, odd bool) error { if odd { if k >= len(luckyOdd) { return fmt.Errorf("the argument, %d, is too big", k) } fmt.Println("Lucky numbers", j, "to", k, "are:") fmt.Println(luckyOdd[j-1 : k]) } else { if k >= len(luckyEven) { return fmt.Errorf("the argument, %d, is too big", k) } fmt.Println("Lucky even numbers", j, "to", k, "are:") fmt.Println(luckyEven[j-1 : k]) } return nil } func printBetween(j, k int, odd bool) error { var r []int if odd { max := luckyOdd[len(luckyOdd)-1] if j > max || k > max { return fmt.Errorf("at least one argument, %d or %d, is too big", j, k) } for _, num := range luckyOdd { if num < j { continue } if num > k { break } r = append(r, num) } fmt.Println("Lucky numbers between", j, "and", k, "are:") fmt.Println(r) } else { max := luckyEven[len(luckyEven)-1] if j > max || k > max { return fmt.Errorf("at least one argument, %d or %d, is too big", j, k) } for _, num := range luckyEven { if num < j { continue } if num > k { break } r = append(r, num) } fmt.Println("Lucky even numbers between", j, "and", k, "are:") fmt.Println(r) } return nil } func main() { nargs := len(os.Args) if nargs < 2 || nargs > 4 { log.Fatal("there must be between 1 and 3 command line arguments") } filterLuckyOdd() filterLuckyEven() j, err := strconv.Atoi(os.Args[1]) if err != nil || j < 1 { log.Fatalf("first argument, %s, must be a positive integer", os.Args[1]) } if nargs == 2 { if err := printSingle(j, true); err != nil { log.Fatal(err) } return } if nargs == 3 { k, err := strconv.Atoi(os.Args[2]) if err != nil { log.Fatalf("second argument, %s, must be an integer", os.Args[2]) } if k >= 0 { if j > k { log.Fatalf("second argument, %d, can't be less than first, %d", k, j) } if err := printRange(j, k, true); err != nil { log.Fatal(err) } } else { l := -k if j > l { log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j) } if err := printBetween(j, l, true); err != nil { log.Fatal(err) } } return } var odd bool switch lucky := strings.ToLower(os.Args[3]); lucky { case "lucky": odd = true case "evenlucky": odd = false default: log.Fatalf("third argument, %s, is invalid", os.Args[3]) } if os.Args[2] == "," { if err := printSingle(j, odd); err != nil { log.Fatal(err) } return } k, err := strconv.Atoi(os.Args[2]) if err != nil { log.Fatal("second argument must be an integer or a comma") } if k >= 0 { if j > k { log.Fatalf("second argument, %d, can't be less than first, %d", k, j) } if err := printRange(j, k, odd); err != nil { log.Fatal(err) } } else { l := -k if j > l { log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j) } if err := printBetween(j, l, odd); err != nil { log.Fatal(err) } } }
Translate the given Python code snippet into Go without altering its behavior.
import argparse from argparse import Namespace import datetime import shlex def parse_args(): 'Set up, parse, and return arguments' parser = argparse.ArgumentParser(epilog=globals()['__doc__']) parser.add_argument('command', choices='add pl plc pa'.split(), help=) parser.add_argument('-d', '--description', help='A description of the item. (e.g., title, name)') parser.add_argument('-t', '--tag', help=( )) parser.add_argument('-f', '--field', nargs=2, action='append', help='Other optional fields with value (can be repeated)') return parser def do_add(args, dbname): 'Add a new entry' if args.description is None: args.description = '' if args.tag is None: args.tag = '' del args.command print('Writing record to %s' % dbname) with open(dbname, 'a') as db: db.write('%r\n' % args) def do_pl(args, dbname): 'Print the latest entry' print('Getting last record from %s' % dbname) with open(dbname, 'r') as db: for line in db: pass record = eval(line) del record._date print(str(record)) def do_plc(args, dbname): 'Print the latest entry for each category/tag' print('Getting latest record for each tag from %s' % dbname) with open(dbname, 'r') as db: records = [eval(line) for line in db] tags = set(record.tag for record in records) records.reverse() for record in records: if record.tag in tags: del record._date print(str(record)) tags.discard(record.tag) if not tags: break def do_pa(args, dbname): 'Print all entries sorted by a date' print('Getting all records by date from %s' % dbname) with open(dbname, 'r') as db: records = [eval(line) for line in db] for record in records: del record._date print(str(record)) def test(): import time parser = parse_args() for cmdline in [ , , , , , ]: args = parser.parse_args(shlex.split(cmdline)) now = datetime.datetime.utcnow() args._date = now.isoformat() do_command[args.command](args, dbname) time.sleep(0.5) do_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa) dbname = '_simple_db_db.py' if __name__ == '__main__': if 0: test() else: parser = parse_args() args = parser.parse_args() now = datetime.datetime.utcnow() args._date = now.isoformat() do_command[args.command](args, dbname)
package main import ( "encoding/json" "fmt" "io" "os" "sort" "strings" "time" "unicode" ) type Item struct { Stamp time.Time Name string Tags []string `json:",omitempty"` Notes string `json:",omitempty"` } func (i *Item) String() string { s := i.Stamp.Format(time.ANSIC) + "\n Name: " + i.Name if len(i.Tags) > 0 { s = fmt.Sprintf("%s\n Tags: %v", s, i.Tags) } if i.Notes > "" { s += "\n Notes: " + i.Notes } return s } type db []*Item func (d db) Len() int { return len(d) } func (d db) Swap(i, j int) { d[i], d[j] = d[j], d[i] } func (d db) Less(i, j int) bool { return d[i].Stamp.Before(d[j].Stamp) } const fn = "sdb.json" func main() { if len(os.Args) == 1 { latest() return } switch os.Args[1] { case "add": add() case "latest": latest() case "tags": tags() case "all": all() case "help": help() default: usage("unrecognized command") } } func usage(err string) { if err > "" { fmt.Println(err) } fmt.Println(`usage: sdb [command] [data] where command is one of add, latest, tags, all, or help.`) } func help() { usage("") fmt.Println(` Commands must be in lower case. If no command is specified, the default command is latest. Latest prints the latest item. All prints all items in chronological order. Tags prints the lastest item for each tag. Help prints this message. Add adds data as a new record. The format is, name [tags] [notes] Name is the name of the item and is required for the add command. Tags are optional. A tag is a single word. A single tag can be specified without enclosing brackets. Multiple tags can be specified by enclosing them in square brackets. Text remaining after tags is taken as notes. Notes do not have to be enclosed in quotes or brackets. The brackets above are only showing that notes are optional. Quotes may be useful however--as recognized by your operating system shell or command line--to allow entry of arbitrary text. In particular, quotes or escape characters may be needed to prevent the shell from trying to interpret brackets or other special characters. Examples: sdb add Bookends sdb add Bookends rock my favorite sdb add Bookends [rock folk] sdb add Bookends [] "Simon & Garfunkel" sdb add "Simon&Garfunkel [artist]" As shown in the last example, if you use features of your shell to pass all data as a single string, the item name and tags will still be identified by separating whitespace. The database is stored in JSON format in the file "sdb.json" `) } func load() (db, bool) { d, f, ok := open() if ok { f.Close() if len(d) == 0 { fmt.Println("no items") ok = false } } return d, ok } func open() (d db, f *os.File, ok bool) { var err error f, err = os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0666) if err != nil { fmt.Println("cant open??") fmt.Println(err) return } jd := json.NewDecoder(f) err = jd.Decode(&d) if err != nil && err != io.EOF { fmt.Println(err) f.Close() return } ok = true return } func latest() { d, ok := load() if !ok { return } sort.Sort(d) fmt.Println(d[len(d)-1]) } func all() { d, ok := load() if !ok { return } sort.Sort(d) for _, i := range d { fmt.Println("-----------------------------------") fmt.Println(i) } fmt.Println("-----------------------------------") } func tags() { d, ok := load() if !ok { return } latest := make(map[string]*Item) for _, item := range d { for _, tag := range item.Tags { li, ok := latest[tag] if !ok || item.Stamp.After(li.Stamp) { latest[tag] = item } } } type itemTags struct { item *Item tags []string } inv := make(map[*Item][]string) for tag, item := range latest { inv[item] = append(inv[item], tag) } li := make(db, len(inv)) i := 0 for item := range inv { li[i] = item i++ } sort.Sort(li) for _, item := range li { tags := inv[item] fmt.Println("-----------------------------------") fmt.Println("Latest item with tags", tags) fmt.Println(item) } fmt.Println("-----------------------------------") } func add() { if len(os.Args) < 3 { usage("add command requires data") return } else if len(os.Args) == 3 { add1() } else { add4() } } func add1() { data := strings.TrimLeftFunc(os.Args[2], unicode.IsSpace) if data == "" { usage("invalid name") return } sep := strings.IndexFunc(data, unicode.IsSpace) if sep < 0 { addItem(data, nil, "") return } name := data[:sep] data = strings.TrimLeftFunc(data[sep:], unicode.IsSpace) if data == "" { addItem(name, nil, "") return } if data[0] == '[' { sep = strings.Index(data, "]") if sep < 0 { addItem(name, strings.Fields(data[1:]), "") } else { addItem(name, strings.Fields(data[1:sep]), strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace)) } return } sep = strings.IndexFunc(data, unicode.IsSpace) if sep < 0 { addItem(name, []string{data}, "") } else { addItem(name, []string{data[:sep]}, strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace)) } } func add4() { name := os.Args[2] tag1 := os.Args[3] if tag1[0] != '[' { addItem(name, []string{tag1}, strings.Join(os.Args[4:], " ")) return } if tag1[len(tag1)-1] == ']' { addItem(name, strings.Fields(tag1[1:len(tag1)-1]), strings.Join(os.Args[4:], " ")) return } var tags []string if tag1 > "[" { tags = []string{tag1[1:]} } for x, tag := range os.Args[4:] { if tag[len(tag)-1] != ']' { tags = append(tags, tag) } else { if tag > "]" { tags = append(tags, tag[:len(tag)-1]) } addItem(name, tags, strings.Join(os.Args[5+x:], " ")) return } } addItem(name, tags, "") } func addItem(name string, tags []string, notes string) { db, f, ok := open() if !ok { return } defer f.Close() db = append(db, &Item{time.Now(), name, tags, notes}) sort.Sort(db) js, err := json.MarshalIndent(db, "", " ") if err != nil { fmt.Println(err) return } if _, err = f.Seek(0, 0); err != nil { fmt.Println(err) return } f.Truncate(0) if _, err = f.Write(js); err != nil { fmt.Println(err) } }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
from collections import namedtuple Circle = namedtuple("Circle", "x y r") circles = [ Circle( 1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle( 0.6110294452, -0.6907087527, 0.9089162485), Circle( 0.3844862411, 0.2923344616, 0.2375743054), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
package main import ( "flag" "fmt" "math" "runtime" "sort" ) type Circle struct{ X, Y, R, rsq float64 } func NewCircle(x, y, r float64) Circle { return Circle{x, y, r, r * r} } func (c Circle) ContainsPt(x, y float64) bool { return distSq(x, y, c.X, c.Y) <= c.rsq } func (c Circle) ContainsC(c2 Circle) bool { return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R) } func (c Circle) ContainsR(r Rect) (full, corner bool) { nw := c.ContainsPt(r.NW()) ne := c.ContainsPt(r.NE()) sw := c.ContainsPt(r.SW()) se := c.ContainsPt(r.SE()) return nw && ne && sw && se, nw || ne || sw || se } func (c Circle) North() (float64, float64) { return c.X, c.Y + c.R } func (c Circle) South() (float64, float64) { return c.X, c.Y - c.R } func (c Circle) West() (float64, float64) { return c.X - c.R, c.Y } func (c Circle) East() (float64, float64) { return c.X + c.R, c.Y } type Rect struct{ X1, Y1, X2, Y2 float64 } func (r Rect) Area() float64 { return (r.X2 - r.X1) * (r.Y2 - r.Y1) } func (r Rect) NW() (float64, float64) { return r.X1, r.Y2 } func (r Rect) NE() (float64, float64) { return r.X2, r.Y2 } func (r Rect) SW() (float64, float64) { return r.X1, r.Y1 } func (r Rect) SE() (float64, float64) { return r.X2, r.Y1 } func (r Rect) Centre() (float64, float64) { return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0 } func (r Rect) ContainsPt(x, y float64) bool { return r.X1 <= x && x < r.X2 && r.Y1 <= y && y < r.Y2 } func (r Rect) ContainsPC(c Circle) bool { return r.ContainsPt(c.North()) || r.ContainsPt(c.South()) || r.ContainsPt(c.West()) || r.ContainsPt(c.East()) } func (r Rect) MinSide() float64 { return math.Min(r.X2-r.X1, r.Y2-r.Y1) } func distSq(x1, y1, x2, y2 float64) float64 { Δx, Δy := x2-x1, y2-y1 return (Δx * Δx) + (Δy * Δy) } type CircleSet []Circle func (s CircleSet) Len() int { return len(s) } func (s CircleSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R } func (sp *CircleSet) RemoveContainedC() { s := *sp sort.Sort(s) for i := 0; i < len(s); i++ { for j := i + 1; j < len(s); { if s[i].ContainsC(s[j]) { s[j], s[len(s)-1] = s[len(s)-1], s[j] s = s[:len(s)-1] } else { j++ } } } *sp = s } func (s CircleSet) Bounds() Rect { x1 := s[0].X - s[0].R x2 := s[0].X + s[0].R y1 := s[0].Y - s[0].R y2 := s[0].Y + s[0].R for _, c := range s[1:] { x1 = math.Min(x1, c.X-c.R) x2 = math.Max(x2, c.X+c.R) y1 = math.Min(y1, c.Y-c.R) y2 = math.Max(y2, c.Y+c.R) } return Rect{x1, y1, x2, y2} } var nWorkers = 4 func (s CircleSet) UnionArea(ε float64) (min, max float64) { sort.Sort(s) stop := make(chan bool) inside := make(chan Rect) outside := make(chan Rect) unknown := make(chan Rect, 5e7) for i := 0; i < nWorkers; i++ { go s.worker(stop, unknown, inside, outside) } r := s.Bounds() max = r.Area() unknown <- r for max-min > ε { select { case r = <-inside: min += r.Area() case r = <-outside: max -= r.Area() } } close(stop) return min, max } func (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) { for { select { case <-stop: return case r := <-unk: inside, outside := s.CategorizeR(r) switch { case inside: in <- r case outside: out <- r default: midX, midY := r.Centre() unk <- Rect{r.X1, r.Y1, midX, midY} unk <- Rect{midX, r.Y1, r.X2, midY} unk <- Rect{r.X1, midY, midX, r.Y2} unk <- Rect{midX, midY, r.X2, r.Y2} } } } } func (s CircleSet) CategorizeR(r Rect) (inside, outside bool) { anyCorner := false for _, c := range s { full, corner := c.ContainsR(r) if full { return true, false } anyCorner = anyCorner || corner } if anyCorner { return false, false } for _, c := range s { if r.ContainsPC(c) { return false, false } } return false, true } func main() { flag.IntVar(&nWorkers, "workers", nWorkers, "how many worker go routines to use") maxproc := flag.Int("cpu", runtime.NumCPU(), "GOMAXPROCS setting") flag.Parse() if *maxproc > 0 { runtime.GOMAXPROCS(*maxproc) } else { *maxproc = runtime.GOMAXPROCS(0) } circles := CircleSet{ NewCircle(1.6417233788, 1.6121789534, 0.0848270516), NewCircle(-1.4944608174, 1.2077959613, 1.1039549836), NewCircle(0.6110294452, -0.6907087527, 0.9089162485), NewCircle(0.3844862411, 0.2923344616, 0.2375743054), NewCircle(-0.2495892950, -0.3832854473, 1.0845181219), NewCircle(1.7813504266, 1.6178237031, 0.8162655711), NewCircle(-0.1985249206, -0.8343333301, 0.0538864941), NewCircle(-1.7011985145, -0.1263820964, 0.4776976918), NewCircle(-0.4319462812, 1.4104420482, 0.7886291537), NewCircle(0.2178372997, -0.9499557344, 0.0357871187), NewCircle(-0.6294854565, -1.3078893852, 0.7653357688), NewCircle(1.7952608455, 0.6281269104, 0.2727652452), NewCircle(1.4168575317, 1.0683357171, 1.1016025378), NewCircle(1.4637371396, 0.9463877418, 1.1846214562), NewCircle(-0.5263668798, 1.7315156631, 1.4428514068), NewCircle(-1.2197352481, 0.9144146579, 1.0727263474), NewCircle(-0.1389358881, 0.1092805780, 0.7350208828), NewCircle(1.5293954595, 0.0030278255, 1.2472867347), NewCircle(-0.5258728625, 1.3782633069, 1.3495508831), NewCircle(-0.1403562064, 0.2437382535, 1.3804956588), NewCircle(0.8055826339, -0.0482092025, 0.3327165165), NewCircle(-0.6311979224, 0.7184578971, 0.2491045282), NewCircle(1.4685857879, -0.8347049536, 1.3670667538), NewCircle(-0.6855727502, 1.6465021616, 1.0593087096), NewCircle(0.0152957411, 0.0638919221, 0.9771215985), } fmt.Println("Starting with", len(circles), "circles.") circles.RemoveContainedC() fmt.Println("Removing redundant ones leaves", len(circles), "circles.") fmt.Println("Using", nWorkers, "workers with maxprocs =", *maxproc) const ε = 0.0001 min, max := circles.UnionArea(ε) avg := (min + max) / 2.0 rng := max - min fmt.Printf("Area = %v±%v\n", avg, rng) fmt.Printf("Area ≈ %.*f\n", 5, avg) }
Produce a language-to-language conversion: from Python to Go, same semantics.
from collections import namedtuple Circle = namedtuple("Circle", "x y r") circles = [ Circle( 1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle( 0.6110294452, -0.6907087527, 0.9089162485), Circle( 0.3844862411, 0.2923344616, 0.2375743054), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
package main import ( "flag" "fmt" "math" "runtime" "sort" ) type Circle struct{ X, Y, R, rsq float64 } func NewCircle(x, y, r float64) Circle { return Circle{x, y, r, r * r} } func (c Circle) ContainsPt(x, y float64) bool { return distSq(x, y, c.X, c.Y) <= c.rsq } func (c Circle) ContainsC(c2 Circle) bool { return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R) } func (c Circle) ContainsR(r Rect) (full, corner bool) { nw := c.ContainsPt(r.NW()) ne := c.ContainsPt(r.NE()) sw := c.ContainsPt(r.SW()) se := c.ContainsPt(r.SE()) return nw && ne && sw && se, nw || ne || sw || se } func (c Circle) North() (float64, float64) { return c.X, c.Y + c.R } func (c Circle) South() (float64, float64) { return c.X, c.Y - c.R } func (c Circle) West() (float64, float64) { return c.X - c.R, c.Y } func (c Circle) East() (float64, float64) { return c.X + c.R, c.Y } type Rect struct{ X1, Y1, X2, Y2 float64 } func (r Rect) Area() float64 { return (r.X2 - r.X1) * (r.Y2 - r.Y1) } func (r Rect) NW() (float64, float64) { return r.X1, r.Y2 } func (r Rect) NE() (float64, float64) { return r.X2, r.Y2 } func (r Rect) SW() (float64, float64) { return r.X1, r.Y1 } func (r Rect) SE() (float64, float64) { return r.X2, r.Y1 } func (r Rect) Centre() (float64, float64) { return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0 } func (r Rect) ContainsPt(x, y float64) bool { return r.X1 <= x && x < r.X2 && r.Y1 <= y && y < r.Y2 } func (r Rect) ContainsPC(c Circle) bool { return r.ContainsPt(c.North()) || r.ContainsPt(c.South()) || r.ContainsPt(c.West()) || r.ContainsPt(c.East()) } func (r Rect) MinSide() float64 { return math.Min(r.X2-r.X1, r.Y2-r.Y1) } func distSq(x1, y1, x2, y2 float64) float64 { Δx, Δy := x2-x1, y2-y1 return (Δx * Δx) + (Δy * Δy) } type CircleSet []Circle func (s CircleSet) Len() int { return len(s) } func (s CircleSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R } func (sp *CircleSet) RemoveContainedC() { s := *sp sort.Sort(s) for i := 0; i < len(s); i++ { for j := i + 1; j < len(s); { if s[i].ContainsC(s[j]) { s[j], s[len(s)-1] = s[len(s)-1], s[j] s = s[:len(s)-1] } else { j++ } } } *sp = s } func (s CircleSet) Bounds() Rect { x1 := s[0].X - s[0].R x2 := s[0].X + s[0].R y1 := s[0].Y - s[0].R y2 := s[0].Y + s[0].R for _, c := range s[1:] { x1 = math.Min(x1, c.X-c.R) x2 = math.Max(x2, c.X+c.R) y1 = math.Min(y1, c.Y-c.R) y2 = math.Max(y2, c.Y+c.R) } return Rect{x1, y1, x2, y2} } var nWorkers = 4 func (s CircleSet) UnionArea(ε float64) (min, max float64) { sort.Sort(s) stop := make(chan bool) inside := make(chan Rect) outside := make(chan Rect) unknown := make(chan Rect, 5e7) for i := 0; i < nWorkers; i++ { go s.worker(stop, unknown, inside, outside) } r := s.Bounds() max = r.Area() unknown <- r for max-min > ε { select { case r = <-inside: min += r.Area() case r = <-outside: max -= r.Area() } } close(stop) return min, max } func (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) { for { select { case <-stop: return case r := <-unk: inside, outside := s.CategorizeR(r) switch { case inside: in <- r case outside: out <- r default: midX, midY := r.Centre() unk <- Rect{r.X1, r.Y1, midX, midY} unk <- Rect{midX, r.Y1, r.X2, midY} unk <- Rect{r.X1, midY, midX, r.Y2} unk <- Rect{midX, midY, r.X2, r.Y2} } } } } func (s CircleSet) CategorizeR(r Rect) (inside, outside bool) { anyCorner := false for _, c := range s { full, corner := c.ContainsR(r) if full { return true, false } anyCorner = anyCorner || corner } if anyCorner { return false, false } for _, c := range s { if r.ContainsPC(c) { return false, false } } return false, true } func main() { flag.IntVar(&nWorkers, "workers", nWorkers, "how many worker go routines to use") maxproc := flag.Int("cpu", runtime.NumCPU(), "GOMAXPROCS setting") flag.Parse() if *maxproc > 0 { runtime.GOMAXPROCS(*maxproc) } else { *maxproc = runtime.GOMAXPROCS(0) } circles := CircleSet{ NewCircle(1.6417233788, 1.6121789534, 0.0848270516), NewCircle(-1.4944608174, 1.2077959613, 1.1039549836), NewCircle(0.6110294452, -0.6907087527, 0.9089162485), NewCircle(0.3844862411, 0.2923344616, 0.2375743054), NewCircle(-0.2495892950, -0.3832854473, 1.0845181219), NewCircle(1.7813504266, 1.6178237031, 0.8162655711), NewCircle(-0.1985249206, -0.8343333301, 0.0538864941), NewCircle(-1.7011985145, -0.1263820964, 0.4776976918), NewCircle(-0.4319462812, 1.4104420482, 0.7886291537), NewCircle(0.2178372997, -0.9499557344, 0.0357871187), NewCircle(-0.6294854565, -1.3078893852, 0.7653357688), NewCircle(1.7952608455, 0.6281269104, 0.2727652452), NewCircle(1.4168575317, 1.0683357171, 1.1016025378), NewCircle(1.4637371396, 0.9463877418, 1.1846214562), NewCircle(-0.5263668798, 1.7315156631, 1.4428514068), NewCircle(-1.2197352481, 0.9144146579, 1.0727263474), NewCircle(-0.1389358881, 0.1092805780, 0.7350208828), NewCircle(1.5293954595, 0.0030278255, 1.2472867347), NewCircle(-0.5258728625, 1.3782633069, 1.3495508831), NewCircle(-0.1403562064, 0.2437382535, 1.3804956588), NewCircle(0.8055826339, -0.0482092025, 0.3327165165), NewCircle(-0.6311979224, 0.7184578971, 0.2491045282), NewCircle(1.4685857879, -0.8347049536, 1.3670667538), NewCircle(-0.6855727502, 1.6465021616, 1.0593087096), NewCircle(0.0152957411, 0.0638919221, 0.9771215985), } fmt.Println("Starting with", len(circles), "circles.") circles.RemoveContainedC() fmt.Println("Removing redundant ones leaves", len(circles), "circles.") fmt.Println("Using", nWorkers, "workers with maxprocs =", *maxproc) const ε = 0.0001 min, max := circles.UnionArea(ε) avg := (min + max) / 2.0 rng := max - min fmt.Printf("Area = %v±%v\n", avg, rng) fmt.Printf("Area ≈ %.*f\n", 5, avg) }
Produce a language-to-language conversion: from Python to Go, same semantics.
from collections import namedtuple Circle = namedtuple("Circle", "x y r") circles = [ Circle( 1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle( 0.6110294452, -0.6907087527, 0.9089162485), Circle( 0.3844862411, 0.2923344616, 0.2375743054), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
package main import ( "flag" "fmt" "math" "runtime" "sort" ) type Circle struct{ X, Y, R, rsq float64 } func NewCircle(x, y, r float64) Circle { return Circle{x, y, r, r * r} } func (c Circle) ContainsPt(x, y float64) bool { return distSq(x, y, c.X, c.Y) <= c.rsq } func (c Circle) ContainsC(c2 Circle) bool { return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R) } func (c Circle) ContainsR(r Rect) (full, corner bool) { nw := c.ContainsPt(r.NW()) ne := c.ContainsPt(r.NE()) sw := c.ContainsPt(r.SW()) se := c.ContainsPt(r.SE()) return nw && ne && sw && se, nw || ne || sw || se } func (c Circle) North() (float64, float64) { return c.X, c.Y + c.R } func (c Circle) South() (float64, float64) { return c.X, c.Y - c.R } func (c Circle) West() (float64, float64) { return c.X - c.R, c.Y } func (c Circle) East() (float64, float64) { return c.X + c.R, c.Y } type Rect struct{ X1, Y1, X2, Y2 float64 } func (r Rect) Area() float64 { return (r.X2 - r.X1) * (r.Y2 - r.Y1) } func (r Rect) NW() (float64, float64) { return r.X1, r.Y2 } func (r Rect) NE() (float64, float64) { return r.X2, r.Y2 } func (r Rect) SW() (float64, float64) { return r.X1, r.Y1 } func (r Rect) SE() (float64, float64) { return r.X2, r.Y1 } func (r Rect) Centre() (float64, float64) { return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0 } func (r Rect) ContainsPt(x, y float64) bool { return r.X1 <= x && x < r.X2 && r.Y1 <= y && y < r.Y2 } func (r Rect) ContainsPC(c Circle) bool { return r.ContainsPt(c.North()) || r.ContainsPt(c.South()) || r.ContainsPt(c.West()) || r.ContainsPt(c.East()) } func (r Rect) MinSide() float64 { return math.Min(r.X2-r.X1, r.Y2-r.Y1) } func distSq(x1, y1, x2, y2 float64) float64 { Δx, Δy := x2-x1, y2-y1 return (Δx * Δx) + (Δy * Δy) } type CircleSet []Circle func (s CircleSet) Len() int { return len(s) } func (s CircleSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R } func (sp *CircleSet) RemoveContainedC() { s := *sp sort.Sort(s) for i := 0; i < len(s); i++ { for j := i + 1; j < len(s); { if s[i].ContainsC(s[j]) { s[j], s[len(s)-1] = s[len(s)-1], s[j] s = s[:len(s)-1] } else { j++ } } } *sp = s } func (s CircleSet) Bounds() Rect { x1 := s[0].X - s[0].R x2 := s[0].X + s[0].R y1 := s[0].Y - s[0].R y2 := s[0].Y + s[0].R for _, c := range s[1:] { x1 = math.Min(x1, c.X-c.R) x2 = math.Max(x2, c.X+c.R) y1 = math.Min(y1, c.Y-c.R) y2 = math.Max(y2, c.Y+c.R) } return Rect{x1, y1, x2, y2} } var nWorkers = 4 func (s CircleSet) UnionArea(ε float64) (min, max float64) { sort.Sort(s) stop := make(chan bool) inside := make(chan Rect) outside := make(chan Rect) unknown := make(chan Rect, 5e7) for i := 0; i < nWorkers; i++ { go s.worker(stop, unknown, inside, outside) } r := s.Bounds() max = r.Area() unknown <- r for max-min > ε { select { case r = <-inside: min += r.Area() case r = <-outside: max -= r.Area() } } close(stop) return min, max } func (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) { for { select { case <-stop: return case r := <-unk: inside, outside := s.CategorizeR(r) switch { case inside: in <- r case outside: out <- r default: midX, midY := r.Centre() unk <- Rect{r.X1, r.Y1, midX, midY} unk <- Rect{midX, r.Y1, r.X2, midY} unk <- Rect{r.X1, midY, midX, r.Y2} unk <- Rect{midX, midY, r.X2, r.Y2} } } } } func (s CircleSet) CategorizeR(r Rect) (inside, outside bool) { anyCorner := false for _, c := range s { full, corner := c.ContainsR(r) if full { return true, false } anyCorner = anyCorner || corner } if anyCorner { return false, false } for _, c := range s { if r.ContainsPC(c) { return false, false } } return false, true } func main() { flag.IntVar(&nWorkers, "workers", nWorkers, "how many worker go routines to use") maxproc := flag.Int("cpu", runtime.NumCPU(), "GOMAXPROCS setting") flag.Parse() if *maxproc > 0 { runtime.GOMAXPROCS(*maxproc) } else { *maxproc = runtime.GOMAXPROCS(0) } circles := CircleSet{ NewCircle(1.6417233788, 1.6121789534, 0.0848270516), NewCircle(-1.4944608174, 1.2077959613, 1.1039549836), NewCircle(0.6110294452, -0.6907087527, 0.9089162485), NewCircle(0.3844862411, 0.2923344616, 0.2375743054), NewCircle(-0.2495892950, -0.3832854473, 1.0845181219), NewCircle(1.7813504266, 1.6178237031, 0.8162655711), NewCircle(-0.1985249206, -0.8343333301, 0.0538864941), NewCircle(-1.7011985145, -0.1263820964, 0.4776976918), NewCircle(-0.4319462812, 1.4104420482, 0.7886291537), NewCircle(0.2178372997, -0.9499557344, 0.0357871187), NewCircle(-0.6294854565, -1.3078893852, 0.7653357688), NewCircle(1.7952608455, 0.6281269104, 0.2727652452), NewCircle(1.4168575317, 1.0683357171, 1.1016025378), NewCircle(1.4637371396, 0.9463877418, 1.1846214562), NewCircle(-0.5263668798, 1.7315156631, 1.4428514068), NewCircle(-1.2197352481, 0.9144146579, 1.0727263474), NewCircle(-0.1389358881, 0.1092805780, 0.7350208828), NewCircle(1.5293954595, 0.0030278255, 1.2472867347), NewCircle(-0.5258728625, 1.3782633069, 1.3495508831), NewCircle(-0.1403562064, 0.2437382535, 1.3804956588), NewCircle(0.8055826339, -0.0482092025, 0.3327165165), NewCircle(-0.6311979224, 0.7184578971, 0.2491045282), NewCircle(1.4685857879, -0.8347049536, 1.3670667538), NewCircle(-0.6855727502, 1.6465021616, 1.0593087096), NewCircle(0.0152957411, 0.0638919221, 0.9771215985), } fmt.Println("Starting with", len(circles), "circles.") circles.RemoveContainedC() fmt.Println("Removing redundant ones leaves", len(circles), "circles.") fmt.Println("Using", nWorkers, "workers with maxprocs =", *maxproc) const ε = 0.0001 min, max := circles.UnionArea(ε) avg := (min + max) / 2.0 rng := max - min fmt.Printf("Area = %v±%v\n", avg, rng) fmt.Printf("Area ≈ %.*f\n", 5, avg) }
Generate a Go translation of this Python snippet without changing its computational steps.
from math import hypot, pi, cos, sin from PIL import Image def hough(im, ntx=460, mry=360): "Calculate Hough transform." pim = im.load() nimx, mimy = im.size mry = int(mry/2)*2 him = Image.new("L", (ntx, mry), 255) phim = him.load() rmax = hypot(nimx, mimy) dr = rmax / (mry/2) dth = pi / ntx for jx in xrange(nimx): for iy in xrange(mimy): col = pim[jx, iy] if col == 255: continue for jtx in xrange(ntx): th = dth * jtx r = jx*cos(th) + iy*sin(th) iry = mry/2 + int(r/dr+0.5) phim[jtx, iry] -= 1 return him def test(): "Test Hough transform with pentagon." im = Image.open("pentagon.png").convert("L") him = hough(im) him.save("ho5.bmp") if __name__ == "__main__": test()
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" ) func hough(im image.Image, ntx, mry int) draw.Image { nimx := im.Bounds().Max.X mimy := im.Bounds().Max.Y him := image.NewGray(image.Rect(0, 0, ntx, mry)) draw.Draw(him, him.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src) rmax := math.Hypot(float64(nimx), float64(mimy)) dr := rmax / float64(mry/2) dth := math.Pi / float64(ntx) for jx := 0; jx < nimx; jx++ { for iy := 0; iy < mimy; iy++ { col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray) if col.Y == 255 { continue } for jtx := 0; jtx < ntx; jtx++ { th := dth * float64(jtx) r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th) iry := mry/2 - int(math.Floor(r/dr+.5)) col = him.At(jtx, iry).(color.Gray) if col.Y > 0 { col.Y-- him.SetGray(jtx, iry, col) } } } } return him } func main() { f, err := os.Open("Pentagon.png") if err != nil { fmt.Println(err) return } pent, err := png.Decode(f) if err != nil { fmt.Println(err) return } if err = f.Close(); err != nil { fmt.Println(err) } h := hough(pent, 460, 360) if f, err = os.Create("hough.png"); err != nil { fmt.Println(err) return } if err = png.Encode(f, h); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(err) } }
Preserve the algorithm and functionality while converting the code from Python to Go.
import math import random def GammaInc_Q( a, x): a1 = a-1 a2 = a-2 def f0( t ): return t**a1*math.exp(-t) def df0(t): return (a1-t)*t**a2*math.exp(-t) y = a1 while f0(y)*(x-y) >2.0e-8 and y < x: y += .3 if y > x: y = x h = 3.0e-4 n = int(y/h) h = y/n hh = 0.5*h gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1))) return gamax/gamma_spounge(a) c = None def gamma_spounge( z): global c a = 12 if c is None: k1_factrl = 1.0 c = [] c.append(math.sqrt(2.0*math.pi)) for k in range(1,a): c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl ) k1_factrl *= -k accm = c[0] for k in range(1,a): accm += c[k] / (z+k) accm *= math.exp( -(z+a)) * (z+a)**(z+0.5) return accm/z; def chi2UniformDistance( dataSet ): expected = sum(dataSet)*1.0/len(dataSet) cntrd = (d-expected for d in dataSet) return sum(x*x for x in cntrd)/expected def chi2Probability(dof, distance): return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance) def chi2IsUniform(dataSet, significance): dof = len(dataSet)-1 dist = chi2UniformDistance(dataSet) return chi2Probability( dof, dist ) > significance dset1 = [ 199809, 200665, 199607, 200270, 199649 ] dset2 = [ 522573, 244456, 139979, 71531, 21461 ] for ds in (dset1, dset2): print "Data set:", ds dof = len(ds)-1 distance =chi2UniformDistance(ds) print "dof: %d distance: %.4f" % (dof, distance), prob = chi2Probability( dof, distance) print "probability: %.4f"%prob, print "uniform? ", "Yes"if chi2IsUniform(ds,0.05) else "No"
package main import ( "fmt" "math" ) type ifctn func(float64) float64 func simpson38(f ifctn, a, b float64, n int) float64 { h := (b - a) / float64(n) h1 := h / 3 sum := f(a) + f(b) for j := 3*n - 1; j > 0; j-- { if j%3 == 0 { sum += 2 * f(a+h1*float64(j)) } else { sum += 3 * f(a+h1*float64(j)) } } return h * sum / 8 } func gammaIncQ(a, x float64) float64 { aa1 := a - 1 var f ifctn = func(t float64) float64 { return math.Pow(t, aa1) * math.Exp(-t) } y := aa1 h := 1.5e-2 for f(y)*(x-y) > 2e-8 && y < x { y += .4 } if y > x { y = x } return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a))) } func chi2ud(ds []int) float64 { var sum, expected float64 for _, d := range ds { expected += float64(d) } expected /= float64(len(ds)) for _, d := range ds { x := float64(d) - expected sum += x * x } return sum / expected } func chi2p(dof int, distance float64) float64 { return gammaIncQ(.5*float64(dof), .5*distance) } const sigLevel = .05 func main() { for _, dset := range [][]int{ {199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}, } { utest(dset) } } func utest(dset []int) { fmt.Println("Uniform distribution test") var sum int for _, c := range dset { sum += c } fmt.Println(" dataset:", dset) fmt.Println(" samples: ", sum) fmt.Println(" categories: ", len(dset)) dof := len(dset) - 1 fmt.Println(" degrees of freedom: ", dof) dist := chi2ud(dset) fmt.Println(" chi square test statistic: ", dist) p := chi2p(dof, dist) fmt.Println(" p-value of test statistic: ", p) sig := p < sigLevel fmt.Printf(" significant at %2.0f%% level? %t\n", sigLevel*100, sig) fmt.Println(" uniform? ", !sig, "\n") }
Translate this program into Go but keep the logic exactly as in Python.
import numpy as np import scipy as sp import scipy.stats def welch_ttest(x1, x2): n1 = x1.size n2 = x2.size m1 = np.mean(x1) m2 = np.mean(x2) v1 = np.var(x1, ddof=1) v2 = np.var(x2, ddof=1) t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2) df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1))) p = 2 * sp.stats.t.cdf(-abs(t), df) return t, df, p welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9])) (-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
package main import ( "fmt" "math" ) var ( d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6, 23.1, 19.6, 19.0, 21.7, 21.4} d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2, 21.9, 22.1, 22.9, 20.5, 24.4} d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8} d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8, 20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8} d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0} d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7, 23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2} d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99} d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98} x = []float64{3.0, 4.0, 1.0, 2.1} y = []float64{490.2, 340.0, 433.9} ) func main() { fmt.Printf("%.6f\n", pValue(d1, d2)) fmt.Printf("%.6f\n", pValue(d3, d4)) fmt.Printf("%.6f\n", pValue(d5, d6)) fmt.Printf("%.6f\n", pValue(d7, d8)) fmt.Printf("%.6f\n", pValue(x, y)) } func mean(a []float64) float64 { sum := 0. for _, x := range a { sum += x } return sum / float64(len(a)) } func sv(a []float64) float64 { m := mean(a) sum := 0. for _, x := range a { d := x - m sum += d * d } return sum / float64(len(a)-1) } func welch(a, b []float64) float64 { return (mean(a) - mean(b)) / math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b))) } func dof(a, b []float64) float64 { sva := sv(a) svb := sv(b) n := sva/float64(len(a)) + svb/float64(len(b)) return n * n / (sva*sva/float64(len(a)*len(a)*(len(a)-1)) + svb*svb/float64(len(b)*len(b)*(len(b)-1))) } func simpson0(n int, upper float64, f func(float64) float64) float64 { sum := 0. nf := float64(n) dx0 := upper / nf sum += f(0) * dx0 sum += f(dx0*.5) * dx0 * 4 x0 := dx0 for i := 1; i < n; i++ { x1 := float64(i+1) * upper / nf xmid := (x0 + x1) * .5 dx := x1 - x0 sum += f(x0) * dx * 2 sum += f(xmid) * dx * 4 x0 = x1 } return (sum + f(upper)*dx0) / 6 } func pValue(a, b []float64) float64 { ν := dof(a, b) t := welch(a, b) g1, _ := math.Lgamma(ν / 2) g2, _ := math.Lgamma(.5) g3, _ := math.Lgamma(ν/2 + .5) return simpson0(2000, ν/(t*t+ν), func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) / math.Exp(g1+g2-g3) }
Keep all operations the same but rewrite the snippet in Go.
import numpy as np import scipy as sp import scipy.stats def welch_ttest(x1, x2): n1 = x1.size n2 = x2.size m1 = np.mean(x1) m2 = np.mean(x2) v1 = np.var(x1, ddof=1) v2 = np.var(x2, ddof=1) t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2) df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1))) p = 2 * sp.stats.t.cdf(-abs(t), df) return t, df, p welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9])) (-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
package main import ( "fmt" "math" ) var ( d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6, 23.1, 19.6, 19.0, 21.7, 21.4} d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2, 21.9, 22.1, 22.9, 20.5, 24.4} d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8} d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8, 20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8} d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0} d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7, 23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2} d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99} d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98} x = []float64{3.0, 4.0, 1.0, 2.1} y = []float64{490.2, 340.0, 433.9} ) func main() { fmt.Printf("%.6f\n", pValue(d1, d2)) fmt.Printf("%.6f\n", pValue(d3, d4)) fmt.Printf("%.6f\n", pValue(d5, d6)) fmt.Printf("%.6f\n", pValue(d7, d8)) fmt.Printf("%.6f\n", pValue(x, y)) } func mean(a []float64) float64 { sum := 0. for _, x := range a { sum += x } return sum / float64(len(a)) } func sv(a []float64) float64 { m := mean(a) sum := 0. for _, x := range a { d := x - m sum += d * d } return sum / float64(len(a)-1) } func welch(a, b []float64) float64 { return (mean(a) - mean(b)) / math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b))) } func dof(a, b []float64) float64 { sva := sv(a) svb := sv(b) n := sva/float64(len(a)) + svb/float64(len(b)) return n * n / (sva*sva/float64(len(a)*len(a)*(len(a)-1)) + svb*svb/float64(len(b)*len(b)*(len(b)-1))) } func simpson0(n int, upper float64, f func(float64) float64) float64 { sum := 0. nf := float64(n) dx0 := upper / nf sum += f(0) * dx0 sum += f(dx0*.5) * dx0 * 4 x0 := dx0 for i := 1; i < n; i++ { x1 := float64(i+1) * upper / nf xmid := (x0 + x1) * .5 dx := x1 - x0 sum += f(x0) * dx * 2 sum += f(xmid) * dx * 4 x0 = x1 } return (sum + f(upper)*dx0) / 6 } func pValue(a, b []float64) float64 { ν := dof(a, b) t := welch(a, b) g1, _ := math.Lgamma(ν / 2) g2, _ := math.Lgamma(.5) g3, _ := math.Lgamma(ν/2 + .5) return simpson0(2000, ν/(t*t+ν), func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) / math.Exp(g1+g2-g3) }
Write the same algorithm in Go as shown in this Python implementation.
try: from functools import reduce except: pass def topx(data, tops=None): 'Extract the set of top-level(s) in topological order' for k, v in data.items(): v.discard(k) if tops is None: tops = toplevels(data) return _topx(data, tops, [], set()) def _topx(data, tops, _sofar, _sofar_set): 'Recursive topological extractor' _sofar += [tops] _sofar_set.union(tops) depends = reduce(set.union, (data.get(top, set()) for top in tops)) if depends: _topx(data, depends, _sofar, _sofar_set) ordered, accum = [], set() for s in _sofar[::-1]: ordered += [sorted(s - accum)] accum |= s return ordered def printorder(order): 'Prettyprint topological ordering' if order: print("First: " + ', '.join(str(s) for s in order[0])) for o in order[1:]: print(" Then: " + ', '.join(str(s) for s in o)) def toplevels(data): for k, v in data.items(): v.discard(k) dependents = reduce(set.union, data.values()) return set(data.keys()) - dependents if __name__ == '__main__': data = dict( top1 = set('ip1 des1 ip2'.split()), top2 = set('ip2 des1 ip3'.split()), des1 = set('des1a des1b des1c'.split()), des1a = set('des1a1 des1a2'.split()), des1c = set('des1c1 extra1'.split()), ip2 = set('ip2a ip2b ip2c ipcommon'.split()), ip1 = set('ip1a ipcommon extra1'.split()), ) tops = toplevels(data) print("The top levels of the dependency graph are: " + ' '.join(tops)) for t in sorted(tops): print("\nThe compile order for top level: %s is..." % t) printorder(topx(data, set([t]))) if len(tops) > 1: print("\nThe compile order for top levels: %s is..." % ' and '.join(str(s) for s in sorted(tops)) ) printorder(topx(data, tops))
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err := parseLibDep(data) if err != nil { fmt.Println(err) return } var tops []string for n := range g { if !dep[n] { tops = append(tops, n) } } fmt.Println("Top levels:", tops) showOrder(g, "top1") showOrder(g, "top2") showOrder(g, "top1", "top2") fmt.Println("Cycle examples:") g, _, err = parseLibDep(data + ` des1a1 des1`) if err != nil { fmt.Println(err) return } showOrder(g, "top1") showOrder(g, "ip1", "ip2") } func showOrder(g graph, target ...string) { order, cyclic := g.orderFrom(target...) if cyclic == nil { reverse(order) fmt.Println("Target", target, "order:", order) } else { fmt.Println("Target", target, "cyclic dependencies:", cyclic) } } func reverse(s []string) { last := len(s) - 1 for i, e := range s[:len(s)/2] { s[i], s[last-i] = s[last-i], e } } type graph map[string][]string type depList map[string]bool func parseLibDep(data string) (g graph, d depList, err error) { lines := strings.Split(data, "\n") if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") { return nil, nil, fmt.Errorf("data format") } lines = lines[3:] g = graph{} d = depList{} for _, line := range lines { libs := strings.Fields(line) if len(libs) == 0 { continue } lib := libs[0] var deps []string for _, dep := range libs[1:] { g[dep] = g[dep] if dep == lib { continue } for i := 0; ; i++ { if i == len(deps) { deps = append(deps, dep) d[dep] = true break } if dep == deps[i] { break } } } g[lib] = deps } return g, d, nil } func (g graph) orderFrom(start ...string) (order, cyclic []string) { L := make([]string, len(g)) i := len(L) temp := map[string]bool{} perm := map[string]bool{} var cycleFound bool var cycleStart string var visit func(string) visit = func(n string) { switch { case temp[n]: cycleFound = true cycleStart = n return case perm[n]: return } temp[n] = true for _, m := range g[n] { visit(m) if cycleFound { if cycleStart > "" { cyclic = append(cyclic, n) if n == cycleStart { cycleStart = "" } } return } } delete(temp, n) perm[n] = true i-- L[i] = n } for _, n := range start { if perm[n] { continue } visit(n) if cycleFound { return nil, cyclic } } return L[i:], nil }
Produce a language-to-language conversion: from Python to Go, same semantics.
try: from functools import reduce except: pass def topx(data, tops=None): 'Extract the set of top-level(s) in topological order' for k, v in data.items(): v.discard(k) if tops is None: tops = toplevels(data) return _topx(data, tops, [], set()) def _topx(data, tops, _sofar, _sofar_set): 'Recursive topological extractor' _sofar += [tops] _sofar_set.union(tops) depends = reduce(set.union, (data.get(top, set()) for top in tops)) if depends: _topx(data, depends, _sofar, _sofar_set) ordered, accum = [], set() for s in _sofar[::-1]: ordered += [sorted(s - accum)] accum |= s return ordered def printorder(order): 'Prettyprint topological ordering' if order: print("First: " + ', '.join(str(s) for s in order[0])) for o in order[1:]: print(" Then: " + ', '.join(str(s) for s in o)) def toplevels(data): for k, v in data.items(): v.discard(k) dependents = reduce(set.union, data.values()) return set(data.keys()) - dependents if __name__ == '__main__': data = dict( top1 = set('ip1 des1 ip2'.split()), top2 = set('ip2 des1 ip3'.split()), des1 = set('des1a des1b des1c'.split()), des1a = set('des1a1 des1a2'.split()), des1c = set('des1c1 extra1'.split()), ip2 = set('ip2a ip2b ip2c ipcommon'.split()), ip1 = set('ip1a ipcommon extra1'.split()), ) tops = toplevels(data) print("The top levels of the dependency graph are: " + ' '.join(tops)) for t in sorted(tops): print("\nThe compile order for top level: %s is..." % t) printorder(topx(data, set([t]))) if len(tops) > 1: print("\nThe compile order for top levels: %s is..." % ' and '.join(str(s) for s in sorted(tops)) ) printorder(topx(data, tops))
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err := parseLibDep(data) if err != nil { fmt.Println(err) return } var tops []string for n := range g { if !dep[n] { tops = append(tops, n) } } fmt.Println("Top levels:", tops) showOrder(g, "top1") showOrder(g, "top2") showOrder(g, "top1", "top2") fmt.Println("Cycle examples:") g, _, err = parseLibDep(data + ` des1a1 des1`) if err != nil { fmt.Println(err) return } showOrder(g, "top1") showOrder(g, "ip1", "ip2") } func showOrder(g graph, target ...string) { order, cyclic := g.orderFrom(target...) if cyclic == nil { reverse(order) fmt.Println("Target", target, "order:", order) } else { fmt.Println("Target", target, "cyclic dependencies:", cyclic) } } func reverse(s []string) { last := len(s) - 1 for i, e := range s[:len(s)/2] { s[i], s[last-i] = s[last-i], e } } type graph map[string][]string type depList map[string]bool func parseLibDep(data string) (g graph, d depList, err error) { lines := strings.Split(data, "\n") if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") { return nil, nil, fmt.Errorf("data format") } lines = lines[3:] g = graph{} d = depList{} for _, line := range lines { libs := strings.Fields(line) if len(libs) == 0 { continue } lib := libs[0] var deps []string for _, dep := range libs[1:] { g[dep] = g[dep] if dep == lib { continue } for i := 0; ; i++ { if i == len(deps) { deps = append(deps, dep) d[dep] = true break } if dep == deps[i] { break } } } g[lib] = deps } return g, d, nil } func (g graph) orderFrom(start ...string) (order, cyclic []string) { L := make([]string, len(g)) i := len(L) temp := map[string]bool{} perm := map[string]bool{} var cycleFound bool var cycleStart string var visit func(string) visit = func(n string) { switch { case temp[n]: cycleFound = true cycleStart = n return case perm[n]: return } temp[n] = true for _, m := range g[n] { visit(m) if cycleFound { if cycleStart > "" { cyclic = append(cyclic, n) if n == cycleStart { cycleStart = "" } } return } } delete(temp, n) perm[n] = true i-- L[i] = n } for _, n := range start { if perm[n] { continue } visit(n) if cycleFound { return nil, cyclic } } return L[i:], nil }
Port the following code from Python to Go with equivalent syntax and logic.
def getitem(s, depth=0): out = [""] while s: c = s[0] if depth and (c == ',' or c == '}'): return out,s if c == '{': x = getgroup(s[1:], depth+1) if x: out,s = [a+b for a in out for b in x[0]], x[1] continue if c == '\\' and len(s) > 1: s, c = s[1:], c + s[1] out, s = [a+c for a in out], s[1:] return out,s def getgroup(s, depth): out, comma = [], False while s: g,s = getitem(s, depth) if not s: break out += g if s[0] == '}': if comma: return out, s[1:] return ['{' + a + '}' for a in out], s[1:] if s[0] == ',': comma,s = True, s[1:] return None for s in .split('\n'): print "\n\t".join([s] + getitem(s)[0]) + "\n"
package expand type Expander interface { Expand() []string } type Text string func (t Text) Expand() []string { return []string{string(t)} } type Alternation []Expander func (alt Alternation) Expand() []string { var out []string for _, e := range alt { out = append(out, e.Expand()...) } return out } type Sequence []Expander func (seq Sequence) Expand() []string { if len(seq) == 0 { return nil } out := seq[0].Expand() for _, e := range seq[1:] { out = combine(out, e.Expand()) } return out } func combine(al, bl []string) []string { out := make([]string, 0, len(al)*len(bl)) for _, a := range al { for _, b := range bl { out = append(out, a+b) } } return out } const ( escape = '\\' altStart = '{' altEnd = '}' altSep = ',' ) type piT struct{ pos, cnt, depth int } type Brace string func Expand(s string) []string { return Brace(s).Expand() } func (b Brace) Expand() []string { return b.Expander().Expand() } func (b Brace) Expander() Expander { s := string(b) var posInfo []piT var stack []int removePosInfo := func(i int) { end := len(posInfo) - 1 copy(posInfo[i:end], posInfo[i+1:]) posInfo = posInfo[:end] } inEscape := false for i, r := range s { if inEscape { inEscape = false continue } switch r { case escape: inEscape = true case altStart: stack = append(stack, len(posInfo)) posInfo = append(posInfo, piT{i, 0, len(stack)}) case altEnd: if len(stack) == 0 { continue } si := len(stack) - 1 pi := stack[si] if posInfo[pi].cnt == 0 { removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == len(stack) { removePosInfo(pi) } else { pi++ } } } else { posInfo = append(posInfo, piT{i, -2, len(stack)}) } stack = stack[:si] case altSep: if len(stack) == 0 { continue } posInfo = append(posInfo, piT{i, -1, len(stack)}) posInfo[stack[len(stack)-1]].cnt++ } } for len(stack) > 0 { si := len(stack) - 1 pi := stack[si] depth := posInfo[pi].depth removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == depth { removePosInfo(pi) } else { pi++ } } stack = stack[:si] } return buildExp(s, 0, posInfo) } func buildExp(s string, off int, info []piT) Expander { if len(info) == 0 { return Text(s) } var seq Sequence i := 0 var dj, j, depth int for dk, piK := range info { k := piK.pos - off switch s[k] { case altStart: if depth == 0 { dj = dk j = k depth = piK.depth } case altEnd: if piK.depth != depth { continue } if j > i { seq = append(seq, Text(s[i:j])) } alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk]) seq = append(seq, alt) i = k + 1 depth = 0 } } if j := len(s); j > i { seq = append(seq, Text(s[i:j])) } if len(seq) == 1 { return seq[0] } return seq } func buildAlt(s string, depth, off int, info []piT) Alternation { var alt Alternation i := 0 var di int for dk, piK := range info { if piK.depth != depth { continue } if k := piK.pos - off; s[k] == altSep { sub := buildExp(s[i:k], i+off, info[di:dk]) alt = append(alt, sub) i = k + 1 di = dk + 1 } } sub := buildExp(s[i:], i+off, info[di:]) alt = append(alt, sub) return alt }
Keep all operations the same but rewrite the snippet in Go.
def no_args(): pass no_args() def fixed_args(x, y): print('x=%r, y=%r' % (x, y)) fixed_args(1, 2) fixed_args(y=2, x=1) myargs=(1,2) fixed_args(*myargs) def opt_args(x=1): print(x) opt_args() opt_args(3.141) def var_args(*v): print(v) var_args(1, 2, 3) var_args(1, (2,3)) var_args() fixed_args(y=2, x=1) if 1: no_args() assert no_args() is None def return_something(): return 1 x = return_something() def is_builtin(x): print(x.__name__ in dir(__builtins__)) is_builtin(pow) is_builtin(is_builtin) def takes_anything(*args, **kwargs): for each in args: print(each) for key, value in sorted(kwargs.items()): print("%s:%s" % (key, value)) wrapped_fn(*args, **kwargs)
import ( "image" "image/gif" "io/ioutil" "strings" "unicode" ) func f() (int, float64) { return 0, 0 } func g(int, float64) int { return 0 } func h(string, ...int) {}
Preserve the algorithm and functionality while converting the code from Python to Go.
def no_args(): pass no_args() def fixed_args(x, y): print('x=%r, y=%r' % (x, y)) fixed_args(1, 2) fixed_args(y=2, x=1) myargs=(1,2) fixed_args(*myargs) def opt_args(x=1): print(x) opt_args() opt_args(3.141) def var_args(*v): print(v) var_args(1, 2, 3) var_args(1, (2,3)) var_args() fixed_args(y=2, x=1) if 1: no_args() assert no_args() is None def return_something(): return 1 x = return_something() def is_builtin(x): print(x.__name__ in dir(__builtins__)) is_builtin(pow) is_builtin(is_builtin) def takes_anything(*args, **kwargs): for each in args: print(each) for key, value in sorted(kwargs.items()): print("%s:%s" % (key, value)) wrapped_fn(*args, **kwargs)
import ( "image" "image/gif" "io/ioutil" "strings" "unicode" ) func f() (int, float64) { return 0, 0 } func g(int, float64) int { return 0 } func h(string, ...int) {}
Convert this Python block to Go, preserving its control flow and logic.
"Generate a short Superpermutation of n characters A... as a string using various algorithms." from __future__ import print_function, division from itertools import permutations from math import factorial import string import datetime import gc MAXN = 7 def s_perm0(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in permutations(allchars)] sp, tofind = allperms[0], set(allperms[1:]) while tofind: for skip in range(1, n): for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])): trial_perm = (sp + trial_add)[-n:] if trial_perm in tofind: sp += trial_add tofind.discard(trial_perm) trial_add = None break if trial_add is None: break assert all(perm in sp for perm in allperms) return sp def s_perm1(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: nxt = perms.pop() if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def s_perm2(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: nxt = perms.pop(0) if nxt not in sp: sp += nxt if perms: nxt = perms.pop(-1) if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def _s_perm3(n, cmp): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: lastn = sp[-n:] nxt = cmp(perms, key=lambda pm: sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn))) perms.remove(nxt) if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def s_perm3_max(n): return _s_perm3(n, max) def s_perm3_min(n): return _s_perm3(n, min) longest = [factorial(n) * n for n in range(MAXN + 1)] weight, runtime = {}, {} print(__doc__) for algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]: print('\n print(algo.__doc__) weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0) for n in range(1, MAXN + 1): gc.collect() gc.disable() t = datetime.datetime.now() sp = algo(n) t = datetime.datetime.now() - t gc.enable() runtime[algo.__name__] += t lensp = len(sp) wt = (lensp / longest[n]) ** 2 print(' For N=%i: SP length %5i Max: %5i Weight: %5.2f' % (n, lensp, longest[n], wt)) weight[algo.__name__] *= wt weight[algo.__name__] **= 1 / n weight[algo.__name__] = 1 / weight[algo.__name__] print('%*s Overall Weight: %5.2f in %.1f seconds.' % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds())) print('\n print('\n'.join('%12s (%.3f)' % kv for kv in sorted(weight.items(), key=lambda keyvalue: -keyvalue[1]))) print('\n print('\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))
package main import "fmt" const max = 12 var ( super []byte pos int cnt [max]int ) func factSum(n int) int { s := 0 for x, f := 0, 1; x < n; { x++ f *= x s += f } return s } func r(n int) bool { if n == 0 { return false } c := super[pos-n] cnt[n]-- if cnt[n] == 0 { cnt[n] = n if !r(n - 1) { return false } } super[pos] = c pos++ return true } func superperm(n int) { pos = n le := factSum(n) super = make([]byte, le) for i := 0; i <= n; i++ { cnt[i] = i } for i := 1; i <= n; i++ { super[i-1] = byte(i) + '0' } for r(n) { } } func main() { for n := 0; n < max; n++ { fmt.Printf("superperm(%2d) ", n) superperm(n) fmt.Printf("len = %d\n", len(super)) } }