Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Produce a language-to-language conversion: from Python to Go, same semantics. | import time, calendar, sched, winsound
duration = 750
freq = 1280
bellchar = "\u2407"
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')
def gap(n=1):
time.sleep(n * duration / 1000)
off = gap
def on(n=1):
winsound.Beep(freq, n * duration)
def bong():
on(); off(0.5)
def bongs(m):
for i in range(m):
print(bellchar, end=' ')
bong()
if i % 2:
print(' ', end='')
off(0.5)
print('')
scheds = sched.scheduler(time.time, time.sleep)
def ships_bell(now=None):
def adjust_to_half_hour(atime):
atime[4] = (atime[4] // 30) * 30
atime[5] = 0
return atime
debug = now is not None
rightnow = time.gmtime()
if not debug:
now = adjust_to_half_hour( list(rightnow) )
then = now[::]
then[4] += 30
hr, mn = now[3:5]
watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)
b += 1
bells = '%i bell%s' % (b, 's' if b > 1 else ' ')
if debug:
print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')
else:
print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')
bongs(b)
if not debug:
scheds.enterabs(calendar.timegm(then), 0, ships_bell)
scheds.run()
def dbg_tester():
for h in range(24):
for m in (0, 30):
if (h,m) == (24,30): break
ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )
if __name__ == '__main__':
ships_bell()
| package main
import (
"fmt"
"strings"
"time"
)
func main() {
watches := []string{
"First", "Middle", "Morning", "Forenoon",
"Afternoon", "Dog", "First",
}
for {
t := time.Now()
h := t.Hour()
m := t.Minute()
s := t.Second()
if (m == 0 || m == 30) && s == 0 {
bell := 0
if m == 30 {
bell = 1
}
bells := (h*2 + bell) % 8
watch := h/4 + 1
if bells == 0 {
bells = 8
watch--
}
sound := strings.Repeat("\a", bells)
pl := "s"
if bells == 1 {
pl = " "
}
w := watches[watch] + " watch"
if watch == 5 {
if bells < 5 {
w = "First " + w
} else {
w = "Last " + w
}
}
fmt.Printf("%s%02d:%02d = %d bell%s : %s\n", sound, h, m, bells, pl, w)
}
time.Sleep(1 * time.Second)
}
}
|
Port the following code from Python to Go with equivalent syntax and logic. | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
| package main
import "fmt"
func main() {
for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {
f, ok := arFib(n)
if ok {
fmt.Printf("fib %d = %d\n", n, f)
} else {
fmt.Println("fib undefined for negative numbers")
}
}
}
func arFib(n int) (int, bool) {
switch {
case n < 0:
return 0, false
case n < 2:
return n, true
}
return yc(func(recurse fn) fn {
return func(left, term1, term2 int) int {
if left == 0 {
return term1+term2
}
return recurse(left-1, term1+term2, term1)
}
})(n-2, 1, 0), true
}
type fn func(int, int, int) int
type ff func(fn) fn
type fx func(fx) fn
func yc(f ff) fn {
return func(x fx) fn {
return x(x)
}(func(x fx) fn {
return f(func(a1, a2, a3 int) int {
return x(x)(a1, a2, a3)
})
})
}
|
Write a version of this Python function in Go with identical behavior. | print "knight"[1:]
print "socks"[:-1]
print "brooms"[1:-1]
| package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "ASCII"
fmt.Println("String: ", s)
fmt.Println("First byte removed: ", s[1:])
fmt.Println("Last byte removed: ", s[:len(s)-1])
fmt.Println("First and last removed:", s[1:len(s)-1])
u := "Δημοτική"
fmt.Println("String: ", u)
_, sizeFirst := utf8.DecodeRuneInString(u)
fmt.Println("First rune removed: ", u[sizeFirst:])
_, sizeLast := utf8.DecodeLastRuneInString(u)
fmt.Println("Last rune removed: ", u[:len(u)-sizeLast])
fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. | print "knight"[1:]
print "socks"[:-1]
print "brooms"[1:-1]
| package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "ASCII"
fmt.Println("String: ", s)
fmt.Println("First byte removed: ", s[1:])
fmt.Println("Last byte removed: ", s[:len(s)-1])
fmt.Println("First and last removed:", s[1:len(s)-1])
u := "Δημοτική"
fmt.Println("String: ", u)
_, sizeFirst := utf8.DecodeRuneInString(u)
fmt.Println("First rune removed: ", u[sizeFirst:])
_, sizeLast := utf8.DecodeLastRuneInString(u)
fmt.Println("Last rune removed: ", u[:len(u)-sizeLast])
fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}
|
Port the following code from Python to Go with equivalent syntax and logic. | print "knight"[1:]
print "socks"[:-1]
print "brooms"[1:-1]
| package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "ASCII"
fmt.Println("String: ", s)
fmt.Println("First byte removed: ", s[1:])
fmt.Println("Last byte removed: ", s[:len(s)-1])
fmt.Println("First and last removed:", s[1:len(s)-1])
u := "Δημοτική"
fmt.Println("String: ", u)
_, sizeFirst := utf8.DecodeRuneInString(u)
fmt.Println("First rune removed: ", u[sizeFirst:])
_, sizeLast := utf8.DecodeLastRuneInString(u)
fmt.Println("Last rune removed: ", u[:len(u)-sizeLast])
fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}
|
Keep all operations the same but rewrite the snippet in Go. | from primesieve import primes
from math import isqrt
from functools import cache
p = primes(isqrt(1_000_000_000))
@cache
def phi(x, a):
res = 0
while True:
if not a or not x:
return x + res
a -= 1
res -= phi(x//p[a], a)
def legpi(n):
if n < 2: return 0
a = legpi(isqrt(n))
return phi(n, a) + a - 1
for e in range(10):
print(f'10^{e}', legpi(10**e))
| package main
import (
"fmt"
"log"
"math"
"rcu"
)
func cantorPair(x, y int) int {
if x < 0 || y < 0 {
log.Fatal("Arguments must be non-negative integers.")
}
return (x*x + 3*x + 2*x*y + y + y*y) / 2
}
func pi(n int) int {
if n < 2 {
return 0
}
if n == 2 {
return 1
}
primes := rcu.Primes(int(math.Sqrt(float64(n))))
a := len(primes)
memoPhi := make(map[int]int)
var phi func(x, a int) int
phi = func(x, a int) int {
if a < 1 {
return x
}
if a == 1 {
return x - (x >> 1)
}
pa := primes[a-1]
if x <= pa {
return 1
}
key := cantorPair(x, a)
if v, ok := memoPhi[key]; ok {
return v
}
memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)
return memoPhi[key]
}
return phi(n, a) + a - 1
}
func main() {
for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {
fmt.Printf("10^%d %d\n", i, pi(n))
}
}
|
Can you help me rewrite this code in Go instead of Python, keeping it the same logically? |
def query(buffer_length):
message = b'Here am I'
L = len(message)
return message[0:L*(L <= buffer_length)]
| package main
import "C"
import "unsafe"
func main() {
C.Run()
}
const msg = "Here am I"
func Query(cbuf *C.char, csiz *C.size_t) C.int {
if int(*csiz) <= len(msg) {
return 0
}
pbuf := uintptr(unsafe.Pointer(cbuf))
for i := 0; i < len(msg); i++ {
*((*byte)(unsafe.Pointer(pbuf))) = msg[i]
pbuf++
}
*((*byte)(unsafe.Pointer(pbuf))) = 0
*csiz = C.size_t(len(msg) + 1)
return 1
}
|
Rewrite the snippet below in Go so it works the same as the original Python code. | import fileinput
def longer(a, b):
try:
b[len(a)-1]
return False
except:
return True
longest, lines = '', ''
for x in fileinput.input():
if longer(x, longest):
lines, longest = x, x
elif not longer(longest, x):
lines += x
print(lines, end='')
| package main
import (
"bufio"
"os"
)
func main() {
in := bufio.NewReader(os.Stdin)
var blankLine = "\n"
var printLongest func(string) string
printLongest = func(candidate string) (longest string) {
longest = candidate
s, err := in.ReadString('\n')
defer func() {
recover()
defer func() {
recover()
}()
_ = blankLine[0]
func() {
defer func() {
recover()
}()
_ = s[len(longest)]
longest = s
}()
longest = printLongest(longest)
func() {
defer func() {
recover()
os.Stdout.WriteString(s)
}()
_ = longest[len(s)]
s = ""
}()
}()
_ = err.(error)
os.Stdout.WriteString(blankLine)
blankLine = ""
return
}
printLongest("")
}
|
Port the provided Python code into Go while preserving the original functionality. | from __future__ import print_function
def run_utm(
state = None,
blank = None,
rules = [],
tape = [],
halt = None,
pos = 0):
st = state
if not tape: tape = [blank]
if pos < 0: pos += len(tape)
if pos >= len(tape) or pos < 0: raise Error( "bad init position")
rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)
while True:
print(st, '\t', end=" ")
for i, v in enumerate(tape):
if i == pos: print("[%s]" % (v,), end=" ")
else: print(v, end=" ")
print()
if st == halt: break
if (st, tape[pos]) not in rules: break
(v1, dr, s1) = rules[(st, tape[pos])]
tape[pos] = v1
if dr == 'left':
if pos > 0: pos -= 1
else: tape.insert(0, blank)
if dr == 'right':
pos += 1
if pos >= len(tape): tape.append(blank)
st = s1
print("incr machine\n")
run_utm(
halt = 'qf',
state = 'q0',
tape = list("111"),
blank = 'B',
rules = map(tuple,
["q0 1 1 right q0".split(),
"q0 B 1 stay qf".split()]
)
)
print("\nbusy beaver\n")
run_utm(
halt = 'halt',
state = 'a',
blank = '0',
rules = map(tuple,
["a 0 1 right b".split(),
"a 1 1 left c".split(),
"b 0 1 left a".split(),
"b 1 1 right b".split(),
"c 0 1 left b".split(),
"c 1 1 stay halt".split()]
)
)
print("\nsorting test\n")
run_utm(halt = 'STOP',
state = 'A',
blank = '0',
tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(),
rules = map(tuple,
["A 1 1 right A".split(),
"A 2 3 right B".split(),
"A 0 0 left E".split(),
"B 1 1 right B".split(),
"B 2 2 right B".split(),
"B 0 0 left C".split(),
"C 1 2 left D".split(),
"C 2 2 left C".split(),
"C 3 2 left E".split(),
"D 1 1 left D".split(),
"D 2 2 left D".split(),
"D 3 1 right A".split(),
"E 1 1 left E".split(),
"E 0 0 right STOP".split()]
)
)
| package turing
type Symbol byte
type Motion byte
const (
Left Motion = 'L'
Right Motion = 'R'
Stay Motion = 'N'
)
type Tape struct {
data []Symbol
pos, left int
blank Symbol
}
func NewTape(blank Symbol, start int, data []Symbol) *Tape {
t := &Tape{
data: data,
blank: blank,
}
if start < 0 {
t.Left(-start)
}
t.Right(start)
return t
}
func (t *Tape) Stay() {}
func (t *Tape) Data() []Symbol { return t.data[t.left:] }
func (t *Tape) Read() Symbol { return t.data[t.pos] }
func (t *Tape) Write(s Symbol) { t.data[t.pos] = s }
func (t *Tape) Dup() *Tape {
t2 := &Tape{
data: make([]Symbol, len(t.Data())),
blank: t.blank,
}
copy(t2.data, t.Data())
t2.pos = t.pos - t.left
return t2
}
func (t *Tape) String() string {
s := ""
for i := t.left; i < len(t.data); i++ {
b := t.data[i]
if i == t.pos {
s += "[" + string(b) + "]"
} else {
s += " " + string(b) + " "
}
}
return s
}
func (t *Tape) Move(a Motion) {
switch a {
case Left:
t.Left(1)
case Right:
t.Right(1)
case Stay:
t.Stay()
}
}
const minSz = 16
func (t *Tape) Left(n int) {
t.pos -= n
if t.pos < 0 {
var sz int
for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
newl := len(newd) - cap(t.data[t.left:])
n := copy(newd[newl:], t.data[t.left:])
t.data = newd[:newl+n]
t.pos += newl - t.left
t.left = newl
}
if t.pos < t.left {
if t.blank != 0 {
for i := t.pos; i < t.left; i++ {
t.data[i] = t.blank
}
}
t.left = t.pos
}
}
func (t *Tape) Right(n int) {
t.pos += n
if t.pos >= cap(t.data) {
var sz int
for sz = minSz; t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
n := copy(newd[t.left:], t.data[t.left:])
t.data = newd[:t.left+n]
}
if i := len(t.data); t.pos >= i {
t.data = t.data[:t.pos+1]
if t.blank != 0 {
for ; i < len(t.data); i++ {
t.data[i] = t.blank
}
}
}
}
type State string
type Rule struct {
State
Symbol
Write Symbol
Motion
Next State
}
func (i *Rule) key() key { return key{i.State, i.Symbol} }
func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }
type key struct {
State
Symbol
}
type action struct {
write Symbol
Motion
next State
}
type Machine struct {
tape *Tape
start, state State
transition map[key]action
l func(string, ...interface{})
}
func NewMachine(rules []Rule) *Machine {
m := &Machine{transition: make(map[key]action, len(rules))}
if len(rules) > 0 {
m.start = rules[0].State
}
for _, r := range rules {
m.transition[r.key()] = r.action()
}
return m
}
func (m *Machine) Run(input *Tape) (int, *Tape) {
m.tape = input.Dup()
m.state = m.start
for cnt := 0; ; cnt++ {
if m.l != nil {
m.l("%3d %4s: %v\n", cnt, m.state, m.tape)
}
sym := m.tape.Read()
act, ok := m.transition[key{m.state, sym}]
if !ok {
return cnt, m.tape
}
m.tape.Write(act.write)
m.tape.Move(act.Motion)
m.state = act.next
}
}
|
Write a version of this Python function in Go with identical behavior. | from __future__ import print_function
def run_utm(
state = None,
blank = None,
rules = [],
tape = [],
halt = None,
pos = 0):
st = state
if not tape: tape = [blank]
if pos < 0: pos += len(tape)
if pos >= len(tape) or pos < 0: raise Error( "bad init position")
rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)
while True:
print(st, '\t', end=" ")
for i, v in enumerate(tape):
if i == pos: print("[%s]" % (v,), end=" ")
else: print(v, end=" ")
print()
if st == halt: break
if (st, tape[pos]) not in rules: break
(v1, dr, s1) = rules[(st, tape[pos])]
tape[pos] = v1
if dr == 'left':
if pos > 0: pos -= 1
else: tape.insert(0, blank)
if dr == 'right':
pos += 1
if pos >= len(tape): tape.append(blank)
st = s1
print("incr machine\n")
run_utm(
halt = 'qf',
state = 'q0',
tape = list("111"),
blank = 'B',
rules = map(tuple,
["q0 1 1 right q0".split(),
"q0 B 1 stay qf".split()]
)
)
print("\nbusy beaver\n")
run_utm(
halt = 'halt',
state = 'a',
blank = '0',
rules = map(tuple,
["a 0 1 right b".split(),
"a 1 1 left c".split(),
"b 0 1 left a".split(),
"b 1 1 right b".split(),
"c 0 1 left b".split(),
"c 1 1 stay halt".split()]
)
)
print("\nsorting test\n")
run_utm(halt = 'STOP',
state = 'A',
blank = '0',
tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(),
rules = map(tuple,
["A 1 1 right A".split(),
"A 2 3 right B".split(),
"A 0 0 left E".split(),
"B 1 1 right B".split(),
"B 2 2 right B".split(),
"B 0 0 left C".split(),
"C 1 2 left D".split(),
"C 2 2 left C".split(),
"C 3 2 left E".split(),
"D 1 1 left D".split(),
"D 2 2 left D".split(),
"D 3 1 right A".split(),
"E 1 1 left E".split(),
"E 0 0 right STOP".split()]
)
)
| package turing
type Symbol byte
type Motion byte
const (
Left Motion = 'L'
Right Motion = 'R'
Stay Motion = 'N'
)
type Tape struct {
data []Symbol
pos, left int
blank Symbol
}
func NewTape(blank Symbol, start int, data []Symbol) *Tape {
t := &Tape{
data: data,
blank: blank,
}
if start < 0 {
t.Left(-start)
}
t.Right(start)
return t
}
func (t *Tape) Stay() {}
func (t *Tape) Data() []Symbol { return t.data[t.left:] }
func (t *Tape) Read() Symbol { return t.data[t.pos] }
func (t *Tape) Write(s Symbol) { t.data[t.pos] = s }
func (t *Tape) Dup() *Tape {
t2 := &Tape{
data: make([]Symbol, len(t.Data())),
blank: t.blank,
}
copy(t2.data, t.Data())
t2.pos = t.pos - t.left
return t2
}
func (t *Tape) String() string {
s := ""
for i := t.left; i < len(t.data); i++ {
b := t.data[i]
if i == t.pos {
s += "[" + string(b) + "]"
} else {
s += " " + string(b) + " "
}
}
return s
}
func (t *Tape) Move(a Motion) {
switch a {
case Left:
t.Left(1)
case Right:
t.Right(1)
case Stay:
t.Stay()
}
}
const minSz = 16
func (t *Tape) Left(n int) {
t.pos -= n
if t.pos < 0 {
var sz int
for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
newl := len(newd) - cap(t.data[t.left:])
n := copy(newd[newl:], t.data[t.left:])
t.data = newd[:newl+n]
t.pos += newl - t.left
t.left = newl
}
if t.pos < t.left {
if t.blank != 0 {
for i := t.pos; i < t.left; i++ {
t.data[i] = t.blank
}
}
t.left = t.pos
}
}
func (t *Tape) Right(n int) {
t.pos += n
if t.pos >= cap(t.data) {
var sz int
for sz = minSz; t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
n := copy(newd[t.left:], t.data[t.left:])
t.data = newd[:t.left+n]
}
if i := len(t.data); t.pos >= i {
t.data = t.data[:t.pos+1]
if t.blank != 0 {
for ; i < len(t.data); i++ {
t.data[i] = t.blank
}
}
}
}
type State string
type Rule struct {
State
Symbol
Write Symbol
Motion
Next State
}
func (i *Rule) key() key { return key{i.State, i.Symbol} }
func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }
type key struct {
State
Symbol
}
type action struct {
write Symbol
Motion
next State
}
type Machine struct {
tape *Tape
start, state State
transition map[key]action
l func(string, ...interface{})
}
func NewMachine(rules []Rule) *Machine {
m := &Machine{transition: make(map[key]action, len(rules))}
if len(rules) > 0 {
m.start = rules[0].State
}
for _, r := range rules {
m.transition[r.key()] = r.action()
}
return m
}
func (m *Machine) Run(input *Tape) (int, *Tape) {
m.tape = input.Dup()
m.state = m.start
for cnt := 0; ; cnt++ {
if m.l != nil {
m.l("%3d %4s: %v\n", cnt, m.state, m.tape)
}
sym := m.tape.Read()
act, ok := m.transition[key{m.state, sym}]
if !ok {
return cnt, m.tape
}
m.tape.Write(act.write)
m.tape.Move(act.Motion)
m.state = act.next
}
}
|
Can you help me rewrite this code in Go instead of Python, keeping it the same logically? | from __future__ import print_function
def run_utm(
state = None,
blank = None,
rules = [],
tape = [],
halt = None,
pos = 0):
st = state
if not tape: tape = [blank]
if pos < 0: pos += len(tape)
if pos >= len(tape) or pos < 0: raise Error( "bad init position")
rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)
while True:
print(st, '\t', end=" ")
for i, v in enumerate(tape):
if i == pos: print("[%s]" % (v,), end=" ")
else: print(v, end=" ")
print()
if st == halt: break
if (st, tape[pos]) not in rules: break
(v1, dr, s1) = rules[(st, tape[pos])]
tape[pos] = v1
if dr == 'left':
if pos > 0: pos -= 1
else: tape.insert(0, blank)
if dr == 'right':
pos += 1
if pos >= len(tape): tape.append(blank)
st = s1
print("incr machine\n")
run_utm(
halt = 'qf',
state = 'q0',
tape = list("111"),
blank = 'B',
rules = map(tuple,
["q0 1 1 right q0".split(),
"q0 B 1 stay qf".split()]
)
)
print("\nbusy beaver\n")
run_utm(
halt = 'halt',
state = 'a',
blank = '0',
rules = map(tuple,
["a 0 1 right b".split(),
"a 1 1 left c".split(),
"b 0 1 left a".split(),
"b 1 1 right b".split(),
"c 0 1 left b".split(),
"c 1 1 stay halt".split()]
)
)
print("\nsorting test\n")
run_utm(halt = 'STOP',
state = 'A',
blank = '0',
tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(),
rules = map(tuple,
["A 1 1 right A".split(),
"A 2 3 right B".split(),
"A 0 0 left E".split(),
"B 1 1 right B".split(),
"B 2 2 right B".split(),
"B 0 0 left C".split(),
"C 1 2 left D".split(),
"C 2 2 left C".split(),
"C 3 2 left E".split(),
"D 1 1 left D".split(),
"D 2 2 left D".split(),
"D 3 1 right A".split(),
"E 1 1 left E".split(),
"E 0 0 right STOP".split()]
)
)
| package turing
type Symbol byte
type Motion byte
const (
Left Motion = 'L'
Right Motion = 'R'
Stay Motion = 'N'
)
type Tape struct {
data []Symbol
pos, left int
blank Symbol
}
func NewTape(blank Symbol, start int, data []Symbol) *Tape {
t := &Tape{
data: data,
blank: blank,
}
if start < 0 {
t.Left(-start)
}
t.Right(start)
return t
}
func (t *Tape) Stay() {}
func (t *Tape) Data() []Symbol { return t.data[t.left:] }
func (t *Tape) Read() Symbol { return t.data[t.pos] }
func (t *Tape) Write(s Symbol) { t.data[t.pos] = s }
func (t *Tape) Dup() *Tape {
t2 := &Tape{
data: make([]Symbol, len(t.Data())),
blank: t.blank,
}
copy(t2.data, t.Data())
t2.pos = t.pos - t.left
return t2
}
func (t *Tape) String() string {
s := ""
for i := t.left; i < len(t.data); i++ {
b := t.data[i]
if i == t.pos {
s += "[" + string(b) + "]"
} else {
s += " " + string(b) + " "
}
}
return s
}
func (t *Tape) Move(a Motion) {
switch a {
case Left:
t.Left(1)
case Right:
t.Right(1)
case Stay:
t.Stay()
}
}
const minSz = 16
func (t *Tape) Left(n int) {
t.pos -= n
if t.pos < 0 {
var sz int
for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
newl := len(newd) - cap(t.data[t.left:])
n := copy(newd[newl:], t.data[t.left:])
t.data = newd[:newl+n]
t.pos += newl - t.left
t.left = newl
}
if t.pos < t.left {
if t.blank != 0 {
for i := t.pos; i < t.left; i++ {
t.data[i] = t.blank
}
}
t.left = t.pos
}
}
func (t *Tape) Right(n int) {
t.pos += n
if t.pos >= cap(t.data) {
var sz int
for sz = minSz; t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
n := copy(newd[t.left:], t.data[t.left:])
t.data = newd[:t.left+n]
}
if i := len(t.data); t.pos >= i {
t.data = t.data[:t.pos+1]
if t.blank != 0 {
for ; i < len(t.data); i++ {
t.data[i] = t.blank
}
}
}
}
type State string
type Rule struct {
State
Symbol
Write Symbol
Motion
Next State
}
func (i *Rule) key() key { return key{i.State, i.Symbol} }
func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }
type key struct {
State
Symbol
}
type action struct {
write Symbol
Motion
next State
}
type Machine struct {
tape *Tape
start, state State
transition map[key]action
l func(string, ...interface{})
}
func NewMachine(rules []Rule) *Machine {
m := &Machine{transition: make(map[key]action, len(rules))}
if len(rules) > 0 {
m.start = rules[0].State
}
for _, r := range rules {
m.transition[r.key()] = r.action()
}
return m
}
func (m *Machine) Run(input *Tape) (int, *Tape) {
m.tape = input.Dup()
m.state = m.start
for cnt := 0; ; cnt++ {
if m.l != nil {
m.l("%3d %4s: %v\n", cnt, m.state, m.tape)
}
sym := m.tape.Read()
act, ok := m.transition[key{m.state, sym}]
if !ok {
return cnt, m.tape
}
m.tape.Write(act.write)
m.tape.Move(act.Motion)
m.state = act.next
}
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. | import os
for directory in ['/', './']:
open(directory + 'output.txt', 'w').close()
os.mkdir(directory + 'docs')
| package main
import (
"fmt"
"os"
)
func createFile(fn string) {
f, err := os.Create(fn)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("file", fn, "created!")
f.Close()
}
func createDir(dn string) {
err := os.Mkdir(dn, 0666)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("directory", dn, "created!")
}
func main() {
createFile("input.txt")
createFile("/input.txt")
createDir("docs")
createDir("/docs")
}
|
Please provide an equivalent version of this Python code in Go. | from itertools import count, islice
def primes(_cache=[2, 3]):
yield from _cache
for n in count(_cache[-1]+2, 2):
if isprime(n):
_cache.append(n)
yield n
def isprime(n, _seen={0: False, 1: False}):
def _isprime(n):
for p in primes():
if p*p > n:
return True
if n%p == 0:
return False
if n not in _seen:
_seen[n] = _isprime(n)
return _seen[n]
def unprime():
for a in count(1):
d = 1
while d <= a:
base = (a//(d*10))*(d*10) + (a%d)
if any(isprime(y) for y in range(base, base + d*10, d)):
break
d *= 10
else:
yield a
print('First 35:')
print(' '.join(str(i) for i in islice(unprime(), 35)))
print('\nThe 600-th:')
print(list(islice(unprime(), 599, 600))[0])
print()
first, need = [False]*10, 10
for p in unprime():
i = p%10
if first[i]: continue
first[i] = p
need -= 1
if not need:
break
for i,v in enumerate(first):
print(f'{i} ending: {v}')
| package main
import (
"fmt"
"strconv"
)
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
fmt.Println("The first 35 unprimeable numbers are:")
count := 0
var firstNum [10]int
outer:
for i, countFirst := 100, 0; countFirst < 10; i++ {
if isPrime(i) {
continue
}
s := strconv.Itoa(i)
le := len(s)
b := []byte(s)
for j := 0; j < le; j++ {
for k := byte('0'); k <= '9'; k++ {
if s[j] == k {
continue
}
b[j] = k
n, _ := strconv.Atoi(string(b))
if isPrime(n) {
continue outer
}
}
b[j] = s[j]
}
lastDigit := s[le-1] - '0'
if firstNum[lastDigit] == 0 {
firstNum[lastDigit] = i
countFirst++
}
count++
if count <= 35 {
fmt.Printf("%d ", i)
}
if count == 35 {
fmt.Print("\n\nThe 600th unprimeable number is: ")
}
if count == 600 {
fmt.Printf("%s\n\n", commatize(i))
}
}
fmt.Println("The first unprimeable number that ends in:")
for i := 0; i < 10; i++ {
fmt.Printf(" %d is: %9s\n", i, commatize(firstNum[i]))
}
}
|
Rewrite the snippet below in Go so it works the same as the original Python code. |
def combine( snl, snr ):
cl = {}
if isinstance(snl, int):
cl['1'] = snl
elif isinstance(snl, string):
cl[snl] = 1
else:
cl.update( snl)
if isinstance(snr, int):
n = cl.get('1', 0)
cl['1'] = n + snr
elif isinstance(snr, string):
n = cl.get(snr, 0)
cl[snr] = n + 1
else:
for k,v in snr.items():
n = cl.get(k, 0)
cl[k] = n+v
return cl
def constrain(nsum, vn ):
nn = {}
nn.update(vn)
n = nn.get('1', 0)
nn['1'] = n - nsum
return nn
def makeMatrix( constraints ):
vmap = set()
for c in constraints:
vmap.update( c.keys())
vmap.remove('1')
nvars = len(vmap)
vmap = sorted(vmap)
mtx = []
for c in constraints:
row = []
for vv in vmap:
row.append(float(c.get(vv, 0)))
row.append(-float(c.get('1',0)))
mtx.append(row)
if len(constraints) == nvars:
print 'System appears solvable'
elif len(constraints) < nvars:
print 'System is not solvable - needs more constraints.'
return mtx, vmap
def SolvePyramid( vl, cnstr ):
vl.reverse()
constraints = [cnstr]
lvls = len(vl)
for lvln in range(1,lvls):
lvd = vl[lvln]
for k in range(lvls - lvln):
sn = lvd[k]
ll = vl[lvln-1]
vn = combine(ll[k], ll[k+1])
if sn is None:
lvd[k] = vn
else:
constraints.append(constrain( sn, vn ))
print 'Constraint Equations:'
for cstr in constraints:
fset = ('%d*%s'%(v,k) for k,v in cstr.items() )
print ' + '.join(fset), ' = 0'
mtx,vmap = makeMatrix(constraints)
MtxSolve(mtx)
d = len(vmap)
for j in range(d):
print vmap[j],'=', mtx[j][d]
def MtxSolve(mtx):
mDim = len(mtx)
for j in range(mDim):
rw0= mtx[j]
f = 1.0/rw0[j]
for k in range(j, mDim+1):
rw0[k] *= f
for l in range(1+j,mDim):
rwl = mtx[l]
f = -rwl[j]
for k in range(j, mDim+1):
rwl[k] += f * rw0[k]
for j1 in range(1,mDim):
j = mDim - j1
rw0= mtx[j]
for l in range(0, j):
rwl = mtx[l]
f = -rwl[j]
rwl[j] += f * rw0[j]
rwl[mDim] += f * rw0[mDim]
return mtx
p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]
addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }
SolvePyramid( p, addlConstraint)
| package main
import "fmt"
type expr struct {
x, y, z float64
c float64
}
func addExpr(a, b expr) expr {
return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}
func subExpr(a, b expr) expr {
return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}
}
func mulExpr(a expr, c float64) expr {
return expr{a.x * c, a.y * c, a.z * c, a.c * c}
}
func addRow(l []expr) []expr {
if len(l) == 0 {
panic("wrong")
}
r := make([]expr, len(l)-1)
for i := range r {
r[i] = addExpr(l[i], l[i+1])
}
return r
}
func substX(a, b expr) expr {
if b.x == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.x/b.x))
}
func substY(a, b expr) expr {
if b.y == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.y/b.y))
}
func substZ(a, b expr) expr {
if b.z == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.z/b.z))
}
func solveX(a expr) float64 {
if a.x == 0 || a.y != 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.x
}
func solveY(a expr) float64 {
if a.x != 0 || a.y == 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.y
}
func solveZ(a expr) float64 {
if a.x != 0 || a.y != 0 || a.z == 0 {
panic("wrong")
}
return -a.c / a.z
}
func main() {
r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}
fmt.Println("bottom row:", r5)
r4 := addRow(r5)
fmt.Println("next row up:", r4)
r3 := addRow(r4)
fmt.Println("middle row:", r3)
xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})
fmt.Println("xyz relation:", xyz)
r3[2] = substZ(r3[2], xyz)
fmt.Println("middle row after substituting for z:", r3)
b := expr{c: 40}
xy := subExpr(r3[0], b)
fmt.Println("xy relation:", xy)
r3[0] = b
r3[2] = substX(r3[2], xy)
fmt.Println("middle row after substituting for x:", r3)
r2 := addRow(r3)
fmt.Println("next row up:", r2)
r1 := addRow(r2)
fmt.Println("top row:", r1)
y := subExpr(r1[0], expr{c: 151})
fmt.Println("y relation:", y)
x := substY(xy, y)
fmt.Println("x relation:", x)
z := substX(substY(xyz, y), x)
fmt.Println("z relation:", z)
fmt.Println("x =", solveX(x))
fmt.Println("y =", solveY(y))
fmt.Println("z =", solveZ(z))
}
|
Can you help me rewrite this code in Go instead of Python, keeping it the same logically? |
def combine( snl, snr ):
cl = {}
if isinstance(snl, int):
cl['1'] = snl
elif isinstance(snl, string):
cl[snl] = 1
else:
cl.update( snl)
if isinstance(snr, int):
n = cl.get('1', 0)
cl['1'] = n + snr
elif isinstance(snr, string):
n = cl.get(snr, 0)
cl[snr] = n + 1
else:
for k,v in snr.items():
n = cl.get(k, 0)
cl[k] = n+v
return cl
def constrain(nsum, vn ):
nn = {}
nn.update(vn)
n = nn.get('1', 0)
nn['1'] = n - nsum
return nn
def makeMatrix( constraints ):
vmap = set()
for c in constraints:
vmap.update( c.keys())
vmap.remove('1')
nvars = len(vmap)
vmap = sorted(vmap)
mtx = []
for c in constraints:
row = []
for vv in vmap:
row.append(float(c.get(vv, 0)))
row.append(-float(c.get('1',0)))
mtx.append(row)
if len(constraints) == nvars:
print 'System appears solvable'
elif len(constraints) < nvars:
print 'System is not solvable - needs more constraints.'
return mtx, vmap
def SolvePyramid( vl, cnstr ):
vl.reverse()
constraints = [cnstr]
lvls = len(vl)
for lvln in range(1,lvls):
lvd = vl[lvln]
for k in range(lvls - lvln):
sn = lvd[k]
ll = vl[lvln-1]
vn = combine(ll[k], ll[k+1])
if sn is None:
lvd[k] = vn
else:
constraints.append(constrain( sn, vn ))
print 'Constraint Equations:'
for cstr in constraints:
fset = ('%d*%s'%(v,k) for k,v in cstr.items() )
print ' + '.join(fset), ' = 0'
mtx,vmap = makeMatrix(constraints)
MtxSolve(mtx)
d = len(vmap)
for j in range(d):
print vmap[j],'=', mtx[j][d]
def MtxSolve(mtx):
mDim = len(mtx)
for j in range(mDim):
rw0= mtx[j]
f = 1.0/rw0[j]
for k in range(j, mDim+1):
rw0[k] *= f
for l in range(1+j,mDim):
rwl = mtx[l]
f = -rwl[j]
for k in range(j, mDim+1):
rwl[k] += f * rw0[k]
for j1 in range(1,mDim):
j = mDim - j1
rw0= mtx[j]
for l in range(0, j):
rwl = mtx[l]
f = -rwl[j]
rwl[j] += f * rw0[j]
rwl[mDim] += f * rw0[mDim]
return mtx
p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]
addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }
SolvePyramid( p, addlConstraint)
| package main
import "fmt"
type expr struct {
x, y, z float64
c float64
}
func addExpr(a, b expr) expr {
return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}
func subExpr(a, b expr) expr {
return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}
}
func mulExpr(a expr, c float64) expr {
return expr{a.x * c, a.y * c, a.z * c, a.c * c}
}
func addRow(l []expr) []expr {
if len(l) == 0 {
panic("wrong")
}
r := make([]expr, len(l)-1)
for i := range r {
r[i] = addExpr(l[i], l[i+1])
}
return r
}
func substX(a, b expr) expr {
if b.x == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.x/b.x))
}
func substY(a, b expr) expr {
if b.y == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.y/b.y))
}
func substZ(a, b expr) expr {
if b.z == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.z/b.z))
}
func solveX(a expr) float64 {
if a.x == 0 || a.y != 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.x
}
func solveY(a expr) float64 {
if a.x != 0 || a.y == 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.y
}
func solveZ(a expr) float64 {
if a.x != 0 || a.y != 0 || a.z == 0 {
panic("wrong")
}
return -a.c / a.z
}
func main() {
r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}
fmt.Println("bottom row:", r5)
r4 := addRow(r5)
fmt.Println("next row up:", r4)
r3 := addRow(r4)
fmt.Println("middle row:", r3)
xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})
fmt.Println("xyz relation:", xyz)
r3[2] = substZ(r3[2], xyz)
fmt.Println("middle row after substituting for z:", r3)
b := expr{c: 40}
xy := subExpr(r3[0], b)
fmt.Println("xy relation:", xy)
r3[0] = b
r3[2] = substX(r3[2], xy)
fmt.Println("middle row after substituting for x:", r3)
r2 := addRow(r3)
fmt.Println("next row up:", r2)
r1 := addRow(r2)
fmt.Println("top row:", r1)
y := subExpr(r1[0], expr{c: 151})
fmt.Println("y relation:", y)
x := substY(xy, y)
fmt.Println("x relation:", x)
z := substX(substY(xyz, y), x)
fmt.Println("z relation:", z)
fmt.Println("x =", solveX(x))
fmt.Println("y =", solveY(y))
fmt.Println("z =", solveZ(z))
}
|
Preserve the algorithm and functionality while converting the code from Python to Go. |
from sympy import isprime
def primality_pretest(k):
if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):
return (k <= 23)
return True
def is_chernick(n, m):
t = 9 * m
if not primality_pretest(6 * m + 1):
return False
if not primality_pretest(12 * m + 1):
return False
for i in range(1,n-1):
if not primality_pretest((t << i) + 1):
return False
if not isprime(6 * m + 1):
return False
if not isprime(12 * m + 1):
return False
for i in range(1,n - 1):
if not isprime((t << i) + 1):
return False
return True
for n in range(3,10):
if n > 4:
multiplier = 1 << (n - 4)
else:
multiplier = 1
if n > 5:
multiplier *= 5
k = 1
while True:
m = k * multiplier
if is_chernick(n, m):
print("a("+str(n)+") has m = "+str(m))
break
k += 1
| package main
import (
"fmt"
"math/big"
)
var (
zero = new(big.Int)
prod = new(big.Int)
fact = new(big.Int)
)
func ccFactors(n, m uint64) (*big.Int, bool) {
prod.SetUint64(6*m + 1)
if !prod.ProbablyPrime(0) {
return zero, false
}
fact.SetUint64(12*m + 1)
if !fact.ProbablyPrime(0) {
return zero, false
}
prod.Mul(prod, fact)
for i := uint64(1); i <= n-2; i++ {
fact.SetUint64((1<<i)*9*m + 1)
if !fact.ProbablyPrime(0) {
return zero, false
}
prod.Mul(prod, fact)
}
return prod, true
}
func ccNumbers(start, end uint64) {
for n := start; n <= end; n++ {
m := uint64(1)
if n > 4 {
m = 1 << (n - 4)
}
for {
num, ok := ccFactors(n, m)
if ok {
fmt.Printf("a(%d) = %d\n", n, num)
break
}
if n <= 4 {
m++
} else {
m += 1 << (n - 4)
}
}
}
}
func main() {
ccNumbers(3, 9)
}
|
Write the same algorithm in Go as shown in this Python implementation. |
from sympy import isprime
def primality_pretest(k):
if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):
return (k <= 23)
return True
def is_chernick(n, m):
t = 9 * m
if not primality_pretest(6 * m + 1):
return False
if not primality_pretest(12 * m + 1):
return False
for i in range(1,n-1):
if not primality_pretest((t << i) + 1):
return False
if not isprime(6 * m + 1):
return False
if not isprime(12 * m + 1):
return False
for i in range(1,n - 1):
if not isprime((t << i) + 1):
return False
return True
for n in range(3,10):
if n > 4:
multiplier = 1 << (n - 4)
else:
multiplier = 1
if n > 5:
multiplier *= 5
k = 1
while True:
m = k * multiplier
if is_chernick(n, m):
print("a("+str(n)+") has m = "+str(m))
break
k += 1
| package main
import (
"fmt"
"math/big"
)
var (
zero = new(big.Int)
prod = new(big.Int)
fact = new(big.Int)
)
func ccFactors(n, m uint64) (*big.Int, bool) {
prod.SetUint64(6*m + 1)
if !prod.ProbablyPrime(0) {
return zero, false
}
fact.SetUint64(12*m + 1)
if !fact.ProbablyPrime(0) {
return zero, false
}
prod.Mul(prod, fact)
for i := uint64(1); i <= n-2; i++ {
fact.SetUint64((1<<i)*9*m + 1)
if !fact.ProbablyPrime(0) {
return zero, false
}
prod.Mul(prod, fact)
}
return prod, true
}
func ccNumbers(start, end uint64) {
for n := start; n <= end; n++ {
m := uint64(1)
if n > 4 {
m = 1 << (n - 4)
}
for {
num, ok := ccFactors(n, m)
if ok {
fmt.Printf("a(%d) = %d\n", n, num)
break
}
if n <= 4 {
m++
} else {
m += 1 << (n - 4)
}
}
}
}
func main() {
ccNumbers(3, 9)
}
|
Ensure the translated Go code behaves exactly like the original Python snippet. |
from sympy.geometry import Point, Triangle
def sign(pt1, pt2, pt3):
return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)
def iswithin(point, pt1, pt2, pt3):
zval1 = sign(point, pt1, pt2)
zval2 = sign(point, pt2, pt3)
zval3 = sign(point, pt3, pt1)
notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0
notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0
return notanyneg or notanypos
if __name__ == "__main__":
POINTS = [Point(0, 0)]
TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))
for pnt in POINTS:
a, b, c = TRI.vertices
isornot = "is" if iswithin(pnt, a, b, c) else "is not"
print("Point", pnt, isornot, "within the triangle", TRI)
| package main
import (
"fmt"
"math"
)
const EPS = 0.001
const EPS_SQUARE = EPS * EPS
func side(x1, y1, x2, y2, x, y float64) float64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
checkSide1 := side(x1, y1, x2, y2, x, y) >= 0
checkSide2 := side(x2, y2, x3, y3, x, y) >= 0
checkSide3 := side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {
xMin := math.Min(x1, math.Min(x2, x3)) - EPS
xMax := math.Max(x1, math.Max(x2, x3)) + EPS
yMin := math.Min(y1, math.Min(y2, y3)) - EPS
yMax := math.Max(y1, math.Max(y2, y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {
p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength
if dotProduct < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dotProduct <= 1 {
p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {
return true
}
return false
}
func main() {
pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}
tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}
fmt.Println("Triangle is", tri)
x1, y1 := tri[0][0], tri[0][1]
x2, y2 := tri[1][0], tri[1][1]
x3, y3 := tri[2][0], tri[2][1]
for _, pt := range pts {
x, y := pt[0], pt[1]
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle?", within)
}
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}
fmt.Println("Triangle is", tri)
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [2]float64{x, y}
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}
fmt.Println("Triangle is", tri)
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
}
|
Translate the given Python code snippet into Go without altering its behavior. |
from sympy.geometry import Point, Triangle
def sign(pt1, pt2, pt3):
return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)
def iswithin(point, pt1, pt2, pt3):
zval1 = sign(point, pt1, pt2)
zval2 = sign(point, pt2, pt3)
zval3 = sign(point, pt3, pt1)
notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0
notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0
return notanyneg or notanypos
if __name__ == "__main__":
POINTS = [Point(0, 0)]
TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))
for pnt in POINTS:
a, b, c = TRI.vertices
isornot = "is" if iswithin(pnt, a, b, c) else "is not"
print("Point", pnt, isornot, "within the triangle", TRI)
| package main
import (
"fmt"
"math"
)
const EPS = 0.001
const EPS_SQUARE = EPS * EPS
func side(x1, y1, x2, y2, x, y float64) float64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
checkSide1 := side(x1, y1, x2, y2, x, y) >= 0
checkSide2 := side(x2, y2, x3, y3, x, y) >= 0
checkSide3 := side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {
xMin := math.Min(x1, math.Min(x2, x3)) - EPS
xMax := math.Max(x1, math.Max(x2, x3)) + EPS
yMin := math.Min(y1, math.Min(y2, y3)) - EPS
yMax := math.Max(y1, math.Max(y2, y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {
p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength
if dotProduct < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dotProduct <= 1 {
p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {
return true
}
return false
}
func main() {
pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}
tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}
fmt.Println("Triangle is", tri)
x1, y1 := tri[0][0], tri[0][1]
x2, y2 := tri[1][0], tri[1][1]
x3, y3 := tri[2][0], tri[2][1]
for _, pt := range pts {
x, y := pt[0], pt[1]
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle?", within)
}
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}
fmt.Println("Triangle is", tri)
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [2]float64{x, y}
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}
fmt.Println("Triangle is", tri)
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
}
|
Convert this Python block to Go, preserving its control flow and logic. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def tau(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= 1 + k
return ans
if __name__ == "__main__":
print(*map(tau, range(1, 101)))
| package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
func main() {
fmt.Println("The tau functions for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%2d ", countDivisors(i))
if i%20 == 0 {
fmt.Println()
}
}
}
|
Generate a Go translation of this Python snippet without changing its computational steps. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def tau(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= 1 + k
return ans
if __name__ == "__main__":
print(*map(tau, range(1, 101)))
| package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
func main() {
fmt.Println("The tau functions for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%2d ", countDivisors(i))
if i%20 == 0 {
fmt.Println()
}
}
}
|
Convert the following code from Python to Go, ensuring the logic remains intact. | import pyprimes
def primorial_prime(_pmax=500):
isprime = pyprimes.isprime
n, primo = 0, 1
for prime in pyprimes.nprimes(_pmax):
n, primo = n+1, primo * prime
if isprime(primo-1) or isprime(primo+1):
yield n
if __name__ == '__main__':
pyprimes.warn_probably = False
for i, n in zip(range(20), primorial_prime()):
print('Primorial prime %2i at primorial index: %3i' % (i+1, n))
| package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewInt(1)
pm := big.NewInt(1)
var px, nx int
var pb big.Int
primes(4000, func(p int64) bool {
pm.Mul(pm, pb.SetInt64(p))
px++
if pb.Add(pm, one).ProbablyPrime(0) ||
pb.Sub(pm, one).ProbablyPrime(0) {
fmt.Print(px, " ")
nx++
if nx == 20 {
fmt.Println()
return false
}
}
return true
})
}
func primes(limit int, f func(int64) bool) {
c := make([]bool, limit)
c[0] = true
c[1] = true
lm := int64(limit)
p := int64(2)
for {
f(p)
p2 := p * p
if p2 >= lm {
break
}
for i := p2; i < lm; i += p {
c[i] = true
}
for {
p++
if !c[p] {
break
}
}
}
for p++; p < lm; p++ {
if !c[p] && !f(p) {
break
}
}
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. | from collections import Counter
def basecount(dna):
return sorted(Counter(dna).items())
def seq_split(dna, n=50):
return [dna[i: i+n] for i in range(0, len(dna), n)]
def seq_pp(dna, n=50):
for i, part in enumerate(seq_split(dna, n)):
print(f"{i*n:>5}: {part}")
print("\n BASECOUNT:")
tot = 0
for base, count in basecount(dna):
print(f" {base:>3}: {count}")
tot += count
base, count = 'TOT', tot
print(f" {base:>3}= {count}")
if __name__ == '__main__':
print("SEQUENCE:")
sequence =
seq_pp(sequence)
| package main
import (
"fmt"
"sort"
)
func main() {
dna := "" +
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" +
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" +
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" +
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" +
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" +
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" +
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" +
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" +
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" +
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += 50 {
k := i + 50
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======")
}
|
Maintain the same structure and functionality when rewriting this code in Go. | from collections import Counter
def basecount(dna):
return sorted(Counter(dna).items())
def seq_split(dna, n=50):
return [dna[i: i+n] for i in range(0, len(dna), n)]
def seq_pp(dna, n=50):
for i, part in enumerate(seq_split(dna, n)):
print(f"{i*n:>5}: {part}")
print("\n BASECOUNT:")
tot = 0
for base, count in basecount(dna):
print(f" {base:>3}: {count}")
tot += count
base, count = 'TOT', tot
print(f" {base:>3}= {count}")
if __name__ == '__main__':
print("SEQUENCE:")
sequence =
seq_pp(sequence)
| package main
import (
"fmt"
"sort"
)
func main() {
dna := "" +
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" +
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" +
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" +
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" +
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" +
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" +
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" +
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" +
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" +
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += 50 {
k := i + 50
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======")
}
|
Transform the following Python implementation into Go, maintaining the same output and logic. | from collections import Counter
def basecount(dna):
return sorted(Counter(dna).items())
def seq_split(dna, n=50):
return [dna[i: i+n] for i in range(0, len(dna), n)]
def seq_pp(dna, n=50):
for i, part in enumerate(seq_split(dna, n)):
print(f"{i*n:>5}: {part}")
print("\n BASECOUNT:")
tot = 0
for base, count in basecount(dna):
print(f" {base:>3}: {count}")
tot += count
base, count = 'TOT', tot
print(f" {base:>3}= {count}")
if __name__ == '__main__':
print("SEQUENCE:")
sequence =
seq_pp(sequence)
| package main
import (
"fmt"
"sort"
)
func main() {
dna := "" +
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" +
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" +
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" +
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" +
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" +
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" +
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" +
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" +
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" +
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += 50 {
k := i + 50
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======")
}
|
Write the same algorithm in Go as shown in this Python implementation. | import threading
import random
import time
class Philosopher(threading.Thread):
running = True
def __init__(self, xname, forkOnLeft, forkOnRight):
threading.Thread.__init__(self)
self.name = xname
self.forkOnLeft = forkOnLeft
self.forkOnRight = forkOnRight
def run(self):
while(self.running):
time.sleep( random.uniform(3,13))
print '%s is hungry.' % self.name
self.dine()
def dine(self):
fork1, fork2 = self.forkOnLeft, self.forkOnRight
while self.running:
fork1.acquire(True)
locked = fork2.acquire(False)
if locked: break
fork1.release()
print '%s swaps forks' % self.name
fork1, fork2 = fork2, fork1
else:
return
self.dining()
fork2.release()
fork1.release()
def dining(self):
print '%s starts eating '% self.name
time.sleep(random.uniform(1,10))
print '%s finishes eating and leaves to think.' % self.name
def DiningPhilosophers():
forks = [threading.Lock() for n in range(5)]
philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')
philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \
for i in range(5)]
random.seed(507129)
Philosopher.running = True
for p in philosophers: p.start()
time.sleep(100)
Philosopher.running = False
print ("Now we're finishing.")
DiningPhilosophers()
| package main
import (
"hash/fnv"
"log"
"math/rand"
"os"
"time"
)
var ph = []string{"Aristotle", "Kant", "Spinoza", "Marx", "Russell"}
const hunger = 3
const think = time.Second / 100
const eat = time.Second / 100
var fmt = log.New(os.Stdout, "", 0)
var done = make(chan bool)
type fork byte
func philosopher(phName string,
dominantHand, otherHand chan fork, done chan bool) {
fmt.Println(phName, "seated")
h := fnv.New64a()
h.Write([]byte(phName))
rg := rand.New(rand.NewSource(int64(h.Sum64())))
rSleep := func(t time.Duration) {
time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))
}
for h := hunger; h > 0; h-- {
fmt.Println(phName, "hungry")
<-dominantHand
<-otherHand
fmt.Println(phName, "eating")
rSleep(eat)
dominantHand <- 'f'
otherHand <- 'f'
fmt.Println(phName, "thinking")
rSleep(think)
}
fmt.Println(phName, "satisfied")
done <- true
fmt.Println(phName, "left the table")
}
func main() {
fmt.Println("table empty")
place0 := make(chan fork, 1)
place0 <- 'f'
placeLeft := place0
for i := 1; i < len(ph); i++ {
placeRight := make(chan fork, 1)
placeRight <- 'f'
go philosopher(ph[i], placeLeft, placeRight, done)
placeLeft = placeRight
}
go philosopher(ph[0], place0, placeLeft, done)
for range ph {
<-done
}
fmt.Println("table empty")
}
|
Translate the given Python code snippet into Go without altering its behavior. | fact = [1]
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
j = j//b
if fact_sum == i:
print(i, end=" ")
print("\n")
| package main
import (
"fmt"
"strconv"
)
func main() {
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++ {
digits := strconv.FormatUint(i, b)
sum := uint64(0)
for _, digit := range digits {
if digit < 'a' {
sum += fact[digit-'0']
} else {
sum += fact[digit+10-'a']
}
}
if sum == i {
fmt.Printf("%d ", i)
}
}
fmt.Println("\n")
}
}
|
Keep all operations the same but rewrite the snippet in Go. | fact = [1]
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
j = j//b
if fact_sum == i:
print(i, end=" ")
print("\n")
| package main
import (
"fmt"
"strconv"
)
func main() {
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++ {
digits := strconv.FormatUint(i, b)
sum := uint64(0)
for _, digit := range digits {
if digit < 'a' {
sum += fact[digit-'0']
} else {
sum += fact[digit+10-'a']
}
}
if sum == i {
fmt.Printf("%d ", i)
}
}
fmt.Println("\n")
}
}
|
Please provide an equivalent version of this Python code in Go. | fact = [1]
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
j = j//b
if fact_sum == i:
print(i, end=" ")
print("\n")
| package main
import (
"fmt"
"strconv"
)
func main() {
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++ {
digits := strconv.FormatUint(i, b)
sum := uint64(0)
for _, digit := range digits {
if digit < 'a' {
sum += fact[digit-'0']
} else {
sum += fact[digit+10-'a']
}
}
if sum == i {
fmt.Printf("%d ", i)
}
}
fmt.Println("\n")
}
}
|
Rewrite the snippet below in Go so it works the same as the original Python code. | import numpy as np
import scipy.optimize as opt
n0, K = 27, 7_800_000_000
def f(t, r):
return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K))
y = [
27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,
61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,
2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,
24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,
60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,
76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,
85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,
105824, 109695, 114232, 118610, 125497, 133852, 143227,
151367, 167418, 180096, 194836, 213150, 242364, 271106,
305117, 338133, 377918, 416845, 468049, 527767, 591704,
656866, 715353, 777796, 851308, 928436, 1000249, 1082054,
1174652,
]
x = np.linspace(0.0, 96, 97)
r, cov = opt.curve_fit(f, x, y, [0.5])
print("The r for the world Covid-19 data is:", r,
", with covariance of", cov)
print("The calculated R0 is then", np.exp(12 * r))
| package main
import (
"fmt"
"github.com/maorshutman/lm"
"log"
"math"
)
const (
K = 7_800_000_000
n0 = 27
)
var y = []float64{
27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,
61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,
2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,
24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,
60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,
76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,
85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,
105824, 109695, 114232, 118610, 125497, 133852, 143227,
151367, 167418, 180096, 194836, 213150, 242364, 271106,
305117, 338133, 377918, 416845, 468049, 527767, 591704,
656866, 715353, 777796, 851308, 928436, 1000249, 1082054,
1174652,
}
func f(dst, p []float64) {
for i := 0; i < len(y); i++ {
t := float64(i)
dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]
}
}
func main() {
j := lm.NumJac{Func: f}
prob := lm.LMProblem{
Dim: 1,
Size: len(y),
Func: f,
Jac: j.Jac,
InitParams: []float64{0.5},
Tau: 1e-6,
Eps1: 1e-8,
Eps2: 1e-8,
}
res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})
if err != nil {
log.Fatal(err)
}
r := res.X[0]
fmt.Printf("The logistic curve r for the world data is %.8f\n", r)
fmt.Printf("R0 is then approximately equal to %.7f\n", math.Exp(12*r))
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Python version. | def merge_list(a, b):
out = []
while len(a) and len(b):
if a[0] < b[0]:
out.append(a.pop(0))
else:
out.append(b.pop(0))
out += a
out += b
return out
def strand(a):
i, s = 0, [a.pop(0)]
while i < len(a):
if a[i] > s[-1]:
s.append(a.pop(i))
else:
i += 1
return s
def strand_sort(a):
out = strand(a)
while len(a):
out = merge_list(out, strand(a))
return out
print strand_sort([1, 6, 3, 2, 1, 7, 5, 3])
| package main
import "fmt"
type link struct {
int
next *link
}
func linkInts(s []int) *link {
if len(s) == 0 {
return nil
}
return &link{s[0], linkInts(s[1:])}
}
func (l *link) String() string {
if l == nil {
return "nil"
}
r := fmt.Sprintf("[%d", l.int)
for l = l.next; l != nil; l = l.next {
r = fmt.Sprintf("%s %d", r, l.int)
}
return r + "]"
}
func main() {
a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})
fmt.Println("before:", a)
b := strandSort(a)
fmt.Println("after: ", b)
}
func strandSort(a *link) (result *link) {
for a != nil {
sublist := a
a = a.next
sTail := sublist
for p, pPrev := a, a; p != nil; p = p.next {
if p.int > sTail.int {
sTail.next = p
sTail = p
if p == a {
a = p.next
} else {
pPrev.next = p.next
}
} else {
pPrev = p
}
}
sTail.next = nil
if result == nil {
result = sublist
continue
}
var m, rr *link
if sublist.int < result.int {
m = sublist
sublist = m.next
rr = result
} else {
m = result
rr = m.next
}
result = m
for {
if sublist == nil {
m.next = rr
break
}
if rr == nil {
m.next = sublist
break
}
if sublist.int < rr.int {
m.next = sublist
m = sublist
sublist = m.next
} else {
m.next = rr
m = rr
rr = m.next
}
}
}
return
}
|
Produce a functionally identical Go code for the snippet given in Python. | def is_prime(n: int) -> bool:
if n <= 3:
return n > 1
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i ** 2 <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def digit_sum(n: int) -> int:
sum = 0
while n > 0:
sum += n % 10
n //= 10
return sum
def main() -> None:
additive_primes = 0
for i in range(2, 500):
if is_prime(i) and is_prime(digit_sum(i)):
additive_primes += 1
print(i, end=" ")
print(f"\nFound {additive_primes} additive primes less than 500")
if __name__ == "__main__":
main()
| package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func sumDigits(n int) int {
sum := 0
for n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func main() {
fmt.Println("Additive primes less than 500:")
i := 2
count := 0
for {
if isPrime(i) && isPrime(sumDigits(i)) {
count++
fmt.Printf("%3d ", i)
if count%10 == 0 {
fmt.Println()
}
}
if i > 2 {
i += 2
} else {
i++
}
if i > 499 {
break
}
}
fmt.Printf("\n\n%d additive primes found.\n", count)
}
|
Port the provided Python code into Go while preserving the original functionality. | x = truevalue if condition else falsevalue
| package main
import "fmt"
type ibool bool
const itrue ibool = true
func (ib ibool) iif(cond bool) bool {
if cond {
return bool(ib)
}
return bool(!ib)
}
func main() {
var needUmbrella bool
raining := true
if raining {
needUmbrella = true
}
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
raining = false
needUmbrella = itrue.iif(raining)
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
}
|
Write the same code in Go as shown below in Python. | x = truevalue if condition else falsevalue
| package main
import "fmt"
type ibool bool
const itrue ibool = true
func (ib ibool) iif(cond bool) bool {
if cond {
return bool(ib)
}
return bool(!ib)
}
func main() {
var needUmbrella bool
raining := true
if raining {
needUmbrella = true
}
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
raining = false
needUmbrella = itrue.iif(raining)
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
}
|
Please provide an equivalent version of this Python code in Go. | from math import gcd
from functools import lru_cache
from itertools import islice, count
@lru_cache(maxsize=None)
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
def perfect_totient():
for n0 in count(1):
parts, n = 0, n0
while n != 1:
n = φ(n)
parts += n
if parts == n0:
yield n0
if __name__ == '__main__':
print(list(islice(perfect_totient(), 20)))
| package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
var perfect []int
for n := 1; len(perfect) < 20; n += 2 {
tot := n
sum := 0
for tot != 1 {
tot = totient(tot)
sum += tot
}
if sum == n {
perfect = append(perfect, n)
}
}
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}
|
Convert the following code from Python to Go, ensuring the logic remains intact. | from math import gcd
from functools import lru_cache
from itertools import islice, count
@lru_cache(maxsize=None)
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
def perfect_totient():
for n0 in count(1):
parts, n = 0, n0
while n != 1:
n = φ(n)
parts += n
if parts == n0:
yield n0
if __name__ == '__main__':
print(list(islice(perfect_totient(), 20)))
| package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
var perfect []int
for n := 1; len(perfect) < 20; n += 2 {
tot := n
sum := 0
for tot != 1 {
tot = totient(tot)
sum += tot
}
if sum == n {
perfect = append(perfect, n)
}
}
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}
|
Rewrite the snippet below in Go so it works the same as the original Python code. | class Delegator:
def __init__(self):
self.delegate = None
def operation(self):
if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):
return self.delegate.thing()
return 'default implementation'
class Delegate:
def thing(self):
return 'delegate implementation'
if __name__ == '__main__':
a = Delegator()
assert a.operation() == 'default implementation'
a.delegate = 'A delegate may be any object'
assert a.operation() == 'default implementation'
a.delegate = Delegate()
assert a.operation() == 'delegate implementation'
| package main
import "fmt"
type Delegator struct {
delegate interface{}
}
type Thingable interface {
thing() string
}
func (self Delegator) operation() string {
if v, ok := self.delegate.(Thingable); ok {
return v.thing()
}
return "default implementation"
}
type Delegate int
func (Delegate) thing() string {
return "delegate implementation"
}
func main() {
a := Delegator{}
fmt.Println(a.operation())
a.delegate = "A delegate may be any object"
fmt.Println(a.operation())
var d Delegate
a.delegate = d
fmt.Println(a.operation())
}
|
Change the following Python code into Go without altering its purpose. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def sum_of_divisors(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= (pow(p,k+1) - 1)//(p-1)
return ans
if __name__ == "__main__":
print([sum_of_divisors(n) for n in range(1,101)])
| package main
import "fmt"
func sumDivisors(n int) int {
sum := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
i += k
}
return sum
}
func main() {
fmt.Println("The sums of positive divisors for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%3d ", sumDivisors(i))
if i%10 == 0 {
fmt.Println()
}
}
}
|
Change the following Python code into Go without altering its purpose. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def sum_of_divisors(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= (pow(p,k+1) - 1)//(p-1)
return ans
if __name__ == "__main__":
print([sum_of_divisors(n) for n in range(1,101)])
| package main
import "fmt"
func sumDivisors(n int) int {
sum := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
i += k
}
return sum
}
func main() {
fmt.Println("The sums of positive divisors for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%3d ", sumDivisors(i))
if i%10 == 0 {
fmt.Println()
}
}
}
|
Produce a functionally identical Go code for the snippet given in Python. | command_table_text = \
user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin"
def find_abbreviations_length(command_table_text):
command_table = dict()
for word in command_table_text.split():
abbr_len = sum(1 for c in word if c.isupper())
if abbr_len == 0:
abbr_len = len(word)
command_table[word] = abbr_len
return command_table
def find_abbreviations(command_table):
abbreviations = dict()
for command, min_abbr_len in command_table.items():
for l in range(min_abbr_len, len(command)+1):
abbr = command[:l].lower()
abbreviations[abbr] = command.upper()
return abbreviations
def parse_user_string(user_string, abbreviations):
user_words = [word.lower() for word in user_string.split()]
commands = [abbreviations.get(user_word, "*error*") for user_word in user_words]
return " ".join(commands)
command_table = find_abbreviations_length(command_table_text)
abbreviations_table = find_abbreviations(command_table)
full_words = parse_user_string(user_words, abbreviations_table)
print("user words:", user_words)
print("full words:", full_words)
| package main
import (
"fmt"
"strings"
)
var table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " +
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " +
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " +
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " +
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " +
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " +
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
func validate(commands, words []string, minLens []int) []string {
results := make([]string, 0)
if len(words) == 0 {
return results
}
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func main() {
table = strings.TrimSpace(table)
commands := strings.Fields(table)
clen := len(commands)
minLens := make([]int, clen)
for i := 0; i < clen; i++ {
count := 0
for _, c := range commands[i] {
if c >= 'A' && c <= 'Z' {
count++
}
}
minLens[i] = count
}
sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin"
words := strings.Fields(sentence)
results := validate(commands, words, minLens)
fmt.Print("user words: ")
for j := 0; j < len(words); j++ {
fmt.Printf("%-*s ", len(results[j]), words[j])
}
fmt.Print("\nfull words: ")
fmt.Println(strings.Join(results, " "))
}
|
Change the programming language of this snippet from Python to Go without modifying what it does. | command_table_text = \
user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin"
def find_abbreviations_length(command_table_text):
command_table = dict()
for word in command_table_text.split():
abbr_len = sum(1 for c in word if c.isupper())
if abbr_len == 0:
abbr_len = len(word)
command_table[word] = abbr_len
return command_table
def find_abbreviations(command_table):
abbreviations = dict()
for command, min_abbr_len in command_table.items():
for l in range(min_abbr_len, len(command)+1):
abbr = command[:l].lower()
abbreviations[abbr] = command.upper()
return abbreviations
def parse_user_string(user_string, abbreviations):
user_words = [word.lower() for word in user_string.split()]
commands = [abbreviations.get(user_word, "*error*") for user_word in user_words]
return " ".join(commands)
command_table = find_abbreviations_length(command_table_text)
abbreviations_table = find_abbreviations(command_table)
full_words = parse_user_string(user_words, abbreviations_table)
print("user words:", user_words)
print("full words:", full_words)
| package main
import (
"fmt"
"strings"
)
var table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " +
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " +
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " +
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " +
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " +
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " +
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
func validate(commands, words []string, minLens []int) []string {
results := make([]string, 0)
if len(words) == 0 {
return results
}
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func main() {
table = strings.TrimSpace(table)
commands := strings.Fields(table)
clen := len(commands)
minLens := make([]int, clen)
for i := 0; i < clen; i++ {
count := 0
for _, c := range commands[i] {
if c >= 'A' && c <= 'Z' {
count++
}
}
minLens[i] = count
}
sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin"
words := strings.Fields(sentence)
results := validate(commands, words, minLens)
fmt.Print("user words: ")
for j := 0; j < len(words); j++ {
fmt.Printf("%-*s ", len(results[j]), words[j])
}
fmt.Print("\nfull words: ")
fmt.Println(strings.Join(results, " "))
}
|
Convert this Python snippet to Go and keep its semantics consistent. | >>> s = "Hello"
>>> s[0] = "h"
Traceback (most recent call last):
File "<pyshell
s[0] = "h"
TypeError: 'str' object does not support item assignment
| package main
func main() {
s := "immutable"
s[0] = 'a'
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Python version. | def clip(subjectPolygon, clipPolygon):
def inside(p):
return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])
def computeIntersection():
dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]
dp = [ s[0] - e[0], s[1] - e[1] ]
n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
n2 = s[0] * e[1] - s[1] * e[0]
n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]
outputList = subjectPolygon
cp1 = clipPolygon[-1]
for clipVertex in clipPolygon:
cp2 = clipVertex
inputList = outputList
outputList = []
s = inputList[-1]
for subjectVertex in inputList:
e = subjectVertex
if inside(e):
if not inside(s):
outputList.append(computeIntersection())
outputList.append(e)
elif inside(s):
outputList.append(computeIntersection())
s = e
cp1 = cp2
return(outputList)
| package main
import "fmt"
type point struct {
x, y float32
}
var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}
var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}
func main() {
var cp1, cp2, s, e point
inside := func(p point) bool {
return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
}
intersection := func() (p point) {
dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y
dpx, dpy := s.x-e.x, s.y-e.y
n1 := cp1.x*cp2.y - cp1.y*cp2.x
n2 := s.x*e.y - s.y*e.x
n3 := 1 / (dcx*dpy - dcy*dpx)
p.x = (n1*dpx - n2*dcx) * n3
p.y = (n1*dpy - n2*dcy) * n3
return
}
outputList := subjectPolygon
cp1 = clipPolygon[len(clipPolygon)-1]
for _, cp2 = range clipPolygon {
inputList := outputList
outputList = nil
s = inputList[len(inputList)-1]
for _, e = range inputList {
if inside(e) {
if !inside(s) {
outputList = append(outputList, intersection())
}
outputList = append(outputList, e)
} else if inside(s) {
outputList = append(outputList, intersection())
}
s = e
}
cp1 = cp2
}
fmt.Println(outputList)
}
|
Translate this program into Go but keep the logic exactly as in Python. | import string
sometext = .lower()
lc2bin = {ch: '{:05b}'.format(i)
for i, ch in enumerate(string.ascii_lowercase + ' .')}
bin2lc = {val: key for key, val in lc2bin.items()}
phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()
def to_5binary(msg):
return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))
def encrypt(message, text):
bin5 = to_5binary(message)
textlist = list(text.lower())
out = []
for capitalise in bin5:
while textlist:
ch = textlist.pop(0)
if ch.isalpha():
if capitalise:
ch = ch.upper()
out.append(ch)
break
else:
out.append(ch)
else:
raise Exception('ERROR: Ran out of characters in sometext')
return ''.join(out) + '...'
def decrypt(bacontext):
binary = []
bin5 = []
out = []
for ch in bacontext:
if ch.isalpha():
binary.append('1' if ch.isupper() else '0')
if len(binary) == 5:
bin5 = ''.join(binary)
out.append(bin2lc[bin5])
binary = []
return ''.join(out)
print('PLAINTEXT = \n%s\n' % phrase)
encrypted = encrypt(phrase, sometext)
print('ENCRYPTED = \n%s\n' % encrypted)
decrypted = decrypt(encrypted)
print('DECRYPTED = \n%s\n' % decrypted)
assert phrase == decrypted, 'Round-tripping error'
| package main
import(
"fmt"
"strings"
)
var codes = map[rune]string {
'a' : "AAAAA", 'b' : "AAAAB", 'c' : "AAABA", 'd' : "AAABB", 'e' : "AABAA",
'f' : "AABAB", 'g' : "AABBA", 'h' : "AABBB", 'i' : "ABAAA", 'j' : "ABAAB",
'k' : "ABABA", 'l' : "ABABB", 'm' : "ABBAA", 'n' : "ABBAB", 'o' : "ABBBA",
'p' : "ABBBB", 'q' : "BAAAA", 'r' : "BAAAB", 's' : "BAABA", 't' : "BAABB",
'u' : "BABAA", 'v' : "BABAB", 'w' : "BABBA", 'x' : "BABBB", 'y' : "BBAAA",
'z' : "BBAAB", ' ' : "BBBAA",
}
func baconEncode(plainText string, message string) string {
pt := strings.ToLower(plainText)
var sb []byte
for _, c := range pt {
if c >= 'a' && c <= 'z' {
sb = append(sb, codes[c]...)
} else {
sb = append(sb, codes[' ']...)
}
}
et := string(sb)
mg := strings.ToLower(message)
sb = nil
var count = 0
for _, c := range mg {
if c >= 'a' && c <= 'z' {
if et[count] == 'A' {
sb = append(sb, byte(c))
} else {
sb = append(sb, byte(c - 32))
}
count++
if count == len(et) { break }
} else {
sb = append(sb, byte(c))
}
}
return string(sb)
}
func baconDecode(message string) string {
var sb []byte
for _, c := range message {
if c >= 'a' && c <= 'z' {
sb = append(sb, 'A')
} else if c >= 'A' && c <= 'Z' {
sb = append(sb, 'B')
}
}
et := string(sb)
sb = nil
for i := 0; i < len(et); i += 5 {
quintet := et[i : i + 5]
for k, v := range codes {
if v == quintet {
sb = append(sb, byte(k))
break
}
}
}
return string(sb)
}
func main() {
plainText := "the quick brown fox jumps over the lazy dog"
message := "bacon's cipher is a method of steganography created by francis bacon." +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
cipherText := baconEncode(plainText, message)
fmt.Printf("Cipher text ->\n\n%s\n", cipherText)
decodedText := baconDecode(cipherText)
fmt.Printf("\nHidden text ->\n\n%s\n", decodedText)
}
|
Port the following code from Python to Go with equivalent syntax and logic. | import string
sometext = .lower()
lc2bin = {ch: '{:05b}'.format(i)
for i, ch in enumerate(string.ascii_lowercase + ' .')}
bin2lc = {val: key for key, val in lc2bin.items()}
phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()
def to_5binary(msg):
return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))
def encrypt(message, text):
bin5 = to_5binary(message)
textlist = list(text.lower())
out = []
for capitalise in bin5:
while textlist:
ch = textlist.pop(0)
if ch.isalpha():
if capitalise:
ch = ch.upper()
out.append(ch)
break
else:
out.append(ch)
else:
raise Exception('ERROR: Ran out of characters in sometext')
return ''.join(out) + '...'
def decrypt(bacontext):
binary = []
bin5 = []
out = []
for ch in bacontext:
if ch.isalpha():
binary.append('1' if ch.isupper() else '0')
if len(binary) == 5:
bin5 = ''.join(binary)
out.append(bin2lc[bin5])
binary = []
return ''.join(out)
print('PLAINTEXT = \n%s\n' % phrase)
encrypted = encrypt(phrase, sometext)
print('ENCRYPTED = \n%s\n' % encrypted)
decrypted = decrypt(encrypted)
print('DECRYPTED = \n%s\n' % decrypted)
assert phrase == decrypted, 'Round-tripping error'
| package main
import(
"fmt"
"strings"
)
var codes = map[rune]string {
'a' : "AAAAA", 'b' : "AAAAB", 'c' : "AAABA", 'd' : "AAABB", 'e' : "AABAA",
'f' : "AABAB", 'g' : "AABBA", 'h' : "AABBB", 'i' : "ABAAA", 'j' : "ABAAB",
'k' : "ABABA", 'l' : "ABABB", 'm' : "ABBAA", 'n' : "ABBAB", 'o' : "ABBBA",
'p' : "ABBBB", 'q' : "BAAAA", 'r' : "BAAAB", 's' : "BAABA", 't' : "BAABB",
'u' : "BABAA", 'v' : "BABAB", 'w' : "BABBA", 'x' : "BABBB", 'y' : "BBAAA",
'z' : "BBAAB", ' ' : "BBBAA",
}
func baconEncode(plainText string, message string) string {
pt := strings.ToLower(plainText)
var sb []byte
for _, c := range pt {
if c >= 'a' && c <= 'z' {
sb = append(sb, codes[c]...)
} else {
sb = append(sb, codes[' ']...)
}
}
et := string(sb)
mg := strings.ToLower(message)
sb = nil
var count = 0
for _, c := range mg {
if c >= 'a' && c <= 'z' {
if et[count] == 'A' {
sb = append(sb, byte(c))
} else {
sb = append(sb, byte(c - 32))
}
count++
if count == len(et) { break }
} else {
sb = append(sb, byte(c))
}
}
return string(sb)
}
func baconDecode(message string) string {
var sb []byte
for _, c := range message {
if c >= 'a' && c <= 'z' {
sb = append(sb, 'A')
} else if c >= 'A' && c <= 'Z' {
sb = append(sb, 'B')
}
}
et := string(sb)
sb = nil
for i := 0; i < len(et); i += 5 {
quintet := et[i : i + 5]
for k, v := range codes {
if v == quintet {
sb = append(sb, byte(k))
break
}
}
}
return string(sb)
}
func main() {
plainText := "the quick brown fox jumps over the lazy dog"
message := "bacon's cipher is a method of steganography created by francis bacon." +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
cipherText := baconEncode(plainText, message)
fmt.Printf("Cipher text ->\n\n%s\n", cipherText)
decodedText := baconDecode(cipherText)
fmt.Printf("\nHidden text ->\n\n%s\n", decodedText)
}
|
Write the same code in Go as shown below in Python. | def spiral(n):
dx,dy = 1,0
x,y = 0,0
myarray = [[None]* n for j in range(n)]
for i in xrange(n**2):
myarray[x][y] = i
nx,ny = x+dx, y+dy
if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:
x,y = nx,ny
else:
dx,dy = -dy,dx
x,y = x+dx, y+dy
return myarray
def printspiral(myarray):
n = range(len(myarray))
for y in n:
for x in n:
print "%2i" % myarray[x][y],
print
printspiral(spiral(5))
| package main
import (
"fmt"
"strconv"
)
var n = 5
func main() {
if n < 1 {
return
}
top, left, bottom, right := 0, 0, n-1, n-1
sz := n * n
a := make([]int, sz)
i := 0
for left < right {
for c := left; c <= right; c++ {
a[top*n+c] = i
i++
}
top++
for r := top; r <= bottom; r++ {
a[r*n+right] = i
i++
}
right--
if top == bottom {
break
}
for c := right; c >= left; c-- {
a[bottom*n+c] = i
i++
}
bottom--
for r := bottom; r >= top; r-- {
a[r*n+left] = i
i++
}
left++
}
a[top*n+left] = i
w := len(strconv.Itoa(n*n - 1))
for i, e := range a {
fmt.Printf("%*d ", w, e)
if i%n == n-1 {
fmt.Println("")
}
}
}
|
Write a version of this Python function in Go with identical behavior. | >>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)
>>> import operator
>>> def sorttable(table, ordering=None, column=0, reverse=False):
return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)
>>> data = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]]
>>> printtable(data)
"a" "b" "c"
"" "q" "z"
"zap" "zip" "Zot"
>>> printtable( sorttable(data) )
"" "q" "z"
"a" "b" "c"
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=2) )
"zap" "zip" "Zot"
"a" "b" "c"
"" "q" "z"
>>> printtable( sorttable(data, column=1) )
"a" "b" "c"
"" "q" "z"
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=1, reverse=True) )
"zap" "zip" "Zot"
"" "q" "z"
"a" "b" "c"
>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )
"zap" "zip" "Zot"
"a" "b" "c"
"" "q" "z"
>>>
| type cell string
type spec struct {
less func(cell, cell) bool
column int
reverse bool
}
func newSpec() (s spec) {
return
}
t.sort(newSpec())
s := newSpec
s.reverse = true
t.sort(s)
|
Preserve the algorithm and functionality while converting the code from Python to Go. | def setup():
size(500, 500)
generate_voronoi_diagram(width, height, 25)
saveFrame("VoronoiDiagram.png")
def generate_voronoi_diagram(w, h, num_cells):
nx, ny, nr, ng, nb = [], [], [], [], []
for i in range(num_cells):
nx.append(int(random(w)))
ny.append(int(random(h)))
nr.append(int(random(256)))
ng.append(int(random(256)))
nb.append(int(random(256)))
for y in range(h):
for x in range(w):
dmin = dist(0, 0, w - 1, h - 1)
j = -1
for i in range(num_cells):
d = dist(0, 0, nx[i] - x, ny[i] - y)
if d < dmin:
dmin = d
j = i
set(x, y, color(nr[j], ng[j], nb[j]))
| package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
const (
imageWidth = 300
imageHeight = 200
nSites = 10
)
func main() {
writePngFile(generateVoronoi(randomSites()))
}
func generateVoronoi(sx, sy []int) image.Image {
sc := make([]color.NRGBA, nSites)
for i := range sx {
sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),
uint8(rand.Intn(256)), 255}
}
img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))
for x := 0; x < imageWidth; x++ {
for y := 0; y < imageHeight; y++ {
dMin := dot(imageWidth, imageHeight)
var sMin int
for s := 0; s < nSites; s++ {
if d := dot(sx[s]-x, sy[s]-y); d < dMin {
sMin = s
dMin = d
}
}
img.SetNRGBA(x, y, sc[sMin])
}
}
black := image.NewUniform(color.Black)
for s := 0; s < nSites; s++ {
draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),
black, image.ZP, draw.Src)
}
return img
}
func dot(x, y int) int {
return x*x + y*y
}
func randomSites() (sx, sy []int) {
rand.Seed(time.Now().Unix())
sx = make([]int, nSites)
sy = make([]int, nSites)
for i := range sx {
sx[i] = rand.Intn(imageWidth)
sy[i] = rand.Intn(imageHeight)
}
return
}
func writePngFile(img image.Image) {
f, err := os.Create("voronoi.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. | def setup():
size(500, 500)
generate_voronoi_diagram(width, height, 25)
saveFrame("VoronoiDiagram.png")
def generate_voronoi_diagram(w, h, num_cells):
nx, ny, nr, ng, nb = [], [], [], [], []
for i in range(num_cells):
nx.append(int(random(w)))
ny.append(int(random(h)))
nr.append(int(random(256)))
ng.append(int(random(256)))
nb.append(int(random(256)))
for y in range(h):
for x in range(w):
dmin = dist(0, 0, w - 1, h - 1)
j = -1
for i in range(num_cells):
d = dist(0, 0, nx[i] - x, ny[i] - y)
if d < dmin:
dmin = d
j = i
set(x, y, color(nr[j], ng[j], nb[j]))
| package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
const (
imageWidth = 300
imageHeight = 200
nSites = 10
)
func main() {
writePngFile(generateVoronoi(randomSites()))
}
func generateVoronoi(sx, sy []int) image.Image {
sc := make([]color.NRGBA, nSites)
for i := range sx {
sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),
uint8(rand.Intn(256)), 255}
}
img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))
for x := 0; x < imageWidth; x++ {
for y := 0; y < imageHeight; y++ {
dMin := dot(imageWidth, imageHeight)
var sMin int
for s := 0; s < nSites; s++ {
if d := dot(sx[s]-x, sy[s]-y); d < dMin {
sMin = s
dMin = d
}
}
img.SetNRGBA(x, y, sc[sMin])
}
}
black := image.NewUniform(color.Black)
for s := 0; s < nSites; s++ {
draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),
black, image.ZP, draw.Src)
}
return img
}
func dot(x, y int) int {
return x*x + y*y
}
func randomSites() (sx, sy []int) {
rand.Seed(time.Now().Unix())
sx = make([]int, nSites)
sy = make([]int, nSites)
for i := range sx {
sx[i] = rand.Intn(imageWidth)
sy[i] = rand.Intn(imageHeight)
}
return
}
func writePngFile(img image.Image) {
f, err := os.Create("voronoi.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Transform the following Python implementation into Go, maintaining the same output and logic. | import ctypes
libc = ctypes.CDLL("/lib/libc.so.6")
libc.strcmp("abc", "def")
libc.strcmp("hello", "hello")
| package main
import "C"
import (
"fmt"
"unsafe"
)
func main() {
go1 := "hello C"
c1 := C.CString(go1)
go1 = ""
c2 := C.strdup(c1)
C.free(unsafe.Pointer(c1))
go2 := C.GoString(c2)
C.free(unsafe.Pointer(c2))
fmt.Println(go2)
}
|
Generate an equivalent Go version of this Python code. | from random import randrange
def s_of_n_creator(n):
sample, i = [], 0
def s_of_n(item):
nonlocal i
i += 1
if i <= n:
sample.append(item)
elif randrange(i) < n:
sample[randrange(n)] = item
return sample
return s_of_n
if __name__ == '__main__':
bin = [0]* 10
items = range(10)
print("Single run samples for n = 3:")
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
print(" Item: %i -> sample: %s" % (item, sample))
for trial in range(100000):
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
for s in sample:
bin[s] += 1
print("\nTest item frequencies for 100000 runs:\n ",
'\n '.join("%i:%i" % x for x in enumerate(bin)))
| package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
}
|
Port the following code from Python to Go with equivalent syntax and logic. | from random import randrange
def s_of_n_creator(n):
sample, i = [], 0
def s_of_n(item):
nonlocal i
i += 1
if i <= n:
sample.append(item)
elif randrange(i) < n:
sample[randrange(n)] = item
return sample
return s_of_n
if __name__ == '__main__':
bin = [0]* 10
items = range(10)
print("Single run samples for n = 3:")
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
print(" Item: %i -> sample: %s" % (item, sample))
for trial in range(100000):
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
for s in sample:
bin[s] += 1
print("\nTest item frequencies for 100000 runs:\n ",
'\n '.join("%i:%i" % x for x in enumerate(bin)))
| package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
}
|
Change the programming language of this snippet from Python to Go without modifying what it does. |
from itertools import accumulate, chain, count, islice
from fractions import Fraction
def faulhaberTriangle(m):
def go(rs, n):
def f(x, y):
return Fraction(n, x) * y
xs = list(map(f, islice(count(2), m), rs))
return [Fraction(1 - sum(xs), 1)] + xs
return list(accumulate(
[[]] + list(islice(count(0), 1 + m)),
go
))[1:]
def faulhaberSum(p, n):
def go(x, y):
return y * (n ** x)
return sum(
map(go, count(1), faulhaberTriangle(p)[-1])
)
def main():
fs = faulhaberTriangle(9)
print(
fTable(__doc__ + ':\n')(str)(
compose(concat)(
fmap(showRatio(3)(3))
)
)(
index(fs)
)(range(0, len(fs)))
)
print('')
print(
faulhaberSum(17, 1000)
)
def fTable(s):
def gox(xShow):
def gofx(fxShow):
def gof(f):
def goxs(xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
def arrowed(x, y):
return y.rjust(w, ' ') + ' -> ' + (
fxShow(f(x))
)
return s + '\n' + '\n'.join(
map(arrowed, xs, ys)
)
return goxs
return gof
return gofx
return gox
def compose(g):
return lambda f: lambda x: g(f(x))
def concat(xs):
def f(ys):
zs = list(chain(*ys))
return ''.join(zs) if isinstance(ys[0], str) else zs
return (
f(xs) if isinstance(xs, list) else (
chain.from_iterable(xs)
)
) if xs else []
def fmap(f):
def go(xs):
return list(map(f, xs))
return go
def index(xs):
return lambda n: None if 0 > n else (
xs[n] if (
hasattr(xs, "__getitem__")
) else next(islice(xs, n, None))
)
def showRatio(m):
def go(n):
def f(r):
d = r.denominator
return str(r.numerator).rjust(m, ' ') + (
('/' + str(d).ljust(n, ' ')) if 1 != d else (
' ' * (1 + n)
)
)
return f
return go
if __name__ == '__main__':
main()
| package main
import (
"fmt"
"math/big"
)
func bernoulli(n uint) *big.Rat {
a := make([]big.Rat, n+1)
z := new(big.Rat)
for m := range a {
a[m].SetFrac64(1, int64(m+1))
for j := m; j >= 1; j-- {
d := &a[j-1]
d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))
}
}
if n != 1 {
return &a[0]
}
a[0].Neg(&a[0])
return &a[0]
}
func binomial(n, k int) int64 {
if n <= 0 || k <= 0 || n < k {
return 1
}
var num, den int64 = 1, 1
for i := k + 1; i <= n; i++ {
num *= int64(i)
}
for i := 2; i <= n-k; i++ {
den *= int64(i)
}
return num / den
}
func faulhaberTriangle(p int) []big.Rat {
coeffs := make([]big.Rat, p+1)
q := big.NewRat(1, int64(p)+1)
t := new(big.Rat)
u := new(big.Rat)
sign := -1
for j := range coeffs {
sign *= -1
d := &coeffs[p-j]
t.SetInt64(int64(sign))
u.SetInt64(binomial(p+1, j))
d.Mul(q, t)
d.Mul(d, u)
d.Mul(d, bernoulli(uint(j)))
}
return coeffs
}
func main() {
for i := 0; i < 10; i++ {
coeffs := faulhaberTriangle(i)
for _, coeff := range coeffs {
fmt.Printf("%5s ", coeff.RatString())
}
fmt.Println()
}
fmt.Println()
k := 17
cc := faulhaberTriangle(k)
n := int64(1000)
nn := big.NewRat(n, 1)
np := big.NewRat(1, 1)
sum := new(big.Rat)
tmp := new(big.Rat)
for _, c := range cc {
np.Mul(np, nn)
tmp.Set(np)
tmp.Mul(tmp, &c)
sum.Add(sum, tmp)
}
fmt.Println(sum.RatString())
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. | import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
| package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
|
Convert this Python block to Go, preserving its control flow and logic. | import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
| package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
|
Please provide an equivalent version of this Python code in Go. | import urllib.request
from collections import Counter
GRID =
def getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):
"Return lowercased words of 3 to 9 characters"
words = urllib.request.urlopen(url).read().decode().strip().lower().split()
return (w for w in words if 2 < len(w) < 10)
def solve(grid, dictionary):
gridcount = Counter(grid)
mid = grid[4]
return [word for word in dictionary
if mid in word and not (Counter(word) - gridcount)]
if __name__ == '__main__':
chars = ''.join(GRID.strip().lower().split())
found = solve(chars, dictionary=getwords())
print('\n'.join(found))
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
)
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
letters := "deegklnow"
wordsAll := bytes.Split(b, []byte{'\n'})
var words [][]byte
for _, word := range wordsAll {
word = bytes.TrimSpace(word)
le := len(word)
if le > 2 && le < 10 {
words = append(words, word)
}
}
var found []string
for _, word := range words {
le := len(word)
if bytes.IndexByte(word, 'k') >= 0 {
lets := letters
ok := true
for i := 0; i < le; i++ {
c := word[i]
ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })
if ix < len(lets) && lets[ix] == c {
lets = lets[0:ix] + lets[ix+1:]
} else {
ok = false
break
}
}
if ok {
found = append(found, string(word))
}
}
}
fmt.Println("The following", len(found), "words are the solutions to the puzzle:")
fmt.Println(strings.Join(found, "\n"))
mostFound := 0
var mostWords9 []string
var mostLetters []byte
var words9 [][]byte
for _, word := range words {
if len(word) == 9 {
words9 = append(words9, word)
}
}
for _, word9 := range words9 {
letterBytes := make([]byte, len(word9))
copy(letterBytes, word9)
sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })
distinctBytes := []byte{letterBytes[0]}
for _, b := range letterBytes[1:] {
if b != distinctBytes[len(distinctBytes)-1] {
distinctBytes = append(distinctBytes, b)
}
}
distinctLetters := string(distinctBytes)
for _, letter := range distinctLetters {
found := 0
letterByte := byte(letter)
for _, word := range words {
le := len(word)
if bytes.IndexByte(word, letterByte) >= 0 {
lets := string(letterBytes)
ok := true
for i := 0; i < le; i++ {
c := word[i]
ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })
if ix < len(lets) && lets[ix] == c {
lets = lets[0:ix] + lets[ix+1:]
} else {
ok = false
break
}
}
if ok {
found = found + 1
}
}
}
if found > mostFound {
mostFound = found
mostWords9 = []string{string(word9)}
mostLetters = []byte{letterByte}
} else if found == mostFound {
mostWords9 = append(mostWords9, string(word9))
mostLetters = append(mostLetters, letterByte)
}
}
}
fmt.Println("\nMost words found =", mostFound)
fmt.Println("Nine letter words producing this total:")
for i := 0; i < len(mostWords9); i++ {
fmt.Println(mostWords9[i], "with central letter", string(mostLetters[i]))
}
}
|
Produce a functionally identical Go code for the snippet given in Python. | arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2
assert arr4 == [1, 2, 3, 4, 5, 6]
arr4.extend(arr3)
assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
| package main
import "fmt"
func main() {
a := []int{1, 2, 3}
b := []int{7, 12, 60}
c := append(a, b...)
fmt.Println(c)
i := []interface{}{1, 2, 3}
j := []interface{}{"Crosby", "Stills", "Nash", "Young"}
k := append(i, j...)
fmt.Println(k)
l := [...]int{1, 2, 3}
m := [...]int{7, 12, 60}
var n [len(l) + len(m)]int
copy(n[:], l[:])
copy(n[len(l):], m[:])
fmt.Println(n)
}
|
Generate a Go translation of this Python snippet without changing its computational steps. | string = raw_input("Input a string: ")
| package main
import "fmt"
func main() {
var s string
var i int
if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
fmt.Println("good")
} else {
fmt.Println("wrong")
}
}
|
Write the same algorithm in Go as shown in this Python implementation. | >>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
winsound.Beep(int(note+.5), 500)
>>>
| package main
import (
"encoding/binary"
"log"
"math"
"os"
"strings"
)
func main() {
const (
sampleRate = 44100
duration = 8
dataLength = sampleRate * duration
hdrSize = 44
fileLen = dataLength + hdrSize - 8
)
buf1 := make([]byte, 1)
buf2 := make([]byte, 2)
buf4 := make([]byte, 4)
var sb strings.Builder
sb.WriteString("RIFF")
binary.LittleEndian.PutUint32(buf4, fileLen)
sb.Write(buf4)
sb.WriteString("WAVE")
sb.WriteString("fmt ")
binary.LittleEndian.PutUint32(buf4, 16)
sb.Write(buf4)
binary.LittleEndian.PutUint16(buf2, 1)
sb.Write(buf2)
sb.Write(buf2)
binary.LittleEndian.PutUint32(buf4, sampleRate)
sb.Write(buf4)
sb.Write(buf4)
sb.Write(buf2)
binary.LittleEndian.PutUint16(buf2, 8)
sb.Write(buf2)
sb.WriteString("data")
binary.LittleEndian.PutUint32(buf4, dataLength)
sb.Write(buf4)
wavhdr := []byte(sb.String())
f, err := os.Create("notes.wav")
if err != nil {
log.Fatal(err)
}
defer f.Close()
f.Write(wavhdr)
freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
for j := 0; j < duration; j++ {
freq := freqs[j]
omega := 2 * math.Pi * freq
for i := 0; i < dataLength/duration; i++ {
y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))
buf1[0] = byte(math.Round(y))
f.Write(buf1)
}
}
}
|
Write a version of this Python function in Go with identical behavior. | >>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
winsound.Beep(int(note+.5), 500)
>>>
| package main
import (
"encoding/binary"
"log"
"math"
"os"
"strings"
)
func main() {
const (
sampleRate = 44100
duration = 8
dataLength = sampleRate * duration
hdrSize = 44
fileLen = dataLength + hdrSize - 8
)
buf1 := make([]byte, 1)
buf2 := make([]byte, 2)
buf4 := make([]byte, 4)
var sb strings.Builder
sb.WriteString("RIFF")
binary.LittleEndian.PutUint32(buf4, fileLen)
sb.Write(buf4)
sb.WriteString("WAVE")
sb.WriteString("fmt ")
binary.LittleEndian.PutUint32(buf4, 16)
sb.Write(buf4)
binary.LittleEndian.PutUint16(buf2, 1)
sb.Write(buf2)
sb.Write(buf2)
binary.LittleEndian.PutUint32(buf4, sampleRate)
sb.Write(buf4)
sb.Write(buf4)
sb.Write(buf2)
binary.LittleEndian.PutUint16(buf2, 8)
sb.Write(buf2)
sb.WriteString("data")
binary.LittleEndian.PutUint32(buf4, dataLength)
sb.Write(buf4)
wavhdr := []byte(sb.String())
f, err := os.Create("notes.wav")
if err != nil {
log.Fatal(err)
}
defer f.Close()
f.Write(wavhdr)
freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
for j := 0; j < duration; j++ {
freq := freqs[j]
omega := 2 * math.Pi * freq
for i := 0; i < dataLength/duration; i++ {
y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))
buf1[0] = byte(math.Round(y))
f.Write(buf1)
}
}
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. | from itertools import combinations
def anycomb(items):
' return combinations of any length from the items '
return ( comb
for r in range(1, len(items)+1)
for comb in combinations(items, r)
)
def totalvalue(comb):
' Totalise a particular combination of items'
totwt = totval = 0
for item, wt, val in comb:
totwt += wt
totval += val
return (totval, -totwt) if totwt <= 400 else (0, 0)
items = (
("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160),
("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40),
("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30),
("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40),
("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75),
("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12),
("socks", 4, 50), ("book", 30, 10),
)
bagged = max( anycomb(items), key=totalvalue)
print("Bagged the following items\n " +
'\n '.join(sorted(item for item,_,_ in bagged)))
val, wt = totalvalue(bagged)
print("for a total value of %i and a total weight of %i" % (val, -wt))
| package main
import "fmt"
type item struct {
string
w, v int
}
var wants = []item{
{"map", 9, 150},
{"compass", 13, 35},
{"water", 153, 200},
{"sandwich", 50, 160},
{"glucose", 15, 60},
{"tin", 68, 45},
{"banana", 27, 60},
{"apple", 39, 40},
{"cheese", 23, 30},
{"beer", 52, 10},
{"suntan cream", 11, 70},
{"camera", 32, 30},
{"T-shirt", 24, 15},
{"trousers", 48, 10},
{"umbrella", 73, 40},
{"waterproof trousers", 42, 70},
{"waterproof overclothes", 43, 75},
{"note-case", 22, 80},
{"sunglasses", 7, 20},
{"towel", 18, 12},
{"socks", 4, 50},
{"book", 30, 10},
}
const maxWt = 400
func main() {
items, w, v := m(len(wants)-1, maxWt)
fmt.Println(items)
fmt.Println("weight:", w)
fmt.Println("value:", v)
}
func m(i, w int) ([]string, int, int) {
if i < 0 || w == 0 {
return nil, 0, 0
} else if wants[i].w > w {
return m(i-1, w)
}
i0, w0, v0 := m(i-1, w)
i1, w1, v1 := m(i-1, w-wants[i].w)
v1 += wants[i].v
if v1 > v0 {
return append(i1, wants[i].string), w1 + wants[i].w, v1
}
return i0, w0, v0
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Python version. | from __future__ import print_function
from itertools import takewhile
maxsum = 99
def get_primes(max):
if max < 2:
return []
lprimes = [2]
for x in range(3, max + 1, 2):
for p in lprimes:
if x % p == 0:
break
else:
lprimes.append(x)
return lprimes
descendants = [[] for _ in range(maxsum + 1)]
ancestors = [[] for _ in range(maxsum + 1)]
primes = get_primes(maxsum)
for p in primes:
descendants[p].append(p)
for s in range(1, len(descendants) - p):
descendants[s + p] += [p * pr for pr in descendants[s]]
for p in primes + [4]:
descendants[p].pop()
total = 0
for s in range(1, maxsum + 1):
descendants[s].sort()
for d in takewhile(lambda x: x <= maxsum, descendants[s]):
ancestors[d] = ancestors[s] + [s]
print([s], "Level:", len(ancestors[s]))
print("Ancestors:", ancestors[s] if len(ancestors[s]) else "None")
print("Descendants:", len(descendants[s]) if len(descendants[s]) else "None")
if len(descendants[s]):
print(descendants[s])
print()
total += len(descendants[s])
print("Total descendants", total)
| package main
import (
"fmt"
"sort"
)
func getPrimes(max int) []int {
if max < 2 {
return []int{}
}
lprimes := []int{2}
outer:
for x := 3; x <= max; x += 2 {
for _, p := range lprimes {
if x%p == 0 {
continue outer
}
}
lprimes = append(lprimes, x)
}
return lprimes
}
func main() {
const maxSum = 99
descendants := make([][]int64, maxSum+1)
ancestors := make([][]int, maxSum+1)
for i := 0; i <= maxSum; i++ {
descendants[i] = []int64{}
ancestors[i] = []int{}
}
primes := getPrimes(maxSum)
for _, p := range primes {
descendants[p] = append(descendants[p], int64(p))
for s := 1; s < len(descendants)-p; s++ {
temp := make([]int64, len(descendants[s]))
for i := 0; i < len(descendants[s]); i++ {
temp[i] = int64(p) * descendants[s][i]
}
descendants[s+p] = append(descendants[s+p], temp...)
}
}
for _, p := range append(primes, 4) {
le := len(descendants[p])
if le == 0 {
continue
}
descendants[p][le-1] = 0
descendants[p] = descendants[p][:le-1]
}
total := 0
for s := 1; s <= maxSum; s++ {
x := descendants[s]
sort.Slice(x, func(i, j int) bool {
return x[i] < x[j]
})
total += len(descendants[s])
index := 0
for ; index < len(descendants[s]); index++ {
if descendants[s][index] > int64(maxSum) {
break
}
}
for _, d := range descendants[s][:index] {
ancestors[d] = append(ancestors[s], s)
}
if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {
continue
}
temp := fmt.Sprintf("%v", ancestors[s])
fmt.Printf("%2d: %d Ancestor(s): %-14s", s, len(ancestors[s]), temp)
le := len(descendants[s])
if le <= 10 {
fmt.Printf("%5d Descendant(s): %v\n", le, descendants[s])
} else {
fmt.Printf("%5d Descendant(s): %v\b ...]\n", le, descendants[s][:10])
}
}
fmt.Println("\nTotal descendants", total)
}
|
Write a version of this Python function in Go with identical behavior. | import itertools
def cp(lsts):
return list(itertools.product(*lsts))
if __name__ == '__main__':
from pprint import pprint as pp
for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],
((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),
((1, 2, 3), (30,), (500, 100)),
((1, 2, 3), (), (500, 100))]:
print(lists, '=>')
pp(cp(lists), indent=2)
| package main
import "fmt"
type pair [2]int
func cart2(a, b []int) []pair {
p := make([]pair, len(a)*len(b))
i := 0
for _, a := range a {
for _, b := range b {
p[i] = pair{a, b}
i++
}
}
return p
}
func main() {
fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
fmt.Println(cart2([]int{1, 2}, nil))
fmt.Println(cart2(nil, []int{1, 2}))
}
|
Port the provided Python code into Go while preserving the original functionality. | import itertools
def cp(lsts):
return list(itertools.product(*lsts))
if __name__ == '__main__':
from pprint import pprint as pp
for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],
((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),
((1, 2, 3), (30,), (500, 100)),
((1, 2, 3), (), (500, 100))]:
print(lists, '=>')
pp(cp(lists), indent=2)
| package main
import "fmt"
type pair [2]int
func cart2(a, b []int) []pair {
p := make([]pair, len(a)*len(b))
i := 0
for _, a := range a {
for _, b := range b {
p[i] = pair{a, b}
i++
}
}
return p
}
func main() {
fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
fmt.Println(cart2([]int{1, 2}, nil))
fmt.Println(cart2(nil, []int{1, 2}))
}
|
Translate this program into Go but keep the logic exactly as in Python. | import itertools
def cp(lsts):
return list(itertools.product(*lsts))
if __name__ == '__main__':
from pprint import pprint as pp
for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],
((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),
((1, 2, 3), (30,), (500, 100)),
((1, 2, 3), (), (500, 100))]:
print(lists, '=>')
pp(cp(lists), indent=2)
| package main
import "fmt"
type pair [2]int
func cart2(a, b []int) []pair {
p := make([]pair, len(a)*len(b))
i := 0
for _, a := range a {
for _, b := range b {
p[i] = pair{a, b}
i++
}
}
return p
}
func main() {
fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
fmt.Println(cart2([]int{1, 2}, nil))
fmt.Println(cart2(nil, []int{1, 2}))
}
|
Write the same code in Go as shown below in Python. | >>>
>>> from math import sin, cos, acos, asin
>>>
>>> cube = lambda x: x * x * x
>>> croot = lambda x: x ** (1/3.0)
>>>
>>>
>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )
>>>
>>> funclist = [sin, cos, cube]
>>> funclisti = [asin, acos, croot]
>>>
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>>
| package main
import "math"
import "fmt"
func cube(x float64) float64 { return math.Pow(x, 3) }
type ffType func(float64) float64
func compose(f, g ffType) ffType {
return func(x float64) float64 {
return f(g(x))
}
}
func main() {
funclist := []ffType{math.Sin, math.Cos, cube}
funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
for i := 0; i < 3; i++ {
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}
|
Generate a Go translation of this Python snippet without changing its computational steps. | >>> def proper_divs2(n):
... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}
...
>>> [proper_divs2(n) for n in range(1, 11)]
[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]
>>>
>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])
>>> n
15120
>>> length
79
>>>
| package main
import (
"fmt"
"strconv"
)
func listProperDivisors(limit int) {
if limit < 1 {
return
}
width := len(strconv.Itoa(limit))
for i := 1; i <= limit; i++ {
fmt.Printf("%*d -> ", width, i)
if i == 1 {
fmt.Println("(None)")
continue
}
for j := 1; j <= i/2; j++ {
if i%j == 0 {
fmt.Printf(" %d", j)
}
}
fmt.Println()
}
}
func countProperDivisors(n int) int {
if n < 2 {
return 0
}
count := 0
for i := 1; i <= n/2; i++ {
if n%i == 0 {
count++
}
}
return count
}
func main() {
fmt.Println("The proper divisors of the following numbers are :\n")
listProperDivisors(10)
fmt.Println()
maxCount := 0
most := []int{1}
for n := 2; n <= 20000; n++ {
count := countProperDivisors(n)
if count == maxCount {
most = append(most, n)
} else if count > maxCount {
maxCount = count
most = most[0:1]
most[0] = n
}
}
fmt.Print("The following number(s) <= 20000 have the most proper divisors, ")
fmt.Println("namely", maxCount, "\b\n")
for _, n := range most {
fmt.Println(n)
}
}
|
Translate this program into Go but keep the logic exactly as in Python. | >>> from xml.etree import ElementTree as ET
>>> from itertools import izip
>>> def characterstoxml(names, remarks):
root = ET.Element("CharacterRemarks")
for name, remark in izip(names, remarks):
c = ET.SubElement(root, "Character", {'name': name})
c.text = remark
return ET.tostring(root)
>>> print characterstoxml(
names = ["April", "Tam O'Shanter", "Emily"],
remarks = [ "Bubbly: I'm > Tam and <= Emily",
'Burns: "When chapman billies leave the street ..."',
'Short & shrift' ] ).replace('><','>\n<')
| package main
import (
"encoding/xml"
"fmt"
)
func xRemarks(r CharacterRemarks) (string, error) {
b, err := xml.MarshalIndent(r, "", " ")
return string(b), err
}
type CharacterRemarks struct {
Character []crm
}
type crm struct {
Name string `xml:"name,attr"`
Remark string `xml:",chardata"`
}
func main() {
x, err := xRemarks(CharacterRemarks{[]crm{
{`April`, `Bubbly: I'm > Tam and <= Emily`},
{`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`},
{`Emily`, `Short & shrift`},
}})
if err != nil {
x = err.Error()
}
fmt.Println(x)
}
|
Translate this program into Go but keep the logic exactly as in Python. | >>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
>>> import pylab
>>> pylab.plot(x, y, 'bo')
>>> pylab.savefig('qsort-range-10-9.png')
| package main
import (
"fmt"
"log"
"os/exec"
)
var (
x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)
func main() {
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
if err != nil {
log.Fatal(err)
}
if err = g.Start(); err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %f\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
|
Port the provided Python code into Go while preserving the original functionality. | >>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
>>> import pylab
>>> pylab.plot(x, y, 'bo')
>>> pylab.savefig('qsort-range-10-9.png')
| package main
import (
"fmt"
"log"
"os/exec"
)
var (
x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)
func main() {
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
if err != nil {
log.Fatal(err)
}
if err = g.Start(); err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %f\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
|
Transform the following Python implementation into Go, maintaining the same output and logic. | import re
string = "This is a string"
if re.search('string$', string):
print("Ends with string.")
string = re.sub(" a ", " another ", string)
print(string)
| package main
import "fmt"
import "regexp"
func main() {
str := "I am the original string"
matched, _ := regexp.MatchString(".*string$", str)
if matched { fmt.Println("ends with 'string'") }
pattern := regexp.MustCompile("original")
result := pattern.ReplaceAllString(str, "modified")
fmt.Println(result)
}
|
Please provide an equivalent version of this Python code in Go. | inclusive_range = mn, mx = (1, 10)
print( % inclusive_range)
i = 0
while True:
i += 1
guess = (mn+mx)//2
txt = input("Guess %2i is: %2i. The score for which is (h,l,=): "
% (i, guess)).strip().lower()[0]
if txt not in 'hl=':
print(" I don't understand your input of '%s' ?" % txt)
continue
if txt == 'h':
mx = guess-1
if txt == 'l':
mn = guess+1
if txt == '=':
print(" Ye-Haw!!")
break
if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):
print("Please check your scoring as I cannot find the value")
break
print("\nThanks for keeping score.")
| package main
import (
"fmt"
"sort"
)
func main() {
lower, upper := 0, 100
fmt.Printf(`Instructions:
Think of integer number from %d (inclusive) to %d (exclusive) and
I will guess it. After each guess, I will ask you if it is less than
or equal to some number, and you will respond with "yes" or "no".
`, lower, upper)
answer := sort.Search(upper-lower, func (i int) bool {
fmt.Printf("Is your number less than or equal to %d? ", lower+i)
s := ""
fmt.Scanf("%s", &s)
return s != "" && s[0] == 'y'
})
fmt.Printf("Your number is %d.\n", lower+answer)
}
|
Change the programming language of this snippet from Python to Go without modifying what it does. | keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)}
| package main
import "fmt"
func main() {
keys := []string{"a", "b", "c"}
vals := []int{1, 2, 3}
hash := map[string]int{}
for i, key := range keys {
hash[key] = vals[i]
}
fmt.Println(hash)
}
|
Port the following code from Python to Go with equivalent syntax and logic. | from bisect import bisect_right
def bin_it(limits: list, data: list) -> list:
"Bin data according to (ascending) limits."
bins = [0] * (len(limits) + 1)
for d in data:
bins[bisect_right(limits, d)] += 1
return bins
def bin_print(limits: list, bins: list) -> list:
print(f" < {limits[0]:3} := {bins[0]:3}")
for lo, hi, count in zip(limits, limits[1:], bins[1:]):
print(f">= {lo:3} .. < {hi:3} := {count:3}")
print(f">= {limits[-1]:3} := {bins[-1]:3}")
if __name__ == "__main__":
print("RC FIRST EXAMPLE\n")
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
bins = bin_it(limits, data)
bin_print(limits, bins)
print("\nRC SECOND EXAMPLE\n")
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
bins = bin_it(limits, data)
bin_print(limits, bins)
| package main
import (
"fmt"
"sort"
)
func getBins(limits, data []int) []int {
n := len(limits)
bins := make([]int, n+1)
for _, d := range data {
index := sort.SearchInts(limits, d)
if index < len(limits) && d == limits[index] {
index++
}
bins[index]++
}
return bins
}
func printBins(limits, bins []int) {
n := len(limits)
fmt.Printf(" < %3d = %2d\n", limits[0], bins[0])
for i := 1; i < n; i++ {
fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i])
}
fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n])
fmt.Println()
}
func main() {
limitsList := [][]int{
{23, 37, 43, 53, 67, 83},
{14, 18, 249, 312, 389, 392, 513, 591, 634, 720},
}
dataList := [][]int{
{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,
16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,
},
{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,
416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,
655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,
346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,
345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,
854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,
787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,
605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,
466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749,
},
}
for i := 0; i < len(limitsList); i++ {
fmt.Println("Example", i+1, "\b\n")
bins := getBins(limitsList[i], dataList[i])
printBins(limitsList[i], bins)
}
}
|
Write the same code in Go as shown below in Python. | from bisect import bisect_right
def bin_it(limits: list, data: list) -> list:
"Bin data according to (ascending) limits."
bins = [0] * (len(limits) + 1)
for d in data:
bins[bisect_right(limits, d)] += 1
return bins
def bin_print(limits: list, bins: list) -> list:
print(f" < {limits[0]:3} := {bins[0]:3}")
for lo, hi, count in zip(limits, limits[1:], bins[1:]):
print(f">= {lo:3} .. < {hi:3} := {count:3}")
print(f">= {limits[-1]:3} := {bins[-1]:3}")
if __name__ == "__main__":
print("RC FIRST EXAMPLE\n")
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
bins = bin_it(limits, data)
bin_print(limits, bins)
print("\nRC SECOND EXAMPLE\n")
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
bins = bin_it(limits, data)
bin_print(limits, bins)
| package main
import (
"fmt"
"sort"
)
func getBins(limits, data []int) []int {
n := len(limits)
bins := make([]int, n+1)
for _, d := range data {
index := sort.SearchInts(limits, d)
if index < len(limits) && d == limits[index] {
index++
}
bins[index]++
}
return bins
}
func printBins(limits, bins []int) {
n := len(limits)
fmt.Printf(" < %3d = %2d\n", limits[0], bins[0])
for i := 1; i < n; i++ {
fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i])
}
fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n])
fmt.Println()
}
func main() {
limitsList := [][]int{
{23, 37, 43, 53, 67, 83},
{14, 18, 249, 312, 389, 392, 513, 591, 634, 720},
}
dataList := [][]int{
{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,
16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,
},
{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,
416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,
655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,
346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,
345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,
854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,
787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,
605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,
466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749,
},
}
for i := 0; i < len(limitsList); i++ {
fmt.Println("Example", i+1, "\b\n")
bins := getBins(limitsList[i], dataList[i])
printBins(limitsList[i], bins)
}
}
|
Generate an equivalent Go version of this Python code. | def setup():
size(600, 600)
background(0)
stroke(255)
drawTree(300, 550, 9)
def drawTree(x, y, depth):
fork_ang = radians(20)
base_len = 10
if depth > 0:
pushMatrix()
translate(x, y - baseLen * depth)
line(0, baseLen * depth, 0, 0)
rotate(fork_ang)
drawTree(0, 0, depth - 1)
rotate(2 * -fork_ang)
drawTree(0, 0, depth - 1)
popMatrix()
| package main
import (
"math"
"raster"
)
const (
width = 400
height = 300
depth = 8
angle = 12
length = 50
frac = .8
)
func main() {
g := raster.NewGrmap(width, height)
ftree(g, width/2, height*9/10, length, 0, depth)
g.Bitmap().WritePpmFile("ftree.ppm")
}
func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {
x2 := x + distance*math.Sin(direction*math.Pi/180)
y2 := y - distance*math.Cos(direction*math.Pi/180)
g.AaLine(x, y, x2, y2)
if depth > 0 {
ftree(g, x2, y2, distance*frac, direction-angle, depth-1)
ftree(g, x2, y2, distance*frac, direction+angle, depth-1)
}
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. | from turtle import *
colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"]
screen = getscreen()
left_edge = -screen.window_width()//2
right_edge = screen.window_width()//2
quarter_height = screen.window_height()//4
half_height = quarter_height * 2
speed("fastest")
for quarter in range(4):
pensize(quarter+1)
colornum = 0
min_y = half_height - ((quarter + 1) * quarter_height)
max_y = half_height - ((quarter) * quarter_height)
for x in range(left_edge,right_edge,quarter+1):
penup()
pencolor(colors[colornum])
colornum = (colornum + 1) % len(colors)
setposition(x,min_y)
pendown()
setposition(x,max_y)
notused = input("Hit enter to continue: ")
| package main
import "github.com/fogleman/gg"
var palette = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func pinstripe(dc *gg.Context) {
w := dc.Width()
h := dc.Height() / 4
for b := 1; b <= 4; b++ {
for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
dc.SetHexColor(palette[ci%8])
y := h * (b - 1)
dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
dc.Fill()
}
}
}
func main() {
dc := gg.NewContext(900, 600)
pinstripe(dc)
dc.SavePNG("color_pinstripe.png")
}
|
Change the programming language of this snippet from Python to Go without modifying what it does. | from datetime import date
from calendar import isleap
def weekday(d):
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"]
dooms = [
[3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],
[4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
]
c = d.year // 100
r = d.year % 100
s = r // 12
t = r % 12
c_anchor = (5 * (c % 4) + 2) % 7
doomsday = (s + t + (t // 4) + c_anchor) % 7
anchorday = dooms[isleap(d.year)][d.month - 1]
weekday = (doomsday + d.day - anchorday + 7) % 7
return days[weekday]
dates = [date(*x) for x in
[(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),
(2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]
]
for d in dates:
tense = "was" if d < date.today() else "is" if d == date.today() else "will be"
print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
| package main
import (
"fmt"
"strconv"
)
var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
func anchorDay(y int) int {
return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}
func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }
var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
func main() {
dates := []string{
"1800-01-06",
"1875-03-29",
"1915-12-07",
"1970-12-23",
"2043-05-14",
"2077-02-12",
"2101-04-02",
}
fmt.Println("Days of week given by Doomsday rule:")
for _, date := range dates {
y, _ := strconv.Atoi(date[0:4])
m, _ := strconv.Atoi(date[5:7])
m--
d, _ := strconv.Atoi(date[8:10])
a := anchorDay(y)
f := firstDaysCommon[m]
if isLeapYear(y) {
f = firstDaysLeap[m]
}
w := d - f
if w < 0 {
w = 7 + w
}
dow := (a + w) % 7
fmt.Printf("%s -> %s\n", date, days[dow])
}
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. | from datetime import date
from calendar import isleap
def weekday(d):
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"]
dooms = [
[3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],
[4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
]
c = d.year // 100
r = d.year % 100
s = r // 12
t = r % 12
c_anchor = (5 * (c % 4) + 2) % 7
doomsday = (s + t + (t // 4) + c_anchor) % 7
anchorday = dooms[isleap(d.year)][d.month - 1]
weekday = (doomsday + d.day - anchorday + 7) % 7
return days[weekday]
dates = [date(*x) for x in
[(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),
(2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]
]
for d in dates:
tense = "was" if d < date.today() else "is" if d == date.today() else "will be"
print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
| package main
import (
"fmt"
"strconv"
)
var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
func anchorDay(y int) int {
return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}
func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }
var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
func main() {
dates := []string{
"1800-01-06",
"1875-03-29",
"1915-12-07",
"1970-12-23",
"2043-05-14",
"2077-02-12",
"2101-04-02",
}
fmt.Println("Days of week given by Doomsday rule:")
for _, date := range dates {
y, _ := strconv.Atoi(date[0:4])
m, _ := strconv.Atoi(date[5:7])
m--
d, _ := strconv.Atoi(date[8:10])
a := anchorDay(y)
f := firstDaysCommon[m]
if isLeapYear(y) {
f = firstDaysLeap[m]
}
w := d - f
if w < 0 {
w = 7 + w
}
dow := (a + w) % 7
fmt.Printf("%s -> %s\n", date, days[dow])
}
}
|
Transform the following Python implementation into Go, maintaining the same output and logic. |
def cocktailshiftingbounds(A):
beginIdx = 0
endIdx = len(A) - 1
while beginIdx <= endIdx:
newBeginIdx = endIdx
newEndIdx = beginIdx
for ii in range(beginIdx,endIdx):
if A[ii] > A[ii + 1]:
A[ii+1], A[ii] = A[ii], A[ii+1]
newEndIdx = ii
endIdx = newEndIdx
for ii in range(endIdx,beginIdx-1,-1):
if A[ii] > A[ii + 1]:
A[ii+1], A[ii] = A[ii], A[ii+1]
newBeginIdx = ii
beginIdx = newBeginIdx + 1
test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
cocktailshiftingbounds(test1)
print(test1)
test2=list('big fjords vex quick waltz nymph')
cocktailshiftingbounds(test2)
print(''.join(test2))
| package main
import (
"fmt"
"math/rand"
"time"
)
func cocktailShakerSort(a []int) {
var begin = 0
var end = len(a) - 2
for begin <= end {
newBegin := end
newEnd := begin
for i := begin; i <= end; i++ {
if a[i] > a[i+1] {
a[i+1], a[i] = a[i], a[i+1]
newEnd = i
}
}
end = newEnd - 1
for i := end; i >= begin; i-- {
if a[i] > a[i+1] {
a[i+1], a[i] = a[i], a[i+1]
newBegin = i
}
}
begin = newBegin + 1
}
}
func cocktailSort(a []int) {
last := len(a) - 1
for {
swapped := false
for i := 0; i < last; i++ {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
return
}
swapped = false
for i := last - 1; i >= 0; i-- {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
return
}
}
}
func main() {
a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}
fmt.Println("Original array:", a)
b := make([]int, len(a))
copy(b, a)
cocktailSort(a)
fmt.Println("Cocktail sort :", a)
cocktailShakerSort(b)
fmt.Println("C/Shaker sort :", b)
rand.Seed(time.Now().UnixNano())
fmt.Println("\nRelative speed of the two sorts")
fmt.Println(" N x faster (CSS v CS)")
fmt.Println("----- -------------------")
const runs = 10
for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {
sum := 0.0
for i := 1; i <= runs; i++ {
nums := make([]int, n)
for i := 0; i < n; i++ {
rn := rand.Intn(100000)
if i%2 == 1 {
rn = -rn
}
nums[i] = rn
}
nums2 := make([]int, n)
copy(nums2, nums)
start := time.Now()
cocktailSort(nums)
elapsed := time.Since(start)
start2 := time.Now()
cocktailShakerSort(nums2)
elapsed2 := time.Since(start2)
sum += float64(elapsed) / float64(elapsed2)
}
fmt.Printf(" %2dk %0.3f\n", n/1000, sum/runs)
}
}
|
Produce a functionally identical Go code for the snippet given in Python. | import pygame, sys
from pygame.locals import *
from math import sin, cos, radians
pygame.init()
WINDOWSIZE = 250
TIMETICK = 100
BOBSIZE = 15
window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))
pygame.display.set_caption("Pendulum")
screen = pygame.display.get_surface()
screen.fill((255,255,255))
PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)
SWINGLENGTH = PIVOT[1]*4
class BobMass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.theta = 45
self.dtheta = 0
self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),
PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),
1,1)
self.draw()
def recomputeAngle(self):
scaling = 3000.0/(SWINGLENGTH**2)
firstDDtheta = -sin(radians(self.theta))*scaling
midDtheta = self.dtheta + firstDDtheta
midtheta = self.theta + (self.dtheta + midDtheta)/2.0
midDDtheta = -sin(radians(midtheta))*scaling
midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2
midtheta = self.theta + (self.dtheta + midDtheta)/2
midDDtheta = -sin(radians(midtheta)) * scaling
lastDtheta = midDtheta + midDDtheta
lasttheta = midtheta + (midDtheta + lastDtheta)/2.0
lastDDtheta = -sin(radians(lasttheta)) * scaling
lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0
lasttheta = midtheta + (midDtheta + lastDtheta)/2.0
self.dtheta = lastDtheta
self.theta = lasttheta
self.rect = pygame.Rect(PIVOT[0]-
SWINGLENGTH*sin(radians(self.theta)),
PIVOT[1]+
SWINGLENGTH*cos(radians(self.theta)),1,1)
def draw(self):
pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)
pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)
pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)
pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))
def update(self):
self.recomputeAngle()
screen.fill((255,255,255))
self.draw()
bob = BobMass()
TICK = USEREVENT + 2
pygame.time.set_timer(TICK, TIMETICK)
def input(events):
for event in events:
if event.type == QUIT:
sys.exit(0)
elif event.type == TICK:
bob.update()
while True:
input(pygame.event.get())
pygame.display.flip()
| package main
import (
"github.com/google/gxui"
"github.com/google/gxui/drivers/gl"
"github.com/google/gxui/math"
"github.com/google/gxui/themes/dark"
omath "math"
"time"
)
const (
ANIMATION_WIDTH int = 480
ANIMATION_HEIGHT int = 320
BALL_RADIUS float32 = 25.0
METER_PER_PIXEL float64 = 1.0 / 20.0
PHI_ZERO float64 = omath.Pi * 0.5
)
var (
l float64 = float64(ANIMATION_HEIGHT) * 0.5
freq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))
)
type Pendulum interface {
GetPhi() float64
}
type mathematicalPendulum struct {
start time.Time
}
func (p *mathematicalPendulum) GetPhi() float64 {
if (p.start == time.Time{}) {
p.start = time.Now()
}
t := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)
return PHI_ZERO * omath.Cos(t*freq)
}
type numericalPendulum struct {
currentPhi float64
angAcc float64
angVel float64
lastTime time.Time
}
func (p *numericalPendulum) GetPhi() float64 {
dt := 0.0
if (p.lastTime != time.Time{}) {
dt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)
}
p.lastTime = time.Now()
p.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)
p.angVel += p.angAcc * dt
p.currentPhi += p.angVel * dt
return p.currentPhi
}
func draw(p Pendulum, canvas gxui.Canvas, x, y int) {
attachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}
phi := p.GetPhi()
ball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}
line := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}
canvas.DrawLines(line, gxui.DefaultPen)
m := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}
rect := math.Rect{ball.Sub(m), ball.Add(m)}
canvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))
}
func appMain(driver gxui.Driver) {
theme := dark.CreateTheme(driver)
window := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, "Pendulum")
window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))
image := theme.CreateImage()
ticker := time.NewTicker(time.Millisecond * 15)
pendulum := &mathematicalPendulum{}
pendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}
go func() {
for _ = range ticker.C {
canvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})
canvas.Clear(gxui.White)
draw(pendulum, canvas, 0, 0)
draw(pendulum2, canvas, 0, ANIMATION_HEIGHT)
canvas.Complete()
driver.Call(func() {
image.SetCanvas(canvas)
})
}
}()
window.AddChild(image)
window.OnClose(ticker.Stop)
window.OnClose(driver.Terminate)
}
func main() {
gl.StartDriver(appMain)
}
|
Please provide an equivalent version of this Python code in Go. | >>> def int2bin(n):
'From positive integer to list of binary bits, msb at index 0'
if n:
bits = []
while n:
n,remainder = divmod(n, 2)
bits.insert(0, remainder)
return bits
else: return [0]
>>> def bin2int(bits):
'From binary bits, msb at index 0 to integer'
i = 0
for bit in bits:
i = i * 2 + bit
return i
| package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
|
Change the following Python code into Go without altering its purpose. | >>> def int2bin(n):
'From positive integer to list of binary bits, msb at index 0'
if n:
bits = []
while n:
n,remainder = divmod(n, 2)
bits.insert(0, remainder)
return bits
else: return [0]
>>> def bin2int(bits):
'From binary bits, msb at index 0 to integer'
i = 0
for bit in bits:
i = i * 2 + bit
return i
| package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
|
Convert the following code from Python to Go, ensuring the logic remains intact. | >>> def int2bin(n):
'From positive integer to list of binary bits, msb at index 0'
if n:
bits = []
while n:
n,remainder = divmod(n, 2)
bits.insert(0, remainder)
return bits
else: return [0]
>>> def bin2int(bits):
'From binary bits, msb at index 0 to integer'
i = 0
for bit in bits:
i = i * 2 + bit
return i
| package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
|
Write the same algorithm in Go as shown in this Python implementation. | >>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n')
...
>>>
| package main
import (
"archive/tar"
"compress/gzip"
"flag"
"io"
"log"
"os"
"time"
)
func main() {
filename := flag.String("file", "TAPE.FILE", "filename within TAR")
data := flag.String("data", "", "data for file")
outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)")
gzipFlag := flag.Bool("gzip", false, "use gzip compression")
flag.Parse()
var w io.Writer = os.Stdout
if *outfile != "" {
f, err := os.Create(*outfile)
if err != nil {
log.Fatalf("opening/creating %q: %v", *outfile, err)
}
defer f.Close()
w = f
}
if *gzipFlag {
zw := gzip.NewWriter(w)
defer zw.Close()
w = zw
}
tw := tar.NewWriter(w)
defer tw.Close()
w = tw
tw.WriteHeader(&tar.Header{
Name: *filename,
Mode: 0660,
Size: int64(len(*data)),
ModTime: time.Now(),
Typeflag: tar.TypeReg,
Uname: "guest",
Gname: "guest",
})
_, err := w.Write([]byte(*data))
if err != nil {
log.Fatal("writing data:", err)
}
}
|
Convert this Python snippet to Go and keep its semantics consistent. | >>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n')
...
>>>
| package main
import (
"archive/tar"
"compress/gzip"
"flag"
"io"
"log"
"os"
"time"
)
func main() {
filename := flag.String("file", "TAPE.FILE", "filename within TAR")
data := flag.String("data", "", "data for file")
outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)")
gzipFlag := flag.Bool("gzip", false, "use gzip compression")
flag.Parse()
var w io.Writer = os.Stdout
if *outfile != "" {
f, err := os.Create(*outfile)
if err != nil {
log.Fatalf("opening/creating %q: %v", *outfile, err)
}
defer f.Close()
w = f
}
if *gzipFlag {
zw := gzip.NewWriter(w)
defer zw.Close()
w = zw
}
tw := tar.NewWriter(w)
defer tw.Close()
w = tw
tw.WriteHeader(&tar.Header{
Name: *filename,
Mode: 0660,
Size: int64(len(*data)),
ModTime: time.Now(),
Typeflag: tar.TypeReg,
Uname: "guest",
Gname: "guest",
})
_, err := w.Write([]byte(*data))
if err != nil {
log.Fatal("writing data:", err)
}
}
|
Translate this program into Go but keep the logic exactly as in Python. | def heapsort(lst):
for start in range((len(lst)-2)/2, -1, -1):
siftdown(lst, start, len(lst)-1)
for end in range(len(lst)-1, 0, -1):
lst[end], lst[0] = lst[0], lst[end]
siftdown(lst, 0, end - 1)
return lst
def siftdown(lst, start, end):
root = start
while True:
child = root * 2 + 1
if child > end: break
if child + 1 <= end and lst[child] < lst[child + 1]:
child += 1
if lst[root] < lst[child]:
lst[root], lst[child] = lst[child], lst[root]
root = child
else:
break
| package main
import (
"sort"
"container/heap"
"fmt"
)
type HeapHelper struct {
container sort.Interface
length int
}
func (self HeapHelper) Len() int { return self.length }
func (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }
func (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }
func (self *HeapHelper) Push(x interface{}) { panic("impossible") }
func (self *HeapHelper) Pop() interface{} {
self.length--
return nil
}
func heapSort(a sort.Interface) {
helper := HeapHelper{ a, a.Len() }
heap.Init(&helper)
for helper.length > 0 {
heap.Pop(&helper)
}
}
func main() {
a := []int{170, 45, 75, -90, -802, 24, 2, 66}
fmt.Println("before:", a)
heapSort(sort.IntSlice(a))
fmt.Println("after: ", a)
}
|
Convert this Python snippet to Go and keep its semantics consistent. | import random
class Card(object):
suits = ("Clubs","Hearts","Spades","Diamonds")
pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace")
def __init__(self, pip,suit):
self.pip=pip
self.suit=suit
def __str__(self):
return "%s %s"%(self.pip,self.suit)
class Deck(object):
def __init__(self):
self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]
def __str__(self):
return "[%s]"%", ".join( (str(card) for card in self.deck))
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
self.shuffle()
return self.deck.pop(0)
| package cards
import (
"math/rand"
)
type Suit uint8
const (
Spade Suit = 3
Heart Suit = 2
Diamond Suit = 1
Club Suit = 0
)
func (s Suit) String() string {
const suites = "CDHS"
return suites[s : s+1]
}
type Rank uint8
const (
Ace Rank = 1
Two Rank = 2
Three Rank = 3
Four Rank = 4
Five Rank = 5
Six Rank = 6
Seven Rank = 7
Eight Rank = 8
Nine Rank = 9
Ten Rank = 10
Jack Rank = 11
Queen Rank = 12
King Rank = 13
)
func (r Rank) String() string {
const ranks = "A23456789TJQK"
return ranks[r-1 : r]
}
type Card uint8
func NewCard(r Rank, s Suit) Card {
return Card(13*uint8(s) + uint8(r-1))
}
func (c Card) RankSuit() (Rank, Suit) {
return Rank(c%13 + 1), Suit(c / 13)
}
func (c Card) Rank() Rank {
return Rank(c%13 + 1)
}
func (c Card) Suit() Suit {
return Suit(c / 13)
}
func (c Card) String() string {
return c.Rank().String() + c.Suit().String()
}
type Deck []Card
func NewDeck() Deck {
d := make(Deck, 52)
for i := range d {
d[i] = Card(i)
}
return d
}
func (d Deck) String() string {
s := ""
for i, c := range d {
switch {
case i == 0:
case i%13 == 0:
s += "\n"
default:
s += " "
}
s += c.String()
}
return s
}
func (d Deck) Shuffle() {
for i := range d {
j := rand.Intn(i + 1)
d[i], d[j] = d[j], d[i]
}
}
func (d Deck) Contains(tc Card) bool {
for _, c := range d {
if c == tc {
return true
}
}
return false
}
func (d *Deck) AddDeck(decks ...Deck) {
for _, o := range decks {
*d = append(*d, o...)
}
}
func (d *Deck) AddCard(c Card) {
*d = append(*d, c)
}
func (d *Deck) Draw(n int) Deck {
old := *d
*d = old[n:]
return old[:n:n]
}
func (d *Deck) DrawCard() (Card, bool) {
if len(*d) == 0 {
return 0, false
}
old := *d
*d = old[1:]
return old[0], true
}
func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {
for i := 0; i < cards; i++ {
for j := range hands {
if len(*d) == 0 {
return hands, false
}
hands[j] = append(hands[j], (*d)[0])
*d = (*d)[1:]
}
}
return hands, true
}
|
Write the same code in Go as shown below in Python. | array = []
array.append(1)
array.append(3)
array[0] = 2
print array[0]
| package main
import (
"fmt"
)
func main() {
var a [5]int
fmt.Println("len(a) =", len(a))
fmt.Println("a =", a)
a[0] = 3
fmt.Println("a =", a)
fmt.Println("a[0] =", a[0])
s := a[:4]
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
s = s[:5]
fmt.Println("s =", s)
a[0] = 22
fmt.Println("a =", a)
fmt.Println("s =", s)
s = append(s, 4, 5, 6)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
a[4] = -1
fmt.Println("a =", a)
fmt.Println("s =", s)
s = make([]int, 8)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
}
|
Rewrite the snippet below in Go so it works the same as the original Python code. | def setup():
size(729, 729)
fill(0)
background(255)
noStroke()
rect(width / 3, height / 3, width / 3, width / 3)
rectangles(width / 3, height / 3, width / 3)
def rectangles(x, y, s):
if s < 1: return
xc, yc = x - s, y - s
for row in range(3):
for col in range(3):
if not (row == 1 and col == 1):
xx, yy = xc + row * s, yc + col * s
delta = s / 3
rect(xx + delta, yy + delta, delta, delta)
rectangles(xx + s / 3, yy + s / 3, s / 3)
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
var order = 3
var grain = "#"
func main() {
carpet := []string{grain}
for ; order > 0; order-- {
hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0]))
middle := make([]string, len(carpet))
for i, s := range carpet {
middle[i] = s + hole + s
carpet[i] = strings.Repeat(s, 3)
}
carpet = append(append(carpet, middle...), carpet...)
}
for _, r := range carpet {
fmt.Println(r)
}
}
|
Port the provided Python code into Go while preserving the original functionality. | import random
def bogosort(l):
while not in_order(l):
random.shuffle(l)
return l
def in_order(l):
if not l:
return True
last = l[0]
for x in l[1:]:
if x < last:
return False
last = x
return True
| package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
rand.Seed(time.Now().UnixNano())
fmt.Println("unsorted:", list)
temp := make([]int, len(list))
copy(temp, list)
for !sort.IntsAreSorted(temp) {
for i, v := range rand.Perm(len(list)) {
temp[i] = list[v]
}
}
fmt.Println("sorted! ", temp)
}
|
Keep all operations the same but rewrite the snippet in Go. |
import pandas as pd
df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".")
df_visits = pd.read_csv (r'visits.csv', sep = ",", decimal=".")
df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])
df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')
df_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)
df_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})
print(df_result)
| package main
import (
"fmt"
"math"
"sort"
)
type Patient struct {
id int
lastName string
}
var patientDir = make(map[int]string)
var patientIds []int
func patientNew(id int, lastName string) Patient {
patientDir[id] = lastName
patientIds = append(patientIds, id)
sort.Ints(patientIds)
return Patient{id, lastName}
}
type DS struct {
dates []string
scores []float64
}
type Visit struct {
id int
date string
score float64
}
var visitDir = make(map[int]DS)
func visitNew(id int, date string, score float64) Visit {
if date == "" {
date = "0000-00-00"
}
v, ok := visitDir[id]
if ok {
v.dates = append(v.dates, date)
v.scores = append(v.scores, score)
visitDir[id] = DS{v.dates, v.scores}
} else {
visitDir[id] = DS{[]string{date}, []float64{score}}
}
return Visit{id, date, score}
}
type Merge struct{ id int }
func (m Merge) lastName() string { return patientDir[m.id] }
func (m Merge) dates() []string { return visitDir[m.id].dates }
func (m Merge) scores() []float64 { return visitDir[m.id].scores }
func (m Merge) lastVisit() string {
dates := m.dates()
dates2 := make([]string, len(dates))
copy(dates2, dates)
sort.Strings(dates2)
return dates2[len(dates2)-1]
}
func (m Merge) scoreSum() float64 {
sum := 0.0
for _, score := range m.scores() {
if score != -1 {
sum += score
}
}
return sum
}
func (m Merge) scoreAvg() float64 {
count := 0
for _, score := range m.scores() {
if score != -1 {
count++
}
}
return m.scoreSum() / float64(count)
}
func mergePrint(merges []Merge) {
fmt.Println("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |")
f := "| %d | %-7s | %s | %4s | %4s |\n"
for _, m := range merges {
_, ok := visitDir[m.id]
if ok {
lv := m.lastVisit()
if lv == "0000-00-00" {
lv = " "
}
scoreSum := m.scoreSum()
ss := fmt.Sprintf("%4.1f", scoreSum)
if scoreSum == 0 {
ss = " "
}
scoreAvg := m.scoreAvg()
sa := " "
if !math.IsNaN(scoreAvg) {
sa = fmt.Sprintf("%4.2f", scoreAvg)
}
fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)
} else {
fmt.Printf(f, m.id, m.lastName(), " ", " ", " ")
}
}
}
func main() {
patientNew(1001, "Hopper")
patientNew(4004, "Wirth")
patientNew(3003, "Kemeny")
patientNew(2002, "Gosling")
patientNew(5005, "Kurtz")
visitNew(2002, "2020-09-10", 6.8)
visitNew(1001, "2020-09-17", 5.5)
visitNew(4004, "2020-09-24", 8.4)
visitNew(2002, "2020-10-08", -1)
visitNew(1001, "", 6.6)
visitNew(3003, "2020-11-12", -1)
visitNew(4004, "2020-11-05", 7.0)
visitNew(1001, "2020-11-19", 5.3)
merges := make([]Merge, len(patientIds))
for i, id := range patientIds {
merges[i] = Merge{id}
}
mergePrint(merges)
}
|
Convert the following code from Python to Go, ensuring the logic remains intact. | def euler(f,y0,a,b,h):
t,y = a,y0
while t <= b:
print "%6.3f %6.3f" % (t,y)
t += h
y += h * f(t,y)
def newtoncooling(time, temp):
return -0.07 * (temp - 20)
euler(newtoncooling,100,0,100,10)
| package main
import (
"fmt"
"math"
)
type fdy func(float64, float64) float64
func eulerStep(f fdy, x, y, h float64) float64 {
return y + h*f(x, y)
}
func newCoolingRate(k float64) func(float64) float64 {
return func(deltaTemp float64) float64 {
return -k * deltaTemp
}
}
func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {
return func(time float64) float64 {
return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)
}
}
func newCoolingRateDy(k, ambientTemp float64) fdy {
crf := newCoolingRate(k)
return func(_, objectTemp float64) float64 {
return crf(objectTemp - ambientTemp)
}
}
func main() {
k := .07
tempRoom := 20.
tempObject := 100.
fcr := newCoolingRateDy(k, tempRoom)
analytic := newTempFunc(k, tempRoom, tempObject)
for _, deltaTime := range []float64{2, 5, 10} {
fmt.Printf("Step size = %.1f\n", deltaTime)
fmt.Println(" Time Euler's Analytic")
temp := tempObject
for time := 0.; time <= 100; time += deltaTime {
fmt.Printf("%5.1f %7.3f %7.3f\n", time, temp, analytic(time))
temp = eulerStep(fcr, time, temp, deltaTime)
}
fmt.Println()
}
}
|
Generate a Go translation of this Python snippet without changing its computational steps. | >>> from math import floor, sqrt
>>> def non_square(n):
return n + floor(1/2 + sqrt(n))
>>>
>>> print(*map(non_square, range(1, 23)))
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
>>>
>>> def is_square(n):
return sqrt(n).is_integer()
>>> non_squares = map(non_square, range(1, 10 ** 6))
>>> next(filter(is_square, non_squares))
StopIteration Traceback (most recent call last)
<ipython-input-45-f32645fc1c0a> in <module>()
1 non_squares = map(non_square, range(1, 10 ** 6))
----> 2 next(filter(is_square, non_squares))
StopIteration:
| package main
import (
"fmt"
"math"
)
func remarkable(n int) int {
return n + int(.5+math.Sqrt(float64(n)))
}
func main() {
fmt.Println(" n r(n)")
fmt.Println("--- ---")
for n := 1; n <= 22; n++ {
fmt.Printf("%3d %3d\n", n, remarkable(n))
}
const limit = 1e6
fmt.Println("\nChecking for squares for n <", limit)
next := 2
nextSq := 4
for n := 1; n < limit; n++ {
r := remarkable(n)
switch {
case r == nextSq:
panic(n)
case r > nextSq:
fmt.Println(nextSq, "didn't occur")
next++
nextSq = next * next
}
}
fmt.Println("No squares occur for n <", limit)
}
|
Convert this Python snippet to Go and keep its semantics consistent. | >>> s = 'abcdefgh'
>>> n, m, char, chars = 2, 3, 'd', 'cd'
>>>
>>> s[n-1:n+m-1]
'bcd'
>>>
>>> s[n-1:]
'bcdefgh'
>>>
>>> s[:-1]
'abcdefg'
>>>
>>> indx = s.index(char)
>>> s[indx:indx+m]
'def'
>>>
>>> indx = s.index(chars)
>>> s[indx:indx+m]
'cde'
>>>
| package main
import (
"fmt"
"strings"
)
func main() {
s := "ABCDEFGH"
n, m := 2, 3
fmt.Println("Index: ", "01234567")
fmt.Println("String:", s)
fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m])
fmt.Printf("Start %d, to end: %s\n", n, s[n:])
fmt.Printf("All but last: %s\n", s[:len(s)-1])
dx := strings.IndexByte(s, 'D')
fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m])
sx := strings.Index(s, "DE")
fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}
|
Keep all operations the same but rewrite the snippet in Go. | >>> def jortsort(sequence):
return list(sequence) == sorted(sequence)
>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:
print(f'jortsort({repr(data)}) is {jortsort(data)}')
jortsort((1, 2, 4, 3)) is False
jortsort((14, 6, 8)) is False
jortsort(['a', 'c']) is True
jortsort(['s', 'u', 'x']) is True
jortsort('CVGH') is False
jortsort('PQRST') is True
>>>
| package main
import (
"log"
"sort"
)
func main() {
log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4}))
log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))
log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))
log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))
}
func jortSort(a []int) bool {
c := make([]int, len(a))
copy(c, a)
sort.Ints(a)
for k, v := range c {
if v == a[k] {
continue
} else {
return false
}
}
return true
}
|
Change the following Python code into Go without altering its purpose. | import calendar
calendar.isleap(year)
| func isLeap(year int) bool {
return year%400 == 0 || year%4 == 0 && year%100 != 0
}
|
Ensure the translated Go code behaves exactly like the original Python snippet. | from __future__ import print_function
from scipy.misc import factorial as fact
from scipy.misc import comb
def perm(N, k, exact=0):
return comb(N, k, exact) * fact(k, exact)
exact=True
print('Sample Perms 1..12')
for N in range(1, 13):
k = max(N-2, 1)
print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\n')
print('\n\nSample Combs 10..60')
for N in range(10, 61, 10):
k = N-2
print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\n')
exact=False
print('\n\nSample Perms 5..1500 Using FP approximations')
for N in [5, 15, 150, 1500, 15000]:
k = N-2
print('%iP%i =' % (N, k), perm(N, k, exact))
print('\nSample Combs 100..1000 Using FP approximations')
for N in range(100, 1001, 100):
k = N-2
print('%iC%i =' % (N, k), comb(N, k, exact))
| package main
import (
"fmt"
"math/big"
)
func main() {
var n, p int64
fmt.Printf("A sample of permutations from 1 to 12:\n")
for n = 1; n < 13; n++ {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 10 to 60:\n")
for n = 10; n < 61; n += 10 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of permutations from 5 to 15000:\n")
nArr := [...]int64{5, 50, 500, 1000, 5000, 15000}
for _, n = range nArr {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 100 to 1000:\n")
for n = 100; n < 1001; n += 100 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
}
func fact(n *big.Int) *big.Int {
if n.Sign() < 1 {
return big.NewInt(0)
}
r := big.NewInt(1)
i := big.NewInt(2)
for i.Cmp(n) < 1 {
r.Mul(r, i)
i.Add(i, big.NewInt(1))
}
return r
}
func perm(n, k *big.Int) *big.Int {
r := fact(n)
r.Div(r, fact(n.Sub(n, k)))
return r
}
func comb(n, r *big.Int) *big.Int {
if r.Cmp(n) == 1 {
return big.NewInt(0)
}
if r.Cmp(n) == 0 {
return big.NewInt(1)
}
c := fact(n)
den := fact(n.Sub(n, r))
den.Mul(den, fact(r))
c.Div(c, den)
return c
}
|
Generate an equivalent Go version of this Python code. | n=13
print(sorted(range(1,n+1), key=str))
| package main
import (
"fmt"
"sort"
"strconv"
)
func lexOrder(n int) []int {
first, last, k := 1, n, n
if n < 1 {
first, last, k = n, 1, 2-n
}
strs := make([]string, k)
for i := first; i <= last; i++ {
strs[i-first] = strconv.Itoa(i)
}
sort.Strings(strs)
ints := make([]int, k)
for i := 0; i < k; i++ {
ints[i], _ = strconv.Atoi(strs[i])
}
return ints
}
func main() {
fmt.Println("In lexicographical order:\n")
for _, n := range []int{0, 5, 13, 21, -22} {
fmt.Printf("%3d: %v\n", n, lexOrder(n))
}
}
|
Produce a language-to-language conversion: from Python to Go, same semantics. | 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)
if __name__ == '__main__':
for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):
print('%+4i -> %s' % (n, spell_integer(n)))
print('')
n = 201021002001
while n:
print('%-12i -> %s' % (n, spell_integer(n)))
n //= -10
print('%-12i -> %s' % (n, spell_integer(n)))
print('')
| package main
import "fmt"
func main() {
for _, n := range []int64{12, 1048576, 9e18, -2, 0} {
fmt.Println(say(n))
}
}
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
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.