Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite the snippet below in Go so it works the same as the original Python code. | import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
s.set(int(s.get())+1)
def rand():
if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
s.set(random.randrange(0,5000))
def update(e):
if not e.char.isdigit():
tkMessageBox.showerror('Error', 'Invalid input !')
return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()
| package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"math/rand"
"strconv"
"time"
)
func validateInput(window *gtk.Window, str string) (int64, bool) {
i, err := strconv.ParseInt(str, 10, 64)
if err != nil {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_OK,
"Invalid value",
)
dialog.Run()
dialog.Destroy()
return 0, false
}
return i, true
}
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
gtk.Init(nil)
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetTitle("Rosetta Code")
window.SetPosition(gtk.WIN_POS_CENTER)
window.Connect("destroy", func() {
gtk.MainQuit()
})
box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create box:")
box.SetBorderWidth(1)
label, err := gtk.LabelNew("Value:")
check(err, "Unable to create label:")
entry, err := gtk.EntryNew()
check(err, "Unable to create entry:")
entry.SetText("0")
entry.Connect("activate", func() {
str, _ := entry.GetText()
validateInput(window, str)
})
ib, err := gtk.ButtonNewWithLabel("Increment")
check(err, "Unable to create increment button:")
ib.Connect("clicked", func() {
str, _ := entry.GetText()
if i, ok := validateInput(window, str); ok {
entry.SetText(strconv.FormatInt(i+1, 10))
}
})
rb, err := gtk.ButtonNewWithLabel("Random")
check(err, "Unable to create random button:")
rb.Connect("clicked", func() {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO,
"Set random value",
)
answer := dialog.Run()
dialog.Destroy()
if answer == gtk.RESPONSE_YES {
entry.SetText(strconv.Itoa(rand.Intn(10000)))
}
})
box.PackStart(label, false, false, 2)
box.PackStart(entry, false, false, 2)
box.PackStart(ib, false, false, 2)
box.PackStart(rb, false, false, 2)
window.Add(box)
window.ShowAll()
gtk.Main()
}
|
Rewrite the snippet below in Go so it works the same as the original Python code. | from random import randrange
try:
range = xrange
except: pass
def one_of_n(lines):
choice = None
for i, line in enumerate(lines):
if randrange(i+1) == 0:
choice = line
return choice
def one_of_n_test(n=10, trials=1000000):
bins = [0] * n
if n:
for i in range(trials):
bins[one_of_n(range(n))] += 1
return bins
print(one_of_n_test())
| package main
import (
"bufio"
"fmt"
"io"
"math/rand"
"time"
)
func choseLineRandomly(r io.Reader) (s string, ln int, err error) {
br := bufio.NewReader(r)
s, err = br.ReadString('\n')
if err != nil {
return
}
ln = 1
lnLast := 1.
var sLast string
for {
sLast, err = br.ReadString('\n')
if err == io.EOF {
return s, ln, nil
}
if err != nil {
break
}
lnLast++
if rand.Float64() < 1/lnLast {
s = sLast
ln = int(lnLast)
}
}
return
}
func oneOfN(n int, file io.Reader) int {
_, ln, err := choseLineRandomly(file)
if err != nil {
panic(err)
}
return ln
}
type simReader int
func (r *simReader) Read(b []byte) (int, error) {
if *r <= 0 {
return 0, io.EOF
}
b[0] = '\n'
*r--
return 1, nil
}
func main() {
n := 10
freq := make([]int, n)
rand.Seed(time.Now().UnixNano())
for times := 0; times < 1e6; times++ {
sr := simReader(n)
freq[oneOfN(n, &sr)-1]++
}
fmt.Println(freq)
}
|
Convert this Python block to Go, preserving its control flow and logic. | from itertools import groupby, permutations
def A036058(number):
return ''.join( str(len(list(g))) + k
for k,g in groupby(sorted(str(number), reverse=True)) )
def A036058_length(numberstring='0', printit=False):
iterations, last_three, queue_index = 1, ([None] * 3), 0
def A036058(number):
return ''.join( str(len(list(g))) + k
for k,g in groupby(number) )
while True:
if printit:
print(" %2i %s" % (iterations, numberstring))
numberstring = ''.join(sorted(numberstring, reverse=True))
if numberstring in last_three:
break
assert iterations < 1000000
last_three[queue_index], numberstring = numberstring, A036058(numberstring)
iterations += 1
queue_index +=1
queue_index %=3
return iterations
def max_A036058_length( start_range=range(11) ):
already_done = set()
max_len = (-1, [])
for n in start_range:
sn = str(n)
sns = tuple(sorted(sn, reverse=True))
if sns not in already_done:
already_done.add(sns)
size = A036058_length(sns)
if size > max_len[0]:
max_len = (size, [n])
elif size == max_len[0]:
max_len[1].append(n)
return max_len
lenmax, starts = max_A036058_length( range(1000000) )
allstarts = []
for n in starts:
allstarts += [int(''.join(x))
for x in set(k
for k in permutations(str(n), 4)
if k[0] != '0')]
allstarts = [x for x in sorted(allstarts) if x < 1000000]
print ( % (lenmax, allstarts) )
print ( )
for n in starts:
print()
A036058_length(str(n), printit=True)
| package main
import (
"fmt"
"strconv"
)
func main() {
var maxLen int
var seqMaxLen [][]string
for n := 1; n < 1e6; n++ {
switch s := seq(n); {
case len(s) == maxLen:
seqMaxLen = append(seqMaxLen, s)
case len(s) > maxLen:
maxLen = len(s)
seqMaxLen = [][]string{s}
}
}
fmt.Println("Max sequence length:", maxLen)
fmt.Println("Sequences:", len(seqMaxLen))
for _, seq := range seqMaxLen {
fmt.Println("Sequence:")
for _, t := range seq {
fmt.Println(t)
}
}
}
func seq(n int) []string {
s := strconv.Itoa(n)
ss := []string{s}
for {
dSeq := sortD(s)
d := dSeq[0]
nd := 1
s = ""
for i := 1; ; i++ {
if i == len(dSeq) {
s = fmt.Sprintf("%s%d%c", s, nd, d)
break
}
if dSeq[i] == d {
nd++
} else {
s = fmt.Sprintf("%s%d%c", s, nd, d)
d = dSeq[i]
nd = 1
}
}
for _, s0 := range ss {
if s == s0 {
return ss
}
}
ss = append(ss, s)
}
panic("unreachable")
}
func sortD(s string) []rune {
r := make([]rune, len(s))
for i, d := range s {
j := 0
for ; j < i; j++ {
if d > r[j] {
copy(r[j+1:], r[j:i])
break
}
}
r[j] = d
}
return r
}
|
Port the following code from Python to Go with equivalent syntax and logic. | from itertools import groupby, permutations
def A036058(number):
return ''.join( str(len(list(g))) + k
for k,g in groupby(sorted(str(number), reverse=True)) )
def A036058_length(numberstring='0', printit=False):
iterations, last_three, queue_index = 1, ([None] * 3), 0
def A036058(number):
return ''.join( str(len(list(g))) + k
for k,g in groupby(number) )
while True:
if printit:
print(" %2i %s" % (iterations, numberstring))
numberstring = ''.join(sorted(numberstring, reverse=True))
if numberstring in last_three:
break
assert iterations < 1000000
last_three[queue_index], numberstring = numberstring, A036058(numberstring)
iterations += 1
queue_index +=1
queue_index %=3
return iterations
def max_A036058_length( start_range=range(11) ):
already_done = set()
max_len = (-1, [])
for n in start_range:
sn = str(n)
sns = tuple(sorted(sn, reverse=True))
if sns not in already_done:
already_done.add(sns)
size = A036058_length(sns)
if size > max_len[0]:
max_len = (size, [n])
elif size == max_len[0]:
max_len[1].append(n)
return max_len
lenmax, starts = max_A036058_length( range(1000000) )
allstarts = []
for n in starts:
allstarts += [int(''.join(x))
for x in set(k
for k in permutations(str(n), 4)
if k[0] != '0')]
allstarts = [x for x in sorted(allstarts) if x < 1000000]
print ( % (lenmax, allstarts) )
print ( )
for n in starts:
print()
A036058_length(str(n), printit=True)
| package main
import (
"fmt"
"strconv"
)
func main() {
var maxLen int
var seqMaxLen [][]string
for n := 1; n < 1e6; n++ {
switch s := seq(n); {
case len(s) == maxLen:
seqMaxLen = append(seqMaxLen, s)
case len(s) > maxLen:
maxLen = len(s)
seqMaxLen = [][]string{s}
}
}
fmt.Println("Max sequence length:", maxLen)
fmt.Println("Sequences:", len(seqMaxLen))
for _, seq := range seqMaxLen {
fmt.Println("Sequence:")
for _, t := range seq {
fmt.Println(t)
}
}
}
func seq(n int) []string {
s := strconv.Itoa(n)
ss := []string{s}
for {
dSeq := sortD(s)
d := dSeq[0]
nd := 1
s = ""
for i := 1; ; i++ {
if i == len(dSeq) {
s = fmt.Sprintf("%s%d%c", s, nd, d)
break
}
if dSeq[i] == d {
nd++
} else {
s = fmt.Sprintf("%s%d%c", s, nd, d)
d = dSeq[i]
nd = 1
}
}
for _, s0 := range ss {
if s == s0 {
return ss
}
}
ss = append(ss, s)
}
panic("unreachable")
}
func sortD(s string) []rune {
r := make([]rune, len(s))
for i, d := range s {
j := 0
for ; j < i; j++ {
if d > r[j] {
copy(r[j+1:], r[j:i])
break
}
}
r[j] = d
}
return r
}
|
Produce a functionally identical Go code for the snippet given in Python. | irregularOrdinals = {
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
def num2ordinal(n):
conversion = int(float(n))
num = spell_integer(conversion)
hyphen = num.rsplit("-", 1)
num = num.rsplit(" ", 1)
delim = " "
if len(num[-1]) > len(hyphen[-1]):
num = hyphen
delim = "-"
if num[-1] in irregularOrdinals:
num[-1] = delim + irregularOrdinals[num[-1]]
elif num[-1].endswith("y"):
num[-1] = delim + num[-1][:-1] + "ieth"
else:
num[-1] = delim + num[-1] + "th"
return "".join(num)
if __name__ == "__main__":
tests = "1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2".split()
for num in tests:
print("{} => {}".format(num, num2ordinal(num)))
TENS = [None, None, "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
SMALL = ["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
HUGE = [None, None] + [h + "illion"
for h in ("m", "b", "tr", "quadr", "quint", "sext",
"sept", "oct", "non", "dec")]
def nonzero(c, n, connect=''):
return "" if n == 0 else connect + c + spell_integer(n)
def last_and(num):
if ',' in num:
pre, last = num.rsplit(',', 1)
if ' and ' not in last:
last = ' and' + last
num = ''.join([pre, ',', last])
return num
def big(e, n):
if e == 0:
return spell_integer(n)
elif e == 1:
return spell_integer(n) + " thousand"
else:
return spell_integer(n) + " " + HUGE[e]
def base1000_rev(n):
while n != 0:
n, r = divmod(n, 1000)
yield r
def spell_integer(n):
if n < 0:
return "minus " + spell_integer(-n)
elif n < 20:
return SMALL[n]
elif n < 100:
a, b = divmod(n, 10)
return TENS[a] + nonzero("-", b)
elif n < 1000:
a, b = divmod(n, 100)
return SMALL[a] + " hundred" + nonzero(" ", b, ' and')
else:
num = ", ".join([big(e, x) for e, x in
enumerate(base1000_rev(n)) if x][::-1])
return last_and(num)
| import (
"fmt"
"strings"
)
func main() {
for _, n := range []int64{
1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
} {
fmt.Println(sayOrdinal(n))
}
}
var irregularOrdinals = map[string]string{
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
func sayOrdinal(n int64) string {
s := say(n)
i := strings.LastIndexAny(s, " -")
i++
if x, ok := irregularOrdinals[s[i:]]; ok {
s = s[:i] + x
} else if s[len(s)-1] == 'y' {
s = s[:i] + s[i:len(s)-1] + "ieth"
} else {
s = s[:i] + s[i:] + "th"
}
return s
}
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
}
|
Port the following code from Python to Go with equivalent syntax and logic. | >>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
| package main
import (
"fmt"
"strconv"
"strings"
)
func sdn(n int64) bool {
if n >= 1e10 {
return false
}
s := strconv.FormatInt(n, 10)
for d, p := range s {
if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
return false
}
}
return true
}
func main() {
for n := int64(0); n < 1e10; n++ {
if sdn(n) {
fmt.Println(n)
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Python version. | >>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
| package main
import (
"fmt"
"strconv"
"strings"
)
func sdn(n int64) bool {
if n >= 1e10 {
return false
}
s := strconv.FormatInt(n, 10)
for d, p := range s {
if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
return false
}
}
return true
}
func main() {
for n := int64(0); n < 1e10; n++ {
if sdn(n) {
fmt.Println(n)
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Python version. | def prepend(n, seq):
return [n] + seq
def check_seq(pos, seq, n, min_len):
if pos > min_len or seq[0] > n:
return min_len, 0
if seq[0] == n:
return pos, 1
if pos < min_len:
return try_perm(0, pos, seq, n, min_len)
return min_len, 0
def try_perm(i, pos, seq, n, min_len):
if i > pos:
return min_len, 0
res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)
res2 = try_perm(i + 1, pos, seq, n, res1[0])
if res2[0] < res1[0]:
return res2
if res2[0] == res1[0]:
return res2[0], res1[1] + res2[1]
raise Exception("try_perm exception")
def init_try_perm(x):
return try_perm(0, 0, [1], x, 12)
def find_brauer(num):
res = init_try_perm(num)
print
print "N = ", num
print "Minimum length of chains: L(n) = ", res[0]
print "Number of minimum length Brauer chains: ", res[1]
nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]
for i in nums:
find_brauer(i)
| package main
import "fmt"
var example []int
func reverse(s []int) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
func checkSeq(pos, n, minLen int, seq []int) (int, int) {
switch {
case pos > minLen || seq[0] > n:
return minLen, 0
case seq[0] == n:
example = seq
return pos, 1
case pos < minLen:
return tryPerm(0, pos, n, minLen, seq)
default:
return minLen, 0
}
}
func tryPerm(i, pos, n, minLen int, seq []int) (int, int) {
if i > pos {
return minLen, 0
}
seq2 := make([]int, len(seq)+1)
copy(seq2[1:], seq)
seq2[0] = seq[0] + seq[i]
res11, res12 := checkSeq(pos+1, n, minLen, seq2)
res21, res22 := tryPerm(i+1, pos, n, res11, seq)
switch {
case res21 < res11:
return res21, res22
case res21 == res11:
return res21, res12 + res22
default:
fmt.Println("Error in tryPerm")
return 0, 0
}
}
func initTryPerm(x, minLen int) (int, int) {
return tryPerm(0, 0, x, minLen, []int{1})
}
func findBrauer(num, minLen, nbLimit int) {
actualMin, brauer := initTryPerm(num, minLen)
fmt.Println("\nN =", num)
fmt.Printf("Minimum length of chains : L(%d) = %d\n", num, actualMin)
fmt.Println("Number of minimum length Brauer chains :", brauer)
if brauer > 0 {
reverse(example)
fmt.Println("Brauer example :", example)
}
example = nil
if num <= nbLimit {
nonBrauer := findNonBrauer(num, actualMin+1, brauer)
fmt.Println("Number of minimum length non-Brauer chains :", nonBrauer)
if nonBrauer > 0 {
fmt.Println("Non-Brauer example :", example)
}
example = nil
} else {
println("Non-Brauer analysis suppressed")
}
}
func isAdditionChain(a []int) bool {
for i := 2; i < len(a); i++ {
if a[i] > a[i-1]*2 {
return false
}
ok := false
jloop:
for j := i - 1; j >= 0; j-- {
for k := j; k >= 0; k-- {
if a[j]+a[k] == a[i] {
ok = true
break jloop
}
}
}
if !ok {
return false
}
}
if example == nil && !isBrauer(a) {
example = make([]int, len(a))
copy(example, a)
}
return true
}
func isBrauer(a []int) bool {
for i := 2; i < len(a); i++ {
ok := false
for j := i - 1; j >= 0; j-- {
if a[i-1]+a[j] == a[i] {
ok = true
break
}
}
if !ok {
return false
}
}
return true
}
func nextChains(index, le int, seq []int, pcount *int) {
for {
if index < le-1 {
nextChains(index+1, le, seq, pcount)
}
if seq[index]+le-1-index >= seq[le-1] {
return
}
seq[index]++
for i := index + 1; i < le-1; i++ {
seq[i] = seq[i-1] + 1
}
if isAdditionChain(seq) {
(*pcount)++
}
}
}
func findNonBrauer(num, le, brauer int) int {
seq := make([]int, le)
seq[0] = 1
seq[le-1] = num
for i := 1; i < le-1; i++ {
seq[i] = seq[i-1] + 1
}
count := 0
if isAdditionChain(seq) {
count = 1
}
nextChains(2, le, seq, &count)
return count - brauer
}
func main() {
nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}
fmt.Println("Searching for Brauer chains up to a minimum length of 12:")
for _, num := range nums {
findBrauer(num, 12, 79)
}
}
|
Translate this program into Go but keep the logic exactly as in Python. |
def repeat(f,n):
for i in range(n):
f();
def procedure():
print("Example");
repeat(procedure,3);
| package main
import "fmt"
func repeat(n int, f func()) {
for i := 0; i < n; i++ {
f()
}
}
func fn() {
fmt.Println("Example")
}
func main() {
repeat(4, fn)
}
|
Write a version of this Python function in Go with identical behavior. |
bar = '▁▂▃▄▅▆▇█'
barcount = len(bar)
def sparkline(numbers):
mn, mx = min(numbers), max(numbers)
extent = mx - mn
sparkline = ''.join(bar[min([barcount - 1,
int((n - mn) / extent * barcount)])]
for n in numbers)
return mn, mx, sparkline
if __name__ == '__main__':
import re
for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;"
"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;"
"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'):
print("\nNumbers:", line)
numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())]
mn, mx, sp = sparkline(numbers)
print(' min: %5f; max: %5f' % (mn, mx))
print(" " + sp)
| package main
import (
"bufio"
"errors"
"fmt"
"math"
"os"
"regexp"
"strconv"
"strings"
)
func main() {
fmt.Println("Numbers please separated by space/commas:")
sc := bufio.NewScanner(os.Stdin)
sc.Scan()
s, n, min, max, err := spark(sc.Text())
if err != nil {
fmt.Println(err)
return
}
if n == 1 {
fmt.Println("1 value =", min)
} else {
fmt.Println(n, "values. Min:", min, "Max:", max)
}
fmt.Println(s)
}
var sep = regexp.MustCompile(`[\s,]+`)
func spark(s0 string) (sp string, n int, min, max float64, err error) {
ss := sep.Split(s0, -1)
n = len(ss)
vs := make([]float64, n)
var v float64
min = math.Inf(1)
max = math.Inf(-1)
for i, s := range ss {
switch v, err = strconv.ParseFloat(s, 64); {
case err != nil:
case math.IsNaN(v):
err = errors.New("NaN not supported.")
case math.IsInf(v, 0):
err = errors.New("Inf not supported.")
default:
if v < min {
min = v
}
if v > max {
max = v
}
vs[i] = v
continue
}
return
}
if min == max {
sp = strings.Repeat("▄", n)
} else {
rs := make([]rune, n)
f := 8 / (max - min)
for j, v := range vs {
i := rune(f * (v - min))
if i > 7 {
i = 7
}
rs[j] = '▁' + i
}
sp = string(rs)
}
return
}
|
Port the provided Python code into Go while preserving the original functionality. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return NULL
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
| package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
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 Tree struct {
nodeType NodeType
left *Tree
right *Tree
value int
}
type atr struct {
enumText string
nodeType NodeType
}
var atrs = []atr{
{"Identifier", ndIdent},
{"String", ndString},
{"Integer", ndInteger},
{"Sequence", ndSequence},
{"If", ndIf},
{"Prtc", ndPrtc},
{"Prts", ndPrts},
{"Prti", ndPrti},
{"While", ndWhile},
{"Assign", ndAssign},
{"Negate", ndNegate},
{"Not", ndNot},
{"Multiply", ndMul},
{"Divide", ndDiv},
{"Mod", ndMod},
{"Add", ndAdd},
{"Subtract", ndSub},
{"Less", ndLss},
{"LessEqual", ndLeq},
{"Greater", ndGtr},
{"GreaterEqual", ndGeq},
{"Equal", ndEql},
{"NotEqual", ndNeq},
{"And", ndAnd},
{"Or", ndOr},
}
var (
stringPool []string
globalNames []string
globalValues = make(map[int]int)
)
var (
err error
scanner *bufio.Scanner
)
func reportError(msg string) {
log.Fatalf("error : %s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func itob(i int) bool {
if i == 0 {
return false
}
return true
}
func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {
return &Tree{nodeType, left, right, 0}
}
func makeLeaf(nodeType NodeType, value int) *Tree {
return &Tree{nodeType, nil, nil, value}
}
func interp(x *Tree) int {
if x == nil {
return 0
}
switch x.nodeType {
case ndInteger:
return x.value
case ndIdent:
return globalValues[x.value]
case ndString:
return x.value
case ndAssign:
n := interp(x.right)
globalValues[x.left.value] = n
return n
case ndAdd:
return interp(x.left) + interp(x.right)
case ndSub:
return interp(x.left) - interp(x.right)
case ndMul:
return interp(x.left) * interp(x.right)
case ndDiv:
return interp(x.left) / interp(x.right)
case ndMod:
return interp(x.left) % interp(x.right)
case ndLss:
return btoi(interp(x.left) < interp(x.right))
case ndGtr:
return btoi(interp(x.left) > interp(x.right))
case ndLeq:
return btoi(interp(x.left) <= interp(x.right))
case ndEql:
return btoi(interp(x.left) == interp(x.right))
case ndNeq:
return btoi(interp(x.left) != interp(x.right))
case ndAnd:
return btoi(itob(interp(x.left)) && itob(interp(x.right)))
case ndOr:
return btoi(itob(interp(x.left)) || itob(interp(x.right)))
case ndNegate:
return -interp(x.left)
case ndNot:
if interp(x.left) == 0 {
return 1
}
return 0
case ndIf:
if interp(x.left) != 0 {
interp(x.right.left)
} else {
interp(x.right.right)
}
return 0
case ndWhile:
for interp(x.left) != 0 {
interp(x.right)
}
return 0
case ndPrtc:
fmt.Printf("%c", interp(x.left))
return 0
case ndPrti:
fmt.Printf("%d", interp(x.left))
return 0
case ndPrts:
fmt.Print(stringPool[interp(x.left)])
return 0
case ndSequence:
interp(x.left)
interp(x.right)
return 0
default:
reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType))
}
return 0
}
func getEnumValue(name string) NodeType {
for _, atr := range atrs {
if atr.enumText == name {
return atr.nodeType
}
}
reportError(fmt.Sprintf("Unknown token %s\n", name))
return -1
}
func fetchStringOffset(s string) int {
var d strings.Builder
s = s[1 : len(s)-1]
for i := 0; i < len(s); i++ {
if s[i] == '\\' && (i+1) < len(s) {
if s[i+1] == 'n' {
d.WriteByte('\n')
i++
} else if s[i+1] == '\\' {
d.WriteByte('\\')
i++
}
} else {
d.WriteByte(s[i])
}
}
s = d.String()
for i := 0; i < len(stringPool); i++ {
if s == stringPool[i] {
return i
}
}
stringPool = append(stringPool, s)
return len(stringPool) - 1
}
func fetchVarOffset(name string) int {
for i := 0; i < len(globalNames); i++ {
if globalNames[i] == name {
return i
}
}
globalNames = append(globalNames, name)
return len(globalNames) - 1
}
func loadAst() *Tree {
var nodeType NodeType
var s string
if scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
tokens := strings.Fields(line)
first := tokens[0]
if first[0] == ';' {
return nil
}
nodeType = getEnumValue(first)
le := len(tokens)
if le == 2 {
s = tokens[1]
} else if le > 2 {
idx := strings.Index(line, `"`)
s = line[idx:]
}
}
check(scanner.Err())
if s != "" {
var n int
switch nodeType {
case ndIdent:
n = fetchVarOffset(s)
case ndInteger:
n, err = strconv.Atoi(s)
check(err)
case ndString:
n = fetchStringOffset(s)
default:
reportError(fmt.Sprintf("Unknown node type: %s\n", s))
}
return makeLeaf(nodeType, n)
}
left := loadAst()
right := loadAst()
return makeNode(nodeType, left, right)
}
func main() {
ast, err := os.Open("ast.txt")
check(err)
defer ast.Close()
scanner = bufio.NewScanner(ast)
x := loadAst()
interp(x)
}
|
Produce a functionally identical Go code for the snippet given in Python. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return NULL
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
| package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
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 Tree struct {
nodeType NodeType
left *Tree
right *Tree
value int
}
type atr struct {
enumText string
nodeType NodeType
}
var atrs = []atr{
{"Identifier", ndIdent},
{"String", ndString},
{"Integer", ndInteger},
{"Sequence", ndSequence},
{"If", ndIf},
{"Prtc", ndPrtc},
{"Prts", ndPrts},
{"Prti", ndPrti},
{"While", ndWhile},
{"Assign", ndAssign},
{"Negate", ndNegate},
{"Not", ndNot},
{"Multiply", ndMul},
{"Divide", ndDiv},
{"Mod", ndMod},
{"Add", ndAdd},
{"Subtract", ndSub},
{"Less", ndLss},
{"LessEqual", ndLeq},
{"Greater", ndGtr},
{"GreaterEqual", ndGeq},
{"Equal", ndEql},
{"NotEqual", ndNeq},
{"And", ndAnd},
{"Or", ndOr},
}
var (
stringPool []string
globalNames []string
globalValues = make(map[int]int)
)
var (
err error
scanner *bufio.Scanner
)
func reportError(msg string) {
log.Fatalf("error : %s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func itob(i int) bool {
if i == 0 {
return false
}
return true
}
func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {
return &Tree{nodeType, left, right, 0}
}
func makeLeaf(nodeType NodeType, value int) *Tree {
return &Tree{nodeType, nil, nil, value}
}
func interp(x *Tree) int {
if x == nil {
return 0
}
switch x.nodeType {
case ndInteger:
return x.value
case ndIdent:
return globalValues[x.value]
case ndString:
return x.value
case ndAssign:
n := interp(x.right)
globalValues[x.left.value] = n
return n
case ndAdd:
return interp(x.left) + interp(x.right)
case ndSub:
return interp(x.left) - interp(x.right)
case ndMul:
return interp(x.left) * interp(x.right)
case ndDiv:
return interp(x.left) / interp(x.right)
case ndMod:
return interp(x.left) % interp(x.right)
case ndLss:
return btoi(interp(x.left) < interp(x.right))
case ndGtr:
return btoi(interp(x.left) > interp(x.right))
case ndLeq:
return btoi(interp(x.left) <= interp(x.right))
case ndEql:
return btoi(interp(x.left) == interp(x.right))
case ndNeq:
return btoi(interp(x.left) != interp(x.right))
case ndAnd:
return btoi(itob(interp(x.left)) && itob(interp(x.right)))
case ndOr:
return btoi(itob(interp(x.left)) || itob(interp(x.right)))
case ndNegate:
return -interp(x.left)
case ndNot:
if interp(x.left) == 0 {
return 1
}
return 0
case ndIf:
if interp(x.left) != 0 {
interp(x.right.left)
} else {
interp(x.right.right)
}
return 0
case ndWhile:
for interp(x.left) != 0 {
interp(x.right)
}
return 0
case ndPrtc:
fmt.Printf("%c", interp(x.left))
return 0
case ndPrti:
fmt.Printf("%d", interp(x.left))
return 0
case ndPrts:
fmt.Print(stringPool[interp(x.left)])
return 0
case ndSequence:
interp(x.left)
interp(x.right)
return 0
default:
reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType))
}
return 0
}
func getEnumValue(name string) NodeType {
for _, atr := range atrs {
if atr.enumText == name {
return atr.nodeType
}
}
reportError(fmt.Sprintf("Unknown token %s\n", name))
return -1
}
func fetchStringOffset(s string) int {
var d strings.Builder
s = s[1 : len(s)-1]
for i := 0; i < len(s); i++ {
if s[i] == '\\' && (i+1) < len(s) {
if s[i+1] == 'n' {
d.WriteByte('\n')
i++
} else if s[i+1] == '\\' {
d.WriteByte('\\')
i++
}
} else {
d.WriteByte(s[i])
}
}
s = d.String()
for i := 0; i < len(stringPool); i++ {
if s == stringPool[i] {
return i
}
}
stringPool = append(stringPool, s)
return len(stringPool) - 1
}
func fetchVarOffset(name string) int {
for i := 0; i < len(globalNames); i++ {
if globalNames[i] == name {
return i
}
}
globalNames = append(globalNames, name)
return len(globalNames) - 1
}
func loadAst() *Tree {
var nodeType NodeType
var s string
if scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
tokens := strings.Fields(line)
first := tokens[0]
if first[0] == ';' {
return nil
}
nodeType = getEnumValue(first)
le := len(tokens)
if le == 2 {
s = tokens[1]
} else if le > 2 {
idx := strings.Index(line, `"`)
s = line[idx:]
}
}
check(scanner.Err())
if s != "" {
var n int
switch nodeType {
case ndIdent:
n = fetchVarOffset(s)
case ndInteger:
n, err = strconv.Atoi(s)
check(err)
case ndString:
n = fetchStringOffset(s)
default:
reportError(fmt.Sprintf("Unknown node type: %s\n", s))
}
return makeLeaf(nodeType, n)
}
left := loadAst()
right := loadAst()
return makeNode(nodeType, left, right)
}
func main() {
ast, err := os.Open("ast.txt")
check(err)
defer ast.Close()
scanner = bufio.NewScanner(ast)
x := loadAst()
interp(x)
}
|
Translate this program into Go but keep the logic exactly as in Python. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return NULL
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
| package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
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 Tree struct {
nodeType NodeType
left *Tree
right *Tree
value int
}
type atr struct {
enumText string
nodeType NodeType
}
var atrs = []atr{
{"Identifier", ndIdent},
{"String", ndString},
{"Integer", ndInteger},
{"Sequence", ndSequence},
{"If", ndIf},
{"Prtc", ndPrtc},
{"Prts", ndPrts},
{"Prti", ndPrti},
{"While", ndWhile},
{"Assign", ndAssign},
{"Negate", ndNegate},
{"Not", ndNot},
{"Multiply", ndMul},
{"Divide", ndDiv},
{"Mod", ndMod},
{"Add", ndAdd},
{"Subtract", ndSub},
{"Less", ndLss},
{"LessEqual", ndLeq},
{"Greater", ndGtr},
{"GreaterEqual", ndGeq},
{"Equal", ndEql},
{"NotEqual", ndNeq},
{"And", ndAnd},
{"Or", ndOr},
}
var (
stringPool []string
globalNames []string
globalValues = make(map[int]int)
)
var (
err error
scanner *bufio.Scanner
)
func reportError(msg string) {
log.Fatalf("error : %s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func itob(i int) bool {
if i == 0 {
return false
}
return true
}
func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {
return &Tree{nodeType, left, right, 0}
}
func makeLeaf(nodeType NodeType, value int) *Tree {
return &Tree{nodeType, nil, nil, value}
}
func interp(x *Tree) int {
if x == nil {
return 0
}
switch x.nodeType {
case ndInteger:
return x.value
case ndIdent:
return globalValues[x.value]
case ndString:
return x.value
case ndAssign:
n := interp(x.right)
globalValues[x.left.value] = n
return n
case ndAdd:
return interp(x.left) + interp(x.right)
case ndSub:
return interp(x.left) - interp(x.right)
case ndMul:
return interp(x.left) * interp(x.right)
case ndDiv:
return interp(x.left) / interp(x.right)
case ndMod:
return interp(x.left) % interp(x.right)
case ndLss:
return btoi(interp(x.left) < interp(x.right))
case ndGtr:
return btoi(interp(x.left) > interp(x.right))
case ndLeq:
return btoi(interp(x.left) <= interp(x.right))
case ndEql:
return btoi(interp(x.left) == interp(x.right))
case ndNeq:
return btoi(interp(x.left) != interp(x.right))
case ndAnd:
return btoi(itob(interp(x.left)) && itob(interp(x.right)))
case ndOr:
return btoi(itob(interp(x.left)) || itob(interp(x.right)))
case ndNegate:
return -interp(x.left)
case ndNot:
if interp(x.left) == 0 {
return 1
}
return 0
case ndIf:
if interp(x.left) != 0 {
interp(x.right.left)
} else {
interp(x.right.right)
}
return 0
case ndWhile:
for interp(x.left) != 0 {
interp(x.right)
}
return 0
case ndPrtc:
fmt.Printf("%c", interp(x.left))
return 0
case ndPrti:
fmt.Printf("%d", interp(x.left))
return 0
case ndPrts:
fmt.Print(stringPool[interp(x.left)])
return 0
case ndSequence:
interp(x.left)
interp(x.right)
return 0
default:
reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType))
}
return 0
}
func getEnumValue(name string) NodeType {
for _, atr := range atrs {
if atr.enumText == name {
return atr.nodeType
}
}
reportError(fmt.Sprintf("Unknown token %s\n", name))
return -1
}
func fetchStringOffset(s string) int {
var d strings.Builder
s = s[1 : len(s)-1]
for i := 0; i < len(s); i++ {
if s[i] == '\\' && (i+1) < len(s) {
if s[i+1] == 'n' {
d.WriteByte('\n')
i++
} else if s[i+1] == '\\' {
d.WriteByte('\\')
i++
}
} else {
d.WriteByte(s[i])
}
}
s = d.String()
for i := 0; i < len(stringPool); i++ {
if s == stringPool[i] {
return i
}
}
stringPool = append(stringPool, s)
return len(stringPool) - 1
}
func fetchVarOffset(name string) int {
for i := 0; i < len(globalNames); i++ {
if globalNames[i] == name {
return i
}
}
globalNames = append(globalNames, name)
return len(globalNames) - 1
}
func loadAst() *Tree {
var nodeType NodeType
var s string
if scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
tokens := strings.Fields(line)
first := tokens[0]
if first[0] == ';' {
return nil
}
nodeType = getEnumValue(first)
le := len(tokens)
if le == 2 {
s = tokens[1]
} else if le > 2 {
idx := strings.Index(line, `"`)
s = line[idx:]
}
}
check(scanner.Err())
if s != "" {
var n int
switch nodeType {
case ndIdent:
n = fetchVarOffset(s)
case ndInteger:
n, err = strconv.Atoi(s)
check(err)
case ndString:
n = fetchStringOffset(s)
default:
reportError(fmt.Sprintf("Unknown node type: %s\n", s))
}
return makeLeaf(nodeType, n)
}
left := loadAst()
right := loadAst()
return makeNode(nodeType, left, right)
}
func main() {
ast, err := os.Open("ast.txt")
check(err)
defer ast.Close()
scanner = bufio.NewScanner(ast)
x := loadAst()
interp(x)
}
|
Write the same code in Go as shown below in Python. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return NULL
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
| package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
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 Tree struct {
nodeType NodeType
left *Tree
right *Tree
value int
}
type atr struct {
enumText string
nodeType NodeType
}
var atrs = []atr{
{"Identifier", ndIdent},
{"String", ndString},
{"Integer", ndInteger},
{"Sequence", ndSequence},
{"If", ndIf},
{"Prtc", ndPrtc},
{"Prts", ndPrts},
{"Prti", ndPrti},
{"While", ndWhile},
{"Assign", ndAssign},
{"Negate", ndNegate},
{"Not", ndNot},
{"Multiply", ndMul},
{"Divide", ndDiv},
{"Mod", ndMod},
{"Add", ndAdd},
{"Subtract", ndSub},
{"Less", ndLss},
{"LessEqual", ndLeq},
{"Greater", ndGtr},
{"GreaterEqual", ndGeq},
{"Equal", ndEql},
{"NotEqual", ndNeq},
{"And", ndAnd},
{"Or", ndOr},
}
var (
stringPool []string
globalNames []string
globalValues = make(map[int]int)
)
var (
err error
scanner *bufio.Scanner
)
func reportError(msg string) {
log.Fatalf("error : %s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func itob(i int) bool {
if i == 0 {
return false
}
return true
}
func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {
return &Tree{nodeType, left, right, 0}
}
func makeLeaf(nodeType NodeType, value int) *Tree {
return &Tree{nodeType, nil, nil, value}
}
func interp(x *Tree) int {
if x == nil {
return 0
}
switch x.nodeType {
case ndInteger:
return x.value
case ndIdent:
return globalValues[x.value]
case ndString:
return x.value
case ndAssign:
n := interp(x.right)
globalValues[x.left.value] = n
return n
case ndAdd:
return interp(x.left) + interp(x.right)
case ndSub:
return interp(x.left) - interp(x.right)
case ndMul:
return interp(x.left) * interp(x.right)
case ndDiv:
return interp(x.left) / interp(x.right)
case ndMod:
return interp(x.left) % interp(x.right)
case ndLss:
return btoi(interp(x.left) < interp(x.right))
case ndGtr:
return btoi(interp(x.left) > interp(x.right))
case ndLeq:
return btoi(interp(x.left) <= interp(x.right))
case ndEql:
return btoi(interp(x.left) == interp(x.right))
case ndNeq:
return btoi(interp(x.left) != interp(x.right))
case ndAnd:
return btoi(itob(interp(x.left)) && itob(interp(x.right)))
case ndOr:
return btoi(itob(interp(x.left)) || itob(interp(x.right)))
case ndNegate:
return -interp(x.left)
case ndNot:
if interp(x.left) == 0 {
return 1
}
return 0
case ndIf:
if interp(x.left) != 0 {
interp(x.right.left)
} else {
interp(x.right.right)
}
return 0
case ndWhile:
for interp(x.left) != 0 {
interp(x.right)
}
return 0
case ndPrtc:
fmt.Printf("%c", interp(x.left))
return 0
case ndPrti:
fmt.Printf("%d", interp(x.left))
return 0
case ndPrts:
fmt.Print(stringPool[interp(x.left)])
return 0
case ndSequence:
interp(x.left)
interp(x.right)
return 0
default:
reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType))
}
return 0
}
func getEnumValue(name string) NodeType {
for _, atr := range atrs {
if atr.enumText == name {
return atr.nodeType
}
}
reportError(fmt.Sprintf("Unknown token %s\n", name))
return -1
}
func fetchStringOffset(s string) int {
var d strings.Builder
s = s[1 : len(s)-1]
for i := 0; i < len(s); i++ {
if s[i] == '\\' && (i+1) < len(s) {
if s[i+1] == 'n' {
d.WriteByte('\n')
i++
} else if s[i+1] == '\\' {
d.WriteByte('\\')
i++
}
} else {
d.WriteByte(s[i])
}
}
s = d.String()
for i := 0; i < len(stringPool); i++ {
if s == stringPool[i] {
return i
}
}
stringPool = append(stringPool, s)
return len(stringPool) - 1
}
func fetchVarOffset(name string) int {
for i := 0; i < len(globalNames); i++ {
if globalNames[i] == name {
return i
}
}
globalNames = append(globalNames, name)
return len(globalNames) - 1
}
func loadAst() *Tree {
var nodeType NodeType
var s string
if scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
tokens := strings.Fields(line)
first := tokens[0]
if first[0] == ';' {
return nil
}
nodeType = getEnumValue(first)
le := len(tokens)
if le == 2 {
s = tokens[1]
} else if le > 2 {
idx := strings.Index(line, `"`)
s = line[idx:]
}
}
check(scanner.Err())
if s != "" {
var n int
switch nodeType {
case ndIdent:
n = fetchVarOffset(s)
case ndInteger:
n, err = strconv.Atoi(s)
check(err)
case ndString:
n = fetchStringOffset(s)
default:
reportError(fmt.Sprintf("Unknown node type: %s\n", s))
}
return makeLeaf(nodeType, n)
}
left := loadAst()
right := loadAst()
return makeNode(nodeType, left, right)
}
func main() {
ast, err := os.Open("ast.txt")
check(err)
defer ast.Close()
scanner = bufio.NewScanner(ast)
x := loadAst()
interp(x)
}
|
Please provide an equivalent version of this Python code in Go. | >>> def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
x, lastx = lastx - quotient*x, x
y, lasty = lasty - quotient*y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
>>> def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
raise ValueError
return x % m
>>> modinv(42, 2017)
1969
>>>
| package main
import (
"fmt"
"math/big"
)
func main() {
a := big.NewInt(42)
m := big.NewInt(2017)
k := new(big.Int).ModInverse(a, m)
fmt.Println(k)
}
|
Translate this program into Go but keep the logic exactly as in Python. | import ctypes
def click():
ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)
ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)
click()
| package main
import "github.com/go-vgo/robotgo"
func main() {
robotgo.MouseClick("left", false)
robotgo.MouseClick("right", true)
}
|
Transform the following Python implementation into Go, maintaining the same output and logic. | from wsgiref.simple_server import make_server
def app(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
yield b"<h1>Goodbye, World!</h1>"
server = make_server('127.0.0.1', 8080, app)
server.serve_forever()
| package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "Goodbye, World!")
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
|
Change the programming language of this snippet from Python to Go without modifying what it does. | from turtle import *
from math import *
iter = 3000
diskRatio = .5
factor = .5 + sqrt(1.25)
screen = getscreen()
(winWidth, winHeight) = screen.screensize()
x = 0.0
y = 0.0
maxRad = pow(iter,factor)/iter;
bgcolor("light blue")
hideturtle()
tracer(0, 0)
for i in range(iter+1):
r = pow(i,factor)/iter;
if r/maxRad < diskRatio:
pencolor("black")
else:
pencolor("yellow")
theta = 2*pi*factor*i;
up()
setposition(x + r*sin(theta), y + r*cos(theta))
down()
circle(10.0 * i/(1.0*iter))
update()
done()
| package main
import (
"github.com/fogleman/gg"
"math"
)
func main() {
dc := gg.NewContext(400, 400)
dc.SetRGB(1, 1, 1)
dc.Clear()
dc.SetRGB(0, 0, 1)
c := (math.Sqrt(5) + 1) / 2
numberOfSeeds := 3000
for i := 0; i <= numberOfSeeds; i++ {
fi := float64(i)
fn := float64(numberOfSeeds)
r := math.Pow(fi, c) / fn
angle := 2 * math.Pi * c * fi
x := r*math.Sin(angle) + 200
y := r*math.Cos(angle) + 200
fi /= fn / 5
dc.DrawCircle(x, y, fi)
}
dc.SetLineWidth(1)
dc.Stroke()
dc.SavePNG("sunflower_fractal.png")
}
|
Write a version of this Python function in Go with identical behavior. | from collections import defaultdict
costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},
'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},
'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},
'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}
demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}
cols = sorted(demand.iterkeys())
supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}
res = dict((k, defaultdict(int)) for k in costs)
g = {}
for x in supply:
g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])
for x in demand:
g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])
while g:
d = {}
for x in demand:
d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]
s = {}
for x in supply:
s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]
f = max(d, key=lambda n: d[n])
t = max(s, key=lambda n: s[n])
t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)
v = min(supply[f], demand[t])
res[f][t] += v
demand[t] -= v
if demand[t] == 0:
for k, n in supply.iteritems():
if n != 0:
g[k].remove(t)
del g[t]
del demand[t]
supply[f] -= v
if supply[f] == 0:
for k, n in demand.iteritems():
if n != 0:
g[k].remove(f)
del g[f]
del supply[f]
for n in cols:
print "\t", n,
print
cost = 0
for g in sorted(costs):
print g, "\t",
for n in cols:
y = res[g][n]
if y != 0:
print y,
cost += y * costs[g][n]
print "\t",
print
print "\n\nTotal Cost = ", cost
| #include <stdio.h>
#include <limits.h>
#define TRUE 1
#define FALSE 0
#define N_ROWS 5
#define N_COLS 5
typedef int bool;
int supply[N_ROWS] = { 461, 277, 356, 488, 393 };
int demand[N_COLS] = { 278, 60, 461, 116, 1060 };
int costs[N_ROWS][N_COLS] = {
{ 46, 74, 9, 28, 99 },
{ 12, 75, 6, 36, 48 },
{ 35, 199, 4, 5, 71 },
{ 61, 81, 44, 88, 9 },
{ 85, 60, 14, 25, 79 }
};
int main() {
printf(" A B C D E\n");
for (i = 0; i < N_ROWS; ++i) {
printf("%c", 'V' + i);
for (j = 0; j < N_COLS; ++j) printf(" %3d", results[i][j]);
printf("\n");
}
printf("\nTotal cost = %d\n", total_cost);
return 0;
}
|
Translate this program into Go but keep the logic exactly as in Python. |
from math import sqrt, cos, exp
DEG = 0.017453292519943295769236907684886127134
RE = 6371000
dd = 0.001
FIN = 10000000
def rho(a):
return exp(-a / 8500.0)
def height(a, z, d):
return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE
def column_density(a, z):
dsum, d = 0.0, 0.0
while d < FIN:
delta = max(dd, (dd)*d)
dsum += rho(height(a, z, d + 0.5 * delta)) * delta
d += delta
return dsum
def airmass(a, z):
return column_density(a, z) / column_density(a, 0)
print('Angle 0 m 13700 m\n', '-' * 36)
for z in range(0, 91, 5):
print(f"{z: 3d} {airmass(0, z): 12.7f} {airmass(13700, z): 12.7f}")
| package main
import (
"fmt"
"math"
)
const (
RE = 6371000
DD = 0.001
FIN = 1e7
)
func rho(a float64) float64 { return math.Exp(-a / 8500) }
func radians(degrees float64) float64 { return degrees * math.Pi / 180 }
func height(a, z, d float64) float64 {
aa := RE + a
hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z)))
return hh - RE
}
func columnDensity(a, z float64) float64 {
sum := 0.0
d := 0.0
for d < FIN {
delta := math.Max(DD, DD*d)
sum += rho(height(a, z, d+0.5*delta)) * delta
d += delta
}
return sum
}
func airmass(a, z float64) float64 {
return columnDensity(a, z) / columnDensity(a, 0)
}
func main() {
fmt.Println("Angle 0 m 13700 m")
fmt.Println("------------------------------------")
for z := 0; z <= 90; z += 5 {
fz := float64(z)
fmt.Printf("%2d %11.8f %11.8f\n", z, airmass(0, fz), airmass(13700, fz))
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. |
from itertools import islice
from fractions import Fraction
from functools import reduce
try:
from itertools import izip as zip
except:
pass
def head(n):
return lambda seq: islice(seq, n)
def pipe(gen, *cmds):
return reduce(lambda gen, cmd: cmd(gen), cmds, gen)
def sinepower():
n = 0
fac = 1
sign = +1
zero = 0
yield zero
while True:
n +=1
fac *= n
yield Fraction(1, fac*sign)
sign = -sign
n +=1
fac *= n
yield zero
def cosinepower():
n = 0
fac = 1
sign = +1
yield Fraction(1,fac)
zero = 0
while True:
n +=1
fac *= n
yield zero
sign = -sign
n +=1
fac *= n
yield Fraction(1, fac*sign)
def pluspower(*powergenerators):
for elements in zip(*powergenerators):
yield sum(elements)
def minuspower(*powergenerators):
for elements in zip(*powergenerators):
yield elements[0] - sum(elements[1:])
def mulpower(fgen,ggen):
'From: http://en.wikipedia.org/wiki/Power_series
a,b = [],[]
for f,g in zip(fgen, ggen):
a.append(f)
b.append(g)
yield sum(f*g for f,g in zip(a, reversed(b)))
def constpower(n):
yield n
while True:
yield 0
def diffpower(gen):
'differentiatiate power series'
next(gen)
for n, an in enumerate(gen, start=1):
yield an*n
def intgpower(k=0):
'integrate power series with constant k'
def _intgpower(gen):
yield k
for n, an in enumerate(gen, start=1):
yield an * Fraction(1,n)
return _intgpower
print("cosine")
c = list(pipe(cosinepower(), head(10)))
print(c)
print("sine")
s = list(pipe(sinepower(), head(10)))
print(s)
integc = list(pipe(cosinepower(),intgpower(0), head(10)))
integs1 = list(minuspower(pipe(constpower(1), head(10)),
pipe(sinepower(),intgpower(0), head(10))))
assert s == integc, "The integral of cos should be sin"
assert c == integs1, "1 minus the integral of sin should be cos"
| package main
import (
"fmt"
"math"
)
type fps interface {
extract(int) float64
}
func one() fps {
return &oneFps{}
}
func add(s1, s2 fps) fps {
return &sum{s1: s1, s2: s2}
}
func sub(s1, s2 fps) fps {
return &diff{s1: s1, s2: s2}
}
func mul(s1, s2 fps) fps {
return &prod{s1: s1, s2: s2}
}
func div(s1, s2 fps) fps {
return &quo{s1: s1, s2: s2}
}
func differentiate(s1 fps) fps {
return &deriv{s1: s1}
}
func integrate(s1 fps) fps {
return &integ{s1: s1}
}
func sinCos() (fps, fps) {
sin := &integ{}
cos := sub(one(), integrate(sin))
sin.s1 = cos
return sin, cos
}
type oneFps struct{}
func (*oneFps) extract(n int) float64 {
if n == 0 {
return 1
}
return 0
}
type sum struct {
s []float64
s1, s2 fps
}
func (s *sum) extract(n int) float64 {
for i := len(s.s); i <= n; i++ {
s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i))
}
return s.s[n]
}
type diff struct {
s []float64
s1, s2 fps
}
func (s *diff) extract(n int) float64 {
for i := len(s.s); i <= n; i++ {
s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i))
}
return s.s[n]
}
type prod struct {
s []float64
s1, s2 fps
}
func (s *prod) extract(n int) float64 {
for i := len(s.s); i <= n; i++ {
c := 0.
for k := 0; k <= i; k++ {
c += s.s1.extract(k) * s.s1.extract(n-k)
}
s.s = append(s.s, c)
}
return s.s[n]
}
type quo struct {
s1, s2 fps
inv float64
c []float64
s []float64
}
func (s *quo) extract(n int) float64 {
switch {
case len(s.s) > 0:
case !math.IsInf(s.inv, 1):
a0 := s.s2.extract(0)
s.inv = 1 / a0
if a0 != 0 {
break
}
fallthrough
default:
return math.NaN()
}
for i := len(s.s); i <= n; i++ {
c := 0.
for k := 1; k <= i; k++ {
c += s.s2.extract(k) * s.c[n-k]
}
c = s.s1.extract(i) - c*s.inv
s.c = append(s.c, c)
s.s = append(s.s, c*s.inv)
}
return s.s[n]
}
type deriv struct {
s []float64
s1 fps
}
func (s *deriv) extract(n int) float64 {
for i := len(s.s); i <= n; {
i++
s.s = append(s.s, float64(i)*s.s1.extract(i))
}
return s.s[n]
}
type integ struct {
s []float64
s1 fps
}
func (s *integ) extract(n int) float64 {
if n == 0 {
return 0
}
for i := len(s.s) + 1; i <= n; i++ {
s.s = append(s.s, s.s1.extract(i-1)/float64(i))
}
return s.s[n-1]
}
func main() {
partialSeries := func(f fps) (s string) {
for i := 0; i < 6; i++ {
s = fmt.Sprintf("%s %8.5f ", s, f.extract(i))
}
return
}
sin, cos := sinCos()
fmt.Println("sin:", partialSeries(sin))
fmt.Println("cos:", partialSeries(cos))
}
|
Translate this program into Go but keep the logic exactly as in Python. |
from itertools import islice
from fractions import Fraction
from functools import reduce
try:
from itertools import izip as zip
except:
pass
def head(n):
return lambda seq: islice(seq, n)
def pipe(gen, *cmds):
return reduce(lambda gen, cmd: cmd(gen), cmds, gen)
def sinepower():
n = 0
fac = 1
sign = +1
zero = 0
yield zero
while True:
n +=1
fac *= n
yield Fraction(1, fac*sign)
sign = -sign
n +=1
fac *= n
yield zero
def cosinepower():
n = 0
fac = 1
sign = +1
yield Fraction(1,fac)
zero = 0
while True:
n +=1
fac *= n
yield zero
sign = -sign
n +=1
fac *= n
yield Fraction(1, fac*sign)
def pluspower(*powergenerators):
for elements in zip(*powergenerators):
yield sum(elements)
def minuspower(*powergenerators):
for elements in zip(*powergenerators):
yield elements[0] - sum(elements[1:])
def mulpower(fgen,ggen):
'From: http://en.wikipedia.org/wiki/Power_series
a,b = [],[]
for f,g in zip(fgen, ggen):
a.append(f)
b.append(g)
yield sum(f*g for f,g in zip(a, reversed(b)))
def constpower(n):
yield n
while True:
yield 0
def diffpower(gen):
'differentiatiate power series'
next(gen)
for n, an in enumerate(gen, start=1):
yield an*n
def intgpower(k=0):
'integrate power series with constant k'
def _intgpower(gen):
yield k
for n, an in enumerate(gen, start=1):
yield an * Fraction(1,n)
return _intgpower
print("cosine")
c = list(pipe(cosinepower(), head(10)))
print(c)
print("sine")
s = list(pipe(sinepower(), head(10)))
print(s)
integc = list(pipe(cosinepower(),intgpower(0), head(10)))
integs1 = list(minuspower(pipe(constpower(1), head(10)),
pipe(sinepower(),intgpower(0), head(10))))
assert s == integc, "The integral of cos should be sin"
assert c == integs1, "1 minus the integral of sin should be cos"
| package main
import (
"fmt"
"math"
)
type fps interface {
extract(int) float64
}
func one() fps {
return &oneFps{}
}
func add(s1, s2 fps) fps {
return &sum{s1: s1, s2: s2}
}
func sub(s1, s2 fps) fps {
return &diff{s1: s1, s2: s2}
}
func mul(s1, s2 fps) fps {
return &prod{s1: s1, s2: s2}
}
func div(s1, s2 fps) fps {
return &quo{s1: s1, s2: s2}
}
func differentiate(s1 fps) fps {
return &deriv{s1: s1}
}
func integrate(s1 fps) fps {
return &integ{s1: s1}
}
func sinCos() (fps, fps) {
sin := &integ{}
cos := sub(one(), integrate(sin))
sin.s1 = cos
return sin, cos
}
type oneFps struct{}
func (*oneFps) extract(n int) float64 {
if n == 0 {
return 1
}
return 0
}
type sum struct {
s []float64
s1, s2 fps
}
func (s *sum) extract(n int) float64 {
for i := len(s.s); i <= n; i++ {
s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i))
}
return s.s[n]
}
type diff struct {
s []float64
s1, s2 fps
}
func (s *diff) extract(n int) float64 {
for i := len(s.s); i <= n; i++ {
s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i))
}
return s.s[n]
}
type prod struct {
s []float64
s1, s2 fps
}
func (s *prod) extract(n int) float64 {
for i := len(s.s); i <= n; i++ {
c := 0.
for k := 0; k <= i; k++ {
c += s.s1.extract(k) * s.s1.extract(n-k)
}
s.s = append(s.s, c)
}
return s.s[n]
}
type quo struct {
s1, s2 fps
inv float64
c []float64
s []float64
}
func (s *quo) extract(n int) float64 {
switch {
case len(s.s) > 0:
case !math.IsInf(s.inv, 1):
a0 := s.s2.extract(0)
s.inv = 1 / a0
if a0 != 0 {
break
}
fallthrough
default:
return math.NaN()
}
for i := len(s.s); i <= n; i++ {
c := 0.
for k := 1; k <= i; k++ {
c += s.s2.extract(k) * s.c[n-k]
}
c = s.s1.extract(i) - c*s.inv
s.c = append(s.c, c)
s.s = append(s.s, c*s.inv)
}
return s.s[n]
}
type deriv struct {
s []float64
s1 fps
}
func (s *deriv) extract(n int) float64 {
for i := len(s.s); i <= n; {
i++
s.s = append(s.s, float64(i)*s.s1.extract(i))
}
return s.s[n]
}
type integ struct {
s []float64
s1 fps
}
func (s *integ) extract(n int) float64 {
if n == 0 {
return 0
}
for i := len(s.s) + 1; i <= n; i++ {
s.s = append(s.s, s.s1.extract(i-1)/float64(i))
}
return s.s[n-1]
}
func main() {
partialSeries := func(f fps) (s string) {
for i := 0; i < 6; i++ {
s = fmt.Sprintf("%s %8.5f ", s, f.extract(i))
}
return
}
sin, cos := sinCos()
fmt.Println("sin:", partialSeries(sin))
fmt.Println("cos:", partialSeries(cos))
}
|
Port the provided Python code into Go while preserving the original functionality. |
def isowndigitspowersum(integer):
digits = [int(c) for c in str(integer)]
exponent = len(digits)
return sum(x ** exponent for x in digits) == integer
print("Own digits power sums for N = 3 to 9 inclusive:")
for i in range(100, 1000000000):
if isowndigitspowersum(i):
print(i)
| package main
import (
"fmt"
"math"
"rcu"
)
func main() {
powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
fmt.Println("Own digits power sums for N = 3 to 9 inclusive:")
for n := 3; n < 10; n++ {
for d := 2; d < 10; d++ {
powers[d] *= d
}
i := int(math.Pow(10, float64(n-1)))
max := i * 10
lastDigit := 0
sum := 0
var digits []int
for i < max {
if lastDigit == 0 {
digits = rcu.Digits(i, 10)
sum = 0
for _, d := range digits {
sum += powers[d]
}
} else if lastDigit == 1 {
sum++
} else {
sum += powers[lastDigit] - powers[lastDigit-1]
}
if sum == i {
fmt.Println(i)
if lastDigit == 0 {
fmt.Println(i + 1)
}
i += 10 - lastDigit
lastDigit = 0
} else if sum > i {
i += 10 - lastDigit
lastDigit = 0
} else if lastDigit < 9 {
i++
lastDigit++
} else {
i++
lastDigit = 0
}
}
}
}
|
Write the same code in Go as shown below in Python. | def run_vm(data_size)
int stack[data_size + 1000]
set stack[0..data_size - 1] to 0
int pc = 0
while True:
op = code[pc]
pc += 1
if op == FETCH:
stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
pc += word_size
elif op == STORE:
stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();
pc += word_size
elif op == PUSH:
stack.append(bytes_to_int(code[pc:pc+word_size])[0]);
pc += word_size
elif op == ADD: stack[-2] += stack[-1]; stack.pop()
elif op == SUB: stack[-2] -= stack[-1]; stack.pop()
elif op == MUL: stack[-2] *= stack[-1]; stack.pop()
elif op == DIV: stack[-2] /= stack[-1]; stack.pop()
elif op == MOD: stack[-2] %= stack[-1]; stack.pop()
elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()
elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()
elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()
elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()
elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()
elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()
elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()
elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()
elif op == NEG: stack[-1] = -stack[-1]
elif op == NOT: stack[-1] = not stack[-1]
elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == PRTC: print stack[-1] as a character; stack.pop()
elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop()
elif op == PRTI: print stack[-1] as an integer; stack.pop()
elif op == HALT: break
| package main
import (
"bufio"
"encoding/binary"
"fmt"
"log"
"math"
"os"
"strconv"
"strings"
)
type code = byte
const (
fetch code = iota
store
push
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
neg
not
jmp
jz
prtc
prts
prti
halt
)
var codeMap = map[string]code{
"fetch": fetch,
"store": store,
"push": push,
"add": add,
"sub": sub,
"mul": mul,
"div": div,
"mod": mod,
"lt": lt,
"gt": gt,
"le": le,
"ge": ge,
"eq": eq,
"ne": ne,
"and": and,
"or": or,
"neg": neg,
"not": not,
"jmp": jmp,
"jz": jz,
"prtc": prtc,
"prts": prts,
"prti": prti,
"halt": halt,
}
var (
err error
scanner *bufio.Scanner
object []code
stringPool []string
)
func reportError(msg string) {
log.Fatalf("error : %s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func btoi(b bool) int32 {
if b {
return 1
}
return 0
}
func itob(i int32) bool {
if i != 0 {
return true
}
return false
}
func emitByte(c code) {
object = append(object, c)
}
func emitWord(n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for _, b := range bs {
emitByte(code(b))
}
}
func runVM(dataSize int) {
stack := make([]int32, dataSize+1)
pc := int32(0)
for {
op := object[pc]
pc++
switch op {
case fetch:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
stack = append(stack, stack[x])
pc += 4
case store:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
ln := len(stack)
stack[x] = stack[ln-1]
stack = stack[:ln-1]
pc += 4
case push:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
stack = append(stack, x)
pc += 4
case add:
ln := len(stack)
stack[ln-2] += stack[ln-1]
stack = stack[:ln-1]
case sub:
ln := len(stack)
stack[ln-2] -= stack[ln-1]
stack = stack[:ln-1]
case mul:
ln := len(stack)
stack[ln-2] *= stack[ln-1]
stack = stack[:ln-1]
case div:
ln := len(stack)
stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1]))
stack = stack[:ln-1]
case mod:
ln := len(stack)
stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1])))
stack = stack[:ln-1]
case lt:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] < stack[ln-1])
stack = stack[:ln-1]
case gt:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] > stack[ln-1])
stack = stack[:ln-1]
case le:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1])
stack = stack[:ln-1]
case ge:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1])
stack = stack[:ln-1]
case eq:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] == stack[ln-1])
stack = stack[:ln-1]
case ne:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] != stack[ln-1])
stack = stack[:ln-1]
case and:
ln := len(stack)
stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1]))
stack = stack[:ln-1]
case or:
ln := len(stack)
stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1]))
stack = stack[:ln-1]
case neg:
ln := len(stack)
stack[ln-1] = -stack[ln-1]
case not:
ln := len(stack)
stack[ln-1] = btoi(!itob(stack[ln-1]))
case jmp:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
pc += x
case jz:
ln := len(stack)
v := stack[ln-1]
stack = stack[:ln-1]
if v != 0 {
pc += 4
} else {
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
pc += x
}
case prtc:
ln := len(stack)
fmt.Printf("%c", stack[ln-1])
stack = stack[:ln-1]
case prts:
ln := len(stack)
fmt.Printf("%s", stringPool[stack[ln-1]])
stack = stack[:ln-1]
case prti:
ln := len(stack)
fmt.Printf("%d", stack[ln-1])
stack = stack[:ln-1]
case halt:
return
default:
reportError(fmt.Sprintf("Unknown opcode %d\n", op))
}
}
}
func translate(s string) string {
var d strings.Builder
for i := 0; i < len(s); i++ {
if s[i] == '\\' && (i+1) < len(s) {
if s[i+1] == 'n' {
d.WriteByte('\n')
i++
} else if s[i+1] == '\\' {
d.WriteByte('\\')
i++
}
} else {
d.WriteByte(s[i])
}
}
return d.String()
}
func loadCode() int {
var dataSize int
firstLine := true
for scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
if len(line) == 0 {
if firstLine {
reportError("empty line")
} else {
break
}
}
lineList := strings.Fields(line)
if firstLine {
dataSize, err = strconv.Atoi(lineList[1])
check(err)
nStrings, err := strconv.Atoi(lineList[3])
check(err)
for i := 0; i < nStrings; i++ {
scanner.Scan()
s := strings.Trim(scanner.Text(), "\"\n")
stringPool = append(stringPool, translate(s))
}
firstLine = false
continue
}
offset, err := strconv.Atoi(lineList[0])
check(err)
instr := lineList[1]
opCode, ok := codeMap[instr]
if !ok {
reportError(fmt.Sprintf("Unknown instruction %s at %d", instr, opCode))
}
emitByte(opCode)
switch opCode {
case jmp, jz:
p, err := strconv.Atoi(lineList[3])
check(err)
emitWord(p - offset - 1)
case push:
value, err := strconv.Atoi(lineList[2])
check(err)
emitWord(value)
case fetch, store:
value, err := strconv.Atoi(strings.Trim(lineList[2], "[]"))
check(err)
emitWord(value)
}
}
check(scanner.Err())
return dataSize
}
func main() {
codeGen, err := os.Open("codegen.txt")
check(err)
defer codeGen.Close()
scanner = bufio.NewScanner(codeGen)
runVM(loadCode())
}
|
Please provide an equivalent version of this Python code in Go. | def run_vm(data_size)
int stack[data_size + 1000]
set stack[0..data_size - 1] to 0
int pc = 0
while True:
op = code[pc]
pc += 1
if op == FETCH:
stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
pc += word_size
elif op == STORE:
stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();
pc += word_size
elif op == PUSH:
stack.append(bytes_to_int(code[pc:pc+word_size])[0]);
pc += word_size
elif op == ADD: stack[-2] += stack[-1]; stack.pop()
elif op == SUB: stack[-2] -= stack[-1]; stack.pop()
elif op == MUL: stack[-2] *= stack[-1]; stack.pop()
elif op == DIV: stack[-2] /= stack[-1]; stack.pop()
elif op == MOD: stack[-2] %= stack[-1]; stack.pop()
elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()
elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()
elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()
elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()
elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()
elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()
elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()
elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()
elif op == NEG: stack[-1] = -stack[-1]
elif op == NOT: stack[-1] = not stack[-1]
elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]
elif op == PRTC: print stack[-1] as a character; stack.pop()
elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop()
elif op == PRTI: print stack[-1] as an integer; stack.pop()
elif op == HALT: break
| package main
import (
"bufio"
"encoding/binary"
"fmt"
"log"
"math"
"os"
"strconv"
"strings"
)
type code = byte
const (
fetch code = iota
store
push
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
neg
not
jmp
jz
prtc
prts
prti
halt
)
var codeMap = map[string]code{
"fetch": fetch,
"store": store,
"push": push,
"add": add,
"sub": sub,
"mul": mul,
"div": div,
"mod": mod,
"lt": lt,
"gt": gt,
"le": le,
"ge": ge,
"eq": eq,
"ne": ne,
"and": and,
"or": or,
"neg": neg,
"not": not,
"jmp": jmp,
"jz": jz,
"prtc": prtc,
"prts": prts,
"prti": prti,
"halt": halt,
}
var (
err error
scanner *bufio.Scanner
object []code
stringPool []string
)
func reportError(msg string) {
log.Fatalf("error : %s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func btoi(b bool) int32 {
if b {
return 1
}
return 0
}
func itob(i int32) bool {
if i != 0 {
return true
}
return false
}
func emitByte(c code) {
object = append(object, c)
}
func emitWord(n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for _, b := range bs {
emitByte(code(b))
}
}
func runVM(dataSize int) {
stack := make([]int32, dataSize+1)
pc := int32(0)
for {
op := object[pc]
pc++
switch op {
case fetch:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
stack = append(stack, stack[x])
pc += 4
case store:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
ln := len(stack)
stack[x] = stack[ln-1]
stack = stack[:ln-1]
pc += 4
case push:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
stack = append(stack, x)
pc += 4
case add:
ln := len(stack)
stack[ln-2] += stack[ln-1]
stack = stack[:ln-1]
case sub:
ln := len(stack)
stack[ln-2] -= stack[ln-1]
stack = stack[:ln-1]
case mul:
ln := len(stack)
stack[ln-2] *= stack[ln-1]
stack = stack[:ln-1]
case div:
ln := len(stack)
stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1]))
stack = stack[:ln-1]
case mod:
ln := len(stack)
stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1])))
stack = stack[:ln-1]
case lt:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] < stack[ln-1])
stack = stack[:ln-1]
case gt:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] > stack[ln-1])
stack = stack[:ln-1]
case le:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1])
stack = stack[:ln-1]
case ge:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1])
stack = stack[:ln-1]
case eq:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] == stack[ln-1])
stack = stack[:ln-1]
case ne:
ln := len(stack)
stack[ln-2] = btoi(stack[ln-2] != stack[ln-1])
stack = stack[:ln-1]
case and:
ln := len(stack)
stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1]))
stack = stack[:ln-1]
case or:
ln := len(stack)
stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1]))
stack = stack[:ln-1]
case neg:
ln := len(stack)
stack[ln-1] = -stack[ln-1]
case not:
ln := len(stack)
stack[ln-1] = btoi(!itob(stack[ln-1]))
case jmp:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
pc += x
case jz:
ln := len(stack)
v := stack[ln-1]
stack = stack[:ln-1]
if v != 0 {
pc += 4
} else {
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
pc += x
}
case prtc:
ln := len(stack)
fmt.Printf("%c", stack[ln-1])
stack = stack[:ln-1]
case prts:
ln := len(stack)
fmt.Printf("%s", stringPool[stack[ln-1]])
stack = stack[:ln-1]
case prti:
ln := len(stack)
fmt.Printf("%d", stack[ln-1])
stack = stack[:ln-1]
case halt:
return
default:
reportError(fmt.Sprintf("Unknown opcode %d\n", op))
}
}
}
func translate(s string) string {
var d strings.Builder
for i := 0; i < len(s); i++ {
if s[i] == '\\' && (i+1) < len(s) {
if s[i+1] == 'n' {
d.WriteByte('\n')
i++
} else if s[i+1] == '\\' {
d.WriteByte('\\')
i++
}
} else {
d.WriteByte(s[i])
}
}
return d.String()
}
func loadCode() int {
var dataSize int
firstLine := true
for scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
if len(line) == 0 {
if firstLine {
reportError("empty line")
} else {
break
}
}
lineList := strings.Fields(line)
if firstLine {
dataSize, err = strconv.Atoi(lineList[1])
check(err)
nStrings, err := strconv.Atoi(lineList[3])
check(err)
for i := 0; i < nStrings; i++ {
scanner.Scan()
s := strings.Trim(scanner.Text(), "\"\n")
stringPool = append(stringPool, translate(s))
}
firstLine = false
continue
}
offset, err := strconv.Atoi(lineList[0])
check(err)
instr := lineList[1]
opCode, ok := codeMap[instr]
if !ok {
reportError(fmt.Sprintf("Unknown instruction %s at %d", instr, opCode))
}
emitByte(opCode)
switch opCode {
case jmp, jz:
p, err := strconv.Atoi(lineList[3])
check(err)
emitWord(p - offset - 1)
case push:
value, err := strconv.Atoi(lineList[2])
check(err)
emitWord(value)
case fetch, store:
value, err := strconv.Atoi(strings.Trim(lineList[2], "[]"))
check(err)
emitWord(value)
}
}
check(scanner.Err())
return dataSize
}
func main() {
codeGen, err := os.Open("codegen.txt")
check(err)
defer codeGen.Close()
scanner = bufio.NewScanner(codeGen)
runVM(loadCode())
}
|
Port the provided Python code into Go while preserving the original functionality. | def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
pts = []
for i in range(n+1):
t = i / n
a = (1. - t)**3
b = 3. * t * (1. - t)**2
c = 3.0 * t**2 * (1.0 - t)
d = t**3
x = int(a * x0 + b * x1 + c * x2 + d * x3)
y = int(a * y0 + b * y1 + c * y2 + d * y3)
pts.append( (x, y) )
for i in range(n):
self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])
Bitmap.cubicbezier = cubicbezier
bitmap = Bitmap(17,17)
bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)
bitmap.chardisplay()
| package raster
const b3Seg = 30
func (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {
var px, py [b3Seg + 1]int
fx1, fy1 := float64(x1), float64(y1)
fx2, fy2 := float64(x2), float64(y2)
fx3, fy3 := float64(x3), float64(y3)
fx4, fy4 := float64(x4), float64(y4)
for i := range px {
d := float64(i) / b3Seg
a := 1 - d
b, c := a * a, d * d
a, b, c, d = a*b, 3*b*d, 3*a*c, c*d
px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)
py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)
}
x0, y0 := px[0], py[0]
for i := 1; i <= b3Seg; i++ {
x1, y1 := px[i], py[i]
b.Line(x0, y0, x1, y1, p)
x0, y0 = x1, y1
}
}
func (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {
b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())
}
|
Preserve the algorithm and functionality while converting the code from Python to Go. | tutor = False
def pancakesort(data):
if len(data) <= 1:
return data
if tutor: print()
for size in range(len(data), 1, -1):
maxindex = max(range(size), key=data.__getitem__)
if maxindex+1 != size:
if maxindex != 0:
if tutor: print('With: %r doflip %i'
% ( ' '.join(str(x) for x in data), maxindex+1 ))
data[:maxindex+1] = reversed(data[:maxindex+1])
if tutor: print('With: %r doflip %i'
% ( ' '.join(str(x) for x in data), size ))
data[:size] = reversed(data[:size])
if tutor: print()
| package main
import "fmt"
func main() {
list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
list.sort()
fmt.Println("sorted! ", list)
}
type pancake []int
func (a pancake) sort() {
for uns := len(a) - 1; uns > 0; uns-- {
lx, lg := 0, a[0]
for i := 1; i <= uns; i++ {
if a[i] > lg {
lx, lg = i, a[i]
}
}
a.flip(lx)
a.flip(uns)
}
}
func (a pancake) flip(r int) {
for l := 0; l < r; l, r = l+1, r-1 {
a[l], a[r] = a[r], a[l]
}
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. |
from random import seed,randint
from datetime import datetime
seed(str(datetime.now()))
largeNum = [randint(1,9)]
for i in range(1,1000):
largeNum.append(randint(0,9))
maxNum,minNum = 0,99999
for i in range(0,994):
num = int("".join(map(str,largeNum[i:i+5])))
if num > maxNum:
maxNum = num
elif num < minNum:
minNum = num
print("Largest 5-adjacent number found ", maxNum)
print("Smallest 5-adjacent number found ", minNum)
| package main
import (
"fmt"
"math/rand"
"rcu"
"strings"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
var sb strings.Builder
for i := 0; i < 1000; i++ {
sb.WriteByte(byte(rand.Intn(10) + 48))
}
number := sb.String()
for i := 99999; i >= 0; i-- {
quintet := fmt.Sprintf("%05d", i)
if strings.Contains(number, quintet) {
ci := rcu.Commatize(i)
fmt.Printf("The largest number formed from 5 adjacent digits (%s) is: %6s\n", quintet, ci)
break
}
}
for i := 0; i <= 99999; i++ {
quintet := fmt.Sprintf("%05d", i)
if strings.Contains(number, quintet) {
ci := rcu.Commatize(i)
fmt.Printf("The smallest number formed from 5 adjacent digits (%s) is: %6s\n", quintet, ci)
return
}
}
}
|
Write the same code in Go as shown below in Python. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def digSum(n, b):
s = 0
while n:
s += (n % b)
n = n // b
return s
if __name__ == '__main__':
for n in range(11, 99):
if isPrime(digSum(n**3, 10)) and isPrime(digSum(n**2, 10)):
print(n, end = " ")
| package main
import (
"fmt"
"rcu"
)
func main() {
for i := 1; i < 100; i++ {
if !rcu.IsPrime(rcu.DigitSum(i*i, 10)) {
continue
}
if rcu.IsPrime(rcu.DigitSum(i*i*i, 10)) {
fmt.Printf("%d ", i)
}
}
fmt.Println()
}
|
Translate this program into Go but keep the logic exactly as in Python. | from numpy import log
def sieve_of_Sundaram(nth, print_all=True):
assert nth > 0, "nth must be a positive integer"
k = int((2.4 * nth * log(nth)) // 2)
integers_list = [True] * k
for i in range(1, k):
j = i
while i + j + 2 * i * j < k:
integers_list[i + j + 2 * i * j] = False
j += 1
pcount = 0
for i in range(1, k + 1):
if integers_list[i]:
pcount += 1
if print_all:
print(f"{2 * i + 1:4}", end=' ')
if pcount % 10 == 0:
print()
if pcount == nth:
print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n")
break
sieve_of_Sundaram(100, True)
sieve_of_Sundaram(1000000, False)
| package main
import (
"fmt"
"math"
"rcu"
"time"
)
func sos(n int) []int {
if n < 3 {
return []int{}
}
var primes []int
k := (n-3)/2 + 1
marked := make([]bool, k)
limit := (int(math.Sqrt(float64(n)))-3)/2 + 1
for i := 0; i < limit; i++ {
p := 2*i + 3
s := (p*p - 3) / 2
for j := s; j < k; j += p {
marked[j] = true
}
}
for i := 0; i < k; i++ {
if !marked[i] {
primes = append(primes, 2*i+3)
}
}
return primes
}
func soe(n int) []int {
if n < 3 {
return []int{}
}
var primes []int
k := (n-3)/2 + 1
marked := make([]bool, k)
limit := (int(math.Sqrt(float64(n)))-3)/2 + 1
for i := 0; i < limit; i++ {
if !marked[i] {
p := 2*i + 3
s := (p*p - 3) / 2
for j := s; j < k; j += p {
marked[j] = true
}
}
}
for i := 0; i < k; i++ {
if !marked[i] {
primes = append(primes, 2*i+3)
}
}
return primes
}
func main() {
const limit = int(16e6)
start := time.Now()
primes := sos(limit)
elapsed := int(time.Since(start).Milliseconds())
climit := rcu.Commatize(limit)
celapsed := rcu.Commatize(elapsed)
million := rcu.Commatize(1e6)
millionth := rcu.Commatize(primes[1e6-1])
fmt.Printf("Using the Sieve of Sundaram generated primes up to %s in %s ms.\n\n", climit, celapsed)
fmt.Println("First 100 odd primes generated by the Sieve of Sundaram:")
for i, p := range primes[0:100] {
fmt.Printf("%3d ", p)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThe %s Sundaram prime is %s\n", million, millionth)
start = time.Now()
primes = soe(limit)
elapsed = int(time.Since(start).Milliseconds())
celapsed = rcu.Commatize(elapsed)
millionth = rcu.Commatize(primes[1e6-1])
fmt.Printf("\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\n", celapsed)
fmt.Printf("\nAs a check, the %s Sundaram prime would again have been %s\n", million, millionth)
}
|
Convert this Python snippet to Go and keep its semantics consistent. | assert 1.008 == molar_mass('H')
assert 2.016 == molar_mass('H2')
assert 18.015 == molar_mass('H2O')
assert 34.014 == molar_mass('H2O2')
assert 34.014 == molar_mass('(HO)2')
assert 142.036 == molar_mass('Na2SO4')
assert 84.162 == molar_mass('C6H12')
assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')
assert 176.124 == molar_mass('C6H4O2(OH)4')
assert 386.664 == molar_mass('C27H46O')
assert 315 == molar_mass('Uue')
| package main
import (
"fmt"
"strconv"
"strings"
)
var atomicMass = map[string]float64{
"H": 1.008,
"He": 4.002602,
"Li": 6.94,
"Be": 9.0121831,
"B": 10.81,
"C": 12.011,
"N": 14.007,
"O": 15.999,
"F": 18.998403163,
"Ne": 20.1797,
"Na": 22.98976928,
"Mg": 24.305,
"Al": 26.9815385,
"Si": 28.085,
"P": 30.973761998,
"S": 32.06,
"Cl": 35.45,
"Ar": 39.948,
"K": 39.0983,
"Ca": 40.078,
"Sc": 44.955908,
"Ti": 47.867,
"V": 50.9415,
"Cr": 51.9961,
"Mn": 54.938044,
"Fe": 55.845,
"Co": 58.933194,
"Ni": 58.6934,
"Cu": 63.546,
"Zn": 65.38,
"Ga": 69.723,
"Ge": 72.630,
"As": 74.921595,
"Se": 78.971,
"Br": 79.904,
"Kr": 83.798,
"Rb": 85.4678,
"Sr": 87.62,
"Y": 88.90584,
"Zr": 91.224,
"Nb": 92.90637,
"Mo": 95.95,
"Ru": 101.07,
"Rh": 102.90550,
"Pd": 106.42,
"Ag": 107.8682,
"Cd": 112.414,
"In": 114.818,
"Sn": 118.710,
"Sb": 121.760,
"Te": 127.60,
"I": 126.90447,
"Xe": 131.293,
"Cs": 132.90545196,
"Ba": 137.327,
"La": 138.90547,
"Ce": 140.116,
"Pr": 140.90766,
"Nd": 144.242,
"Pm": 145,
"Sm": 150.36,
"Eu": 151.964,
"Gd": 157.25,
"Tb": 158.92535,
"Dy": 162.500,
"Ho": 164.93033,
"Er": 167.259,
"Tm": 168.93422,
"Yb": 173.054,
"Lu": 174.9668,
"Hf": 178.49,
"Ta": 180.94788,
"W": 183.84,
"Re": 186.207,
"Os": 190.23,
"Ir": 192.217,
"Pt": 195.084,
"Au": 196.966569,
"Hg": 200.592,
"Tl": 204.38,
"Pb": 207.2,
"Bi": 208.98040,
"Po": 209,
"At": 210,
"Rn": 222,
"Fr": 223,
"Ra": 226,
"Ac": 227,
"Th": 232.0377,
"Pa": 231.03588,
"U": 238.02891,
"Np": 237,
"Pu": 244,
"Am": 243,
"Cm": 247,
"Bk": 247,
"Cf": 251,
"Es": 252,
"Fm": 257,
"Uue": 315,
"Ubn": 299,
}
func replaceParens(s string) string {
var letter byte = 'a'
for {
start := strings.IndexByte(s, '(')
if start == -1 {
break
}
restart:
for i := start + 1; i < len(s); i++ {
if s[i] == ')' {
expr := s[start+1 : i]
symbol := fmt.Sprintf("@%c", letter)
s = strings.Replace(s, s[start:i+1], symbol, 1)
atomicMass[symbol] = evaluate(expr)
letter++
break
}
if s[i] == '(' {
start = i
goto restart
}
}
}
return s
}
func evaluate(s string) float64 {
s += string('[')
var symbol, number string
sum := 0.0
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c >= '@' && c <= '[':
n := 1
if number != "" {
n, _ = strconv.Atoi(number)
}
if symbol != "" {
sum += atomicMass[symbol] * float64(n)
}
if c == '[' {
break
}
symbol = string(c)
number = ""
case c >= 'a' && c <= 'z':
symbol += string(c)
case c >= '0' && c <= '9':
number += string(c)
default:
panic(fmt.Sprintf("Unexpected symbol %c in molecule", c))
}
}
return sum
}
func main() {
molecules := []string{
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3",
"C6H4O2(OH)4", "C27H46O", "Uue",
}
for _, molecule := range molecules {
mass := evaluate(replaceParens(molecule))
fmt.Printf("%17s -> %7.3f\n", molecule, mass)
}
}
|
Generate an equivalent Go version of this Python code. | import ldap
l = ldap.initialize("ldap://ldap.example.com")
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s("me@example.com", "password")
finally:
l.unbind()
| 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,
UseSSL: false,
BindDN: "uid=readonlyuser,ou=People,dc=example,dc=com",
BindPassword: "readonlypassword",
UserFilter: "(uid=%s)",
GroupFilter: "(memberUid=%s)",
Attributes: []string{"givenName", "sn", "mail", "uid"},
}
defer client.Close()
err := client.Connect()
if err != nil {
log.Fatalf("Failed to connect : %+v", err)
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. |
from itertools import dropwhile, takewhile
def nnPeers(n):
def p(x):
return n == x
def go(xs):
fromFirstMatch = list(dropwhile(
lambda v: not p(v),
xs
))
ns = list(takewhile(p, fromFirstMatch))
rest = fromFirstMatch[len(ns):]
return p(len(ns)) and (
not any(p(x) for x in rest)
)
return go
def main():
print(
'\n'.join([
f'{xs} -> {nnPeers(3)(xs)}' for xs in [
[9, 3, 3, 3, 2, 1, 7, 8, 5],
[5, 2, 9, 3, 3, 7, 8, 4, 1],
[1, 4, 3, 6, 7, 3, 8, 3, 2],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[4, 6, 8, 7, 2, 3, 3, 3, 1]
]
])
)
if __name__ == '__main__':
main()
| package main
import "fmt"
func main() {
lists := [][]int{
{9, 3, 3, 3, 2, 1, 7, 8, 5},
{5, 2, 9, 3, 3, 7, 8, 4, 1},
{1, 4, 3, 6, 7, 3, 8, 3, 2},
{1, 2, 3, 4, 5, 6, 7, 8, 9},
{4, 6, 8, 7, 2, 3, 3, 3, 1},
{3, 3, 3, 1, 2, 4, 5, 1, 3},
{0, 3, 3, 3, 3, 7, 2, 2, 6},
{3, 3, 3, 3, 3, 4, 4, 4, 4},
}
for d := 1; d <= 4; d++ {
fmt.Printf("Exactly %d adjacent %d's:\n", d, d)
for _, list := range lists {
var indices []int
for i, e := range list {
if e == d {
indices = append(indices, i)
}
}
adjacent := false
if len(indices) == d {
adjacent = true
for i := 1; i < len(indices); i++ {
if indices[i]-indices[i-1] != 1 {
adjacent = false
break
}
}
}
fmt.Printf("%v -> %t\n", list, adjacent)
}
fmt.Println()
}
}
|
Change the following Python code into Go without altering its purpose. | from operator import itemgetter
DEBUG = False
def spermutations(n):
sign = 1
p = [[i, 0 if i == 0 else -1]
for i in range(n)]
if DEBUG: print '
yield tuple(pp[0] for pp in p), sign
while any(pp[1] for pp in p):
i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),
key=itemgetter(1))
sign *= -1
if d1 == -1:
i2 = i1 - 1
p[i1], p[i2] = p[i2], p[i1]
if i2 == 0 or p[i2 - 1][0] > n1:
p[i2][1] = 0
elif d1 == 1:
i2 = i1 + 1
p[i1], p[i2] = p[i2], p[i1]
if i2 == n - 1 or p[i2 + 1][0] > n1:
p[i2][1] = 0
if DEBUG: print '
yield tuple(pp[0] for pp in p), sign
for i3, pp in enumerate(p):
n3, d3 = pp
if n3 > n1:
pp[1] = 1 if i3 < i2 else -1
if DEBUG: print '
if __name__ == '__main__':
from itertools import permutations
for n in (3, 4):
print '\nPermutations and sign of %i items' % n
sp = set()
for i in spermutations(n):
sp.add(i[0])
print('Perm: %r Sign: %2i' % i)
p = set(permutations(range(n)))
assert sp == p, 'Two methods of generating permutations do not agree'
| package permute
func Iter(p []int) func() int {
f := pf(len(p))
return func() int {
return f(p)
}
}
func pf(n int) func([]int) int {
sign := 1
switch n {
case 0, 1:
return func([]int) (s int) {
s = sign
sign = 0
return
}
default:
p0 := pf(n - 1)
i := n
var d int
return func(p []int) int {
switch {
case sign == 0:
case i == n:
i--
sign = p0(p[:i])
d = -1
case i == 0:
i++
sign *= p0(p[1:])
d = 1
if sign == 0 {
p[0], p[1] = p[1], p[0]
}
default:
p[i], p[i-1] = p[i-1], p[i]
sign = -sign
i += d
}
return sign
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Python version. |
from itertools import count, islice
def a131382():
return (
elemIndex(x)(
productDigitSums(x)
) for x in count(1)
)
def productDigitSums(n):
return (digitSum(n * x) for x in count(0))
def main():
print(
table(10)([
str(x) for x in islice(
a131382(),
40
)
])
)
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 digitSum(n):
return sum(int(x) for x in list(str(n)))
def elemIndex(x):
def go(xs):
try:
return next(
i for i, v in enumerate(xs) if x == v
)
except StopIteration:
return None
return go
def table(n):
def go(xs):
w = len(xs[-1])
return '\n'.join(
' '.join(row) for row in chunksOf(n)([
s.rjust(w, ' ') for s in xs
])
)
return go
if __name__ == '__main__':
main()
| package main
import "rcu"
func main() {
var res []int
for n := 1; n <= 70; n++ {
m := 1
for rcu.DigitSum(m*n, 10) != n {
m++
}
res = append(res, m)
}
rcu.PrintTable(res, 7, 10, true)
}
|
Rewrite the snippet below in Go so it works the same as the original Python code. | def quad(top=2200):
r = [False] * top
ab = [False] * (top * 2)**2
for a in range(1, top):
for b in range(a, top):
ab[a * a + b * b] = True
s = 3
for c in range(1, top):
s1, s, s2 = s, s + 2, s + 2
for d in range(c + 1, top):
if ab[s1]:
r[d] = True
s1 += s2
s2 += 2
return [i for i, val in enumerate(r) if not val and i]
if __name__ == '__main__':
n = 2200
print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
| package main
import "fmt"
const (
N = 2200
N2 = N * N * 2
)
func main() {
s := 3
var s1, s2 int
var r [N + 1]bool
var ab [N2 + 1]bool
for a := 1; a <= N; a++ {
a2 := a * a
for b := a; b <= N; b++ {
ab[a2 + b * b] = true
}
}
for c := 1; c <= N; c++ {
s1 = s
s += 2
s2 = s
for d := c + 1; d <= N; d++ {
if ab[s1] {
r[d] = true
}
s1 += s2
s2 += 2
}
}
for d := 1; d <= N; d++ {
if !r[d] {
fmt.Printf("%d ", d)
}
}
fmt.Println()
}
|
Write a version of this Python function in Go with identical behavior. | MULTIPLICATION_TABLE = [
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(1, 2, 3, 4, 0, 6, 7, 8, 9, 5),
(2, 3, 4, 0, 1, 7, 8, 9, 5, 6),
(3, 4, 0, 1, 2, 8, 9, 5, 6, 7),
(4, 0, 1, 2, 3, 9, 5, 6, 7, 8),
(5, 9, 8, 7, 6, 0, 4, 3, 2, 1),
(6, 5, 9, 8, 7, 1, 0, 4, 3, 2),
(7, 6, 5, 9, 8, 2, 1, 0, 4, 3),
(8, 7, 6, 5, 9, 3, 2, 1, 0, 4),
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0),
]
INV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9)
PERMUTATION_TABLE = [
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(1, 5, 7, 6, 2, 8, 3, 0, 9, 4),
(5, 8, 0, 3, 7, 9, 6, 1, 4, 2),
(8, 9, 1, 6, 0, 4, 3, 5, 2, 7),
(9, 4, 5, 3, 1, 2, 6, 8, 7, 0),
(4, 2, 8, 6, 5, 7, 3, 9, 0, 1),
(2, 7, 9, 3, 8, 0, 6, 4, 1, 5),
(7, 0, 4, 6, 9, 1, 3, 2, 5, 8),
]
def verhoeffchecksum(n, validate=True, terse=True, verbose=False):
if verbose:
print(f"\n{'Validation' if validate else 'Check digit'}",\
f"calculations for {n}:\n\n i nᵢ p[i,nᵢ] c\n------------------")
c, dig = 0, list(str(n if validate else 10 * n))
for i, ni in enumerate(dig[::-1]):
p = PERMUTATION_TABLE[i % 8][int(ni)]
c = MULTIPLICATION_TABLE[c][p]
if verbose:
print(f"{i:2} {ni} {p} {c}")
if verbose and not validate:
print(f"\ninv({c}) = {INV[c]}")
if not terse:
print(f"\nThe validation for '{n}' is {'correct' if c == 0 else 'incorrect'}."\
if validate else f"\nThe check digit for '{n}' is {INV[c]}.")
return c == 0 if validate else INV[c]
if __name__ == '__main__':
for n, va, t, ve in [
(236, False, False, True), (2363, True, False, True), (2369, True, False, True),
(12345, False, False, True), (123451, True, False, True), (123459, True, False, True),
(123456789012, False, False, False), (1234567890120, True, False, False),
(1234567890129, True, False, False)]:
verhoeffchecksum(n, va, t, ve)
| package main
import "fmt"
var d = [][]int{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{1, 2, 3, 4, 0, 6, 7, 8, 9, 5},
{2, 3, 4, 0, 1, 7, 8, 9, 5, 6},
{3, 4, 0, 1, 2, 8, 9, 5, 6, 7},
{4, 0, 1, 2, 3, 9, 5, 6, 7, 8},
{5, 9, 8, 7, 6, 0, 4, 3, 2, 1},
{6, 5, 9, 8, 7, 1, 0, 4, 3, 2},
{7, 6, 5, 9, 8, 2, 1, 0, 4, 3},
{8, 7, 6, 5, 9, 3, 2, 1, 0, 4},
{9, 8, 7, 6, 5, 4, 3, 2, 1, 0},
}
var inv = []int{0, 4, 3, 2, 1, 5, 6, 7, 8, 9}
var p = [][]int{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{1, 5, 7, 6, 2, 8, 3, 0, 9, 4},
{5, 8, 0, 3, 7, 9, 6, 1, 4, 2},
{8, 9, 1, 6, 0, 4, 3, 5, 2, 7},
{9, 4, 5, 3, 1, 2, 6, 8, 7, 0},
{4, 2, 8, 6, 5, 7, 3, 9, 0, 1},
{2, 7, 9, 3, 8, 0, 6, 4, 1, 5},
{7, 0, 4, 6, 9, 1, 3, 2, 5, 8},
}
func verhoeff(s string, validate, table bool) interface{} {
if table {
t := "Check digit"
if validate {
t = "Validation"
}
fmt.Printf("%s calculations for '%s':\n\n", t, s)
fmt.Println(" i nᵢ p[i,nᵢ] c")
fmt.Println("------------------")
}
if !validate {
s = s + "0"
}
c := 0
le := len(s) - 1
for i := le; i >= 0; i-- {
ni := int(s[i] - 48)
pi := p[(le-i)%8][ni]
c = d[c][pi]
if table {
fmt.Printf("%2d %d %d %d\n", le-i, ni, pi, c)
}
}
if table && !validate {
fmt.Printf("\ninv[%d] = %d\n", c, inv[c])
}
if !validate {
return inv[c]
}
return c == 0
}
func main() {
ss := []string{"236", "12345", "123456789012"}
ts := []bool{true, true, false, true}
for i, s := range ss {
c := verhoeff(s, false, ts[i]).(int)
fmt.Printf("\nThe check digit for '%s' is '%d'\n\n", s, c)
for _, sc := range []string{s + string(c+48), s + "9"} {
v := verhoeff(sc, true, ts[i]).(bool)
ans := "correct"
if !v {
ans = "incorrect"
}
fmt.Printf("\nThe validation for '%s' is %s\n\n", sc, ans)
}
}
}
|
Write the same code in Go as shown below in Python. | print("working...")
print("Steady squares under 10.000 are:")
limit = 10000
for n in range(1,limit):
nstr = str(n)
nlen = len(nstr)
square = str(pow(n,2))
rn = square[-nlen:]
if nstr == rn:
print(str(n) + " " + str(square))
print("done...")
| package main
import (
"fmt"
"rcu"
"strconv"
"strings"
)
func contains(list []int, s int) bool {
for _, e := range list {
if e == s {
return true
}
}
return false
}
func main() {
fmt.Println("Steady squares under 10,000:")
finalDigits := []int{1, 5, 6}
for i := 1; i < 10000; i++ {
if !contains(finalDigits, i%10) {
continue
}
sq := i * i
sqs := strconv.Itoa(sq)
is := strconv.Itoa(i)
if strings.HasSuffix(sqs, is) {
fmt.Printf("%5s -> %10s\n", rcu.Commatize(i), rcu.Commatize(sq))
}
}
}
|
Convert this Python block to Go, preserving its control flow and logic. | def reverse(n, base):
r = 0
while n > 0:
r = r*base + n%base
n = n//base
return r
def palindrome(n, base):
return n == reverse(n, base)
cnt = 0
for i in range(25000):
if all(palindrome(i, base) for base in (2,4,16)):
cnt += 1
print("{:5}".format(i), end=" \n"[cnt % 12 == 0])
print()
| package main
import (
"fmt"
"rcu"
"strconv"
)
func reverse(s string) string {
chars := []rune(s)
for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
chars[i], chars[j] = chars[j], chars[i]
}
return string(chars)
}
func main() {
fmt.Println("Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:")
var numbers []int
for i := int64(0); i < 25000; i++ {
b2 := strconv.FormatInt(i, 2)
if b2 == reverse(b2) {
b4 := strconv.FormatInt(i, 4)
if b4 == reverse(b4) {
b16 := strconv.FormatInt(i, 16)
if b16 == reverse(b16) {
numbers = append(numbers, int(i))
}
}
}
}
for i, n := range numbers {
fmt.Printf("%6s ", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\n\nFound", len(numbers), "such numbers.")
}
|
Please provide an equivalent version of this Python code in Go. |
from numpy import mean
from random import sample
def gen_long_stairs(start_step, start_length, climber_steps, add_steps):
secs, behind, total = 0, start_step, start_length
while True:
behind += climber_steps
behind += sum([behind > n for n in sample(range(total), add_steps)])
total += add_steps
secs += 1
yield (secs, behind, total)
ls = gen_long_stairs(1, 100, 1, 5)
print("Seconds Behind Ahead\n----------------------")
while True:
secs, pos, len = next(ls)
if 600 <= secs < 610:
print(secs, " ", pos, " ", len - pos)
elif secs == 610:
break
print("\nTen thousand trials to top:")
times, heights = [], []
for trial in range(10_000):
trialstairs = gen_long_stairs(1, 100, 1, 5)
while True:
sec, step, height = next(trialstairs)
if step >= height:
times.append(sec)
heights.append(height)
break
print("Mean time:", mean(times), "secs. Mean height:", mean(heights))
| package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
totalSecs := 0
totalSteps := 0
fmt.Println("Seconds steps behind steps ahead")
fmt.Println("------- ------------ -----------")
for trial := 1; trial < 10000; trial++ {
sbeh := 0
slen := 100
secs := 0
for sbeh < slen {
sbeh++
for wiz := 1; wiz < 6; wiz++ {
if rand.Intn(slen) < sbeh {
sbeh++
}
slen++
}
secs++
if trial == 1 && secs > 599 && secs < 610 {
fmt.Printf("%d %d %d\n", secs, sbeh, slen-sbeh)
}
}
totalSecs += secs
totalSteps += slen
}
fmt.Println("\nAverage secs taken:", float64(totalSecs)/10000)
fmt.Println("Average final length of staircase:", float64(totalSteps)/10000)
}
|
Convert this Python snippet to Go and keep its semantics consistent. | import curses
from random import randint
stdscr = curses.initscr()
for rows in range(10):
line = ''.join([chr(randint(41, 90)) for i in range(10)])
stdscr.addstr(line + '\n')
icol = 3 - 1
irow = 6 - 1
ch = stdscr.instr(irow, icol, 1).decode(encoding="utf-8")
stdscr.move(irow, icol + 10)
stdscr.addstr('Character at column 3, row 6 = ' + ch + '\n')
stdscr.getch()
curses.endwin()
| package main
import "C"
import "fmt"
func main() {
for i := 0; i < 80*25; i++ {
fmt.Print("A")
}
fmt.Println()
conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE)
info := C.CONSOLE_SCREEN_BUFFER_INFO{}
pos := C.COORD{}
C.GetConsoleScreenBufferInfo(conOut, &info)
pos.X = info.srWindow.Left + 3
pos.Y = info.srWindow.Top + 6
var c C.wchar_t
var le C.ulong
ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le)
if ret == 0 || le <= 0 {
fmt.Println("Something went wrong!")
return
}
fmt.Printf("The character at column 3, row 6 is '%c'\n", c)
}
|
Preserve the algorithm and functionality while converting the code from Python to Go. | seed = 675248
def random():
global seed
seed = int(str(seed ** 2).zfill(12)[3:9])
return seed
for _ in range(5):
print(random())
| package main
import "fmt"
func random(seed int) int {
return seed * seed / 1e3 % 1e6
}
func main() {
seed := 675248
for i := 1; i <= 5; i++ {
seed = random(seed)
fmt.Println(seed)
}
}
|
Translate the given Python code snippet into Go without altering its behavior. | seed = 675248
def random():
global seed
seed = int(str(seed ** 2).zfill(12)[3:9])
return seed
for _ in range(5):
print(random())
| package main
import "fmt"
func random(seed int) int {
return seed * seed / 1e3 % 1e6
}
func main() {
seed := 675248
for i := 1; i <= 5; i++ {
seed = random(seed)
fmt.Println(seed)
}
}
|
Generate a Go translation of this Python snippet without changing its computational steps. |
import re
import string
DISABLED_PREFIX = ';'
class Option(object):
def __init__(self, name, value=None, disabled=False,
disabled_prefix=DISABLED_PREFIX):
self.name = str(name)
self.value = value
self.disabled = bool(disabled)
self.disabled_prefix = disabled_prefix
def __str__(self):
disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]
value = (' %s' % self.value, '')[self.value is None]
return ''.join((disabled, self.name, value))
def get(self):
enabled = not bool(self.disabled)
if self.value is None:
value = enabled
else:
value = enabled and self.value
return value
class Config(object):
reOPTION = r'^\s*(?P<disabled>%s*)\s*(?P<name>\w+)(?:\s+(?P<value>.+?))?\s*$'
def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):
self.disabled_prefix = disabled_prefix
self.contents = []
self.options = {}
self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)
if fname:
self.parse_file(fname)
def __str__(self):
return '\n'.join(map(str, self.contents))
def parse_file(self, fname):
with open(fname) as f:
self.parse_lines(f)
return self
def parse_lines(self, lines):
for line in lines:
self.parse_line(line)
return self
def parse_line(self, line):
s = ''.join(c for c in line.strip() if c in string.printable)
moOPTION = self.creOPTION.match(s)
if moOPTION:
name = moOPTION.group('name').upper()
if not name in self.options:
self.add_option(name, moOPTION.group('value'),
moOPTION.group('disabled'))
else:
if not s.startswith(self.disabled_prefix):
self.contents.append(line.rstrip())
return self
def add_option(self, name, value=None, disabled=False):
name = name.upper()
opt = Option(name, value, disabled)
self.options[name] = opt
self.contents.append(opt)
return opt
def set_option(self, name, value=None, disabled=False):
name = name.upper()
opt = self.options.get(name)
if opt:
opt.value = value
opt.disabled = disabled
else:
opt = self.add_option(name, value, disabled)
return opt
def enable_option(self, name, value=None):
return self.set_option(name, value, False)
def disable_option(self, name, value=None):
return self.set_option(name, value, True)
def get_option(self, name):
opt = self.options.get(name.upper())
value = opt.get() if opt else None
return value
if __name__ == '__main__':
import sys
cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)
cfg.disable_option('needspeeling')
cfg.enable_option('seedsremoved')
cfg.enable_option('numberofbananas', 1024)
cfg.enable_option('numberofstrawberries', 62000)
print cfg
| package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
)
type line struct {
kind lineKind
option string
value string
disabled bool
}
type lineKind int
const (
_ lineKind = iota
ignore
parseError
comment
blank
value
)
func (l line) String() string {
switch l.kind {
case ignore, parseError, comment, blank:
return l.value
case value:
s := l.option
if l.disabled {
s = "; " + s
}
if l.value != "" {
s += " " + l.value
}
return s
}
panic("unexpected line kind")
}
func removeDross(s string) string {
return strings.Map(func(r rune) rune {
if r < 32 || r > 0x7f || unicode.IsControl(r) {
return -1
}
return r
}, s)
}
func parseLine(s string) line {
if s == "" {
return line{kind: blank}
}
if s[0] == '#' {
return line{kind: comment, value: s}
}
s = removeDross(s)
fields := strings.Fields(s)
if len(fields) == 0 {
return line{kind: blank}
}
semi := false
for len(fields[0]) > 0 && fields[0][0] == ';' {
semi = true
fields[0] = fields[0][1:]
}
if fields[0] == "" {
fields = fields[1:]
}
switch len(fields) {
case 0:
return line{kind: ignore}
case 1:
return line{
kind: value,
option: strings.ToUpper(fields[0]),
disabled: semi,
}
case 2:
return line{
kind: value,
option: strings.ToUpper(fields[0]),
value: fields[1],
disabled: semi,
}
}
return line{kind: parseError, value: s}
}
type Config struct {
options map[string]int
lines []line
}
func (c *Config) index(option string) int {
if i, ok := c.options[option]; ok {
return i
}
return -1
}
func (c *Config) addLine(l line) {
switch l.kind {
case ignore:
return
case value:
if c.index(l.option) >= 0 {
return
}
c.options[l.option] = len(c.lines)
c.lines = append(c.lines, l)
default:
c.lines = append(c.lines, l)
}
}
func ReadConfig(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
r := bufio.NewReader(f)
c := &Config{options: make(map[string]int)}
for {
s, err := r.ReadString('\n')
if s != "" {
if err == nil {
s = s[:len(s)-1]
}
c.addLine(parseLine(s))
}
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
}
return c, nil
}
func (c *Config) Set(option string, val string) {
if i := c.index(option); i >= 0 {
line := &c.lines[i]
line.disabled = false
line.value = val
return
}
c.addLine(line{
kind: value,
option: option,
value: val,
})
}
func (c *Config) Enable(option string, enabled bool) {
if i := c.index(option); i >= 0 {
c.lines[i].disabled = !enabled
}
}
func (c *Config) Write(w io.Writer) {
for _, line := range c.lines {
fmt.Println(line)
}
}
func main() {
c, err := ReadConfig("/tmp/cfg")
if err != nil {
log.Fatalln(err)
}
c.Enable("NEEDSPEELING", false)
c.Set("SEEDSREMOVED", "")
c.Set("NUMBEROFBANANAS", "1024")
c.Set("NUMBEROFSTRAWBERRIES", "62000")
c.Write(os.Stdout)
}
|
Produce a functionally identical Go code for the snippet given in Python. |
from PIL import Image, ImageFilter
if __name__=="__main__":
im = Image.open("test.jpg")
kernelValues = [-2,-1,0,-1,1,1,0,1,2]
kernel = ImageFilter.Kernel((3,3), kernelValues)
im2 = im.filter(kernel)
im2.show()
| package main
import (
"fmt"
"image"
"image/color"
"image/jpeg"
"math"
"os"
)
func kf3(k *[9]float64, src, dst *image.Gray) {
for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ {
for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ {
var sum float64
var i int
for yo := y - 1; yo <= y+1; yo++ {
for xo := x - 1; xo <= x+1; xo++ {
if (image.Point{xo, yo}).In(src.Rect) {
sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y)
} else {
sum += k[i] * float64(src.At(x, y).(color.Gray).Y)
}
i++
}
}
dst.SetGray(x, y,
color.Gray{uint8(math.Min(255, math.Max(0, sum)))})
}
}
}
var blur = [9]float64{
1. / 9, 1. / 9, 1. / 9,
1. / 9, 1. / 9, 1. / 9,
1. / 9, 1. / 9, 1. / 9}
func blurY(src *image.YCbCr) *image.YCbCr {
dst := *src
if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y {
return &dst
}
srcGray := image.Gray{src.Y, src.YStride, src.Rect}
dstGray := srcGray
dstGray.Pix = make([]uint8, len(src.Y))
kf3(&blur, &srcGray, &dstGray)
dst.Y = dstGray.Pix
dst.Cb = append([]uint8{}, src.Cb...)
dst.Cr = append([]uint8{}, src.Cr...)
return &dst
}
func main() {
f, err := os.Open("Lenna100.jpg")
if err != nil {
fmt.Println(err)
return
}
img, err := jpeg.Decode(f)
if err != nil {
fmt.Println(err)
return
}
f.Close()
y, ok := img.(*image.YCbCr)
if !ok {
fmt.Println("expected color jpeg")
return
}
f, err = os.Create("blur.jpg")
if err != nil {
fmt.Println(err)
return
}
err = jpeg.Encode(f, blurY(y), &jpeg.Options{90})
if err != nil {
fmt.Println(err)
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. |
import numpy
import pprint
h = [
[[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]],
[[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]
f = [
[[-9, 5, -8], [3, 5, 1]],
[[-1, -7, 2], [-5, -6, 6]],
[[8, 5, 8],[-2, -6, -4]]]
g = [
[
[54, 42, 53, -42, 85, -72],
[45, -170, 94, -36, 48, 73],
[-39, 65, -112, -16, -78, -72],
[6, -11, -6, 62, 49, 8]],
[
[-57, 49, -23, 52, -135, 66],
[-23, 127, -58, -5, -118, 64],
[87, -16, 121, 23, -41, -12],
[-19, 29, 35, -148, -11, 45]],
[
[-55, -147, -146, -31, 55, 60],
[-88, -45, -28, 46, -26, -144],
[-12, -107, -34, 150, 249, 66],
[11, -15, -34, 27, -78, -50]],
[
[56, 67, 108, 4, 2, -48],
[58, 67, 89, 32, 32, -8],
[-42, -31, -103, -30, -23, -8],
[6, 4, -26, -10, 26, 12]]]
def trim_zero_empty(x):
if len(x) > 0:
if type(x[0]) != numpy.ndarray:
return list(numpy.trim_zeros(x))
else:
new_x = []
for l in x:
tl = trim_zero_empty(l)
if len(tl) > 0:
new_x.append(tl)
return new_x
else:
return x
def deconv(a, b):
ffta = numpy.fft.fftn(a)
ashape = numpy.shape(a)
fftb = numpy.fft.fftn(b,ashape)
fftquotient = ffta / fftb
c = numpy.fft.ifftn(fftquotient)
trimmedc = numpy.around(numpy.real(c),decimals=6)
cleanc = trim_zero_empty(trimmedc)
return cleanc
print("deconv(g,h)=")
pprint.pprint(deconv(g,h))
print(" ")
print("deconv(g,f)=")
pprint.pprint(deconv(g,f))
| package main
import (
"fmt"
"math"
"math/cmplx"
)
func fft(buf []complex128, n int) {
out := make([]complex128, n)
copy(out, buf)
fft2(buf, out, n, 1)
}
func fft2(buf, out []complex128, n, step int) {
if step < n {
fft2(out, buf, n, step*2)
fft2(out[step:], buf[step:], n, step*2)
for j := 0; j < n; j += 2 * step {
fj, fn := float64(j), float64(n)
t := cmplx.Exp(-1i*complex(math.Pi, 0)*complex(fj, 0)/complex(fn, 0)) * out[j+step]
buf[j/2] = out[j] + t
buf[(j+n)/2] = out[j] - t
}
}
}
func padTwo(g []float64, le int, ns *int) []complex128 {
n := 1
if *ns != 0 {
n = *ns
} else {
for n < le {
n *= 2
}
}
buf := make([]complex128, n)
for i := 0; i < le; i++ {
buf[i] = complex(g[i], 0)
}
*ns = n
return buf
}
func deconv(g []float64, lg int, f []float64, lf int, out []float64, rowLe int) {
ns := 0
g2 := padTwo(g, lg, &ns)
f2 := padTwo(f, lf, &ns)
fft(g2, ns)
fft(f2, ns)
h := make([]complex128, ns)
for i := 0; i < ns; i++ {
h[i] = g2[i] / f2[i]
}
fft(h, ns)
for i := 0; i < ns; i++ {
if math.Abs(real(h[i])) < 1e-10 {
h[i] = 0
}
}
for i := 0; i > lf-lg-rowLe; i-- {
out[-i] = real(h[(i+ns)%ns] / 32)
}
}
func unpack2(m [][]float64, rows, le, toLe int) []float64 {
buf := make([]float64, rows*toLe)
for i := 0; i < rows; i++ {
for j := 0; j < le; j++ {
buf[i*toLe+j] = m[i][j]
}
}
return buf
}
func pack2(buf []float64, rows, fromLe, toLe int, out [][]float64) {
for i := 0; i < rows; i++ {
for j := 0; j < toLe; j++ {
out[i][j] = buf[i*fromLe+j] / 4
}
}
}
func deconv2(g [][]float64, rowG, colG int, f [][]float64, rowF, colF int, out [][]float64) {
g2 := unpack2(g, rowG, colG, colG)
f2 := unpack2(f, rowF, colF, colG)
ff := make([]float64, (rowG-rowF+1)*colG)
deconv(g2, rowG*colG, f2, rowF*colG, ff, colG)
pack2(ff, rowG-rowF+1, colG, colG-colF+1, out)
}
func unpack3(m [][][]float64, x, y, z, toY, toZ int) []float64 {
buf := make([]float64, x*toY*toZ)
for i := 0; i < x; i++ {
for j := 0; j < y; j++ {
for k := 0; k < z; k++ {
buf[(i*toY+j)*toZ+k] = m[i][j][k]
}
}
}
return buf
}
func pack3(buf []float64, x, y, z, toY, toZ int, out [][][]float64) {
for i := 0; i < x; i++ {
for j := 0; j < toY; j++ {
for k := 0; k < toZ; k++ {
out[i][j][k] = buf[(i*y+j)*z+k] / 4
}
}
}
}
func deconv3(g [][][]float64, gx, gy, gz int, f [][][]float64, fx, fy, fz int, out [][][]float64) {
g2 := unpack3(g, gx, gy, gz, gy, gz)
f2 := unpack3(f, fx, fy, fz, gy, gz)
ff := make([]float64, (gx-fx+1)*gy*gz)
deconv(g2, gx*gy*gz, f2, fx*gy*gz, ff, gy*gz)
pack3(ff, gx-fx+1, gy, gz, gy-fy+1, gz-fz+1, out)
}
func main() {
f := [][][]float64{
{{-9, 5, -8}, {3, 5, 1}},
{{-1, -7, 2}, {-5, -6, 6}},
{{8, 5, 8}, {-2, -6, -4}},
}
fx, fy, fz := len(f), len(f[0]), len(f[0][0])
g := [][][]float64{
{{54, 42, 53, -42, 85, -72}, {45, -170, 94, -36, 48, 73},
{-39, 65, -112, -16, -78, -72}, {6, -11, -6, 62, 49, 8}},
{{-57, 49, -23, 52, -135, 66}, {-23, 127, -58, -5, -118, 64},
{87, -16, 121, 23, -41, -12}, {-19, 29, 35, -148, -11, 45}},
{{-55, -147, -146, -31, 55, 60}, {-88, -45, -28, 46, -26, -144},
{-12, -107, -34, 150, 249, 66}, {11, -15, -34, 27, -78, -50}},
{{56, 67, 108, 4, 2, -48}, {58, 67, 89, 32, 32, -8},
{-42, -31, -103, -30, -23, -8}, {6, 4, -26, -10, 26, 12},
},
}
gx, gy, gz := len(g), len(g[0]), len(g[0][0])
h := [][][]float64{
{{-6, -8, -5, 9}, {-7, 9, -6, -8}, {2, -7, 9, 8}},
{{7, 4, 4, -6}, {9, 9, 4, -4}, {-3, 7, -2, -3}},
}
hx, hy, hz := gx-fx+1, gy-fy+1, gz-fz+1
h2 := make([][][]float64, hx)
for i := 0; i < hx; i++ {
h2[i] = make([][]float64, hy)
for j := 0; j < hy; j++ {
h2[i][j] = make([]float64, hz)
}
}
deconv3(g, gx, gy, gz, f, fx, fy, fz, h2)
fmt.Println("deconv3(g, f):\n")
for i := 0; i < hx; i++ {
for j := 0; j < hy; j++ {
for k := 0; k < hz; k++ {
fmt.Printf("% .10g ", h2[i][j][k])
}
fmt.Println()
}
if i < hx-1 {
fmt.Println()
}
}
kx, ky, kz := gx-hx+1, gy-hy+1, gz-hz+1
f2 := make([][][]float64, kx)
for i := 0; i < kx; i++ {
f2[i] = make([][]float64, ky)
for j := 0; j < ky; j++ {
f2[i][j] = make([]float64, kz)
}
}
deconv3(g, gx, gy, gz, h, hx, hy, hz, f2)
fmt.Println("\ndeconv(g, h):\n")
for i := 0; i < kx; i++ {
for j := 0; j < ky; j++ {
for k := 0; k < kz; k++ {
fmt.Printf("% .10g ", f2[i][j][k])
}
fmt.Println()
}
if i < kx-1 {
fmt.Println()
}
}
}
|
Write the same algorithm in Go as shown in this Python implementation. | from itertools import product
def gen_dict(n_faces, n_dice):
counts = [0] * ((n_faces + 1) * n_dice)
for t in product(range(1, n_faces + 1), repeat=n_dice):
counts[sum(t)] += 1
return counts, n_faces ** n_dice
def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):
c1, p1 = gen_dict(n_sides1, n_dice1)
c2, p2 = gen_dict(n_sides2, n_dice2)
p12 = float(p1 * p2)
return sum(p[1] * q[1] / p12
for p, q in product(enumerate(c1), enumerate(c2))
if p[0] > q[0])
print beating_probability(4, 9, 6, 6)
print beating_probability(10, 5, 7, 6)
| package main
import(
"math"
"fmt"
)
func minOf(x, y uint) uint {
if x < y {
return x
}
return y
}
func throwDie(nSides, nDice, s uint, counts []uint) {
if nDice == 0 {
counts[s]++
return
}
for i := uint(1); i <= nSides; i++ {
throwDie(nSides, nDice - 1, s + i, counts)
}
}
func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {
len1 := (nSides1 + 1) * nDice1
c1 := make([]uint, len1)
throwDie(nSides1, nDice1, 0, c1)
len2 := (nSides2 + 1) * nDice2
c2 := make([]uint, len2)
throwDie(nSides2, nDice2, 0, c2)
p12 := math.Pow(float64(nSides1), float64(nDice1)) *
math.Pow(float64(nSides2), float64(nDice2))
tot := 0.0
for i := uint(0); i < len1; i++ {
for j := uint(0); j < minOf(i, len2); j++ {
tot += float64(c1[i] * c2[j]) / p12
}
}
return tot
}
func main() {
fmt.Println(beatingProbability(4, 9, 6, 6))
fmt.Println(beatingProbability(10, 5, 7, 6))
}
|
Write the same algorithm in Go as shown in this Python implementation. | from logpy import *
from logpy.core import lall
import time
def lefto(q, p, list):
return membero((q,p), zip(list, list[1:]))
def nexto(q, p, list):
return conde([lefto(q, p, list)], [lefto(p, q, list)])
houses = var()
zebraRules = lall(
(eq, (var(), var(), var(), var(), var()), houses),
(membero, ('Englishman', var(), var(), var(), 'red'), houses),
(membero, ('Swede', var(), var(), 'dog', var()), houses),
(membero, ('Dane', var(), 'tea', var(), var()), houses),
(lefto, (var(), var(), var(), var(), 'green'),
(var(), var(), var(), var(), 'white'), houses),
(membero, (var(), var(), 'coffee', var(), 'green'), houses),
(membero, (var(), 'Pall Mall', var(), 'birds', var()), houses),
(membero, (var(), 'Dunhill', var(), var(), 'yellow'), houses),
(eq, (var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),
(eq, (('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),
(nexto, (var(), 'Blend', var(), var(), var()),
(var(), var(), var(), 'cats', var()), houses),
(nexto, (var(), 'Dunhill', var(), var(), var()),
(var(), var(), var(), 'horse', var()), houses),
(membero, (var(), 'Blue Master', 'beer', var(), var()), houses),
(membero, ('German', 'Prince', var(), var(), var()), houses),
(nexto, ('Norwegian', var(), var(), var(), var()),
(var(), var(), var(), var(), 'blue'), houses),
(nexto, (var(), 'Blend', var(), var(), var()),
(var(), var(), 'water', var(), var()), houses),
(membero, (var(), var(), var(), 'zebra', var()), houses)
)
t0 = time.time()
solutions = run(0, houses, zebraRules)
t1 = time.time()
dur = t1-t0
count = len(solutions)
zebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]
print "%i solutions in %.2f seconds" % (count, dur)
print "The %s is the owner of the zebra" % zebraOwner
print "Here are all the houses:"
for line in solutions[0]:
print str(line)
| package main
import (
"fmt"
"log"
"strings"
)
type HouseSet [5]*House
type House struct {
n Nationality
c Colour
a Animal
d Drink
s Smoke
}
type Nationality int8
type Colour int8
type Animal int8
type Drink int8
type Smoke int8
const (
English Nationality = iota
Swede
Dane
Norwegian
German
)
const (
Red Colour = iota
Green
White
Yellow
Blue
)
const (
Dog Animal = iota
Birds
Cats
Horse
Zebra
)
const (
Tea Drink = iota
Coffee
Milk
Beer
Water
)
const (
PallMall Smoke = iota
Dunhill
Blend
BlueMaster
Prince
)
var nationalities = [...]string{"English", "Swede", "Dane", "Norwegian", "German"}
var colours = [...]string{"red", "green", "white", "yellow", "blue"}
var animals = [...]string{"dog", "birds", "cats", "horse", "zebra"}
var drinks = [...]string{"tea", "coffee", "milk", "beer", "water"}
var smokes = [...]string{"Pall Mall", "Dunhill", "Blend", "Blue Master", "Prince"}
func (n Nationality) String() string { return nationalities[n] }
func (c Colour) String() string { return colours[c] }
func (a Animal) String() string { return animals[a] }
func (d Drink) String() string { return drinks[d] }
func (s Smoke) String() string { return smokes[s] }
func (h House) String() string {
return fmt.Sprintf("%-9s %-6s %-5s %-6s %s", h.n, h.c, h.a, h.d, h.s)
}
func (hs HouseSet) String() string {
lines := make([]string, 0, len(hs))
for i, h := range hs {
s := fmt.Sprintf("%d %s", i, h)
lines = append(lines, s)
}
return strings.Join(lines, "\n")
}
func simpleBruteForce() (int, HouseSet) {
var v []House
for n := range nationalities {
for c := range colours {
for a := range animals {
for d := range drinks {
for s := range smokes {
h := House{
n: Nationality(n),
c: Colour(c),
a: Animal(a),
d: Drink(d),
s: Smoke(s),
}
if !h.Valid() {
continue
}
v = append(v, h)
}
}
}
}
}
n := len(v)
log.Println("Generated", n, "valid houses")
combos := 0
first := 0
valid := 0
var validSet HouseSet
for a := 0; a < n; a++ {
if v[a].n != Norwegian {
continue
}
for b := 0; b < n; b++ {
if b == a {
continue
}
if v[b].anyDups(&v[a]) {
continue
}
for c := 0; c < n; c++ {
if c == b || c == a {
continue
}
if v[c].d != Milk {
continue
}
if v[c].anyDups(&v[b], &v[a]) {
continue
}
for d := 0; d < n; d++ {
if d == c || d == b || d == a {
continue
}
if v[d].anyDups(&v[c], &v[b], &v[a]) {
continue
}
for e := 0; e < n; e++ {
if e == d || e == c || e == b || e == a {
continue
}
if v[e].anyDups(&v[d], &v[c], &v[b], &v[a]) {
continue
}
combos++
set := HouseSet{&v[a], &v[b], &v[c], &v[d], &v[e]}
if set.Valid() {
valid++
if valid == 1 {
first = combos
}
validSet = set
}
}
}
}
}
}
log.Println("Tested", first, "different combinations of valid houses before finding solution")
log.Println("Tested", combos, "different combinations of valid houses in total")
return valid, validSet
}
func (h *House) anyDups(list ...*House) bool {
for _, b := range list {
if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s {
return true
}
}
return false
}
func (h *House) Valid() bool {
if h.n == English && h.c != Red || h.n != English && h.c == Red {
return false
}
if h.n == Swede && h.a != Dog || h.n != Swede && h.a == Dog {
return false
}
if h.n == Dane && h.d != Tea || h.n != Dane && h.d == Tea {
return false
}
if h.c == Green && h.d != Coffee || h.c != Green && h.d == Coffee {
return false
}
if h.a == Birds && h.s != PallMall || h.a != Birds && h.s == PallMall {
return false
}
if h.c == Yellow && h.s != Dunhill || h.c != Yellow && h.s == Dunhill {
return false
}
if h.a == Cats && h.s == Blend {
return false
}
if h.a == Horse && h.s == Dunhill {
return false
}
if h.d == Beer && h.s != BlueMaster || h.d != Beer && h.s == BlueMaster {
return false
}
if h.n == German && h.s != Prince || h.n != German && h.s == Prince {
return false
}
if h.n == Norwegian && h.c == Blue {
return false
}
if h.d == Water && h.s == Blend {
return false
}
return true
}
func (hs *HouseSet) Valid() bool {
ni := make(map[Nationality]int, 5)
ci := make(map[Colour]int, 5)
ai := make(map[Animal]int, 5)
di := make(map[Drink]int, 5)
si := make(map[Smoke]int, 5)
for i, h := range hs {
ni[h.n] = i
ci[h.c] = i
ai[h.a] = i
di[h.d] = i
si[h.s] = i
}
if ci[Green]+1 != ci[White] {
return false
}
if dist(ai[Cats], si[Blend]) != 1 {
return false
}
if dist(ai[Horse], si[Dunhill]) != 1 {
return false
}
if dist(ni[Norwegian], ci[Blue]) != 1 {
return false
}
if dist(di[Water], si[Blend]) != 1 {
return false
}
if hs[2].d != Milk {
return false
}
if hs[0].n != Norwegian {
return false
}
return true
}
func dist(a, b int) int {
if a > b {
return a - b
}
return b - a
}
func main() {
log.SetFlags(0)
n, sol := simpleBruteForce()
fmt.Println(n, "solution found")
fmt.Println(sol)
}
|
Translate this program into Go but keep the logic exactly as in Python. |
from operator import attrgetter
from typing import Iterator
import mwclient
URL = 'www.rosettacode.org'
API_PATH = '/mw/'
def unimplemented_tasks(language: str,
*,
url: str,
api_path: str) -> Iterator[str]:
site = mwclient.Site(url, path=api_path)
all_tasks = site.categories['Programming Tasks']
language_tasks = site.categories[language]
name = attrgetter('name')
all_tasks_names = map(name, all_tasks)
language_tasks_names = set(map(name, language_tasks))
for task in all_tasks_names:
if task not in language_tasks_names:
yield task
if __name__ == '__main__':
tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)
print(*tasks, sep='\n')
| package main
import (
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
)
const language = "Go"
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=100"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
fmt.Println(err)
return ""
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
fmt.Println(err)
return ""
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) { langMap[cm] = true }
languageQuery := baseQuery + "&cmtitle=Category:" + language
continueAt := req(languageQuery, storeLang)
for continueAt > "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
if len(langMap) == 0 {
fmt.Println("no tasks implemented for", language)
return
}
printUnImp := func(cm string) {
if !langMap[cm] {
fmt.Println(cm)
}
}
taskQuery := baseQuery + "&cmtitle=Category:Programming_Tasks"
continueAt = req(taskQuery, printUnImp)
for continueAt > "" {
continueAt = req(taskQuery+"&cmcontinue="+continueAt, printUnImp)
}
}
|
Convert this Python snippet to Go and keep its semantics consistent. | IDLE 2.6.1
>>>
>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25
>>>
>>> z = x + y
>>> zi = 1.0 / (x + y)
>>>
>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)
>>>
>>> numlist = [x, y, z]
>>> numlisti = [xi, yi, zi]
>>>
>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]
[0.5, 0.5, 0.5]
>>>
| package main
import "fmt"
func main() {
x := 2.
xi := .5
y := 4.
yi := .25
z := x + y
zi := 1 / (x + y)
numbers := []float64{x, y, z}
inverses := []float64{xi, yi, zi}
mfs := make([]func(float64) float64, len(numbers))
for i := range mfs {
mfs[i] = multiplier(numbers[i], inverses[i])
}
for _, mf := range mfs {
fmt.Println(mf(1))
}
}
func multiplier(n1, n2 float64) func(float64) float64 {
n1n2 := n1 * n2
return func(m float64) float64 {
return n1n2 * m
}
}
|
Write a version of this Python function in Go with identical behavior. | IDLE 2.6.1
>>>
>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25
>>>
>>> z = x + y
>>> zi = 1.0 / (x + y)
>>>
>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)
>>>
>>> numlist = [x, y, z]
>>> numlisti = [xi, yi, zi]
>>>
>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]
[0.5, 0.5, 0.5]
>>>
| package main
import "fmt"
func main() {
x := 2.
xi := .5
y := 4.
yi := .25
z := x + y
zi := 1 / (x + y)
numbers := []float64{x, y, z}
inverses := []float64{xi, yi, zi}
mfs := make([]func(float64) float64, len(numbers))
for i := range mfs {
mfs[i] = multiplier(numbers[i], inverses[i])
}
for _, mf := range mfs {
fmt.Println(mf(1))
}
}
func multiplier(n1, n2 float64) func(float64) float64 {
n1n2 := n1 * n2
return func(m float64) float64 {
return n1n2 * m
}
}
|
Keep all operations the same but rewrite the snippet in Go. | from array import array
from collections import deque
import psyco
data = []
nrows = 0
px = py = 0
sdata = ""
ddata = ""
def init(board):
global data, nrows, sdata, ddata, px, py
data = filter(None, board.splitlines())
nrows = max(len(r) for r in data)
maps = {' ':' ', '.': '.', '@':' ', '
mapd = {' ':' ', '.': ' ', '@':'@', '
for r, row in enumerate(data):
for c, ch in enumerate(row):
sdata += maps[ch]
ddata += mapd[ch]
if ch == '@':
px = c
py = r
def push(x, y, dx, dy, data):
if sdata[(y+2*dy) * nrows + x+2*dx] == '
data[(y+2*dy) * nrows + x+2*dx] != ' ':
return None
data2 = array("c", data)
data2[y * nrows + x] = ' '
data2[(y+dy) * nrows + x+dx] = '@'
data2[(y+2*dy) * nrows + x+2*dx] = '*'
return data2.tostring()
def is_solved(data):
for i in xrange(len(data)):
if (sdata[i] == '.') != (data[i] == '*'):
return False
return True
def solve():
open = deque([(ddata, "", px, py)])
visited = set([ddata])
dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),
(0, 1, 'd', 'D'), (-1, 0, 'l', 'L'))
lnrows = nrows
while open:
cur, csol, x, y = open.popleft()
for di in dirs:
temp = cur
dx, dy = di[0], di[1]
if temp[(y+dy) * lnrows + x+dx] == '*':
temp = push(x, y, dx, dy, temp)
if temp and temp not in visited:
if is_solved(temp):
return csol + di[3]
open.append((temp, csol + di[3], x+dx, y+dy))
visited.add(temp)
else:
if sdata[(y+dy) * lnrows + x+dx] == '
temp[(y+dy) * lnrows + x+dx] != ' ':
continue
data2 = array("c", temp)
data2[y * lnrows + x] = ' '
data2[(y+dy) * lnrows + x+dx] = '@'
temp = data2.tostring()
if temp not in visited:
if is_solved(temp):
return csol + di[2]
open.append((temp, csol + di[2], x+dx, y+dy))
visited.add(temp)
return "No solution"
level = """\
psyco.full()
init(level)
print level, "\n\n", solve()
| package main
import (
"fmt"
"strings"
)
func main() {
level := `
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######`
fmt.Printf("level:%s\n", level)
fmt.Printf("solution:\n%s\n", solve(level))
}
func solve(board string) string {
buffer = make([]byte, len(board))
width := strings.Index(board[1:], "\n") + 1
dirs := []struct {
move, push string
dPos int
}{
{"u", "U", -width},
{"r", "R", 1},
{"d", "D", width},
{"l", "L", -1},
}
visited := map[string]bool{board: true}
open := []state{state{board, "", strings.Index(board, "@")}}
for len(open) > 0 {
s1 := &open[0]
open = open[1:]
for _, dir := range dirs {
var newBoard, newSol string
newPos := s1.pos + dir.dPos
switch s1.board[newPos] {
case '$', '*':
newBoard = s1.push(dir.dPos)
if newBoard == "" || visited[newBoard] {
continue
}
newSol = s1.cSol + dir.push
if strings.IndexAny(newBoard, ".+") < 0 {
return newSol
}
case ' ', '.':
newBoard = s1.move(dir.dPos)
if visited[newBoard] {
continue
}
newSol = s1.cSol + dir.move
default:
continue
}
open = append(open, state{newBoard, newSol, newPos})
visited[newBoard] = true
}
}
return "No solution"
}
type state struct {
board string
cSol string
pos int
}
var buffer []byte
func (s *state) move(dPos int) string {
copy(buffer, s.board)
if buffer[s.pos] == '@' {
buffer[s.pos] = ' '
} else {
buffer[s.pos] = '.'
}
newPos := s.pos + dPos
if buffer[newPos] == ' ' {
buffer[newPos] = '@'
} else {
buffer[newPos] = '+'
}
return string(buffer)
}
func (s *state) push(dPos int) string {
newPos := s.pos + dPos
boxPos := newPos + dPos
switch s.board[boxPos] {
case ' ', '.':
default:
return ""
}
copy(buffer, s.board)
if buffer[s.pos] == '@' {
buffer[s.pos] = ' '
} else {
buffer[s.pos] = '.'
}
if buffer[newPos] == '$' {
buffer[newPos] = '@'
} else {
buffer[newPos] = '+'
}
if buffer[boxPos] == ' ' {
buffer[boxPos] = '$'
} else {
buffer[boxPos] = '*'
}
return string(buffer)
}
|
Generate a Go translation of this Python snippet without changing its computational steps. | import mpmath as mp
with mp.workdps(72):
def integer_term(n):
p = 532 * n * n + 126 * n + 9
return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)
def exponent_term(n):
return -(mp.mpf("6.0") * n + 3)
def nthterm(n):
return integer_term(n) * mp.mpf("10.0")**exponent_term(n)
for n in range(10):
print("Term ", n, ' ', int(integer_term(n)))
def almkvist_guillera(floatprecision):
summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')
for n in range(100000000):
nextadd = summed + nthterm(n)
if abs(nextadd - summed) < 10.0**(-floatprecision):
break
summed = nextadd
return nextadd
print('\nπ to 70 digits is ', end='')
mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)
print('mpmath π is ', end='')
mp.nprint(mp.pi, 71)
| package main
import (
"fmt"
"math/big"
"strings"
)
func factorial(n int64) *big.Int {
var z big.Int
return z.MulRange(1, n)
}
var one = big.NewInt(1)
var three = big.NewInt(3)
var six = big.NewInt(6)
var ten = big.NewInt(10)
var seventy = big.NewInt(70)
func almkvistGiullera(n int64, print bool) *big.Rat {
t1 := big.NewInt(32)
t1.Mul(factorial(6*n), t1)
t2 := big.NewInt(532*n*n + 126*n + 9)
t3 := new(big.Int)
t3.Exp(factorial(n), six, nil)
t3.Mul(t3, three)
ip := new(big.Int)
ip.Mul(t1, t2)
ip.Quo(ip, t3)
pw := 6*n + 3
t1.SetInt64(pw)
tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))
if print {
fmt.Printf("%d %44d %3d %-35s\n", n, ip, -pw, tm.FloatString(33))
}
return tm
}
func main() {
fmt.Println("N Integer Portion Pow Nth Term (33 dp)")
fmt.Println(strings.Repeat("-", 89))
for n := int64(0); n < 10; n++ {
almkvistGiullera(n, true)
}
sum := new(big.Rat)
prev := new(big.Rat)
pow70 := new(big.Int).Exp(ten, seventy, nil)
prec := new(big.Rat).SetFrac(one, pow70)
n := int64(0)
for {
term := almkvistGiullera(n, false)
sum.Add(sum, term)
z := new(big.Rat).Sub(sum, prev)
z.Abs(z)
if z.Cmp(prec) < 0 {
break
}
prev.Set(sum)
n++
}
sum.Inv(sum)
pi := new(big.Float).SetPrec(256).SetRat(sum)
pi.Sqrt(pi)
fmt.Println("\nPi to 70 decimal places is:")
fmt.Println(pi.Text('f', 70))
}
|
Generate a Go translation of this Python snippet without changing its computational steps. | import mpmath as mp
with mp.workdps(72):
def integer_term(n):
p = 532 * n * n + 126 * n + 9
return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)
def exponent_term(n):
return -(mp.mpf("6.0") * n + 3)
def nthterm(n):
return integer_term(n) * mp.mpf("10.0")**exponent_term(n)
for n in range(10):
print("Term ", n, ' ', int(integer_term(n)))
def almkvist_guillera(floatprecision):
summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')
for n in range(100000000):
nextadd = summed + nthterm(n)
if abs(nextadd - summed) < 10.0**(-floatprecision):
break
summed = nextadd
return nextadd
print('\nπ to 70 digits is ', end='')
mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)
print('mpmath π is ', end='')
mp.nprint(mp.pi, 71)
| package main
import (
"fmt"
"math/big"
"strings"
)
func factorial(n int64) *big.Int {
var z big.Int
return z.MulRange(1, n)
}
var one = big.NewInt(1)
var three = big.NewInt(3)
var six = big.NewInt(6)
var ten = big.NewInt(10)
var seventy = big.NewInt(70)
func almkvistGiullera(n int64, print bool) *big.Rat {
t1 := big.NewInt(32)
t1.Mul(factorial(6*n), t1)
t2 := big.NewInt(532*n*n + 126*n + 9)
t3 := new(big.Int)
t3.Exp(factorial(n), six, nil)
t3.Mul(t3, three)
ip := new(big.Int)
ip.Mul(t1, t2)
ip.Quo(ip, t3)
pw := 6*n + 3
t1.SetInt64(pw)
tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))
if print {
fmt.Printf("%d %44d %3d %-35s\n", n, ip, -pw, tm.FloatString(33))
}
return tm
}
func main() {
fmt.Println("N Integer Portion Pow Nth Term (33 dp)")
fmt.Println(strings.Repeat("-", 89))
for n := int64(0); n < 10; n++ {
almkvistGiullera(n, true)
}
sum := new(big.Rat)
prev := new(big.Rat)
pow70 := new(big.Int).Exp(ten, seventy, nil)
prec := new(big.Rat).SetFrac(one, pow70)
n := int64(0)
for {
term := almkvistGiullera(n, false)
sum.Add(sum, term)
z := new(big.Rat).Sub(sum, prev)
z.Abs(z)
if z.Cmp(prec) < 0 {
break
}
prev.Set(sum)
n++
}
sum.Inv(sum)
pi := new(big.Float).SetPrec(256).SetRat(sum)
pi.Sqrt(pi)
fmt.Println("\nPi to 70 decimal places is:")
fmt.Println(pi.Text('f', 70))
}
|
Generate an equivalent Go version of this Python code. | import mpmath as mp
with mp.workdps(72):
def integer_term(n):
p = 532 * n * n + 126 * n + 9
return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)
def exponent_term(n):
return -(mp.mpf("6.0") * n + 3)
def nthterm(n):
return integer_term(n) * mp.mpf("10.0")**exponent_term(n)
for n in range(10):
print("Term ", n, ' ', int(integer_term(n)))
def almkvist_guillera(floatprecision):
summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')
for n in range(100000000):
nextadd = summed + nthterm(n)
if abs(nextadd - summed) < 10.0**(-floatprecision):
break
summed = nextadd
return nextadd
print('\nπ to 70 digits is ', end='')
mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)
print('mpmath π is ', end='')
mp.nprint(mp.pi, 71)
| package main
import (
"fmt"
"math/big"
"strings"
)
func factorial(n int64) *big.Int {
var z big.Int
return z.MulRange(1, n)
}
var one = big.NewInt(1)
var three = big.NewInt(3)
var six = big.NewInt(6)
var ten = big.NewInt(10)
var seventy = big.NewInt(70)
func almkvistGiullera(n int64, print bool) *big.Rat {
t1 := big.NewInt(32)
t1.Mul(factorial(6*n), t1)
t2 := big.NewInt(532*n*n + 126*n + 9)
t3 := new(big.Int)
t3.Exp(factorial(n), six, nil)
t3.Mul(t3, three)
ip := new(big.Int)
ip.Mul(t1, t2)
ip.Quo(ip, t3)
pw := 6*n + 3
t1.SetInt64(pw)
tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))
if print {
fmt.Printf("%d %44d %3d %-35s\n", n, ip, -pw, tm.FloatString(33))
}
return tm
}
func main() {
fmt.Println("N Integer Portion Pow Nth Term (33 dp)")
fmt.Println(strings.Repeat("-", 89))
for n := int64(0); n < 10; n++ {
almkvistGiullera(n, true)
}
sum := new(big.Rat)
prev := new(big.Rat)
pow70 := new(big.Int).Exp(ten, seventy, nil)
prec := new(big.Rat).SetFrac(one, pow70)
n := int64(0)
for {
term := almkvistGiullera(n, false)
sum.Add(sum, term)
z := new(big.Rat).Sub(sum, prev)
z.Abs(z)
if z.Cmp(prec) < 0 {
break
}
prev.Set(sum)
n++
}
sum.Inv(sum)
pi := new(big.Float).SetPrec(256).SetRat(sum)
pi.Sqrt(pi)
fmt.Println("\nPi to 70 decimal places is:")
fmt.Println(pi.Text('f', 70))
}
|
Change the following Python code into Go without altering its purpose. | from itertools import chain, cycle, accumulate, combinations
from typing import List, Tuple
def factors5(n: int) -> List[int]:
def prime_powers(n):
for c in accumulate(chain([2, 1, 2], cycle([2,4]))):
if c*c > n: break
if n%c: continue
d,p = (), c
while not n%c:
n,p,d = n//c, p*c, d + (p,)
yield(d)
if n > 1: yield((n,))
r = [1]
for e in prime_powers(n):
r += [a*b for a in r for b in e]
return r[:-1]
def powerset(s: List[int]) -> List[Tuple[int, ...]]:
return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))
def is_practical(x: int) -> bool:
if x == 1:
return True
if x %2:
return False
f = factors5(x)
ps = powerset(f)
found = {y for y in {sum(i) for i in ps}
if 1 <= y < x}
return len(found) == x - 1
if __name__ == '__main__':
n = 333
p = [x for x in range(1, n + 1) if is_practical(x)]
print(f"There are {len(p)} Practical numbers from 1 to {n}:")
print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])
x = 666
print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
| package main
import (
"fmt"
"rcu"
)
func powerset(set []int) [][]int {
if len(set) == 0 {
return [][]int{{}}
}
head := set[0]
tail := set[1:]
p1 := powerset(tail)
var p2 [][]int
for _, s := range powerset(tail) {
h := []int{head}
h = append(h, s...)
p2 = append(p2, h)
}
return append(p1, p2...)
}
func isPractical(n int) bool {
if n == 1 {
return true
}
divs := rcu.ProperDivisors(n)
subsets := powerset(divs)
found := make([]bool, n)
count := 0
for _, subset := range subsets {
sum := rcu.SumInts(subset)
if sum > 0 && sum < n && !found[sum] {
found[sum] = true
count++
if count == n-1 {
return true
}
}
}
return false
}
func main() {
fmt.Println("In the range 1..333, there are:")
var practical []int
for i := 1; i <= 333; i++ {
if isPractical(i) {
practical = append(practical, i)
}
}
fmt.Println(" ", len(practical), "practical numbers")
fmt.Println(" The first ten are", practical[0:10])
fmt.Println(" The final ten are", practical[len(practical)-10:])
fmt.Println("\n666 is practical:", isPractical(666))
}
|
Port the following code from Python to Go with equivalent syntax and logic. | from sympy import sieve
primelist = list(sieve.primerange(2,1000000))
listlen = len(primelist)
pindex = 1
old_diff = -1
curr_list=[primelist[0]]
longest_list=[]
while pindex < listlen:
diff = primelist[pindex] - primelist[pindex-1]
if diff > old_diff:
curr_list.append(primelist[pindex])
if len(curr_list) > len(longest_list):
longest_list = curr_list
else:
curr_list = [primelist[pindex-1],primelist[pindex]]
old_diff = diff
pindex += 1
print(longest_list)
pindex = 1
old_diff = -1
curr_list=[primelist[0]]
longest_list=[]
while pindex < listlen:
diff = primelist[pindex] - primelist[pindex-1]
if diff < old_diff:
curr_list.append(primelist[pindex])
if len(curr_list) > len(longest_list):
longest_list = curr_list
else:
curr_list = [primelist[pindex-1],primelist[pindex]]
old_diff = diff
pindex += 1
print(longest_list)
| package main
import (
"fmt"
"rcu"
)
const LIMIT = 999999
var primes = rcu.Primes(LIMIT)
func longestSeq(dir string) {
pd := 0
longSeqs := [][]int{{2}}
currSeq := []int{2}
for i := 1; i < len(primes); i++ {
d := primes[i] - primes[i-1]
if (dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd) {
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
currSeq = []int{primes[i-1], primes[i]}
} else {
currSeq = append(currSeq, primes[i])
}
pd = d
}
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":")
for _, ls := range longSeqs {
var diffs []int
for i := 1; i < len(ls); i++ {
diffs = append(diffs, ls[i]-ls[i-1])
}
for i := 0; i < len(ls)-1; i++ {
fmt.Print(ls[i], " (", diffs[i], ") ")
}
fmt.Println(ls[len(ls)-1])
}
fmt.Println()
}
func main() {
fmt.Println("For primes < 1 million:\n")
for _, dir := range []string{"ascending", "descending"} {
longestSeq(dir)
}
}
|
Port the provided Python code into Go while preserving the original functionality. | from sys import stdout
neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]
exists = []
lastNumber = 0
wid = 0
hei = 0
def find_next(pa, x, y, z):
for i in range(4):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if wid > a > -1 and hei > b > -1:
if pa[a][b] == z:
return a, b
return -1, -1
def find_solution(pa, x, y, z):
if z > lastNumber:
return 1
if exists[z] == 1:
s = find_next(pa, x, y, z)
if s[0] < 0:
return 0
return find_solution(pa, s[0], s[1], z + 1)
for i in range(4):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if wid > a > -1 and hei > b > -1:
if pa[a][b] == 0:
pa[a][b] = z
r = find_solution(pa, a, b, z + 1)
if r == 1:
return 1
pa[a][b] = 0
return 0
def solve(pz, w, h):
global lastNumber, wid, hei, exists
lastNumber = w * h
wid = w
hei = h
exists = [0 for j in range(lastNumber + 1)]
pa = [[0 for j in range(h)] for i in range(w)]
st = pz.split()
idx = 0
for j in range(h):
for i in range(w):
if st[idx] == ".":
idx += 1
else:
pa[i][j] = int(st[idx])
exists[pa[i][j]] = 1
idx += 1
x = 0
y = 0
t = w * h + 1
for j in range(h):
for i in range(w):
if pa[i][j] != 0 and pa[i][j] < t:
t = pa[i][j]
x = i
y = j
return find_solution(pa, x, y, t + 1), pa
def show_result(r):
if r[0] == 1:
for j in range(hei):
for i in range(wid):
stdout.write(" {:0{}d}".format(r[1][i][j], 2))
print()
else:
stdout.write("No Solution!\n")
print()
r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17"
" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9)
show_result(r)
r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37"
" . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9)
show_result(r)
r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55"
" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9)
show_result(r)
| package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
var example1 = []string{
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00",
}
var example2 = []string{
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00",
}
var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
var (
grid [][]int
clues []int
totalToFill = 0
)
func solve(r, c, count, nextClue int) bool {
if count > totalToFill {
return true
}
back := grid[r][c]
if back != 0 && back != count {
return false
}
if back == 0 && nextClue < len(clues) && clues[nextClue] == count {
return false
}
if back == count {
nextClue++
}
grid[r][c] = count
for _, move := range moves {
if solve(r+move[1], c+move[0], count+1, nextClue) {
return true
}
}
grid[r][c] = back
return false
}
func printResult(n int) {
fmt.Println("Solution for example", n, "\b:")
for _, row := range grid {
for _, i := range row {
if i == -1 {
continue
}
fmt.Printf("%2d ", i)
}
fmt.Println()
}
}
func main() {
for n, board := range [2][]string{example1, example2} {
nRows := len(board) + 2
nCols := len(strings.Split(board[0], ",")) + 2
startRow, startCol := 0, 0
grid = make([][]int, nRows)
totalToFill = (nRows - 2) * (nCols - 2)
var lst []int
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
if r >= 1 && r < nRows-1 {
row := strings.Split(board[r-1], ",")
for c := 1; c < nCols-1; c++ {
val, _ := strconv.Atoi(row[c-1])
if val > 0 {
lst = append(lst, val)
}
if val == 1 {
startRow, startCol = r, c
}
grid[r][c] = val
}
}
}
sort.Ints(lst)
clues = lst
if solve(startRow, startCol, 1, 0) {
printResult(n + 1)
}
}
}
|
Can you help me rewrite this code in Go instead of Python, keeping it the same logically? | from sys import stdout
neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]
exists = []
lastNumber = 0
wid = 0
hei = 0
def find_next(pa, x, y, z):
for i in range(4):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if wid > a > -1 and hei > b > -1:
if pa[a][b] == z:
return a, b
return -1, -1
def find_solution(pa, x, y, z):
if z > lastNumber:
return 1
if exists[z] == 1:
s = find_next(pa, x, y, z)
if s[0] < 0:
return 0
return find_solution(pa, s[0], s[1], z + 1)
for i in range(4):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if wid > a > -1 and hei > b > -1:
if pa[a][b] == 0:
pa[a][b] = z
r = find_solution(pa, a, b, z + 1)
if r == 1:
return 1
pa[a][b] = 0
return 0
def solve(pz, w, h):
global lastNumber, wid, hei, exists
lastNumber = w * h
wid = w
hei = h
exists = [0 for j in range(lastNumber + 1)]
pa = [[0 for j in range(h)] for i in range(w)]
st = pz.split()
idx = 0
for j in range(h):
for i in range(w):
if st[idx] == ".":
idx += 1
else:
pa[i][j] = int(st[idx])
exists[pa[i][j]] = 1
idx += 1
x = 0
y = 0
t = w * h + 1
for j in range(h):
for i in range(w):
if pa[i][j] != 0 and pa[i][j] < t:
t = pa[i][j]
x = i
y = j
return find_solution(pa, x, y, t + 1), pa
def show_result(r):
if r[0] == 1:
for j in range(hei):
for i in range(wid):
stdout.write(" {:0{}d}".format(r[1][i][j], 2))
print()
else:
stdout.write("No Solution!\n")
print()
r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17"
" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9)
show_result(r)
r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37"
" . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9)
show_result(r)
r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55"
" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9)
show_result(r)
| package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
var example1 = []string{
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00",
}
var example2 = []string{
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00",
}
var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
var (
grid [][]int
clues []int
totalToFill = 0
)
func solve(r, c, count, nextClue int) bool {
if count > totalToFill {
return true
}
back := grid[r][c]
if back != 0 && back != count {
return false
}
if back == 0 && nextClue < len(clues) && clues[nextClue] == count {
return false
}
if back == count {
nextClue++
}
grid[r][c] = count
for _, move := range moves {
if solve(r+move[1], c+move[0], count+1, nextClue) {
return true
}
}
grid[r][c] = back
return false
}
func printResult(n int) {
fmt.Println("Solution for example", n, "\b:")
for _, row := range grid {
for _, i := range row {
if i == -1 {
continue
}
fmt.Printf("%2d ", i)
}
fmt.Println()
}
}
func main() {
for n, board := range [2][]string{example1, example2} {
nRows := len(board) + 2
nCols := len(strings.Split(board[0], ",")) + 2
startRow, startCol := 0, 0
grid = make([][]int, nRows)
totalToFill = (nRows - 2) * (nCols - 2)
var lst []int
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
if r >= 1 && r < nRows-1 {
row := strings.Split(board[r-1], ",")
for c := 1; c < nCols-1; c++ {
val, _ := strconv.Atoi(row[c-1])
if val > 0 {
lst = append(lst, val)
}
if val == 1 {
startRow, startCol = r, c
}
grid[r][c] = val
}
}
}
sort.Ints(lst)
clues = lst
if solve(startRow, startCol, 1, 0) {
printResult(n + 1)
}
}
}
|
Convert this Python block to Go, preserving its control flow and logic. |
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
def churchExp(m):
return lambda n: n(m)
def churchFromInt(n):
return lambda f: (
foldl
(compose)
(identity)
(replicate(n)(f))
)
def churchFromInt_(n):
if 0 == n:
return churchZero()
else:
return churchSucc(churchFromInt(n - 1))
def intFromChurch(cn):
return cn(succ)(0)
def main():
'Tests'
cThree = churchFromInt(3)
cFour = churchFromInt(4)
print(list(map(intFromChurch, [
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
])))
def compose(f):
return lambda g: lambda x: g(f(x))
def foldl(f):
def go(acc, xs):
return reduce(lambda a, x: f(a)(x), xs, acc)
return lambda acc: lambda xs: go(acc, xs)
def identity(x):
return x
def replicate(n):
return lambda x: repeat(x, n)
def succ(x):
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
if __name__ == '__main__':
main()
| package main
import "fmt"
type any = interface{}
type fn func(any) any
type church func(fn) fn
func zero(f fn) fn {
return func(x any) any {
return x
}
}
func (c church) succ() church {
return func(f fn) fn {
return func(x any) any {
return f(c(f)(x))
}
}
}
func (c church) add(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(f)(d(f)(x))
}
}
}
func (c church) mul(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(d(f))(x)
}
}
}
func (c church) pow(d church) church {
di := d.toInt()
prod := c
for i := 1; i < di; i++ {
prod = prod.mul(c)
}
return prod
}
func (c church) toInt() int {
return c(incr)(0).(int)
}
func intToChurch(i int) church {
if i == 0 {
return zero
} else {
return intToChurch(i - 1).succ()
}
}
func incr(i any) any {
return i.(int) + 1
}
func main() {
z := church(zero)
three := z.succ().succ().succ()
four := three.succ()
fmt.Println("three ->", three.toInt())
fmt.Println("four ->", four.toInt())
fmt.Println("three + four ->", three.add(four).toInt())
fmt.Println("three * four ->", three.mul(four).toInt())
fmt.Println("three ^ four ->", three.pow(four).toInt())
fmt.Println("four ^ three ->", four.pow(three).toInt())
fmt.Println("5 -> five ->", intToChurch(5).toInt())
}
|
Generate a Go translation of this Python snippet without changing its computational steps. |
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
def churchExp(m):
return lambda n: n(m)
def churchFromInt(n):
return lambda f: (
foldl
(compose)
(identity)
(replicate(n)(f))
)
def churchFromInt_(n):
if 0 == n:
return churchZero()
else:
return churchSucc(churchFromInt(n - 1))
def intFromChurch(cn):
return cn(succ)(0)
def main():
'Tests'
cThree = churchFromInt(3)
cFour = churchFromInt(4)
print(list(map(intFromChurch, [
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
])))
def compose(f):
return lambda g: lambda x: g(f(x))
def foldl(f):
def go(acc, xs):
return reduce(lambda a, x: f(a)(x), xs, acc)
return lambda acc: lambda xs: go(acc, xs)
def identity(x):
return x
def replicate(n):
return lambda x: repeat(x, n)
def succ(x):
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
if __name__ == '__main__':
main()
| package main
import "fmt"
type any = interface{}
type fn func(any) any
type church func(fn) fn
func zero(f fn) fn {
return func(x any) any {
return x
}
}
func (c church) succ() church {
return func(f fn) fn {
return func(x any) any {
return f(c(f)(x))
}
}
}
func (c church) add(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(f)(d(f)(x))
}
}
}
func (c church) mul(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(d(f))(x)
}
}
}
func (c church) pow(d church) church {
di := d.toInt()
prod := c
for i := 1; i < di; i++ {
prod = prod.mul(c)
}
return prod
}
func (c church) toInt() int {
return c(incr)(0).(int)
}
func intToChurch(i int) church {
if i == 0 {
return zero
} else {
return intToChurch(i - 1).succ()
}
}
func incr(i any) any {
return i.(int) + 1
}
func main() {
z := church(zero)
three := z.succ().succ().succ()
four := three.succ()
fmt.Println("three ->", three.toInt())
fmt.Println("four ->", four.toInt())
fmt.Println("three + four ->", three.add(four).toInt())
fmt.Println("three * four ->", three.mul(four).toInt())
fmt.Println("three ^ four ->", three.pow(four).toInt())
fmt.Println("four ^ three ->", four.pow(three).toInt())
fmt.Println("5 -> five ->", intToChurch(5).toInt())
}
|
Produce a functionally identical Go code for the snippet given in Python. | from sys import stdout
neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]
cnt = 0
pWid = 0
pHei = 0
def is_valid(a, b):
return -1 < a < pWid and -1 < b < pHei
def iterate(pa, x, y, v):
if v > cnt:
return 1
for i in range(len(neighbours)):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if is_valid(a, b) and pa[a][b] == 0:
pa[a][b] = v
r = iterate(pa, a, b, v + 1)
if r == 1:
return r
pa[a][b] = 0
return 0
def solve(pz, w, h):
global cnt, pWid, pHei
pa = [[-1 for j in range(h)] for i in range(w)]
f = 0
pWid = w
pHei = h
for j in range(h):
for i in range(w):
if pz[f] == "1":
pa[i][j] = 0
cnt += 1
f += 1
for y in range(h):
for x in range(w):
if pa[x][y] == 0:
pa[x][y] = 1
if 1 == iterate(pa, x, y, 2):
return 1, pa
pa[x][y] = 0
return 0, pa
r = solve("011011011111111111111011111000111000001000", 7, 6)
if r[0] == 1:
for j in range(6):
for i in range(7):
if r[1][i][j] == -1:
stdout.write(" ")
else:
stdout.write(" {:0{}d}".format(r[1][i][j], 2))
print()
else:
stdout.write("No solution!")
| package main
import (
"fmt"
"sort"
)
var board = []string{
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0...",
}
var moves = [][2]int{
{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2},
}
var grid [][]int
var totalToFill = 0
func solve(r, c, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
}
|
Preserve the algorithm and functionality while converting the code from Python to Go. | from sys import stdout
neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]
cnt = 0
pWid = 0
pHei = 0
def is_valid(a, b):
return -1 < a < pWid and -1 < b < pHei
def iterate(pa, x, y, v):
if v > cnt:
return 1
for i in range(len(neighbours)):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if is_valid(a, b) and pa[a][b] == 0:
pa[a][b] = v
r = iterate(pa, a, b, v + 1)
if r == 1:
return r
pa[a][b] = 0
return 0
def solve(pz, w, h):
global cnt, pWid, pHei
pa = [[-1 for j in range(h)] for i in range(w)]
f = 0
pWid = w
pHei = h
for j in range(h):
for i in range(w):
if pz[f] == "1":
pa[i][j] = 0
cnt += 1
f += 1
for y in range(h):
for x in range(w):
if pa[x][y] == 0:
pa[x][y] = 1
if 1 == iterate(pa, x, y, 2):
return 1, pa
pa[x][y] = 0
return 0, pa
r = solve("011011011111111111111011111000111000001000", 7, 6)
if r[0] == 1:
for j in range(6):
for i in range(7):
if r[1][i][j] == -1:
stdout.write(" ")
else:
stdout.write(" {:0{}d}".format(r[1][i][j], 2))
print()
else:
stdout.write("No solution!")
| package main
import (
"fmt"
"sort"
)
var board = []string{
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0...",
}
var moves = [][2]int{
{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2},
}
var grid [][]int
var totalToFill = 0
func solve(r, c, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
}
|
Ensure the translated Go code behaves exactly like the original Python snippet. | from sys import stdout
neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]
cnt = 0
pWid = 0
pHei = 0
def is_valid(a, b):
return -1 < a < pWid and -1 < b < pHei
def iterate(pa, x, y, v):
if v > cnt:
return 1
for i in range(len(neighbours)):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if is_valid(a, b) and pa[a][b] == 0:
pa[a][b] = v
r = iterate(pa, a, b, v + 1)
if r == 1:
return r
pa[a][b] = 0
return 0
def solve(pz, w, h):
global cnt, pWid, pHei
pa = [[-1 for j in range(h)] for i in range(w)]
f = 0
pWid = w
pHei = h
for j in range(h):
for i in range(w):
if pz[f] == "1":
pa[i][j] = 0
cnt += 1
f += 1
for y in range(h):
for x in range(w):
if pa[x][y] == 0:
pa[x][y] = 1
if 1 == iterate(pa, x, y, 2):
return 1, pa
pa[x][y] = 0
return 0, pa
r = solve("011011011111111111111011111000111000001000", 7, 6)
if r[0] == 1:
for j in range(6):
for i in range(7):
if r[1][i][j] == -1:
stdout.write(" ")
else:
stdout.write(" {:0{}d}".format(r[1][i][j], 2))
print()
else:
stdout.write("No solution!")
| package main
import (
"fmt"
"sort"
)
var board = []string{
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0...",
}
var moves = [][2]int{
{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2},
}
var grid [][]int
var totalToFill = 0
func solve(r, c, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
}
|
Convert this Python block to Go, preserving its control flow and logic. | from itertools import izip
def gen_row(w, s):
def gen_seg(o, sp):
if not o:
return [[2] * sp]
return [[2] * x + o[0] + tail
for x in xrange(1, sp - len(o) + 2)
for tail in gen_seg(o[1:], sp - x)]
return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]
def deduce(hr, vr):
def allowable(row):
return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)
def fits(a, b):
return all(x & y for x, y in izip(a, b))
def fix_col(n):
c = [x[n] for x in can_do]
cols[n] = [x for x in cols[n] if fits(x, c)]
for i, x in enumerate(allowable(cols[n])):
if x != can_do[i][n]:
mod_rows.add(i)
can_do[i][n] &= x
def fix_row(n):
c = can_do[n]
rows[n] = [x for x in rows[n] if fits(x, c)]
for i, x in enumerate(allowable(rows[n])):
if x != can_do[n][i]:
mod_cols.add(i)
can_do[n][i] &= x
def show_gram(m):
for x in m:
print " ".join("x
print
w, h = len(vr), len(hr)
rows = [gen_row(w, x) for x in hr]
cols = [gen_row(h, x) for x in vr]
can_do = map(allowable, rows)
mod_rows, mod_cols = set(), set(xrange(w))
while mod_cols:
for i in mod_cols:
fix_col(i)
mod_cols = set()
for i in mod_rows:
fix_row(i)
mod_rows = set()
if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):
print "Solution would be unique"
else:
print "Solution may not be unique, doing exhaustive search:"
out = [0] * h
def try_all(n = 0):
if n >= h:
for j in xrange(w):
if [x[j] for x in out] not in cols[j]:
return 0
show_gram(out)
return 1
sol = 0
for x in rows[n]:
out[n] = x
sol += try_all(n + 1)
return sol
n = try_all()
if not n:
print "No solution."
elif n == 1:
print "Unique solution."
else:
print n, "solutions."
print
def solve(p, show_runs=True):
s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]
for l in p.splitlines()]
if show_runs:
print "Horizontal runs:", s[0]
print "Vertical runs:", s[1]
deduce(s[0], s[1])
def main():
fn = "nonogram_problems.txt"
for p in (x for x in open(fn).read().split("\n\n") if x):
solve(p)
print "Extra example not solvable by deduction alone:"
solve("B B A A\nB B A A")
print "Extra example where there is no solution:"
solve("B A A\nA A A")
main()
| package main
import (
"fmt"
"strings"
)
type BitSet []bool
func (bs BitSet) and(other BitSet) {
for i := range bs {
if bs[i] && other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func (bs BitSet) or(other BitSet) {
for i := range bs {
if bs[i] || other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func iff(cond bool, s1, s2 string) string {
if cond {
return s1
}
return s2
}
func newPuzzle(data [2]string) {
rowData := strings.Fields(data[0])
colData := strings.Fields(data[1])
rows := getCandidates(rowData, len(colData))
cols := getCandidates(colData, len(rowData))
for {
numChanged := reduceMutual(cols, rows)
if numChanged == -1 {
fmt.Println("No solution")
return
}
if numChanged == 0 {
break
}
}
for _, row := range rows {
for i := 0; i < len(cols); i++ {
fmt.Printf(iff(row[0][i], "# ", ". "))
}
fmt.Println()
}
fmt.Println()
}
func getCandidates(data []string, le int) [][]BitSet {
var result [][]BitSet
for _, s := range data {
var lst []BitSet
a := []byte(s)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 'A' + 1)
}
prep := make([]string, len(a))
for i, b := range a {
prep[i] = strings.Repeat("1", int(b-'A'+1))
}
for _, r := range genSequence(prep, le-sumBytes+1) {
bits := []byte(r[1:])
bitset := make(BitSet, len(bits))
for i, b := range bits {
bitset[i] = b == '1'
}
lst = append(lst, bitset)
}
result = append(result, lst)
}
return result
}
func genSequence(ones []string, numZeros int) []string {
le := len(ones)
if le == 0 {
return []string{strings.Repeat("0", numZeros)}
}
var result []string
for x := 1; x < numZeros-le+2; x++ {
skipOne := ones[1:]
for _, tail := range genSequence(skipOne, numZeros-x) {
result = append(result, strings.Repeat("0", x)+ones[0]+tail)
}
}
return result
}
func reduceMutual(cols, rows [][]BitSet) int {
countRemoved1 := reduce(cols, rows)
if countRemoved1 == -1 {
return -1
}
countRemoved2 := reduce(rows, cols)
if countRemoved2 == -1 {
return -1
}
return countRemoved1 + countRemoved2
}
func reduce(a, b [][]BitSet) int {
countRemoved := 0
for i := 0; i < len(a); i++ {
commonOn := make(BitSet, len(b))
for j := 0; j < len(b); j++ {
commonOn[j] = true
}
commonOff := make(BitSet, len(b))
for _, candidate := range a[i] {
commonOn.and(candidate)
commonOff.or(candidate)
}
for j := 0; j < len(b); j++ {
fi, fj := i, j
for k := len(b[j]) - 1; k >= 0; k-- {
cnd := b[j][k]
if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {
lb := len(b[j])
copy(b[j][k:], b[j][k+1:])
b[j][lb-1] = nil
b[j] = b[j][:lb-1]
countRemoved++
}
}
if len(b[j]) == 0 {
return -1
}
}
}
return countRemoved
}
func main() {
p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}
p2 := [2]string{
"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA",
}
p3 := [2]string{
"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " +
"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " +
"AAAAD BDG CEF CBDB BBB FC",
}
p4 := [2]string{
"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " +
"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM",
}
for _, puzzleData := range [][2]string{p1, p2, p3, p4} {
newPuzzle(puzzleData)
}
}
|
Please provide an equivalent version of this Python code in Go. | from itertools import izip
def gen_row(w, s):
def gen_seg(o, sp):
if not o:
return [[2] * sp]
return [[2] * x + o[0] + tail
for x in xrange(1, sp - len(o) + 2)
for tail in gen_seg(o[1:], sp - x)]
return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]
def deduce(hr, vr):
def allowable(row):
return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)
def fits(a, b):
return all(x & y for x, y in izip(a, b))
def fix_col(n):
c = [x[n] for x in can_do]
cols[n] = [x for x in cols[n] if fits(x, c)]
for i, x in enumerate(allowable(cols[n])):
if x != can_do[i][n]:
mod_rows.add(i)
can_do[i][n] &= x
def fix_row(n):
c = can_do[n]
rows[n] = [x for x in rows[n] if fits(x, c)]
for i, x in enumerate(allowable(rows[n])):
if x != can_do[n][i]:
mod_cols.add(i)
can_do[n][i] &= x
def show_gram(m):
for x in m:
print " ".join("x
print
w, h = len(vr), len(hr)
rows = [gen_row(w, x) for x in hr]
cols = [gen_row(h, x) for x in vr]
can_do = map(allowable, rows)
mod_rows, mod_cols = set(), set(xrange(w))
while mod_cols:
for i in mod_cols:
fix_col(i)
mod_cols = set()
for i in mod_rows:
fix_row(i)
mod_rows = set()
if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):
print "Solution would be unique"
else:
print "Solution may not be unique, doing exhaustive search:"
out = [0] * h
def try_all(n = 0):
if n >= h:
for j in xrange(w):
if [x[j] for x in out] not in cols[j]:
return 0
show_gram(out)
return 1
sol = 0
for x in rows[n]:
out[n] = x
sol += try_all(n + 1)
return sol
n = try_all()
if not n:
print "No solution."
elif n == 1:
print "Unique solution."
else:
print n, "solutions."
print
def solve(p, show_runs=True):
s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]
for l in p.splitlines()]
if show_runs:
print "Horizontal runs:", s[0]
print "Vertical runs:", s[1]
deduce(s[0], s[1])
def main():
fn = "nonogram_problems.txt"
for p in (x for x in open(fn).read().split("\n\n") if x):
solve(p)
print "Extra example not solvable by deduction alone:"
solve("B B A A\nB B A A")
print "Extra example where there is no solution:"
solve("B A A\nA A A")
main()
| package main
import (
"fmt"
"strings"
)
type BitSet []bool
func (bs BitSet) and(other BitSet) {
for i := range bs {
if bs[i] && other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func (bs BitSet) or(other BitSet) {
for i := range bs {
if bs[i] || other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func iff(cond bool, s1, s2 string) string {
if cond {
return s1
}
return s2
}
func newPuzzle(data [2]string) {
rowData := strings.Fields(data[0])
colData := strings.Fields(data[1])
rows := getCandidates(rowData, len(colData))
cols := getCandidates(colData, len(rowData))
for {
numChanged := reduceMutual(cols, rows)
if numChanged == -1 {
fmt.Println("No solution")
return
}
if numChanged == 0 {
break
}
}
for _, row := range rows {
for i := 0; i < len(cols); i++ {
fmt.Printf(iff(row[0][i], "# ", ". "))
}
fmt.Println()
}
fmt.Println()
}
func getCandidates(data []string, le int) [][]BitSet {
var result [][]BitSet
for _, s := range data {
var lst []BitSet
a := []byte(s)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 'A' + 1)
}
prep := make([]string, len(a))
for i, b := range a {
prep[i] = strings.Repeat("1", int(b-'A'+1))
}
for _, r := range genSequence(prep, le-sumBytes+1) {
bits := []byte(r[1:])
bitset := make(BitSet, len(bits))
for i, b := range bits {
bitset[i] = b == '1'
}
lst = append(lst, bitset)
}
result = append(result, lst)
}
return result
}
func genSequence(ones []string, numZeros int) []string {
le := len(ones)
if le == 0 {
return []string{strings.Repeat("0", numZeros)}
}
var result []string
for x := 1; x < numZeros-le+2; x++ {
skipOne := ones[1:]
for _, tail := range genSequence(skipOne, numZeros-x) {
result = append(result, strings.Repeat("0", x)+ones[0]+tail)
}
}
return result
}
func reduceMutual(cols, rows [][]BitSet) int {
countRemoved1 := reduce(cols, rows)
if countRemoved1 == -1 {
return -1
}
countRemoved2 := reduce(rows, cols)
if countRemoved2 == -1 {
return -1
}
return countRemoved1 + countRemoved2
}
func reduce(a, b [][]BitSet) int {
countRemoved := 0
for i := 0; i < len(a); i++ {
commonOn := make(BitSet, len(b))
for j := 0; j < len(b); j++ {
commonOn[j] = true
}
commonOff := make(BitSet, len(b))
for _, candidate := range a[i] {
commonOn.and(candidate)
commonOff.or(candidate)
}
for j := 0; j < len(b); j++ {
fi, fj := i, j
for k := len(b[j]) - 1; k >= 0; k-- {
cnd := b[j][k]
if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {
lb := len(b[j])
copy(b[j][k:], b[j][k+1:])
b[j][lb-1] = nil
b[j] = b[j][:lb-1]
countRemoved++
}
}
if len(b[j]) == 0 {
return -1
}
}
}
return countRemoved
}
func main() {
p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}
p2 := [2]string{
"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA",
}
p3 := [2]string{
"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " +
"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " +
"AAAAD BDG CEF CBDB BBB FC",
}
p4 := [2]string{
"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " +
"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM",
}
for _, puzzleData := range [][2]string{p1, p2, p3, p4} {
newPuzzle(puzzleData)
}
}
|
Can you help me rewrite this code in Go instead of Python, keeping it the same logically? | import re
from random import shuffle, randint
dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]
n_rows = 10
n_cols = 10
grid_size = n_rows * n_cols
min_words = 25
class Grid:
def __init__(self):
self.num_attempts = 0
self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]
self.solutions = []
def read_words(filename):
max_len = max(n_rows, n_cols)
words = []
with open(filename, "r") as file:
for line in file:
s = line.strip().lower()
if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:
words.append(s)
return words
def place_message(grid, msg):
msg = re.sub(r'[^A-Z]', "", msg.upper())
message_len = len(msg)
if 0 < message_len < grid_size:
gap_size = grid_size // message_len
for i in range(0, message_len):
pos = i * gap_size + randint(0, gap_size)
grid.cells[pos // n_cols][pos % n_cols] = msg[i]
return message_len
return 0
def try_location(grid, word, direction, pos):
r = pos // n_cols
c = pos % n_cols
length = len(word)
if (dirs[direction][0] == 1 and (length + c) > n_cols) or \
(dirs[direction][0] == -1 and (length - 1) > c) or \
(dirs[direction][1] == 1 and (length + r) > n_rows) or \
(dirs[direction][1] == -1 and (length - 1) > r):
return 0
rr = r
cc = c
i = 0
overlaps = 0
while i < length:
if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:
return 0
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
rr = r
cc = c
i = 0
while i < length:
if grid.cells[rr][cc] == word[i]:
overlaps += 1
else:
grid.cells[rr][cc] = word[i]
if i < length - 1:
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
letters_placed = length - overlaps
if letters_placed > 0:
grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr))
return letters_placed
def try_place_word(grid, word):
rand_dir = randint(0, len(dirs))
rand_pos = randint(0, grid_size)
for direction in range(0, len(dirs)):
direction = (direction + rand_dir) % len(dirs)
for pos in range(0, grid_size):
pos = (pos + rand_pos) % grid_size
letters_placed = try_location(grid, word, direction, pos)
if letters_placed > 0:
return letters_placed
return 0
def create_word_search(words):
grid = None
num_attempts = 0
while num_attempts < 100:
num_attempts += 1
shuffle(words)
grid = Grid()
message_len = place_message(grid, "Rosetta Code")
target = grid_size - message_len
cells_filled = 0
for word in words:
cells_filled += try_place_word(grid, word)
if cells_filled == target:
if len(grid.solutions) >= min_words:
grid.num_attempts = num_attempts
return grid
else:
break
return grid
def print_result(grid):
if grid is None or grid.num_attempts == 0:
print("No grid to display")
return
size = len(grid.solutions)
print("Attempts: {0}".format(grid.num_attempts))
print("Number of words: {0}".format(size))
print("\n 0 1 2 3 4 5 6 7 8 9\n")
for r in range(0, n_rows):
print("{0} ".format(r), end='')
for c in range(0, n_cols):
print(" %c " % grid.cells[r][c], end='')
print()
print()
for i in range(0, size - 1, 2):
print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1]))
if size % 2 == 1:
print(grid.solutions[size - 1])
if __name__ == "__main__":
print_result(create_word_search(read_words("unixdict.txt")))
| package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"regexp"
"strings"
"time"
)
var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}
const (
nRows = 10
nCols = nRows
gridSize = nRows * nCols
minWords = 25
)
var (
re1 = regexp.MustCompile(fmt.Sprintf("^[a-z]{3,%d}$", nRows))
re2 = regexp.MustCompile("[^A-Z]")
)
type grid struct {
numAttempts int
cells [nRows][nCols]byte
solutions []string
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func readWords(fileName string) []string {
file, err := os.Open(fileName)
check(err)
defer file.Close()
var words []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
word := strings.ToLower(strings.TrimSpace(scanner.Text()))
if re1.MatchString(word) {
words = append(words, word)
}
}
check(scanner.Err())
return words
}
func createWordSearch(words []string) *grid {
var gr *grid
outer:
for i := 1; i < 100; i++ {
gr = new(grid)
messageLen := gr.placeMessage("Rosetta Code")
target := gridSize - messageLen
cellsFilled := 0
rand.Shuffle(len(words), func(i, j int) {
words[i], words[j] = words[j], words[i]
})
for _, word := range words {
cellsFilled += gr.tryPlaceWord(word)
if cellsFilled == target {
if len(gr.solutions) >= minWords {
gr.numAttempts = i
break outer
} else {
break
}
}
}
}
return gr
}
func (gr *grid) placeMessage(msg string) int {
msg = strings.ToUpper(msg)
msg = re2.ReplaceAllLiteralString(msg, "")
messageLen := len(msg)
if messageLen > 0 && messageLen < gridSize {
gapSize := gridSize / messageLen
for i := 0; i < messageLen; i++ {
pos := i*gapSize + rand.Intn(gapSize)
gr.cells[pos/nCols][pos%nCols] = msg[i]
}
return messageLen
}
return 0
}
func (gr *grid) tryPlaceWord(word string) int {
randDir := rand.Intn(len(dirs))
randPos := rand.Intn(gridSize)
for dir := 0; dir < len(dirs); dir++ {
dir = (dir + randDir) % len(dirs)
for pos := 0; pos < gridSize; pos++ {
pos = (pos + randPos) % gridSize
lettersPlaced := gr.tryLocation(word, dir, pos)
if lettersPlaced > 0 {
return lettersPlaced
}
}
}
return 0
}
func (gr *grid) tryLocation(word string, dir, pos int) int {
r := pos / nCols
c := pos % nCols
le := len(word)
if (dirs[dir][0] == 1 && (le+c) > nCols) ||
(dirs[dir][0] == -1 && (le-1) > c) ||
(dirs[dir][1] == 1 && (le+r) > nRows) ||
(dirs[dir][1] == -1 && (le-1) > r) {
return 0
}
overlaps := 0
rr := r
cc := c
for i := 0; i < le; i++ {
if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {
return 0
}
cc += dirs[dir][0]
rr += dirs[dir][1]
}
rr = r
cc = c
for i := 0; i < le; i++ {
if gr.cells[rr][cc] == word[i] {
overlaps++
} else {
gr.cells[rr][cc] = word[i]
}
if i < le-1 {
cc += dirs[dir][0]
rr += dirs[dir][1]
}
}
lettersPlaced := le - overlaps
if lettersPlaced > 0 {
sol := fmt.Sprintf("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr)
gr.solutions = append(gr.solutions, sol)
}
return lettersPlaced
}
func printResult(gr *grid) {
if gr.numAttempts == 0 {
fmt.Println("No grid to display")
return
}
size := len(gr.solutions)
fmt.Println("Attempts:", gr.numAttempts)
fmt.Println("Number of words:", size)
fmt.Println("\n 0 1 2 3 4 5 6 7 8 9")
for r := 0; r < nRows; r++ {
fmt.Printf("\n%d ", r)
for c := 0; c < nCols; c++ {
fmt.Printf(" %c ", gr.cells[r][c])
}
}
fmt.Println("\n")
for i := 0; i < size-1; i += 2 {
fmt.Printf("%s %s\n", gr.solutions[i], gr.solutions[i+1])
}
if size%2 == 1 {
fmt.Println(gr.solutions[size-1])
}
}
func main() {
rand.Seed(time.Now().UnixNano())
unixDictPath := "/usr/share/dict/words"
printResult(createWordSearch(readWords(unixDictPath)))
}
|
Write a version of this Python function in Go with identical behavior. | >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
| package main
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"unsafe"
)
type foobar struct {
Exported int
unexported int
}
func main() {
obj := foobar{12, 42}
fmt.Println("obj:", obj)
examineAndModify(&obj)
fmt.Println("obj:", obj)
anotherExample()
}
func examineAndModify(any interface{}) {
v := reflect.ValueOf(any)
v = v.Elem()
fmt.Println(" v:", v, "=", v.Interface())
t := v.Type()
fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
fmt.Printf(" %2d: %-10s %-4s %t\n", i,
t.Field(i).Name, f.Type(), f.CanSet())
}
v.Field(0).SetInt(16)
vp := v.Field(1).Addr()
up := unsafe.Pointer(vp.Pointer())
p := (*int)(up)
fmt.Printf(" vp has type %-14T = %v\n", vp, vp)
fmt.Printf(" up has type %-14T = %#0x\n", up, up)
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p)
*p = 43
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++
}
func anotherExample() {
r := bufio.NewReader(os.Stdin)
errp := (*error)(unsafe.Pointer(
reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
*errp = errors.New("unsafely injected error value into bufio inner workings")
_, err := r.ReadByte()
fmt.Println("bufio.ReadByte returned error:", err)
}
|
Port the provided Python code into Go while preserving the original functionality. | >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
| package main
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"unsafe"
)
type foobar struct {
Exported int
unexported int
}
func main() {
obj := foobar{12, 42}
fmt.Println("obj:", obj)
examineAndModify(&obj)
fmt.Println("obj:", obj)
anotherExample()
}
func examineAndModify(any interface{}) {
v := reflect.ValueOf(any)
v = v.Elem()
fmt.Println(" v:", v, "=", v.Interface())
t := v.Type()
fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
fmt.Printf(" %2d: %-10s %-4s %t\n", i,
t.Field(i).Name, f.Type(), f.CanSet())
}
v.Field(0).SetInt(16)
vp := v.Field(1).Addr()
up := unsafe.Pointer(vp.Pointer())
p := (*int)(up)
fmt.Printf(" vp has type %-14T = %v\n", vp, vp)
fmt.Printf(" up has type %-14T = %#0x\n", up, up)
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p)
*p = 43
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++
}
func anotherExample() {
r := bufio.NewReader(os.Stdin)
errp := (*error)(unsafe.Pointer(
reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
*errp = errors.New("unsafely injected error value into bufio inner workings")
_, err := r.ReadByte()
fmt.Println("bufio.ReadByte returned error:", err)
}
|
Convert the following code from Python to Go, ensuring the logic remains intact. |
import pickle
class Entity:
def __init__(self):
self.name = "Entity"
def printName(self):
print self.name
class Person(Entity):
def __init__(self):
self.name = "Cletus"
instance1 = Person()
instance1.printName()
instance2 = Entity()
instance2.printName()
target = file("objects.dat", "w")
pickle.dump((instance1, instance2), target)
target.close()
print "Serialized..."
target = file("objects.dat")
i1, i2 = pickle.load(target)
print "Unserialized..."
i1.printName()
i2.printName()
| package main
import (
"encoding/gob"
"fmt"
"os"
)
type printable interface {
print()
}
func main() {
animals := []printable{
&Animal{Alive: true},
&Cat{},
&Lab{
Dog: Dog{Animal: Animal{Alive: true}},
Color: "yellow",
},
&Collie{Dog: Dog{
Animal: Animal{Alive: true},
ObedienceTrained: true,
}},
}
fmt.Println("created:")
for _, a := range animals {
a.print()
}
f, err := os.Create("objects.dat")
if err != nil {
fmt.Println(err)
return
}
for _, a := range animals {
gob.Register(a)
}
err = gob.NewEncoder(f).Encode(animals)
if err != nil {
fmt.Println(err)
return
}
f.Close()
f, err = os.Open("objects.dat")
if err != nil {
fmt.Println(err)
return
}
var clones []printable
gob.NewDecoder(f).Decode(&clones)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("\nloaded from objects.dat:")
for _, c := range clones {
c.print()
}
}
type Animal struct {
Alive bool
}
func (a *Animal) print() {
if a.Alive {
fmt.Println(" live animal, unspecified type")
} else {
fmt.Println(" dead animal, unspecified type")
}
}
type Dog struct {
Animal
ObedienceTrained bool
}
func (d *Dog) print() {
switch {
case !d.Alive:
fmt.Println(" dead dog")
case d.ObedienceTrained:
fmt.Println(" trained dog")
default:
fmt.Println(" dog, not trained")
}
}
type Cat struct {
Animal
LitterBoxTrained bool
}
func (c *Cat) print() {
switch {
case !c.Alive:
fmt.Println(" dead cat")
case c.LitterBoxTrained:
fmt.Println(" litter box trained cat")
default:
fmt.Println(" cat, not litter box trained")
}
}
type Lab struct {
Dog
Color string
}
func (l *Lab) print() {
var r string
if l.Color == "" {
r = "lab, color unspecified"
} else {
r = l.Color + " lab"
}
switch {
case !l.Alive:
fmt.Println(" dead", r)
case l.ObedienceTrained:
fmt.Println(" trained", r)
default:
fmt.Printf(" %s, not trained\n", r)
}
}
type Collie struct {
Dog
CatchesFrisbee bool
}
func (c *Collie) print() {
switch {
case !c.Alive:
fmt.Println(" dead collie")
case c.ObedienceTrained && c.CatchesFrisbee:
fmt.Println(" trained collie, catches frisbee")
case c.ObedienceTrained && !c.CatchesFrisbee:
fmt.Println(" trained collie, but doesn't catch frisbee")
case !c.ObedienceTrained && c.CatchesFrisbee:
fmt.Println(" collie, not trained, but catches frisbee")
case !c.ObedienceTrained && !c.CatchesFrisbee:
fmt.Println(" collie, not trained, doesn't catch frisbee")
}
}
|
Rewrite the snippet below in Go so it works the same as the original Python code. |
from __future__ import print_function
class Node(object):
def __init__(self):
self.edges = {}
self.link = None
self.len = 0
class Eertree(object):
def __init__(self):
self.nodes = []
self.rto = Node()
self.rte = Node()
self.rto.link = self.rte.link = self.rto;
self.rto.len = -1
self.rte.len = 0
self.S = [0]
self.maxSufT = self.rte
def get_max_suffix_pal(self, startNode, a):
u = startNode
i = len(self.S)
k = u.len
while id(u) != id(self.rto) and self.S[i - k - 1] != a:
assert id(u) != id(u.link)
u = u.link
k = u.len
return u
def add(self, a):
Q = self.get_max_suffix_pal(self.maxSufT, a)
createANewNode = not a in Q.edges
if createANewNode:
P = Node()
self.nodes.append(P)
P.len = Q.len + 2
if P.len == 1:
P.link = self.rte
else:
P.link = self.get_max_suffix_pal(Q.link, a).edges[a]
Q.edges[a] = P
self.maxSufT = Q.edges[a]
self.S.append(a)
return createANewNode
def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):
for lnkName in nd.edges:
nd2 = nd.edges[lnkName]
self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)
if id(nd) != id(self.rto) and id(nd) != id(self.rte):
tmp = "".join(charsToHere)
if id(nodesToHere[0]) == id(self.rte):
assembled = tmp[::-1] + tmp
else:
assembled = tmp[::-1] + tmp[1:]
result.append(assembled)
if __name__=="__main__":
st = "eertree"
print ("Processing string", st)
eertree = Eertree()
for ch in st:
eertree.add(ch)
print ("Number of sub-palindromes:", len(eertree.nodes))
result = []
eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result)
eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result)
print ("Sub-palindromes:", result)
| package main
import "fmt"
func main() {
tree := eertree([]byte("eertree"))
fmt.Println(subPalindromes(tree))
}
type edges map[byte]int
type node struct {
length int
edges
suffix int
}
const evenRoot = 0
const oddRoot = 1
func eertree(s []byte) []node {
tree := []node{
evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},
oddRoot: {length: -1, suffix: oddRoot, edges: edges{}},
}
suffix := oddRoot
var n, k int
for i, c := range s {
for n = suffix; ; n = tree[n].suffix {
k = tree[n].length
if b := i - k - 1; b >= 0 && s[b] == c {
break
}
}
if e, ok := tree[n].edges[c]; ok {
suffix = e
continue
}
suffix = len(tree)
tree = append(tree, node{length: k + 2, edges: edges{}})
tree[n].edges[c] = suffix
if tree[suffix].length == 1 {
tree[suffix].suffix = 0
continue
}
for {
n = tree[n].suffix
if b := i - tree[n].length - 1; b >= 0 && s[b] == c {
break
}
}
tree[suffix].suffix = tree[n].edges[c]
}
return tree
}
func subPalindromes(tree []node) (s []string) {
var children func(int, string)
children = func(n int, p string) {
for c, n := range tree[n].edges {
c := string(c)
p := c + p + c
s = append(s, p)
children(n, p)
}
}
children(0, "")
for c, n := range tree[1].edges {
c := string(c)
s = append(s, c)
children(n, c)
}
return
}
|
Ensure the translated Go code behaves exactly like the original Python snippet. |
from __future__ import print_function
class Node(object):
def __init__(self):
self.edges = {}
self.link = None
self.len = 0
class Eertree(object):
def __init__(self):
self.nodes = []
self.rto = Node()
self.rte = Node()
self.rto.link = self.rte.link = self.rto;
self.rto.len = -1
self.rte.len = 0
self.S = [0]
self.maxSufT = self.rte
def get_max_suffix_pal(self, startNode, a):
u = startNode
i = len(self.S)
k = u.len
while id(u) != id(self.rto) and self.S[i - k - 1] != a:
assert id(u) != id(u.link)
u = u.link
k = u.len
return u
def add(self, a):
Q = self.get_max_suffix_pal(self.maxSufT, a)
createANewNode = not a in Q.edges
if createANewNode:
P = Node()
self.nodes.append(P)
P.len = Q.len + 2
if P.len == 1:
P.link = self.rte
else:
P.link = self.get_max_suffix_pal(Q.link, a).edges[a]
Q.edges[a] = P
self.maxSufT = Q.edges[a]
self.S.append(a)
return createANewNode
def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):
for lnkName in nd.edges:
nd2 = nd.edges[lnkName]
self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)
if id(nd) != id(self.rto) and id(nd) != id(self.rte):
tmp = "".join(charsToHere)
if id(nodesToHere[0]) == id(self.rte):
assembled = tmp[::-1] + tmp
else:
assembled = tmp[::-1] + tmp[1:]
result.append(assembled)
if __name__=="__main__":
st = "eertree"
print ("Processing string", st)
eertree = Eertree()
for ch in st:
eertree.add(ch)
print ("Number of sub-palindromes:", len(eertree.nodes))
result = []
eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result)
eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result)
print ("Sub-palindromes:", result)
| package main
import "fmt"
func main() {
tree := eertree([]byte("eertree"))
fmt.Println(subPalindromes(tree))
}
type edges map[byte]int
type node struct {
length int
edges
suffix int
}
const evenRoot = 0
const oddRoot = 1
func eertree(s []byte) []node {
tree := []node{
evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},
oddRoot: {length: -1, suffix: oddRoot, edges: edges{}},
}
suffix := oddRoot
var n, k int
for i, c := range s {
for n = suffix; ; n = tree[n].suffix {
k = tree[n].length
if b := i - k - 1; b >= 0 && s[b] == c {
break
}
}
if e, ok := tree[n].edges[c]; ok {
suffix = e
continue
}
suffix = len(tree)
tree = append(tree, node{length: k + 2, edges: edges{}})
tree[n].edges[c] = suffix
if tree[suffix].length == 1 {
tree[suffix].suffix = 0
continue
}
for {
n = tree[n].suffix
if b := i - tree[n].length - 1; b >= 0 && s[b] == c {
break
}
}
tree[suffix].suffix = tree[n].edges[c]
}
return tree
}
func subPalindromes(tree []node) (s []string) {
var children func(int, string)
children = func(n int, p string) {
for c, n := range tree[n].edges {
c := string(c)
p := c + p + c
s = append(s, p)
children(n, p)
}
}
children(0, "")
for c, n := range tree[1].edges {
c := string(c)
s = append(s, c)
children(n, c)
}
return
}
|
Preserve the algorithm and functionality while converting the code from Python to Go. |
from datetime import date
def longYear(y):
return 52 < date(y, 12, 28).isocalendar()[1]
def main():
for year in [
x for x in range(2000, 1 + 2100)
if longYear(x)
]:
print(year)
if __name__ == '__main__':
main()
| package main
import (
"fmt"
"time"
)
func main() {
centuries := []string{"20th", "21st", "22nd"}
starts := []int{1900, 2000, 2100}
for i := 0; i < len(centuries); i++ {
var longYears []int
fmt.Printf("\nLong years in the %s century:\n", centuries[i])
for j := starts[i]; j < starts[i] + 100; j++ {
t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)
if _, week := t.ISOWeek(); week == 53 {
longYears = append(longYears, j)
}
}
fmt.Println(longYears)
}
}
|
Translate the given Python code snippet into Go without altering its behavior. | from sympy import divisors
from sympy.combinatorics.subsets import Subset
def isZumkeller(n):
d = divisors(n)
s = sum(d)
if not s % 2 and max(d) <= s/2:
for x in range(1, 2**len(d)):
if sum(Subset.unrank_binary(x, d).subset) == s/2:
return True
return False
def printZumkellers(N, oddonly=False):
nprinted = 0
for n in range(1, 10**5):
if (oddonly == False or n % 2) and isZumkeller(n):
print(f'{n:>8}', end='')
nprinted += 1
if nprinted % 10 == 0:
print()
if nprinted >= N:
return
print("220 Zumkeller numbers:")
printZumkellers(220)
print("\n\n40 odd Zumkeller numbers:")
printZumkellers(40, True)
| package main
import "fmt"
func getDivisors(n int) []int {
divs := []int{1, n}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs = append(divs, j)
}
}
}
return divs
}
func sum(divs []int) int {
sum := 0
for _, div := range divs {
sum += div
}
return sum
}
func isPartSum(divs []int, sum int) bool {
if sum == 0 {
return true
}
le := len(divs)
if le == 0 {
return false
}
last := divs[le-1]
divs = divs[0 : le-1]
if last > sum {
return isPartSum(divs, sum)
}
return isPartSum(divs, sum) || isPartSum(divs, sum-last)
}
func isZumkeller(n int) bool {
divs := getDivisors(n)
sum := sum(divs)
if sum%2 == 1 {
return false
}
if n%2 == 1 {
abundance := sum - 2*n
return abundance > 0 && abundance%2 == 0
}
return isPartSum(divs, sum/2)
}
func main() {
fmt.Println("The first 220 Zumkeller numbers are:")
for i, count := 2, 0; count < 220; i++ {
if isZumkeller(i) {
fmt.Printf("%3d ", i)
count++
if count%20 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nThe first 40 odd Zumkeller numbers are:")
for i, count := 3, 0; count < 40; i += 2 {
if isZumkeller(i) {
fmt.Printf("%5d ", i)
count++
if count%10 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:")
for i, count := 3, 0; count < 40; i += 2 {
if (i % 10 != 5) && isZumkeller(i) {
fmt.Printf("%7d ", i)
count++
if count%8 == 0 {
fmt.Println()
}
}
}
fmt.Println()
}
|
Ensure the translated Go code behaves exactly like the original Python snippet. | base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
| package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
|
Convert this Python snippet to Go and keep its semantics consistent. | base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
| package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
|
Rewrite the snippet below in Go so it works the same as the original Python code. | base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
| package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
|
Port the provided Python code into Go while preserving the original functionality. | from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext().prec = prec
last = 0
for i,x in zip(count(), to_decimal(b)):
if x == last:
print(f'after {i} iterations:\n\t{x}')
break
last = x
for b in range(4):
coefs = [n for _,n in islice(metallic_ratio(b), 15)]
print(f'\nb = {b}: {coefs}')
stable(b, 32)
print(f'\nb = 1 with 256 digits:')
stable(1, 256)
| package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var x0, x1 int64 = 1, 1
fmt.Printf("%d, %d", x0, x1)
for i := 1; i <= 13; i++ {
x2 := b*x1 + x0
fmt.Printf(", %d", x2)
x0, x1 = x1, x2
}
fmt.Println()
}
func metallic(b int64, dp int) {
x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
ratio := big.NewRat(1, 1)
iters := 0
prev := ratio.FloatString(dp)
for {
iters++
x2.Mul(bb, x1)
x2.Add(x2, x0)
this := ratio.SetFrac(x2, x1).FloatString(dp)
if prev == this {
plural := "s"
if iters == 1 {
plural = " "
}
fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this)
return
}
prev = this
x0.Set(x1)
x1.Set(x2)
}
}
func main() {
for b := int64(0); b < 10; b++ {
lucas(b)
metallic(b, 32)
}
fmt.Println("Golden ratio, where b = 1:")
metallic(1, 256)
}
|
Translate the given Python code snippet into Go without altering its behavior. | from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext().prec = prec
last = 0
for i,x in zip(count(), to_decimal(b)):
if x == last:
print(f'after {i} iterations:\n\t{x}')
break
last = x
for b in range(4):
coefs = [n for _,n in islice(metallic_ratio(b), 15)]
print(f'\nb = {b}: {coefs}')
stable(b, 32)
print(f'\nb = 1 with 256 digits:')
stable(1, 256)
| package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var x0, x1 int64 = 1, 1
fmt.Printf("%d, %d", x0, x1)
for i := 1; i <= 13; i++ {
x2 := b*x1 + x0
fmt.Printf(", %d", x2)
x0, x1 = x1, x2
}
fmt.Println()
}
func metallic(b int64, dp int) {
x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
ratio := big.NewRat(1, 1)
iters := 0
prev := ratio.FloatString(dp)
for {
iters++
x2.Mul(bb, x1)
x2.Add(x2, x0)
this := ratio.SetFrac(x2, x1).FloatString(dp)
if prev == this {
plural := "s"
if iters == 1 {
plural = " "
}
fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this)
return
}
prev = this
x0.Set(x1)
x1.Set(x2)
}
}
func main() {
for b := int64(0); b < 10; b++ {
lucas(b)
metallic(b, 32)
}
fmt.Println("Golden ratio, where b = 1:")
metallic(1, 256)
}
|
Convert the following code from Python to Go, ensuring the logic remains intact. | import random, sys
def makerule(data, context):
rule = {}
words = data.split(' ')
index = context
for word in words[index:]:
key = ' '.join(words[index-context:index])
if key in rule:
rule[key].append(word)
else:
rule[key] = [word]
index += 1
return rule
def makestring(rule, length):
oldwords = random.choice(list(rule.keys())).split(' ')
string = ' '.join(oldwords) + ' '
for i in range(length):
try:
key = ' '.join(oldwords)
newword = random.choice(rule[key])
string += newword + ' '
for word in range(len(oldwords)):
oldwords[word] = oldwords[(word + 1) % len(oldwords)]
oldwords[-1] = newword
except KeyError:
return string
return string
if __name__ == '__main__':
with open(sys.argv[1], encoding='utf8') as f:
data = f.read()
rule = makerule(data, int(sys.argv[2]))
string = makestring(rule, int(sys.argv[3]))
print(string)
| package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"math/rand"
"os"
"strings"
"time"
"unicode"
"unicode/utf8"
)
func main() {
log.SetFlags(0)
log.SetPrefix("markov: ")
input := flag.String("in", "alice_oz.txt", "input file")
n := flag.Int("n", 2, "number of words to use as prefix")
runs := flag.Int("runs", 1, "number of runs to generate")
wordsPerRun := flag.Int("words", 300, "number of words per run")
startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix")
stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)")
flag.Parse()
rand.Seed(time.Now().UnixNano())
m, err := NewMarkovFromFile(*input, *n)
if err != nil {
log.Fatal(err)
}
for i := 0; i < *runs; i++ {
err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)
if err != nil {
log.Fatal(err)
}
fmt.Println()
}
}
type Markov struct {
n int
capitalized int
suffix map[string][]string
}
func NewMarkovFromFile(filename string, n int) (*Markov, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return NewMarkov(f, n)
}
func NewMarkov(r io.Reader, n int) (*Markov, error) {
m := &Markov{
n: n,
suffix: make(map[string][]string),
}
sc := bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
window := make([]string, 0, n)
for sc.Scan() {
word := sc.Text()
if len(window) > 0 {
prefix := strings.Join(window, " ")
m.suffix[prefix] = append(m.suffix[prefix], word)
if isCapitalized(prefix) {
m.capitalized++
}
}
window = appendMax(n, window, word)
}
if err := sc.Err(); err != nil {
return nil, err
}
return m, nil
}
func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {
bw := bufio.NewWriter(w)
var i int
if startCapital {
i = rand.Intn(m.capitalized)
} else {
i = rand.Intn(len(m.suffix))
}
var prefix string
for prefix = range m.suffix {
if startCapital && !isCapitalized(prefix) {
continue
}
if i == 0 {
break
}
i--
}
bw.WriteString(prefix)
prefixWords := strings.Fields(prefix)
n -= len(prefixWords)
for {
suffixChoices := m.suffix[prefix]
if len(suffixChoices) == 0 {
break
}
i = rand.Intn(len(suffixChoices))
suffix := suffixChoices[i]
bw.WriteByte(' ')
if _, err := bw.WriteString(suffix); err != nil {
break
}
n--
if n < 0 && (!stopSentence || isSentenceEnd(suffix)) {
break
}
prefixWords = appendMax(m.n, prefixWords, suffix)
prefix = strings.Join(prefixWords, " ")
}
return bw.Flush()
}
func isCapitalized(s string) bool {
r, _ := utf8.DecodeRuneInString(s)
return unicode.IsUpper(r)
}
func isSentenceEnd(s string) bool {
r, _ := utf8.DecodeLastRuneInString(s)
return r == '.' || r == '?' || r == '!'
}
func appendMax(max int, slice []string, value string) []string {
if len(slice)+1 > max {
n := copy(slice, slice[1:])
slice = slice[:n]
}
return append(slice, value)
}
|
Port the provided Python code into Go while preserving the original functionality. | from collections import namedtuple, deque
from pprint import pprint as pp
inf = float('inf')
Edge = namedtuple('Edge', ['start', 'end', 'cost'])
class Graph():
def __init__(self, edges):
self.edges = [Edge(*edge) for edge in edges]
self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}
def dijkstra(self, source, dest):
assert source in self.vertices
dist = {vertex: inf for vertex in self.vertices}
previous = {vertex: None for vertex in self.vertices}
dist[source] = 0
q = self.vertices.copy()
neighbours = {vertex: set() for vertex in self.vertices}
for start, end, cost in self.edges:
neighbours[start].add((end, cost))
neighbours[end].add((start, cost))
while q:
u = min(q, key=lambda vertex: dist[vertex])
q.remove(u)
if dist[u] == inf or u == dest:
break
for v, cost in neighbours[u]:
alt = dist[u] + cost
if alt < dist[v]:
dist[v] = alt
previous[v] = u
s, u = deque(), dest
while previous[u]:
s.appendleft(u)
u = previous[u]
s.appendleft(u)
return s
graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10),
("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6),
("e", "f", 9)])
pp(graph.dijkstra("a", "e"))
| package main
import (
"container/heap"
"fmt"
)
type PriorityQueue struct {
items []Vertex
m map[Vertex]int
pr map[Vertex]int
}
func (pq *PriorityQueue) Len() int { return len(pq.items) }
func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }
func (pq *PriorityQueue) Swap(i, j int) {
pq.items[i], pq.items[j] = pq.items[j], pq.items[i]
pq.m[pq.items[i]] = i
pq.m[pq.items[j]] = j
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(pq.items)
item := x.(Vertex)
pq.m[item] = n
pq.items = append(pq.items, item)
}
func (pq *PriorityQueue) Pop() interface{} {
old := pq.items
n := len(old)
item := old[n-1]
pq.m[item] = -1
pq.items = old[0 : n-1]
return item
}
func (pq *PriorityQueue) update(item Vertex, priority int) {
pq.pr[item] = priority
heap.Fix(pq, pq.m[item])
}
func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {
heap.Push(pq, item)
pq.update(item, priority)
}
const (
Infinity = int(^uint(0) >> 1)
Uninitialized = -1
)
func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {
vs := g.Vertices()
dist = make(map[Vertex]int, len(vs))
prev = make(map[Vertex]Vertex, len(vs))
sid := source
dist[sid] = 0
q := &PriorityQueue{
items: make([]Vertex, 0, len(vs)),
m: make(map[Vertex]int, len(vs)),
pr: make(map[Vertex]int, len(vs)),
}
for _, v := range vs {
if v != sid {
dist[v] = Infinity
}
prev[v] = Uninitialized
q.addWithPriority(v, dist[v])
}
for len(q.items) != 0 {
u := heap.Pop(q).(Vertex)
for _, v := range g.Neighbors(u) {
alt := dist[u] + g.Weight(u, v)
if alt < dist[v] {
dist[v] = alt
prev[v] = u
q.update(v, alt)
}
}
}
return dist, prev
}
type Graph interface {
Vertices() []Vertex
Neighbors(v Vertex) []Vertex
Weight(u, v Vertex) int
}
type Vertex int
type sg struct {
ids map[string]Vertex
names map[Vertex]string
edges map[Vertex]map[Vertex]int
}
func newsg(ids map[string]Vertex) sg {
g := sg{ids: ids}
g.names = make(map[Vertex]string, len(ids))
for k, v := range ids {
g.names[v] = k
}
g.edges = make(map[Vertex]map[Vertex]int)
return g
}
func (g sg) edge(u, v string, w int) {
if _, ok := g.edges[g.ids[u]]; !ok {
g.edges[g.ids[u]] = make(map[Vertex]int)
}
g.edges[g.ids[u]][g.ids[v]] = w
}
func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {
s = g.names[v]
for prev[v] >= 0 {
v = prev[v]
s = g.names[v] + s
}
return s
}
func (g sg) Vertices() []Vertex {
vs := make([]Vertex, 0, len(g.ids))
for _, v := range g.ids {
vs = append(vs, v)
}
return vs
}
func (g sg) Neighbors(u Vertex) []Vertex {
vs := make([]Vertex, 0, len(g.edges[u]))
for v := range g.edges[u] {
vs = append(vs, v)
}
return vs
}
func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }
func main() {
g := newsg(map[string]Vertex{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
})
g.edge("a", "b", 7)
g.edge("a", "c", 9)
g.edge("a", "f", 14)
g.edge("b", "c", 10)
g.edge("b", "d", 15)
g.edge("c", "d", 11)
g.edge("c", "f", 2)
g.edge("d", "e", 6)
g.edge("e", "f", 9)
dist, prev := Dijkstra(g, g.ids["a"])
fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev))
fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev))
}
|
Maintain the same structure and functionality when rewriting this code in Go. | import copy, random
def bitcount(n):
return bin(n).count("1")
def reoderingSign(i, j):
k = i >> 1
sum = 0
while k != 0:
sum += bitcount(k & j)
k = k >> 1
return 1.0 if ((sum & 1) == 0) else -1.0
class Vector:
def __init__(self, da):
self.dims = da
def dot(self, other):
return (self * other + other * self) * 0.5
def __getitem__(self, i):
return self.dims[i]
def __setitem__(self, i, v):
self.dims[i] = v
def __neg__(self):
return self * -1.0
def __add__(self, other):
result = copy.copy(other.dims)
for i in xrange(0, len(self.dims)):
result[i] += self.dims[i]
return Vector(result)
def __mul__(self, other):
if isinstance(other, Vector):
result = [0.0] * 32
for i in xrange(0, len(self.dims)):
if self.dims[i] != 0.0:
for j in xrange(0, len(self.dims)):
if other.dims[j] != 0.0:
s = reoderingSign(i, j) * self.dims[i] * other.dims[j]
k = i ^ j
result[k] += s
return Vector(result)
else:
result = copy.copy(self.dims)
for i in xrange(0, len(self.dims)):
self.dims[i] *= other
return Vector(result)
def __str__(self):
return str(self.dims)
def e(n):
assert n <= 4, "n must be less than 5"
result = Vector([0.0] * 32)
result[1 << n] = 1.0
return result
def randomVector():
result = Vector([0.0] * 32)
for i in xrange(0, 5):
result += Vector([random.uniform(0, 1)]) * e(i)
return result
def randomMultiVector():
result = Vector([0.0] * 32)
for i in xrange(0, 32):
result[i] = random.uniform(0, 1)
return result
def main():
for i in xrange(0, 5):
for j in xrange(0, 5):
if i < j:
if e(i).dot(e(j))[0] != 0.0:
print "Unexpected non-null scalar product"
return
elif i == j:
if e(i).dot(e(j))[0] == 0.0:
print "Unexpected non-null scalar product"
a = randomMultiVector()
b = randomMultiVector()
c = randomMultiVector()
x = randomVector()
print (a * b) * c
print a * (b * c)
print
print a * (b + c)
print a * b + a * c
print
print (a + b) * c
print a * c + b * c
print
print x * x
main()
| package main
import (
"fmt"
"math/rand"
"time"
)
type vector []float64
func e(n uint) vector {
if n > 4 {
panic("n must be less than 5")
}
result := make(vector, 32)
result[1<<n] = 1.0
return result
}
func cdot(a, b vector) vector {
return mul(vector{0.5}, add(mul(a, b), mul(b, a)))
}
func neg(x vector) vector {
return mul(vector{-1}, x)
}
func bitCount(i int) int {
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
i = (i + (i >> 4)) & 0x0F0F0F0F
i = i + (i >> 8)
i = i + (i >> 16)
return i & 0x0000003F
}
func reorderingSign(i, j int) float64 {
i >>= 1
sum := 0
for i != 0 {
sum += bitCount(i & j)
i >>= 1
}
cond := (sum & 1) == 0
if cond {
return 1.0
}
return -1.0
}
func add(a, b vector) vector {
result := make(vector, 32)
copy(result, a)
for i, _ := range b {
result[i] += b[i]
}
return result
}
func mul(a, b vector) vector {
result := make(vector, 32)
for i, _ := range a {
if a[i] != 0 {
for j, _ := range b {
if b[j] != 0 {
s := reorderingSign(i, j) * a[i] * b[j]
k := i ^ j
result[k] += s
}
}
}
}
return result
}
func randomVector() vector {
result := make(vector, 32)
for i := uint(0); i < 5; i++ {
result = add(result, mul(vector{rand.Float64()}, e(i)))
}
return result
}
func randomMultiVector() vector {
result := make(vector, 32)
for i := 0; i < 32; i++ {
result[i] = rand.Float64()
}
return result
}
func main() {
rand.Seed(time.Now().UnixNano())
for i := uint(0); i < 5; i++ {
for j := uint(0); j < 5; j++ {
if i < j {
if cdot(e(i), e(j))[0] != 0 {
fmt.Println("Unexpected non-null scalar product.")
return
}
} else if i == j {
if cdot(e(i), e(j))[0] == 0 {
fmt.Println("Unexpected null scalar product.")
}
}
}
}
a := randomMultiVector()
b := randomMultiVector()
c := randomMultiVector()
x := randomVector()
fmt.Println(mul(mul(a, b), c))
fmt.Println(mul(a, mul(b, c)))
fmt.Println(mul(a, add(b, c)))
fmt.Println(add(mul(a, b), mul(a, c)))
fmt.Println(mul(add(a, b), c))
fmt.Println(add(mul(a, c), mul(b, c)))
fmt.Println(mul(x, x))
}
|
Produce a functionally identical Go code for the snippet given in Python. | class Node:
def __init__(self, sub="", children=None):
self.sub = sub
self.ch = children or []
class SuffixTree:
def __init__(self, str):
self.nodes = [Node()]
for i in range(len(str)):
self.addSuffix(str[i:])
def addSuffix(self, suf):
n = 0
i = 0
while i < len(suf):
b = suf[i]
x2 = 0
while True:
children = self.nodes[n].ch
if x2 == len(children):
n2 = len(self.nodes)
self.nodes.append(Node(suf[i:], []))
self.nodes[n].ch.append(n2)
return
n2 = children[x2]
if self.nodes[n2].sub[0] == b:
break
x2 = x2 + 1
sub2 = self.nodes[n2].sub
j = 0
while j < len(sub2):
if suf[i + j] != sub2[j]:
n3 = n2
n2 = len(self.nodes)
self.nodes.append(Node(sub2[:j], [n3]))
self.nodes[n3].sub = sub2[j:]
self.nodes[n].ch[x2] = n2
break
j = j + 1
i = i + j
n = n2
def visualize(self):
if len(self.nodes) == 0:
print "<empty>"
return
def f(n, pre):
children = self.nodes[n].ch
if len(children) == 0:
print "--", self.nodes[n].sub
return
print "+-", self.nodes[n].sub
for c in children[:-1]:
print pre, "+-",
f(c, pre + " | ")
print pre, "+-",
f(children[-1], pre + " ")
f(0, "")
SuffixTree("banana$").visualize()
| package main
import "fmt"
func main() {
vis(buildTree("banana$"))
}
type tree []node
type node struct {
sub string
ch []int
}
func buildTree(s string) tree {
t := tree{node{}}
for i := range s {
t = t.addSuffix(s[i:])
}
return t
}
func (t tree) addSuffix(suf string) tree {
n := 0
for i := 0; i < len(suf); {
b := suf[i]
ch := t[n].ch
var x2, n2 int
for ; ; x2++ {
if x2 == len(ch) {
n2 = len(t)
t = append(t, node{sub: suf[i:]})
t[n].ch = append(t[n].ch, n2)
return t
}
n2 = ch[x2]
if t[n2].sub[0] == b {
break
}
}
sub2 := t[n2].sub
j := 0
for ; j < len(sub2); j++ {
if suf[i+j] != sub2[j] {
n3 := n2
n2 = len(t)
t = append(t, node{sub2[:j], []int{n3}})
t[n3].sub = sub2[j:]
t[n].ch[x2] = n2
break
}
}
i += j
n = n2
}
return t
}
func vis(t tree) {
if len(t) == 0 {
fmt.Println("<empty>")
return
}
var f func(int, string)
f = func(n int, pre string) {
children := t[n].ch
if len(children) == 0 {
fmt.Println("╴", t[n].sub)
return
}
fmt.Println("┐", t[n].sub)
last := len(children) - 1
for _, ch := range children[:last] {
fmt.Print(pre, "├─")
f(ch, pre+"│ ")
}
fmt.Print(pre, "└─")
f(children[last], pre+" ")
}
f(0, "")
}
|
Generate an equivalent Go version of this Python code. | class Node:
def __init__(self, sub="", children=None):
self.sub = sub
self.ch = children or []
class SuffixTree:
def __init__(self, str):
self.nodes = [Node()]
for i in range(len(str)):
self.addSuffix(str[i:])
def addSuffix(self, suf):
n = 0
i = 0
while i < len(suf):
b = suf[i]
x2 = 0
while True:
children = self.nodes[n].ch
if x2 == len(children):
n2 = len(self.nodes)
self.nodes.append(Node(suf[i:], []))
self.nodes[n].ch.append(n2)
return
n2 = children[x2]
if self.nodes[n2].sub[0] == b:
break
x2 = x2 + 1
sub2 = self.nodes[n2].sub
j = 0
while j < len(sub2):
if suf[i + j] != sub2[j]:
n3 = n2
n2 = len(self.nodes)
self.nodes.append(Node(sub2[:j], [n3]))
self.nodes[n3].sub = sub2[j:]
self.nodes[n].ch[x2] = n2
break
j = j + 1
i = i + j
n = n2
def visualize(self):
if len(self.nodes) == 0:
print "<empty>"
return
def f(n, pre):
children = self.nodes[n].ch
if len(children) == 0:
print "--", self.nodes[n].sub
return
print "+-", self.nodes[n].sub
for c in children[:-1]:
print pre, "+-",
f(c, pre + " | ")
print pre, "+-",
f(children[-1], pre + " ")
f(0, "")
SuffixTree("banana$").visualize()
| package main
import "fmt"
func main() {
vis(buildTree("banana$"))
}
type tree []node
type node struct {
sub string
ch []int
}
func buildTree(s string) tree {
t := tree{node{}}
for i := range s {
t = t.addSuffix(s[i:])
}
return t
}
func (t tree) addSuffix(suf string) tree {
n := 0
for i := 0; i < len(suf); {
b := suf[i]
ch := t[n].ch
var x2, n2 int
for ; ; x2++ {
if x2 == len(ch) {
n2 = len(t)
t = append(t, node{sub: suf[i:]})
t[n].ch = append(t[n].ch, n2)
return t
}
n2 = ch[x2]
if t[n2].sub[0] == b {
break
}
}
sub2 := t[n2].sub
j := 0
for ; j < len(sub2); j++ {
if suf[i+j] != sub2[j] {
n3 := n2
n2 = len(t)
t = append(t, node{sub2[:j], []int{n3}})
t[n3].sub = sub2[j:]
t[n].ch[x2] = n2
break
}
}
i += j
n = n2
}
return t
}
func vis(t tree) {
if len(t) == 0 {
fmt.Println("<empty>")
return
}
var f func(int, string)
f = func(n int, pre string) {
children := t[n].ch
if len(children) == 0 {
fmt.Println("╴", t[n].sub)
return
}
fmt.Println("┐", t[n].sub)
last := len(children) - 1
for _, ch := range children[:last] {
fmt.Print(pre, "├─")
f(ch, pre+"│ ")
}
fmt.Print(pre, "└─")
f(children[last], pre+" ")
}
f(0, "")
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. | myDict = { "hello": 13,
"world": 31,
"!" : 71 }
for key, value in myDict.items():
print ("key = %s, value = %s" % (key, value))
for key in myDict:
print ("key = %s" % key)
for key in myDict.keys():
print ("key = %s" % key)
for value in myDict.values():
print ("value = %s" % value)
| myMap := map[string]int {
"hello": 13,
"world": 31,
"!" : 71 }
for key, value := range myMap {
fmt.Printf("key = %s, value = %d\n", key, value)
}
for key := range myMap {
fmt.Printf("key = %s\n", key)
}
for _, value := range myMap {
fmt.Printf("value = %d\n", value)
}
|
Generate an equivalent Go version of this Python code. | >>> class num(int):
def __init__(self, b):
if 1 <= b <= 10:
return int.__init__(self+0)
else:
raise ValueError,"Value %s should be >=0 and <= 10" % b
>>> x = num(3)
>>> x = num(11)
Traceback (most recent call last):
File "<pyshell
x = num(11)
File "<pyshell
raise ValueError,"Value %s should be >=0 and <= 10" % b
ValueError: Value 11 should be >=0 and <= 10
>>> x
3
>>> type(x)
<class '__main__.num'>
>>>
| package main
import "fmt"
type TinyInt int
func NewTinyInt(i int) TinyInt {
if i < 1 {
i = 1
} else if i > 10 {
i = 10
}
return TinyInt(i)
}
func (t1 TinyInt) Add(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) + int(t2))
}
func (t1 TinyInt) Sub(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) - int(t2))
}
func (t1 TinyInt) Mul(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) * int(t2))
}
func (t1 TinyInt) Div(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) / int(t2))
}
func (t1 TinyInt) Rem(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) % int(t2))
}
func (t TinyInt) Inc() TinyInt {
return t.Add(TinyInt(1))
}
func (t TinyInt) Dec() TinyInt {
return t.Sub(TinyInt(1))
}
func main() {
t1 := NewTinyInt(6)
t2 := NewTinyInt(3)
fmt.Println("t1 =", t1)
fmt.Println("t2 =", t2)
fmt.Println("t1 + t2 =", t1.Add(t2))
fmt.Println("t1 - t2 =", t1.Sub(t2))
fmt.Println("t1 * t2 =", t1.Mul(t2))
fmt.Println("t1 / t2 =", t1.Div(t2))
fmt.Println("t1 % t2 =", t1.Rem(t2))
fmt.Println("t1 + 1 =", t1.Inc())
fmt.Println("t1 - 1 =", t1.Dec())
}
|
Transform the following Python implementation into Go, maintaining the same output and logic. | from sympy.ntheory import factorint
def D(n):
if n < 0:
return -D(-n)
elif n < 2:
return 0
else:
fdict = factorint(n)
if len(fdict) == 1 and 1 in fdict:
return 1
return sum([n * e // p for p, e in fdict.items()])
for n in range(-99, 101):
print('{:5}'.format(D(n)), end='\n' if n % 10 == 0 else '')
print()
for m in range(1, 21):
print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))
| package main
import (
"fmt"
"rcu"
)
func D(n float64) float64 {
if n < 0 {
return -D(-n)
}
if n < 2 {
return 0
}
var f []int
if n < 1e19 {
f = rcu.PrimeFactors(int(n))
} else {
g := int(n / 100)
f = rcu.PrimeFactors(g)
f = append(f, []int{2, 2, 5, 5}...)
}
c := len(f)
if c == 1 {
return 1
}
if c == 2 {
return float64(f[0] + f[1])
}
d := n / float64(f[0])
return D(d)*float64(f[0]) + d
}
func main() {
ad := make([]int, 200)
for n := -99; n < 101; n++ {
ad[n+99] = int(D(float64(n)))
}
rcu.PrintTable(ad, 10, 4, false)
fmt.Println()
pow := 1.0
for m := 1; m < 21; m++ {
pow *= 10
fmt.Printf("D(10^%-2d) / 7 = %.0f\n", m, D(pow)/7)
}
}
|
Please provide an equivalent version of this Python code in Go. |
from itertools import permutations
numList = [2,3,1]
baseList = []
for i in numList:
for j in range(0,i):
baseList.append(i)
stringDict = {'A':2,'B':3,'C':1}
baseString=""
for i in stringDict:
for j in range(0,stringDict[i]):
baseString+=i
print("Permutations for " + str(baseList) + " : ")
[print(i) for i in set(permutations(baseList))]
print("Permutations for " + baseString + " : ")
[print(i) for i in set(permutations(baseString))]
| package main
import "fmt"
func shouldSwap(s []byte, start, curr int) bool {
for i := start; i < curr; i++ {
if s[i] == s[curr] {
return false
}
}
return true
}
func findPerms(s []byte, index, n int, res *[]string) {
if index >= n {
*res = append(*res, string(s))
return
}
for i := index; i < n; i++ {
check := shouldSwap(s, index, i)
if check {
s[index], s[i] = s[i], s[index]
findPerms(s, index+1, n, res)
s[index], s[i] = s[i], s[index]
}
}
}
func createSlice(nums []int, charSet string) []byte {
var chars []byte
for i := 0; i < len(nums); i++ {
for j := 0; j < nums[i]; j++ {
chars = append(chars, charSet[i])
}
}
return chars
}
func main() {
var res, res2, res3 []string
nums := []int{2, 1}
s := createSlice(nums, "12")
findPerms(s, 0, len(s), &res)
fmt.Println(res)
fmt.Println()
nums = []int{2, 3, 1}
s = createSlice(nums, "123")
findPerms(s, 0, len(s), &res2)
fmt.Println(res2)
fmt.Println()
s = createSlice(nums, "ABC")
findPerms(s, 0, len(s), &res3)
fmt.Println(res3)
}
|
Generate an equivalent Go version of this Python code. | def penrose(depth):
print( <g id="A{d+1}" transform="translate(100, 0) scale(0.6180339887498949)">
<use href="
<use href="
</g>
<g id="B{d+1}">
<use href="
<use href="
</g> <g id="G">
<use href="
<use href="
</g>
</defs>
<g transform="scale(2, 2)">
<use href="
<use href="
<use href="
<use href="
<use href="
</g>
</svg>''')
penrose(6)
| package main
import (
"github.com/fogleman/gg"
"math"
)
type tiletype int
const (
kite tiletype = iota
dart
)
type tile struct {
tt tiletype
x, y float64
angle, size float64
}
var gr = (1 + math.Sqrt(5)) / 2
const theta = math.Pi / 5
func setupPrototiles(w, h int) []tile {
var proto []tile
for a := math.Pi/2 + theta; a < 3*math.Pi; a += 2 * theta {
ww := float64(w / 2)
hh := float64(h / 2)
proto = append(proto, tile{kite, ww, hh, a, float64(w) / 2.5})
}
return proto
}
func distinctTiles(tls []tile) []tile {
tileset := make(map[tile]bool)
for _, tl := range tls {
tileset[tl] = true
}
distinct := make([]tile, len(tileset))
for tl, _ := range tileset {
distinct = append(distinct, tl)
}
return distinct
}
func deflateTiles(tls []tile, gen int) []tile {
if gen <= 0 {
return tls
}
var next []tile
for _, tl := range tls {
x, y, a, size := tl.x, tl.y, tl.angle, tl.size/gr
var nx, ny float64
if tl.tt == dart {
next = append(next, tile{kite, x, y, a + 5*theta, size})
for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {
nx = x + math.Cos(a-4*theta*sign)*gr*tl.size
ny = y - math.Sin(a-4*theta*sign)*gr*tl.size
next = append(next, tile{dart, nx, ny, a - 4*theta*sign, size})
}
} else {
for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {
next = append(next, tile{dart, x, y, a - 4*theta*sign, size})
nx = x + math.Cos(a-theta*sign)*gr*tl.size
ny = y - math.Sin(a-theta*sign)*gr*tl.size
next = append(next, tile{kite, nx, ny, a + 3*theta*sign, size})
}
}
}
tls = distinctTiles(next)
return deflateTiles(tls, gen-1)
}
func drawTiles(dc *gg.Context, tls []tile) {
dist := [2][3]float64{{gr, gr, gr}, {-gr, -1, -gr}}
for _, tl := range tls {
angle := tl.angle - theta
dc.MoveTo(tl.x, tl.y)
ord := tl.tt
for i := 0; i < 3; i++ {
x := tl.x + dist[ord][i]*tl.size*math.Cos(angle)
y := tl.y - dist[ord][i]*tl.size*math.Sin(angle)
dc.LineTo(x, y)
angle += theta
}
dc.ClosePath()
if ord == kite {
dc.SetHexColor("FFA500")
} else {
dc.SetHexColor("FFFF00")
}
dc.FillPreserve()
dc.SetHexColor("A9A9A9")
dc.SetLineWidth(1)
dc.Stroke()
}
}
func main() {
w, h := 700, 450
dc := gg.NewContext(w, h)
dc.SetRGB(1, 1, 1)
dc.Clear()
tiles := deflateTiles(setupPrototiles(w, h), 5)
drawTiles(dc, tiles)
dc.SavePNG("penrose_tiling.png")
}
|
Maintain the same structure and functionality when rewriting this code in Go. |
from sympy import factorint
sphenics1m, sphenic_triplets1m = [], []
for i in range(3, 1_000_000):
d = factorint(i)
if len(d) == 3 and sum(d.values()) == 3:
sphenics1m.append(i)
if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1:
sphenic_triplets1m.append(i)
print('Sphenic numbers less than 1000:')
for i, n in enumerate(sphenics1m):
if n < 1000:
print(f'{n : 5}', end='\n' if (i + 1) % 15 == 0 else '')
else:
break
print('\n\nSphenic triplets less than 10_000:')
for i, n in enumerate(sphenic_triplets1m):
if n < 10_000:
print(f'({n - 2} {n - 1} {n})', end='\n' if (i + 1) % 3 == 0 else ' ')
else:
break
print('\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m),
'sphenic triplets less than 1 million.')
S2HK = sphenics1m[200_000 - 1]
T5K = sphenic_triplets1m[5000 - 1]
print(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.')
print(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')
| package main
import (
"fmt"
"math"
"rcu"
"sort"
)
func main() {
const limit = 1000000
limit2 := int(math.Cbrt(limit))
primes := rcu.Primes(limit / 6)
pc := len(primes)
var sphenic []int
fmt.Println("Sphenic numbers less than 1,000:")
for i := 0; i < pc-2; i++ {
if primes[i] > limit2 {
break
}
for j := i + 1; j < pc-1; j++ {
prod := primes[i] * primes[j]
if prod+primes[j+1] >= limit {
break
}
for k := j + 1; k < pc; k++ {
res := prod * primes[k]
if res >= limit {
break
}
sphenic = append(sphenic, res)
}
}
}
sort.Ints(sphenic)
ix := sort.Search(len(sphenic), func(i int) bool { return sphenic[i] >= 1000 })
rcu.PrintTable(sphenic[:ix], 15, 3, false)
fmt.Println("\nSphenic triplets less than 10,000:")
var triplets [][3]int
for i := 0; i < len(sphenic)-2; i++ {
s := sphenic[i]
if sphenic[i+1] == s+1 && sphenic[i+2] == s+2 {
triplets = append(triplets, [3]int{s, s + 1, s + 2})
}
}
ix = sort.Search(len(triplets), func(i int) bool { return triplets[i][2] >= 10000 })
for i := 0; i < ix; i++ {
fmt.Printf("%4d ", triplets[i])
if (i+1)%3 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThere are %s sphenic numbers less than 1,000,000.\n", rcu.Commatize(len(sphenic)))
fmt.Printf("There are %s sphenic triplets less than 1,000,000.\n", rcu.Commatize(len(triplets)))
s := sphenic[199999]
pf := rcu.PrimeFactors(s)
fmt.Printf("The 200,000th sphenic number is %s (%d*%d*%d).\n", rcu.Commatize(s), pf[0], pf[1], pf[2])
fmt.Printf("The 5,000th sphenic triplet is %v.\n.", triplets[4999])
}
|
Write a version of this Python function in Go with identical behavior. | def to_tree(x, index=0, depth=1):
so_far = []
while index < len(x):
this = x[index]
if this == depth:
so_far.append(this)
elif this > depth:
index, deeper = to_tree(x, index, depth + 1)
so_far.append(deeper)
else:
index -=1
break
index += 1
return (index, so_far) if depth > 1 else so_far
if __name__ == "__main__":
from pprint import pformat
def pnest(nest:list, width: int=9) -> str:
text = pformat(nest, width=width).replace('\n', '\n ')
print(f" OR {text}\n")
exercises = [
[],
[1, 2, 4],
[3, 1, 3, 1],
[1, 2, 3, 1],
[3, 2, 1, 3],
[3, 3, 3, 1, 1, 3, 3, 3],
]
for flat in exercises:
nest = to_tree(flat)
print(f"{flat} NESTS TO: {nest}")
pnest(nest)
| package main
import "fmt"
type any = interface{}
func toTree(list []int) any {
s := []any{[]any{}}
for _, n := range list {
for n != len(s) {
if n > len(s) {
inner := []any{}
s[len(s)-1] = append(s[len(s)-1].([]any), inner)
s = append(s, inner)
} else {
s = s[0 : len(s)-1]
}
}
s[len(s)-1] = append(s[len(s)-1].([]any), n)
for i := len(s) - 2; i >= 0; i-- {
le := len(s[i].([]any))
s[i].([]any)[le-1] = s[i+1]
}
}
return s[0]
}
func main() {
tests := [][]int{
{},
{1, 2, 4},
{3, 1, 3, 1},
{1, 2, 3, 1},
{3, 2, 1, 3},
{3, 3, 3, 1, 1, 3, 3, 3},
}
for _, test := range tests {
nest := toTree(test)
fmt.Printf("%17s => %v\n", fmt.Sprintf("%v", test), nest)
}
}
|
Generate an equivalent Go version of this Python code. | def to_tree(x, index=0, depth=1):
so_far = []
while index < len(x):
this = x[index]
if this == depth:
so_far.append(this)
elif this > depth:
index, deeper = to_tree(x, index, depth + 1)
so_far.append(deeper)
else:
index -=1
break
index += 1
return (index, so_far) if depth > 1 else so_far
if __name__ == "__main__":
from pprint import pformat
def pnest(nest:list, width: int=9) -> str:
text = pformat(nest, width=width).replace('\n', '\n ')
print(f" OR {text}\n")
exercises = [
[],
[1, 2, 4],
[3, 1, 3, 1],
[1, 2, 3, 1],
[3, 2, 1, 3],
[3, 3, 3, 1, 1, 3, 3, 3],
]
for flat in exercises:
nest = to_tree(flat)
print(f"{flat} NESTS TO: {nest}")
pnest(nest)
| package main
import "fmt"
type any = interface{}
func toTree(list []int) any {
s := []any{[]any{}}
for _, n := range list {
for n != len(s) {
if n > len(s) {
inner := []any{}
s[len(s)-1] = append(s[len(s)-1].([]any), inner)
s = append(s, inner)
} else {
s = s[0 : len(s)-1]
}
}
s[len(s)-1] = append(s[len(s)-1].([]any), n)
for i := len(s) - 2; i >= 0; i-- {
le := len(s[i].([]any))
s[i].([]any)[le-1] = s[i+1]
}
}
return s[0]
}
func main() {
tests := [][]int{
{},
{1, 2, 4},
{3, 1, 3, 1},
{1, 2, 3, 1},
{3, 2, 1, 3},
{3, 3, 3, 1, 1, 3, 3, 3},
}
for _, test := range tests {
nest := toTree(test)
fmt.Printf("%17s => %v\n", fmt.Sprintf("%v", test), nest)
}
}
|
Convert this Python block to Go, preserving its control flow and logic. | from __future__ import print_function
import os
import hashlib
import datetime
def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"):
knownFiles = {}
for root, dirs, files in os.walk(pth):
for fina in files:
fullFina = os.path.join(root, fina)
isSymLink = os.path.islink(fullFina)
if isSymLink:
continue
si = os.path.getsize(fullFina)
if si < minSize:
continue
if si not in knownFiles:
knownFiles[si] = {}
h = hashlib.new(hashName)
h.update(open(fullFina, "rb").read())
hashed = h.digest()
if hashed in knownFiles[si]:
fileRec = knownFiles[si][hashed]
fileRec.append(fullFina)
else:
knownFiles[si][hashed] = [fullFina]
sizeList = list(knownFiles.keys())
sizeList.sort(reverse=True)
for si in sizeList:
filesAtThisSize = knownFiles[si]
for hashVal in filesAtThisSize:
if len(filesAtThisSize[hashVal]) < 2:
continue
fullFinaLi = filesAtThisSize[hashVal]
print ("=======Duplicate=======")
for fullFina in fullFinaLi:
st = os.stat(fullFina)
isHardLink = st.st_nlink > 1
infoStr = []
if isHardLink:
infoStr.append("(Hard linked)")
fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')
print (fmtModTime, si, os.path.relpath(fullFina, pth), " ".join(infoStr))
if __name__=="__main__":
FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)
| package main
import (
"fmt"
"crypto/md5"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"time"
)
type fileData struct {
filePath string
info os.FileInfo
}
type hash [16]byte
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func checksum(filePath string) hash {
bytes, err := ioutil.ReadFile(filePath)
check(err)
return hash(md5.Sum(bytes))
}
func findDuplicates(dirPath string, minSize int64) [][2]fileData {
var dups [][2]fileData
m := make(map[hash]fileData)
werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && info.Size() >= minSize {
h := checksum(path)
fd, ok := m[h]
fd2 := fileData{path, info}
if !ok {
m[h] = fd2
} else {
dups = append(dups, [2]fileData{fd, fd2})
}
}
return nil
})
check(werr)
return dups
}
func main() {
dups := findDuplicates(".", 1)
fmt.Println("The following pairs of files have the same size and the same hash:\n")
fmt.Println("File name Size Date last modified")
fmt.Println("==========================================================")
sort.Slice(dups, func(i, j int) bool {
return dups[i][0].info.Size() > dups[j][0].info.Size()
})
for _, dup := range dups {
for i := 0; i < 2; i++ {
d := dup[i]
fmt.Printf("%-20s %8d %v\n", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))
}
fmt.Println()
}
}
|
Change the programming language of this snippet from Python to Go without modifying what it does. |
from functools import reduce
from itertools import count, islice
def sylvester():
def go(n):
return 1 + reduce(
lambda a, x: a * go(x),
range(0, n),
1
) if 0 != n else 2
return map(go, count(0))
def main():
print("First 10 terms of OEIS A000058:")
xs = list(islice(sylvester(), 10))
print('\n'.join([
str(x) for x in xs
]))
print("\nSum of the reciprocals of the first 10 terms:")
print(
reduce(lambda a, x: a + 1 / x, xs, 0)
)
if __name__ == '__main__':
main()
| package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewInt(1)
two := big.NewInt(2)
next := new(big.Int)
sylvester := []*big.Int{two}
prod := new(big.Int).Set(two)
count := 1
for count < 10 {
next.Add(prod, one)
sylvester = append(sylvester, new(big.Int).Set(next))
count++
prod.Mul(prod, next)
}
fmt.Println("The first 10 terms in the Sylvester sequence are:")
for i := 0; i < 10; i++ {
fmt.Println(sylvester[i])
}
sumRecip := new(big.Rat)
for _, s := range sylvester {
sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))
}
fmt.Println("\nThe sum of their reciprocals as a rational number is:")
fmt.Println(sumRecip)
fmt.Println("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
fmt.Println(sumRecip.FloatString(211))
}
|
Translate the given Python code snippet into Go without altering its behavior. | from sys import stdout
moves = [
[-1, -2], [1, -2], [-1, 2], [1, 2],
[-2, -1], [-2, 1], [2, -1], [2, 1]
]
def solve(pz, sz, sx, sy, idx, cnt):
if idx > cnt:
return 1
for i in range(len(moves)):
x = sx + moves[i][0]
y = sy + moves[i][1]
if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:
pz[x][y] = idx
if 1 == solve(pz, sz, x, y, idx + 1, cnt):
return 1
pz[x][y] = 0
return 0
def find_solution(pz, sz):
p = [[-1 for j in range(sz)] for i in range(sz)]
idx = x = y = cnt = 0
for j in range(sz):
for i in range(sz):
if pz[idx] == "x":
p[i][j] = 0
cnt += 1
elif pz[idx] == "s":
p[i][j] = 1
cnt += 1
x = i
y = j
idx += 1
if 1 == solve(p, sz, x, y, 2, cnt):
for j in range(sz):
for i in range(sz):
if p[i][j] != -1:
stdout.write(" {:0{}d}".format(p[i][j], 2))
else:
stdout.write(" ")
print()
else:
print("Cannot solve this puzzle!")
find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8)
print()
find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
| package main
import "fmt"
var moves = [][2]int{
{-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},
}
var board1 = " xxx " +
" x xx " +
" xxxxxxx" +
"xxx x x" +
"x x xxx" +
"sxxxxxx " +
" xx x " +
" xxx "
var board2 = ".....s.x....." +
".....x.x....." +
"....xxxxx...." +
".....xxx....." +
"..x..x.x..x.." +
"xxxxx...xxxxx" +
"..xx.....xx.." +
"xxxxx...xxxxx" +
"..x..x.x..x.." +
".....xxx....." +
"....xxxxx...." +
".....x.x....." +
".....x.x....."
func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {
if idx > cnt {
return true
}
for i := 0; i < len(moves); i++ {
x := sx + moves[i][0]
y := sy + moves[i][1]
if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {
pz[x][y] = idx
if solve(pz, sz, x, y, idx+1, cnt) {
return true
}
pz[x][y] = 0
}
}
return false
}
func findSolution(b string, sz int) {
pz := make([][]int, sz)
for i := 0; i < sz; i++ {
pz[i] = make([]int, sz)
for j := 0; j < sz; j++ {
pz[i][j] = -1
}
}
var x, y, idx, cnt int
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
switch b[idx] {
case 'x':
pz[i][j] = 0
cnt++
case 's':
pz[i][j] = 1
cnt++
x, y = i, j
}
idx++
}
}
if solve(pz, sz, x, y, 2, cnt) {
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
if pz[i][j] != -1 {
fmt.Printf("%02d ", pz[i][j])
} else {
fmt.Print("-- ")
}
}
fmt.Println()
}
} else {
fmt.Println("Cannot solve this puzzle!")
}
}
func main() {
findSolution(board1, 8)
fmt.Println()
findSolution(board2, 13)
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. | from sys import stdout
moves = [
[-1, -2], [1, -2], [-1, 2], [1, 2],
[-2, -1], [-2, 1], [2, -1], [2, 1]
]
def solve(pz, sz, sx, sy, idx, cnt):
if idx > cnt:
return 1
for i in range(len(moves)):
x = sx + moves[i][0]
y = sy + moves[i][1]
if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:
pz[x][y] = idx
if 1 == solve(pz, sz, x, y, idx + 1, cnt):
return 1
pz[x][y] = 0
return 0
def find_solution(pz, sz):
p = [[-1 for j in range(sz)] for i in range(sz)]
idx = x = y = cnt = 0
for j in range(sz):
for i in range(sz):
if pz[idx] == "x":
p[i][j] = 0
cnt += 1
elif pz[idx] == "s":
p[i][j] = 1
cnt += 1
x = i
y = j
idx += 1
if 1 == solve(p, sz, x, y, 2, cnt):
for j in range(sz):
for i in range(sz):
if p[i][j] != -1:
stdout.write(" {:0{}d}".format(p[i][j], 2))
else:
stdout.write(" ")
print()
else:
print("Cannot solve this puzzle!")
find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8)
print()
find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
| package main
import "fmt"
var moves = [][2]int{
{-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},
}
var board1 = " xxx " +
" x xx " +
" xxxxxxx" +
"xxx x x" +
"x x xxx" +
"sxxxxxx " +
" xx x " +
" xxx "
var board2 = ".....s.x....." +
".....x.x....." +
"....xxxxx...." +
".....xxx....." +
"..x..x.x..x.." +
"xxxxx...xxxxx" +
"..xx.....xx.." +
"xxxxx...xxxxx" +
"..x..x.x..x.." +
".....xxx....." +
"....xxxxx...." +
".....x.x....." +
".....x.x....."
func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {
if idx > cnt {
return true
}
for i := 0; i < len(moves); i++ {
x := sx + moves[i][0]
y := sy + moves[i][1]
if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {
pz[x][y] = idx
if solve(pz, sz, x, y, idx+1, cnt) {
return true
}
pz[x][y] = 0
}
}
return false
}
func findSolution(b string, sz int) {
pz := make([][]int, sz)
for i := 0; i < sz; i++ {
pz[i] = make([]int, sz)
for j := 0; j < sz; j++ {
pz[i][j] = -1
}
}
var x, y, idx, cnt int
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
switch b[idx] {
case 'x':
pz[i][j] = 0
cnt++
case 's':
pz[i][j] = 1
cnt++
x, y = i, j
}
idx++
}
}
if solve(pz, sz, x, y, 2, cnt) {
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
if pz[i][j] != -1 {
fmt.Printf("%02d ", pz[i][j])
} else {
fmt.Print("-- ")
}
}
fmt.Println()
}
} else {
fmt.Println("Cannot solve this puzzle!")
}
}
func main() {
findSolution(board1, 8)
fmt.Println()
findSolution(board2, 13)
}
|
Write a version of this Python function in Go with identical behavior. | from __future__ import print_function
def order_disjoint_list_items(data, items):
itemindices = []
for item in set(items):
itemcount = items.count(item)
lastindex = [-1]
for i in range(itemcount):
lastindex.append(data.index(item, lastindex[-1] + 1))
itemindices += lastindex[1:]
itemindices.sort()
for index, item in zip(itemindices, items):
data[index] = item
if __name__ == '__main__':
tostring = ' '.join
for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')),
(str.split('the cat sat on the mat'), str.split('cat mat')),
(list('ABCABCABC'), list('CACA')),
(list('ABCABDABE'), list('EADA')),
(list('AB'), list('B')),
(list('AB'), list('BA')),
(list('ABBA'), list('BA')),
(list(''), list('')),
(list('A'), list('A')),
(list('AB'), list('')),
(list('ABBA'), list('AB')),
(list('ABAB'), list('AB')),
(list('ABAB'), list('BABA')),
(list('ABCCBA'), list('ACAC')),
(list('ABCCBA'), list('CACA')),
]:
print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ')
order_disjoint_list_items(data, items)
print("-> M' %r" % tostring(data))
| package main
import (
"fmt"
"sort"
"strings"
)
type indexSort struct {
val sort.Interface
ind []int
}
func (s indexSort) Len() int { return len(s.ind) }
func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }
func (s indexSort) Swap(i, j int) {
s.val.Swap(s.ind[i], s.ind[j])
s.ind[i], s.ind[j] = s.ind[j], s.ind[i]
}
func disjointSliceSort(m, n []string) []string {
s := indexSort{sort.StringSlice(m), make([]int, 0, len(n))}
used := make(map[int]bool)
for _, nw := range n {
for i, mw := range m {
if used[i] || mw != nw {
continue
}
used[i] = true
s.ind = append(s.ind, i)
break
}
}
sort.Sort(s)
return s.val.(sort.StringSlice)
}
func disjointStringSort(m, n string) string {
return strings.Join(
disjointSliceSort(strings.Fields(m), strings.Fields(n)), " ")
}
func main() {
for _, data := range []struct{ m, n string }{
{"the cat sat on the mat", "mat cat"},
{"the cat sat on the mat", "cat mat"},
{"A B C A B C A B C", "C A C A"},
{"A B C A B D A B E", "E A D A"},
{"A B", "B"},
{"A B", "B A"},
{"A B B A", "B A"},
} {
mp := disjointStringSort(data.m, data.n)
fmt.Printf("%s → %s » %s\n", data.m, data.n, mp)
}
}
|
Convert this Python snippet to Go and keep its semantics consistent. | from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
for s in table1:
h[s[index1]].append(s)
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "Popeye"),
(28, "Alan")]
table2 = [("Jonah", "Whales"),
("Jonah", "Spiders"),
("Alan", "Ghosts"),
("Alan", "Zombies"),
("Glory", "Buffy")]
for row in hashJoin(table1, 1, table2, 0):
print(row)
| package main
import "fmt"
func main() {
tableA := []struct {
value int
key string
}{
{27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"},
{28, "Alan"},
}
tableB := []struct {
key string
value string
}{
{"Jonah", "Whales"}, {"Jonah", "Spiders"},
{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
}
h := map[string][]int{}
for i, r := range tableA {
h[r.key] = append(h[r.key], i)
}
for _, x := range tableB {
for _, a := range h[x.key] {
fmt.Println(tableA[a], x)
}
}
}
|
Translate the given Python code snippet into Go without altering its behavior. | from math import gcd
from sympy import factorint
def is_Achilles(n):
p = factorint(n).values()
return all(i > 1 for i in p) and gcd(*p) == 1
def is_strong_Achilles(n):
return is_Achilles(n) and is_Achilles(totient(n))
def test_strong_Achilles(nachilles, nstrongachilles):
print('First', nachilles, 'Achilles numbers:')
n, found = 0, 0
while found < nachilles:
if is_Achilles(n):
found += 1
print(f'{n: 8,}', end='\n' if found % 10 == 0 else '')
n += 1
print('\nFirst', nstrongachilles, 'strong Achilles numbers:')
n, found = 0, 0
while found < nstrongachilles:
if is_strong_Achilles(n):
found += 1
print(f'{n: 9,}', end='\n' if found % 10 == 0 else '')
n += 1
print('\nCount of Achilles numbers for various intervals:')
intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]
for interval in intervals:
print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))
test_strong_Achilles(50, 100)
| package main
import (
"fmt"
"math"
"sort"
)
func totient(n int) int {
tot := n
i := 2
for i*i <= n {
if n%i == 0 {
for n%i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
var pps = make(map[int]bool)
func getPerfectPowers(maxExp int) {
upper := math.Pow(10, float64(maxExp))
for i := 2; i <= int(math.Sqrt(upper)); i++ {
fi := float64(i)
p := fi
for {
p *= fi
if p >= upper {
break
}
pps[int(p)] = true
}
}
}
func getAchilles(minExp, maxExp int) map[int]bool {
lower := math.Pow(10, float64(minExp))
upper := math.Pow(10, float64(maxExp))
achilles := make(map[int]bool)
for b := 1; b <= int(math.Cbrt(upper)); b++ {
b3 := b * b * b
for a := 1; a <= int(math.Sqrt(upper)); a++ {
p := b3 * a * a
if p >= int(upper) {
break
}
if p >= int(lower) {
if _, ok := pps[p]; !ok {
achilles[p] = true
}
}
}
}
return achilles
}
func main() {
maxDigits := 15
getPerfectPowers(maxDigits)
achillesSet := getAchilles(1, 5)
achilles := make([]int, len(achillesSet))
i := 0
for k := range achillesSet {
achilles[i] = k
i++
}
sort.Ints(achilles)
fmt.Println("First 50 Achilles numbers:")
for i = 0; i < 50; i++ {
fmt.Printf("%4d ", achilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 strong Achilles numbers:")
var strongAchilles []int
count := 0
for n := 0; count < 30; n++ {
tot := totient(achilles[n])
if _, ok := achillesSet[tot]; ok {
strongAchilles = append(strongAchilles, achilles[n])
count++
}
}
for i = 0; i < 30; i++ {
fmt.Printf("%5d ", strongAchilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nNumber of Achilles numbers with:")
for d := 2; d <= maxDigits; d++ {
ac := len(getAchilles(d-1, d))
fmt.Printf("%2d digits: %d\n", d, ac)
}
}
|
Port the following code from Python to Go with equivalent syntax and logic. | from math import gcd
from sympy import factorint
def is_Achilles(n):
p = factorint(n).values()
return all(i > 1 for i in p) and gcd(*p) == 1
def is_strong_Achilles(n):
return is_Achilles(n) and is_Achilles(totient(n))
def test_strong_Achilles(nachilles, nstrongachilles):
print('First', nachilles, 'Achilles numbers:')
n, found = 0, 0
while found < nachilles:
if is_Achilles(n):
found += 1
print(f'{n: 8,}', end='\n' if found % 10 == 0 else '')
n += 1
print('\nFirst', nstrongachilles, 'strong Achilles numbers:')
n, found = 0, 0
while found < nstrongachilles:
if is_strong_Achilles(n):
found += 1
print(f'{n: 9,}', end='\n' if found % 10 == 0 else '')
n += 1
print('\nCount of Achilles numbers for various intervals:')
intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]
for interval in intervals:
print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))
test_strong_Achilles(50, 100)
| package main
import (
"fmt"
"math"
"sort"
)
func totient(n int) int {
tot := n
i := 2
for i*i <= n {
if n%i == 0 {
for n%i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
var pps = make(map[int]bool)
func getPerfectPowers(maxExp int) {
upper := math.Pow(10, float64(maxExp))
for i := 2; i <= int(math.Sqrt(upper)); i++ {
fi := float64(i)
p := fi
for {
p *= fi
if p >= upper {
break
}
pps[int(p)] = true
}
}
}
func getAchilles(minExp, maxExp int) map[int]bool {
lower := math.Pow(10, float64(minExp))
upper := math.Pow(10, float64(maxExp))
achilles := make(map[int]bool)
for b := 1; b <= int(math.Cbrt(upper)); b++ {
b3 := b * b * b
for a := 1; a <= int(math.Sqrt(upper)); a++ {
p := b3 * a * a
if p >= int(upper) {
break
}
if p >= int(lower) {
if _, ok := pps[p]; !ok {
achilles[p] = true
}
}
}
}
return achilles
}
func main() {
maxDigits := 15
getPerfectPowers(maxDigits)
achillesSet := getAchilles(1, 5)
achilles := make([]int, len(achillesSet))
i := 0
for k := range achillesSet {
achilles[i] = k
i++
}
sort.Ints(achilles)
fmt.Println("First 50 Achilles numbers:")
for i = 0; i < 50; i++ {
fmt.Printf("%4d ", achilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 strong Achilles numbers:")
var strongAchilles []int
count := 0
for n := 0; count < 30; n++ {
tot := totient(achilles[n])
if _, ok := achillesSet[tot]; ok {
strongAchilles = append(strongAchilles, achilles[n])
count++
}
}
for i = 0; i < 30; i++ {
fmt.Printf("%5d ", strongAchilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nNumber of Achilles numbers with:")
for d := 2; d <= maxDigits; d++ {
ac := len(getAchilles(d-1, d))
fmt.Printf("%2d digits: %d\n", d, ac)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.