Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "math" "math/cmplx" ) func fft(buf []complex128, n int) { out := make([]complex128, n) copy(out, buf) fft2(buf, out, n, 1) } func fft2(buf, out []complex128, n, step int) { if step < n { fft2(out, buf, n, step*2) fft2(out[step:], buf[step:], n, step*2) for j := 0; j < n; j += 2 * step { fj, fn := float64(j), float64(n) t := cmplx.Exp(-1i*complex(math.Pi, 0)*complex(fj, 0)/complex(fn, 0)) * out[j+step] buf[j/2] = out[j] + t buf[(j+n)/2] = out[j] - t } } } func padTwo(g []float64, le int, ns *int) []complex128 { n := 1 if *ns != 0 { n = *ns } else { for n < le { n *= 2 } } buf := make([]complex128, n) for i := 0; i < le; i++ { buf[i] = complex(g[i], 0) } *ns = n return buf } func deconv(g []float64, lg int, f []float64, lf int, out []float64, rowLe int) { ns := 0 g2 := padTwo(g, lg, &ns) f2 := padTwo(f, lf, &ns) fft(g2, ns) fft(f2, ns) h := make([]complex128, ns) for i := 0; i < ns; i++ { h[i] = g2[i] / f2[i] } fft(h, ns) for i := 0; i < ns; i++ { if math.Abs(real(h[i])) < 1e-10 { h[i] = 0 } } for i := 0; i > lf-lg-rowLe; i-- { out[-i] = real(h[(i+ns)%ns] / 32) } } func unpack2(m [][]float64, rows, le, toLe int) []float64 { buf := make([]float64, rows*toLe) for i := 0; i < rows; i++ { for j := 0; j < le; j++ { buf[i*toLe+j] = m[i][j] } } return buf } func pack2(buf []float64, rows, fromLe, toLe int, out [][]float64) { for i := 0; i < rows; i++ { for j := 0; j < toLe; j++ { out[i][j] = buf[i*fromLe+j] / 4 } } } func deconv2(g [][]float64, rowG, colG int, f [][]float64, rowF, colF int, out [][]float64) { g2 := unpack2(g, rowG, colG, colG) f2 := unpack2(f, rowF, colF, colG) ff := make([]float64, (rowG-rowF+1)*colG) deconv(g2, rowG*colG, f2, rowF*colG, ff, colG) pack2(ff, rowG-rowF+1, colG, colG-colF+1, out) } func unpack3(m [][][]float64, x, y, z, toY, toZ int) []float64 { buf := make([]float64, x*toY*toZ) for i := 0; i < x; i++ { for j := 0; j < y; j++ { for k := 0; k < z; k++ { buf[(i*toY+j)*toZ+k] = m[i][j][k] } } } return buf } func pack3(buf []float64, x, y, z, toY, toZ int, out [][][]float64) { for i := 0; i < x; i++ { for j := 0; j < toY; j++ { for k := 0; k < toZ; k++ { out[i][j][k] = buf[(i*y+j)*z+k] / 4 } } } } func deconv3(g [][][]float64, gx, gy, gz int, f [][][]float64, fx, fy, fz int, out [][][]float64) { g2 := unpack3(g, gx, gy, gz, gy, gz) f2 := unpack3(f, fx, fy, fz, gy, gz) ff := make([]float64, (gx-fx+1)*gy*gz) deconv(g2, gx*gy*gz, f2, fx*gy*gz, ff, gy*gz) pack3(ff, gx-fx+1, gy, gz, gy-fy+1, gz-fz+1, out) } func main() { f := [][][]float64{ {{-9, 5, -8}, {3, 5, 1}}, {{-1, -7, 2}, {-5, -6, 6}}, {{8, 5, 8}, {-2, -6, -4}}, } fx, fy, fz := len(f), len(f[0]), len(f[0][0]) g := [][][]float64{ {{54, 42, 53, -42, 85, -72}, {45, -170, 94, -36, 48, 73}, {-39, 65, -112, -16, -78, -72}, {6, -11, -6, 62, 49, 8}}, {{-57, 49, -23, 52, -135, 66}, {-23, 127, -58, -5, -118, 64}, {87, -16, 121, 23, -41, -12}, {-19, 29, 35, -148, -11, 45}}, {{-55, -147, -146, -31, 55, 60}, {-88, -45, -28, 46, -26, -144}, {-12, -107, -34, 150, 249, 66}, {11, -15, -34, 27, -78, -50}}, {{56, 67, 108, 4, 2, -48}, {58, 67, 89, 32, 32, -8}, {-42, -31, -103, -30, -23, -8}, {6, 4, -26, -10, 26, 12}, }, } gx, gy, gz := len(g), len(g[0]), len(g[0][0]) h := [][][]float64{ {{-6, -8, -5, 9}, {-7, 9, -6, -8}, {2, -7, 9, 8}}, {{7, 4, 4, -6}, {9, 9, 4, -4}, {-3, 7, -2, -3}}, } hx, hy, hz := gx-fx+1, gy-fy+1, gz-fz+1 h2 := make([][][]float64, hx) for i := 0; i < hx; i++ { h2[i] = make([][]float64, hy) for j := 0; j < hy; j++ { h2[i][j] = make([]float64, hz) } } deconv3(g, gx, gy, gz, f, fx, fy, fz, h2) fmt.Println("deconv3(g, f):\n") for i := 0; i < hx; i++ { for j := 0; j < hy; j++ { for k := 0; k < hz; k++ { fmt.Printf("% .10g ", h2[i][j][k]) } fmt.Println() } if i < hx-1 { fmt.Println() } } kx, ky, kz := gx-hx+1, gy-hy+1, gz-hz+1 f2 := make([][][]float64, kx) for i := 0; i < kx; i++ { f2[i] = make([][]float64, ky) for j := 0; j < ky; j++ { f2[i][j] = make([]float64, kz) } } deconv3(g, gx, gy, gz, h, hx, hy, hz, f2) fmt.Println("\ndeconv(g, h):\n") for i := 0; i < kx; i++ { for j := 0; j < ky; j++ { for k := 0; k < kz; k++ { fmt.Printf("% .10g ", f2[i][j][k]) } fmt.Println() } if i < kx-1 { fmt.Println() } } }
import numpy import pprint h = [ [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]] f = [ [[-9, 5, -8], [3, 5, 1]], [[-1, -7, 2], [-5, -6, 6]], [[8, 5, 8],[-2, -6, -4]]] g = [ [ [54, 42, 53, -42, 85, -72], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]] def trim_zero_empty(x): if len(x) > 0: if type(x[0]) != numpy.ndarray: return list(numpy.trim_zeros(x)) else: new_x = [] for l in x: tl = trim_zero_empty(l) if len(tl) > 0: new_x.append(tl) return new_x else: return x def deconv(a, b): ffta = numpy.fft.fftn(a) ashape = numpy.shape(a) fftb = numpy.fft.fftn(b,ashape) fftquotient = ffta / fftb c = numpy.fft.ifftn(fftquotient) trimmedc = numpy.around(numpy.real(c),decimals=6) cleanc = trim_zero_empty(trimmedc) return cleanc print("deconv(g,h)=") pprint.pprint(deconv(g,h)) print(" ") print("deconv(g,f)=") pprint.pprint(deconv(g,f))
Maintain the same structure and functionality when rewriting this code in Python.
package main import( "math" "fmt" ) func minOf(x, y uint) uint { if x < y { return x } return y } func throwDie(nSides, nDice, s uint, counts []uint) { if nDice == 0 { counts[s]++ return } for i := uint(1); i <= nSides; i++ { throwDie(nSides, nDice - 1, s + i, counts) } } func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 { len1 := (nSides1 + 1) * nDice1 c1 := make([]uint, len1) throwDie(nSides1, nDice1, 0, c1) len2 := (nSides2 + 1) * nDice2 c2 := make([]uint, len2) throwDie(nSides2, nDice2, 0, c2) p12 := math.Pow(float64(nSides1), float64(nDice1)) * math.Pow(float64(nSides2), float64(nDice2)) tot := 0.0 for i := uint(0); i < len1; i++ { for j := uint(0); j < minOf(i, len2); j++ { tot += float64(c1[i] * c2[j]) / p12 } } return tot } func main() { fmt.Println(beatingProbability(4, 9, 6, 6)) fmt.Println(beatingProbability(10, 5, 7, 6)) }
from itertools import product def gen_dict(n_faces, n_dice): counts = [0] * ((n_faces + 1) * n_dice) for t in product(range(1, n_faces + 1), repeat=n_dice): counts[sum(t)] += 1 return counts, n_faces ** n_dice def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2): c1, p1 = gen_dict(n_sides1, n_dice1) c2, p2 = gen_dict(n_sides2, n_dice2) p12 = float(p1 * p2) return sum(p[1] * q[1] / p12 for p, q in product(enumerate(c1), enumerate(c2)) if p[0] > q[0]) print beating_probability(4, 9, 6, 6) print beating_probability(10, 5, 7, 6)
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "log" "strings" ) type HouseSet [5]*House type House struct { n Nationality c Colour a Animal d Drink s Smoke } type Nationality int8 type Colour int8 type Animal int8 type Drink int8 type Smoke int8 const ( English Nationality = iota Swede Dane Norwegian German ) const ( Red Colour = iota Green White Yellow Blue ) const ( Dog Animal = iota Birds Cats Horse Zebra ) const ( Tea Drink = iota Coffee Milk Beer Water ) const ( PallMall Smoke = iota Dunhill Blend BlueMaster Prince ) var nationalities = [...]string{"English", "Swede", "Dane", "Norwegian", "German"} var colours = [...]string{"red", "green", "white", "yellow", "blue"} var animals = [...]string{"dog", "birds", "cats", "horse", "zebra"} var drinks = [...]string{"tea", "coffee", "milk", "beer", "water"} var smokes = [...]string{"Pall Mall", "Dunhill", "Blend", "Blue Master", "Prince"} func (n Nationality) String() string { return nationalities[n] } func (c Colour) String() string { return colours[c] } func (a Animal) String() string { return animals[a] } func (d Drink) String() string { return drinks[d] } func (s Smoke) String() string { return smokes[s] } func (h House) String() string { return fmt.Sprintf("%-9s  %-6s  %-5s  %-6s %s", h.n, h.c, h.a, h.d, h.s) } func (hs HouseSet) String() string { lines := make([]string, 0, len(hs)) for i, h := range hs { s := fmt.Sprintf("%d %s", i, h) lines = append(lines, s) } return strings.Join(lines, "\n") } func simpleBruteForce() (int, HouseSet) { var v []House for n := range nationalities { for c := range colours { for a := range animals { for d := range drinks { for s := range smokes { h := House{ n: Nationality(n), c: Colour(c), a: Animal(a), d: Drink(d), s: Smoke(s), } if !h.Valid() { continue } v = append(v, h) } } } } } n := len(v) log.Println("Generated", n, "valid houses") combos := 0 first := 0 valid := 0 var validSet HouseSet for a := 0; a < n; a++ { if v[a].n != Norwegian { continue } for b := 0; b < n; b++ { if b == a { continue } if v[b].anyDups(&v[a]) { continue } for c := 0; c < n; c++ { if c == b || c == a { continue } if v[c].d != Milk { continue } if v[c].anyDups(&v[b], &v[a]) { continue } for d := 0; d < n; d++ { if d == c || d == b || d == a { continue } if v[d].anyDups(&v[c], &v[b], &v[a]) { continue } for e := 0; e < n; e++ { if e == d || e == c || e == b || e == a { continue } if v[e].anyDups(&v[d], &v[c], &v[b], &v[a]) { continue } combos++ set := HouseSet{&v[a], &v[b], &v[c], &v[d], &v[e]} if set.Valid() { valid++ if valid == 1 { first = combos } validSet = set } } } } } } log.Println("Tested", first, "different combinations of valid houses before finding solution") log.Println("Tested", combos, "different combinations of valid houses in total") return valid, validSet } func (h *House) anyDups(list ...*House) bool { for _, b := range list { if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s { return true } } return false } func (h *House) Valid() bool { if h.n == English && h.c != Red || h.n != English && h.c == Red { return false } if h.n == Swede && h.a != Dog || h.n != Swede && h.a == Dog { return false } if h.n == Dane && h.d != Tea || h.n != Dane && h.d == Tea { return false } if h.c == Green && h.d != Coffee || h.c != Green && h.d == Coffee { return false } if h.a == Birds && h.s != PallMall || h.a != Birds && h.s == PallMall { return false } if h.c == Yellow && h.s != Dunhill || h.c != Yellow && h.s == Dunhill { return false } if h.a == Cats && h.s == Blend { return false } if h.a == Horse && h.s == Dunhill { return false } if h.d == Beer && h.s != BlueMaster || h.d != Beer && h.s == BlueMaster { return false } if h.n == German && h.s != Prince || h.n != German && h.s == Prince { return false } if h.n == Norwegian && h.c == Blue { return false } if h.d == Water && h.s == Blend { return false } return true } func (hs *HouseSet) Valid() bool { ni := make(map[Nationality]int, 5) ci := make(map[Colour]int, 5) ai := make(map[Animal]int, 5) di := make(map[Drink]int, 5) si := make(map[Smoke]int, 5) for i, h := range hs { ni[h.n] = i ci[h.c] = i ai[h.a] = i di[h.d] = i si[h.s] = i } if ci[Green]+1 != ci[White] { return false } if dist(ai[Cats], si[Blend]) != 1 { return false } if dist(ai[Horse], si[Dunhill]) != 1 { return false } if dist(ni[Norwegian], ci[Blue]) != 1 { return false } if dist(di[Water], si[Blend]) != 1 { return false } if hs[2].d != Milk { return false } if hs[0].n != Norwegian { return false } return true } func dist(a, b int) int { if a > b { return a - b } return b - a } func main() { log.SetFlags(0) n, sol := simpleBruteForce() fmt.Println(n, "solution found") fmt.Println(sol) }
from logpy import * from logpy.core import lall import time def lefto(q, p, list): return membero((q,p), zip(list, list[1:])) def nexto(q, p, list): return conde([lefto(q, p, list)], [lefto(p, q, list)]) houses = var() zebraRules = lall( (eq, (var(), var(), var(), var(), var()), houses), (membero, ('Englishman', var(), var(), var(), 'red'), houses), (membero, ('Swede', var(), var(), 'dog', var()), houses), (membero, ('Dane', var(), 'tea', var(), var()), houses), (lefto, (var(), var(), var(), var(), 'green'), (var(), var(), var(), var(), 'white'), houses), (membero, (var(), var(), 'coffee', var(), 'green'), houses), (membero, (var(), 'Pall Mall', var(), 'birds', var()), houses), (membero, (var(), 'Dunhill', var(), var(), 'yellow'), houses), (eq, (var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses), (eq, (('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), var(), 'cats', var()), houses), (nexto, (var(), 'Dunhill', var(), var(), var()), (var(), var(), var(), 'horse', var()), houses), (membero, (var(), 'Blue Master', 'beer', var(), var()), houses), (membero, ('German', 'Prince', var(), var(), var()), houses), (nexto, ('Norwegian', var(), var(), var(), var()), (var(), var(), var(), var(), 'blue'), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), 'water', var(), var()), houses), (membero, (var(), var(), var(), 'zebra', var()), houses) ) t0 = time.time() solutions = run(0, houses, zebraRules) t1 = time.time() dur = t1-t0 count = len(solutions) zebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0] print "%i solutions in %.2f seconds" % (count, dur) print "The %s is the owner of the zebra" % zebraOwner print "Here are all the houses:" for line in solutions[0]: print str(line)
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "encoding/xml" "fmt" "io" "net/http" "net/url" ) const language = "Go" var baseQuery = "http: "&format=xml&list=categorymembers&cmlimit=100" func req(u string, foundCm func(string)) string { resp, err := http.Get(u) if err != nil { fmt.Println(err) return "" } defer resp.Body.Close() for p := xml.NewDecoder(resp.Body); ; { t, err := p.RawToken() switch s, ok := t.(xml.StartElement); { case err == io.EOF: return "" case err != nil: fmt.Println(err) return "" case !ok: continue case s.Name.Local == "cm": for _, a := range s.Attr { if a.Name.Local == "title" { foundCm(a.Value) } } case s.Name.Local == "categorymembers" && len(s.Attr) > 0 && s.Attr[0].Name.Local == "cmcontinue": return url.QueryEscape(s.Attr[0].Value) } } return "" } func main() { langMap := make(map[string]bool) storeLang := func(cm string) { langMap[cm] = true } languageQuery := baseQuery + "&cmtitle=Category:" + language continueAt := req(languageQuery, storeLang) for continueAt > "" { continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang) } if len(langMap) == 0 { fmt.Println("no tasks implemented for", language) return } printUnImp := func(cm string) { if !langMap[cm] { fmt.Println(cm) } } taskQuery := baseQuery + "&cmtitle=Category:Programming_Tasks" continueAt = req(taskQuery, printUnImp) for continueAt > "" { continueAt = req(taskQuery+"&cmcontinue="+continueAt, printUnImp) } }
from operator import attrgetter from typing import Iterator import mwclient URL = 'www.rosettacode.org' API_PATH = '/mw/' def unimplemented_tasks(language: str, *, url: str, api_path: str) -> Iterator[str]: site = mwclient.Site(url, path=api_path) all_tasks = site.categories['Programming Tasks'] language_tasks = site.categories[language] name = attrgetter('name') all_tasks_names = map(name, all_tasks) language_tasks_names = set(map(name, language_tasks)) for task in all_tasks_names: if task not in language_tasks_names: yield task if __name__ == '__main__': tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH) print(*tasks, sep='\n')
Maintain the same structure and functionality when rewriting this code in Python.
package main import "fmt" func main() { x := 2. xi := .5 y := 4. yi := .25 z := x + y zi := 1 / (x + y) numbers := []float64{x, y, z} inverses := []float64{xi, yi, zi} mfs := make([]func(float64) float64, len(numbers)) for i := range mfs { mfs[i] = multiplier(numbers[i], inverses[i]) } for _, mf := range mfs { fmt.Println(mf(1)) } } func multiplier(n1, n2 float64) func(float64) float64 { n1n2 := n1 * n2 return func(m float64) float64 { return n1n2 * m } }
IDLE 2.6.1 >>> >>> x,xi, y,yi = 2.0,0.5, 4.0,0.25 >>> >>> z = x + y >>> zi = 1.0 / (x + y) >>> >>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m) >>> >>> numlist = [x, y, z] >>> numlisti = [xi, yi, zi] >>> >>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)] [0.5, 0.5, 0.5] >>>
Generate a Python translation of this Go snippet without changing its computational steps.
package main import "fmt" func main() { x := 2. xi := .5 y := 4. yi := .25 z := x + y zi := 1 / (x + y) numbers := []float64{x, y, z} inverses := []float64{xi, yi, zi} mfs := make([]func(float64) float64, len(numbers)) for i := range mfs { mfs[i] = multiplier(numbers[i], inverses[i]) } for _, mf := range mfs { fmt.Println(mf(1)) } } func multiplier(n1, n2 float64) func(float64) float64 { n1n2 := n1 * n2 return func(m float64) float64 { return n1n2 * m } }
IDLE 2.6.1 >>> >>> x,xi, y,yi = 2.0,0.5, 4.0,0.25 >>> >>> z = x + y >>> zi = 1.0 / (x + y) >>> >>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m) >>> >>> numlist = [x, y, z] >>> numlisti = [xi, yi, zi] >>> >>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)] [0.5, 0.5, 0.5] >>>
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "strings" ) func main() { level := ` ####### # # # # #. # # #. $$ # #.$$ # #.# @# #######` fmt.Printf("level:%s\n", level) fmt.Printf("solution:\n%s\n", solve(level)) } func solve(board string) string { buffer = make([]byte, len(board)) width := strings.Index(board[1:], "\n") + 1 dirs := []struct { move, push string dPos int }{ {"u", "U", -width}, {"r", "R", 1}, {"d", "D", width}, {"l", "L", -1}, } visited := map[string]bool{board: true} open := []state{state{board, "", strings.Index(board, "@")}} for len(open) > 0 { s1 := &open[0] open = open[1:] for _, dir := range dirs { var newBoard, newSol string newPos := s1.pos + dir.dPos switch s1.board[newPos] { case '$', '*': newBoard = s1.push(dir.dPos) if newBoard == "" || visited[newBoard] { continue } newSol = s1.cSol + dir.push if strings.IndexAny(newBoard, ".+") < 0 { return newSol } case ' ', '.': newBoard = s1.move(dir.dPos) if visited[newBoard] { continue } newSol = s1.cSol + dir.move default: continue } open = append(open, state{newBoard, newSol, newPos}) visited[newBoard] = true } } return "No solution" } type state struct { board string cSol string pos int } var buffer []byte func (s *state) move(dPos int) string { copy(buffer, s.board) if buffer[s.pos] == '@' { buffer[s.pos] = ' ' } else { buffer[s.pos] = '.' } newPos := s.pos + dPos if buffer[newPos] == ' ' { buffer[newPos] = '@' } else { buffer[newPos] = '+' } return string(buffer) } func (s *state) push(dPos int) string { newPos := s.pos + dPos boxPos := newPos + dPos switch s.board[boxPos] { case ' ', '.': default: return "" } copy(buffer, s.board) if buffer[s.pos] == '@' { buffer[s.pos] = ' ' } else { buffer[s.pos] = '.' } if buffer[newPos] == '$' { buffer[newPos] = '@' } else { buffer[newPos] = '+' } if buffer[boxPos] == ' ' { buffer[boxPos] = '$' } else { buffer[boxPos] = '*' } return string(buffer) }
from array import array from collections import deque import psyco data = [] nrows = 0 px = py = 0 sdata = "" ddata = "" def init(board): global data, nrows, sdata, ddata, px, py data = filter(None, board.splitlines()) nrows = max(len(r) for r in data) maps = {' ':' ', '.': '.', '@':' ', ' mapd = {' ':' ', '.': ' ', '@':'@', ' for r, row in enumerate(data): for c, ch in enumerate(row): sdata += maps[ch] ddata += mapd[ch] if ch == '@': px = c py = r def push(x, y, dx, dy, data): if sdata[(y+2*dy) * nrows + x+2*dx] == ' data[(y+2*dy) * nrows + x+2*dx] != ' ': return None data2 = array("c", data) data2[y * nrows + x] = ' ' data2[(y+dy) * nrows + x+dx] = '@' data2[(y+2*dy) * nrows + x+2*dx] = '*' return data2.tostring() def is_solved(data): for i in xrange(len(data)): if (sdata[i] == '.') != (data[i] == '*'): return False return True def solve(): open = deque([(ddata, "", px, py)]) visited = set([ddata]) dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'), (0, 1, 'd', 'D'), (-1, 0, 'l', 'L')) lnrows = nrows while open: cur, csol, x, y = open.popleft() for di in dirs: temp = cur dx, dy = di[0], di[1] if temp[(y+dy) * lnrows + x+dx] == '*': temp = push(x, y, dx, dy, temp) if temp and temp not in visited: if is_solved(temp): return csol + di[3] open.append((temp, csol + di[3], x+dx, y+dy)) visited.add(temp) else: if sdata[(y+dy) * lnrows + x+dx] == ' temp[(y+dy) * lnrows + x+dx] != ' ': continue data2 = array("c", temp) data2[y * lnrows + x] = ' ' data2[(y+dy) * lnrows + x+dx] = '@' temp = data2.tostring() if temp not in visited: if is_solved(temp): return csol + di[2] open.append((temp, csol + di[2], x+dx, y+dy)) visited.add(temp) return "No solution" level = """\ psyco.full() init(level) print level, "\n\n", solve()
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "fmt" "math/big" "strings" ) func factorial(n int64) *big.Int { var z big.Int return z.MulRange(1, n) } var one = big.NewInt(1) var three = big.NewInt(3) var six = big.NewInt(6) var ten = big.NewInt(10) var seventy = big.NewInt(70) func almkvistGiullera(n int64, print bool) *big.Rat { t1 := big.NewInt(32) t1.Mul(factorial(6*n), t1) t2 := big.NewInt(532*n*n + 126*n + 9) t3 := new(big.Int) t3.Exp(factorial(n), six, nil) t3.Mul(t3, three) ip := new(big.Int) ip.Mul(t1, t2) ip.Quo(ip, t3) pw := 6*n + 3 t1.SetInt64(pw) tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil)) if print { fmt.Printf("%d %44d %3d  %-35s\n", n, ip, -pw, tm.FloatString(33)) } return tm } func main() { fmt.Println("N Integer Portion Pow Nth Term (33 dp)") fmt.Println(strings.Repeat("-", 89)) for n := int64(0); n < 10; n++ { almkvistGiullera(n, true) } sum := new(big.Rat) prev := new(big.Rat) pow70 := new(big.Int).Exp(ten, seventy, nil) prec := new(big.Rat).SetFrac(one, pow70) n := int64(0) for { term := almkvistGiullera(n, false) sum.Add(sum, term) z := new(big.Rat).Sub(sum, prev) z.Abs(z) if z.Cmp(prec) < 0 { break } prev.Set(sum) n++ } sum.Inv(sum) pi := new(big.Float).SetPrec(256).SetRat(sum) pi.Sqrt(pi) fmt.Println("\nPi to 70 decimal places is:") fmt.Println(pi.Text('f', 70)) }
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "math/big" "strings" ) func factorial(n int64) *big.Int { var z big.Int return z.MulRange(1, n) } var one = big.NewInt(1) var three = big.NewInt(3) var six = big.NewInt(6) var ten = big.NewInt(10) var seventy = big.NewInt(70) func almkvistGiullera(n int64, print bool) *big.Rat { t1 := big.NewInt(32) t1.Mul(factorial(6*n), t1) t2 := big.NewInt(532*n*n + 126*n + 9) t3 := new(big.Int) t3.Exp(factorial(n), six, nil) t3.Mul(t3, three) ip := new(big.Int) ip.Mul(t1, t2) ip.Quo(ip, t3) pw := 6*n + 3 t1.SetInt64(pw) tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil)) if print { fmt.Printf("%d %44d %3d  %-35s\n", n, ip, -pw, tm.FloatString(33)) } return tm } func main() { fmt.Println("N Integer Portion Pow Nth Term (33 dp)") fmt.Println(strings.Repeat("-", 89)) for n := int64(0); n < 10; n++ { almkvistGiullera(n, true) } sum := new(big.Rat) prev := new(big.Rat) pow70 := new(big.Int).Exp(ten, seventy, nil) prec := new(big.Rat).SetFrac(one, pow70) n := int64(0) for { term := almkvistGiullera(n, false) sum.Add(sum, term) z := new(big.Rat).Sub(sum, prev) z.Abs(z) if z.Cmp(prec) < 0 { break } prev.Set(sum) n++ } sum.Inv(sum) pi := new(big.Float).SetPrec(256).SetRat(sum) pi.Sqrt(pi) fmt.Println("\nPi to 70 decimal places is:") fmt.Println(pi.Text('f', 70)) }
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "math/big" "strings" ) func factorial(n int64) *big.Int { var z big.Int return z.MulRange(1, n) } var one = big.NewInt(1) var three = big.NewInt(3) var six = big.NewInt(6) var ten = big.NewInt(10) var seventy = big.NewInt(70) func almkvistGiullera(n int64, print bool) *big.Rat { t1 := big.NewInt(32) t1.Mul(factorial(6*n), t1) t2 := big.NewInt(532*n*n + 126*n + 9) t3 := new(big.Int) t3.Exp(factorial(n), six, nil) t3.Mul(t3, three) ip := new(big.Int) ip.Mul(t1, t2) ip.Quo(ip, t3) pw := 6*n + 3 t1.SetInt64(pw) tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil)) if print { fmt.Printf("%d %44d %3d  %-35s\n", n, ip, -pw, tm.FloatString(33)) } return tm } func main() { fmt.Println("N Integer Portion Pow Nth Term (33 dp)") fmt.Println(strings.Repeat("-", 89)) for n := int64(0); n < 10; n++ { almkvistGiullera(n, true) } sum := new(big.Rat) prev := new(big.Rat) pow70 := new(big.Int).Exp(ten, seventy, nil) prec := new(big.Rat).SetFrac(one, pow70) n := int64(0) for { term := almkvistGiullera(n, false) sum.Add(sum, term) z := new(big.Rat).Sub(sum, prev) z.Abs(z) if z.Cmp(prec) < 0 { break } prev.Set(sum) n++ } sum.Inv(sum) pi := new(big.Float).SetPrec(256).SetRat(sum) pi.Sqrt(pi) fmt.Println("\nPi to 70 decimal places is:") fmt.Println(pi.Text('f', 70)) }
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "rcu" ) func powerset(set []int) [][]int { if len(set) == 0 { return [][]int{{}} } head := set[0] tail := set[1:] p1 := powerset(tail) var p2 [][]int for _, s := range powerset(tail) { h := []int{head} h = append(h, s...) p2 = append(p2, h) } return append(p1, p2...) } func isPractical(n int) bool { if n == 1 { return true } divs := rcu.ProperDivisors(n) subsets := powerset(divs) found := make([]bool, n) count := 0 for _, subset := range subsets { sum := rcu.SumInts(subset) if sum > 0 && sum < n && !found[sum] { found[sum] = true count++ if count == n-1 { return true } } } return false } func main() { fmt.Println("In the range 1..333, there are:") var practical []int for i := 1; i <= 333; i++ { if isPractical(i) { practical = append(practical, i) } } fmt.Println(" ", len(practical), "practical numbers") fmt.Println(" The first ten are", practical[0:10]) fmt.Println(" The final ten are", practical[len(practical)-10:]) fmt.Println("\n666 is practical:", isPractical(666)) }
from itertools import chain, cycle, accumulate, combinations from typing import List, Tuple def factors5(n: int) -> List[int]: def prime_powers(n): for c in accumulate(chain([2, 1, 2], cycle([2,4]))): if c*c > n: break if n%c: continue d,p = (), c while not n%c: n,p,d = n//c, p*c, d + (p,) yield(d) if n > 1: yield((n,)) r = [1] for e in prime_powers(n): r += [a*b for a in r for b in e] return r[:-1] def powerset(s: List[int]) -> List[Tuple[int, ...]]: return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1)) def is_practical(x: int) -> bool: if x == 1: return True if x %2: return False f = factors5(x) ps = powerset(f) found = {y for y in {sum(i) for i in ps} if 1 <= y < x} return len(found) == x - 1 if __name__ == '__main__': n = 333 p = [x for x in range(1, n + 1) if is_practical(x)] print(f"There are {len(p)} Practical numbers from 1 to {n}:") print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1]) x = 666 print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "rcu" ) const LIMIT = 999999 var primes = rcu.Primes(LIMIT) func longestSeq(dir string) { pd := 0 longSeqs := [][]int{{2}} currSeq := []int{2} for i := 1; i < len(primes); i++ { d := primes[i] - primes[i-1] if (dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd) { if len(currSeq) > len(longSeqs[0]) { longSeqs = [][]int{currSeq} } else if len(currSeq) == len(longSeqs[0]) { longSeqs = append(longSeqs, currSeq) } currSeq = []int{primes[i-1], primes[i]} } else { currSeq = append(currSeq, primes[i]) } pd = d } if len(currSeq) > len(longSeqs[0]) { longSeqs = [][]int{currSeq} } else if len(currSeq) == len(longSeqs[0]) { longSeqs = append(longSeqs, currSeq) } fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":") for _, ls := range longSeqs { var diffs []int for i := 1; i < len(ls); i++ { diffs = append(diffs, ls[i]-ls[i-1]) } for i := 0; i < len(ls)-1; i++ { fmt.Print(ls[i], " (", diffs[i], ") ") } fmt.Println(ls[len(ls)-1]) } fmt.Println() } func main() { fmt.Println("For primes < 1 million:\n") for _, dir := range []string{"ascending", "descending"} { longestSeq(dir) } }
from sympy import sieve primelist = list(sieve.primerange(2,1000000)) listlen = len(primelist) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff > old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff < old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list)
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "sort" "strconv" "strings" ) var example1 = []string{ "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00", } var example2 = []string{ "00,00,00,00,00,00,00,00,00", "00,11,12,15,18,21,62,61,00", "00,06,00,00,00,00,00,60,00", "00,33,00,00,00,00,00,57,00", "00,32,00,00,00,00,00,56,00", "00,37,00,01,00,00,00,73,00", "00,38,00,00,00,00,00,72,00", "00,43,44,47,48,51,76,77,00", "00,00,00,00,00,00,00,00,00", } var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}} var ( grid [][]int clues []int totalToFill = 0 ) func solve(r, c, count, nextClue int) bool { if count > totalToFill { return true } back := grid[r][c] if back != 0 && back != count { return false } if back == 0 && nextClue < len(clues) && clues[nextClue] == count { return false } if back == count { nextClue++ } grid[r][c] = count for _, move := range moves { if solve(r+move[1], c+move[0], count+1, nextClue) { return true } } grid[r][c] = back return false } func printResult(n int) { fmt.Println("Solution for example", n, "\b:") for _, row := range grid { for _, i := range row { if i == -1 { continue } fmt.Printf("%2d ", i) } fmt.Println() } } func main() { for n, board := range [2][]string{example1, example2} { nRows := len(board) + 2 nCols := len(strings.Split(board[0], ",")) + 2 startRow, startCol := 0, 0 grid = make([][]int, nRows) totalToFill = (nRows - 2) * (nCols - 2) var lst []int for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } if r >= 1 && r < nRows-1 { row := strings.Split(board[r-1], ",") for c := 1; c < nCols-1; c++ { val, _ := strconv.Atoi(row[c-1]) if val > 0 { lst = append(lst, val) } if val == 1 { startRow, startCol = r, c } grid[r][c] = val } } } sort.Ints(lst) clues = lst if solve(startRow, startCol, 1, 0) { printResult(n + 1) } } }
from sys import stdout neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: return a, b return -1, -1 def find_solution(pa, x, y, z): if z > lastNumber: return 1 if exists[z] == 1: s = find_next(pa, x, y, z) if s[0] < 0: return 0 return find_solution(pa, s[0], s[1], z + 1) for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == 0: pa[a][b] = z r = find_solution(pa, a, b, z + 1) if r == 1: return 1 pa[a][b] = 0 return 0 def solve(pz, w, h): global lastNumber, wid, hei, exists lastNumber = w * h wid = w hei = h exists = [0 for j in range(lastNumber + 1)] pa = [[0 for j in range(h)] for i in range(w)] st = pz.split() idx = 0 for j in range(h): for i in range(w): if st[idx] == ".": idx += 1 else: pa[i][j] = int(st[idx]) exists[pa[i][j]] = 1 idx += 1 x = 0 y = 0 t = w * h + 1 for j in range(h): for i in range(w): if pa[i][j] != 0 and pa[i][j] < t: t = pa[i][j] x = i y = j return find_solution(pa, x, y, t + 1), pa def show_result(r): if r[0] == 1: for j in range(hei): for i in range(wid): stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No Solution!\n") print() r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17" " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9) show_result(r) r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37" " . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9) show_result(r) r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55" " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9) show_result(r)
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "sort" "strconv" "strings" ) var example1 = []string{ "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00,11,00,00,64,00", "00,00,24,21,00,01,02,00,00", "00,00,00,00,00,00,00,00,00", } var example2 = []string{ "00,00,00,00,00,00,00,00,00", "00,11,12,15,18,21,62,61,00", "00,06,00,00,00,00,00,60,00", "00,33,00,00,00,00,00,57,00", "00,32,00,00,00,00,00,56,00", "00,37,00,01,00,00,00,73,00", "00,38,00,00,00,00,00,72,00", "00,43,44,47,48,51,76,77,00", "00,00,00,00,00,00,00,00,00", } var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}} var ( grid [][]int clues []int totalToFill = 0 ) func solve(r, c, count, nextClue int) bool { if count > totalToFill { return true } back := grid[r][c] if back != 0 && back != count { return false } if back == 0 && nextClue < len(clues) && clues[nextClue] == count { return false } if back == count { nextClue++ } grid[r][c] = count for _, move := range moves { if solve(r+move[1], c+move[0], count+1, nextClue) { return true } } grid[r][c] = back return false } func printResult(n int) { fmt.Println("Solution for example", n, "\b:") for _, row := range grid { for _, i := range row { if i == -1 { continue } fmt.Printf("%2d ", i) } fmt.Println() } } func main() { for n, board := range [2][]string{example1, example2} { nRows := len(board) + 2 nCols := len(strings.Split(board[0], ",")) + 2 startRow, startCol := 0, 0 grid = make([][]int, nRows) totalToFill = (nRows - 2) * (nCols - 2) var lst []int for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } if r >= 1 && r < nRows-1 { row := strings.Split(board[r-1], ",") for c := 1; c < nCols-1; c++ { val, _ := strconv.Atoi(row[c-1]) if val > 0 { lst = append(lst, val) } if val == 1 { startRow, startCol = r, c } grid[r][c] = val } } } sort.Ints(lst) clues = lst if solve(startRow, startCol, 1, 0) { printResult(n + 1) } } }
from sys import stdout neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: return a, b return -1, -1 def find_solution(pa, x, y, z): if z > lastNumber: return 1 if exists[z] == 1: s = find_next(pa, x, y, z) if s[0] < 0: return 0 return find_solution(pa, s[0], s[1], z + 1) for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == 0: pa[a][b] = z r = find_solution(pa, a, b, z + 1) if r == 1: return 1 pa[a][b] = 0 return 0 def solve(pz, w, h): global lastNumber, wid, hei, exists lastNumber = w * h wid = w hei = h exists = [0 for j in range(lastNumber + 1)] pa = [[0 for j in range(h)] for i in range(w)] st = pz.split() idx = 0 for j in range(h): for i in range(w): if st[idx] == ".": idx += 1 else: pa[i][j] = int(st[idx]) exists[pa[i][j]] = 1 idx += 1 x = 0 y = 0 t = w * h + 1 for j in range(h): for i in range(w): if pa[i][j] != 0 and pa[i][j] < t: t = pa[i][j] x = i y = j return find_solution(pa, x, y, t + 1), pa def show_result(r): if r[0] == 1: for j in range(hei): for i in range(wid): stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No Solution!\n") print() r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17" " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9) show_result(r) r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37" " . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9) show_result(r) r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55" " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9) show_result(r)
Translate the given Go code snippet into Python without altering its behavior.
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) def churchExp(m): return lambda n: n(m) def churchFromInt(n): return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) ) def churchFromInt_(n): if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1)) def intFromChurch(cn): return cn(succ)(0) def main(): 'Tests' cThree = churchFromInt(3) cFour = churchFromInt(4) print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ]))) def compose(f): return lambda g: lambda x: g(f(x)) def foldl(f): def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs) def identity(x): return x def replicate(n): return lambda x: repeat(x, n) def succ(x): return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) ) if __name__ == '__main__': main()
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) def churchExp(m): return lambda n: n(m) def churchFromInt(n): return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) ) def churchFromInt_(n): if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1)) def intFromChurch(cn): return cn(succ)(0) def main(): 'Tests' cThree = churchFromInt(3) cFour = churchFromInt(4) print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ]))) def compose(f): return lambda g: lambda x: g(f(x)) def foldl(f): def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs) def identity(x): return x def replicate(n): return lambda x: repeat(x, n) def succ(x): return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) ) if __name__ == '__main__': main()
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c, count int) bool { if count > totalToFill { return true } nbrs := neighbors(r, c) if len(nbrs) == 0 && count != totalToFill { return false } sort.Slice(nbrs, func(i, j int) bool { return nbrs[i][2] < nbrs[j][2] }) for _, nb := range nbrs { r = nb[0] c = nb[1] grid[r][c] = count if solve(r, c, count+1) { return true } grid[r][c] = 0 } return false } func neighbors(r, c int) (nbrs [][3]int) { for _, m := range moves { x := m[0] y := m[1] if grid[r+y][c+x] == 0 { num := countNeighbors(r+y, c+x) - 1 nbrs = append(nbrs, [3]int{r + y, c + x, num}) } } return } func countNeighbors(r, c int) int { num := 0 for _, m := range moves { if grid[r+m[1]][c+m[0]] == 0 { num++ } } return num } func printResult() { for _, row := range grid { for _, i := range row { if i == -1 { fmt.Print(" ") } else { fmt.Printf("%2d ", i) } } fmt.Println() } } func main() { nRows := len(board) + 6 nCols := len(board[0]) + 6 grid = make([][]int, nRows) for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } for c := 3; c < nCols-3; c++ { if r >= 3 && r < nRows-3 { if board[r-3][c-3] == '0' { grid[r][c] = 0 totalToFill++ } } } } pos, r, c := -1, 0, 0 for { for { pos++ r = pos / nCols c = pos % nCols if grid[r][c] != -1 { break } } grid[r][c] = 1 if solve(r, c, 2) { break } grid[r][c] = 0 if pos >= nRows*nCols { break } } printResult() }
from sys import stdout neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighbours[i][0] b = y + neighbours[i][1] if is_valid(a, b) and pa[a][b] == 0: pa[a][b] = v r = iterate(pa, a, b, v + 1) if r == 1: return r pa[a][b] = 0 return 0 def solve(pz, w, h): global cnt, pWid, pHei pa = [[-1 for j in range(h)] for i in range(w)] f = 0 pWid = w pHei = h for j in range(h): for i in range(w): if pz[f] == "1": pa[i][j] = 0 cnt += 1 f += 1 for y in range(h): for x in range(w): if pa[x][y] == 0: pa[x][y] = 1 if 1 == iterate(pa, x, y, 2): return 1, pa pa[x][y] = 0 return 0, pa r = solve("011011011111111111111011111000111000001000", 7, 6) if r[0] == 1: for j in range(6): for i in range(7): if r[1][i][j] == -1: stdout.write(" ") else: stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No solution!")
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c, count int) bool { if count > totalToFill { return true } nbrs := neighbors(r, c) if len(nbrs) == 0 && count != totalToFill { return false } sort.Slice(nbrs, func(i, j int) bool { return nbrs[i][2] < nbrs[j][2] }) for _, nb := range nbrs { r = nb[0] c = nb[1] grid[r][c] = count if solve(r, c, count+1) { return true } grid[r][c] = 0 } return false } func neighbors(r, c int) (nbrs [][3]int) { for _, m := range moves { x := m[0] y := m[1] if grid[r+y][c+x] == 0 { num := countNeighbors(r+y, c+x) - 1 nbrs = append(nbrs, [3]int{r + y, c + x, num}) } } return } func countNeighbors(r, c int) int { num := 0 for _, m := range moves { if grid[r+m[1]][c+m[0]] == 0 { num++ } } return num } func printResult() { for _, row := range grid { for _, i := range row { if i == -1 { fmt.Print(" ") } else { fmt.Printf("%2d ", i) } } fmt.Println() } } func main() { nRows := len(board) + 6 nCols := len(board[0]) + 6 grid = make([][]int, nRows) for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } for c := 3; c < nCols-3; c++ { if r >= 3 && r < nRows-3 { if board[r-3][c-3] == '0' { grid[r][c] = 0 totalToFill++ } } } } pos, r, c := -1, 0, 0 for { for { pos++ r = pos / nCols c = pos % nCols if grid[r][c] != -1 { break } } grid[r][c] = 1 if solve(r, c, 2) { break } grid[r][c] = 0 if pos >= nRows*nCols { break } } printResult() }
from sys import stdout neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighbours[i][0] b = y + neighbours[i][1] if is_valid(a, b) and pa[a][b] == 0: pa[a][b] = v r = iterate(pa, a, b, v + 1) if r == 1: return r pa[a][b] = 0 return 0 def solve(pz, w, h): global cnt, pWid, pHei pa = [[-1 for j in range(h)] for i in range(w)] f = 0 pWid = w pHei = h for j in range(h): for i in range(w): if pz[f] == "1": pa[i][j] = 0 cnt += 1 f += 1 for y in range(h): for x in range(w): if pa[x][y] == 0: pa[x][y] = 1 if 1 == iterate(pa, x, y, 2): return 1, pa pa[x][y] = 0 return 0, pa r = solve("011011011111111111111011111000111000001000", 7, 6) if r[0] == 1: for j in range(6): for i in range(7): if r[1][i][j] == -1: stdout.write(" ") else: stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No solution!")
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c, count int) bool { if count > totalToFill { return true } nbrs := neighbors(r, c) if len(nbrs) == 0 && count != totalToFill { return false } sort.Slice(nbrs, func(i, j int) bool { return nbrs[i][2] < nbrs[j][2] }) for _, nb := range nbrs { r = nb[0] c = nb[1] grid[r][c] = count if solve(r, c, count+1) { return true } grid[r][c] = 0 } return false } func neighbors(r, c int) (nbrs [][3]int) { for _, m := range moves { x := m[0] y := m[1] if grid[r+y][c+x] == 0 { num := countNeighbors(r+y, c+x) - 1 nbrs = append(nbrs, [3]int{r + y, c + x, num}) } } return } func countNeighbors(r, c int) int { num := 0 for _, m := range moves { if grid[r+m[1]][c+m[0]] == 0 { num++ } } return num } func printResult() { for _, row := range grid { for _, i := range row { if i == -1 { fmt.Print(" ") } else { fmt.Printf("%2d ", i) } } fmt.Println() } } func main() { nRows := len(board) + 6 nCols := len(board[0]) + 6 grid = make([][]int, nRows) for r := 0; r < nRows; r++ { grid[r] = make([]int, nCols) for c := 0; c < nCols; c++ { grid[r][c] = -1 } for c := 3; c < nCols-3; c++ { if r >= 3 && r < nRows-3 { if board[r-3][c-3] == '0' { grid[r][c] = 0 totalToFill++ } } } } pos, r, c := -1, 0, 0 for { for { pos++ r = pos / nCols c = pos % nCols if grid[r][c] != -1 { break } } grid[r][c] = 1 if solve(r, c, 2) { break } grid[r][c] = 0 if pos >= nRows*nCols { break } } printResult() }
from sys import stdout neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighbours[i][0] b = y + neighbours[i][1] if is_valid(a, b) and pa[a][b] == 0: pa[a][b] = v r = iterate(pa, a, b, v + 1) if r == 1: return r pa[a][b] = 0 return 0 def solve(pz, w, h): global cnt, pWid, pHei pa = [[-1 for j in range(h)] for i in range(w)] f = 0 pWid = w pHei = h for j in range(h): for i in range(w): if pz[f] == "1": pa[i][j] = 0 cnt += 1 f += 1 for y in range(h): for x in range(w): if pa[x][y] == 0: pa[x][y] = 1 if 1 == iterate(pa, x, y, 2): return 1, pa pa[x][y] = 0 return 0, pa r = solve("011011011111111111111011111000111000001000", 7, 6) if r[0] == 1: for j in range(6): for i in range(7): if r[1][i][j] == -1: stdout.write(" ") else: stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No solution!")
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "strings" ) type BitSet []bool func (bs BitSet) and(other BitSet) { for i := range bs { if bs[i] && other[i] { bs[i] = true } else { bs[i] = false } } } func (bs BitSet) or(other BitSet) { for i := range bs { if bs[i] || other[i] { bs[i] = true } else { bs[i] = false } } } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func newPuzzle(data [2]string) { rowData := strings.Fields(data[0]) colData := strings.Fields(data[1]) rows := getCandidates(rowData, len(colData)) cols := getCandidates(colData, len(rowData)) for { numChanged := reduceMutual(cols, rows) if numChanged == -1 { fmt.Println("No solution") return } if numChanged == 0 { break } } for _, row := range rows { for i := 0; i < len(cols); i++ { fmt.Printf(iff(row[0][i], "# ", ". ")) } fmt.Println() } fmt.Println() } func getCandidates(data []string, le int) [][]BitSet { var result [][]BitSet for _, s := range data { var lst []BitSet a := []byte(s) sumBytes := 0 for _, b := range a { sumBytes += int(b - 'A' + 1) } prep := make([]string, len(a)) for i, b := range a { prep[i] = strings.Repeat("1", int(b-'A'+1)) } for _, r := range genSequence(prep, le-sumBytes+1) { bits := []byte(r[1:]) bitset := make(BitSet, len(bits)) for i, b := range bits { bitset[i] = b == '1' } lst = append(lst, bitset) } result = append(result, lst) } return result } func genSequence(ones []string, numZeros int) []string { le := len(ones) if le == 0 { return []string{strings.Repeat("0", numZeros)} } var result []string for x := 1; x < numZeros-le+2; x++ { skipOne := ones[1:] for _, tail := range genSequence(skipOne, numZeros-x) { result = append(result, strings.Repeat("0", x)+ones[0]+tail) } } return result } func reduceMutual(cols, rows [][]BitSet) int { countRemoved1 := reduce(cols, rows) if countRemoved1 == -1 { return -1 } countRemoved2 := reduce(rows, cols) if countRemoved2 == -1 { return -1 } return countRemoved1 + countRemoved2 } func reduce(a, b [][]BitSet) int { countRemoved := 0 for i := 0; i < len(a); i++ { commonOn := make(BitSet, len(b)) for j := 0; j < len(b); j++ { commonOn[j] = true } commonOff := make(BitSet, len(b)) for _, candidate := range a[i] { commonOn.and(candidate) commonOff.or(candidate) } for j := 0; j < len(b); j++ { fi, fj := i, j for k := len(b[j]) - 1; k >= 0; k-- { cnd := b[j][k] if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) { lb := len(b[j]) copy(b[j][k:], b[j][k+1:]) b[j][lb-1] = nil b[j] = b[j][:lb-1] countRemoved++ } } if len(b[j]) == 0 { return -1 } } } return countRemoved } func main() { p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"} p2 := [2]string{ "F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA", } p3 := [2]string{ "CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " + "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " + "AAAAD BDG CEF CBDB BBB FC", } p4 := [2]string{ "E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " + "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM", } for _, puzzleData := range [][2]string{p1, p2, p3, p4} { newPuzzle(puzzleData) } }
from itertools import izip def gen_row(w, s): def gen_seg(o, sp): if not o: return [[2] * sp] return [[2] * x + o[0] + tail for x in xrange(1, sp - len(o) + 2) for tail in gen_seg(o[1:], sp - x)] return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))] def deduce(hr, vr): def allowable(row): return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row) def fits(a, b): return all(x & y for x, y in izip(a, b)) def fix_col(n): c = [x[n] for x in can_do] cols[n] = [x for x in cols[n] if fits(x, c)] for i, x in enumerate(allowable(cols[n])): if x != can_do[i][n]: mod_rows.add(i) can_do[i][n] &= x def fix_row(n): c = can_do[n] rows[n] = [x for x in rows[n] if fits(x, c)] for i, x in enumerate(allowable(rows[n])): if x != can_do[n][i]: mod_cols.add(i) can_do[n][i] &= x def show_gram(m): for x in m: print " ".join("x print w, h = len(vr), len(hr) rows = [gen_row(w, x) for x in hr] cols = [gen_row(h, x) for x in vr] can_do = map(allowable, rows) mod_rows, mod_cols = set(), set(xrange(w)) while mod_cols: for i in mod_cols: fix_col(i) mod_cols = set() for i in mod_rows: fix_row(i) mod_rows = set() if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)): print "Solution would be unique" else: print "Solution may not be unique, doing exhaustive search:" out = [0] * h def try_all(n = 0): if n >= h: for j in xrange(w): if [x[j] for x in out] not in cols[j]: return 0 show_gram(out) return 1 sol = 0 for x in rows[n]: out[n] = x sol += try_all(n + 1) return sol n = try_all() if not n: print "No solution." elif n == 1: print "Unique solution." else: print n, "solutions." print def solve(p, show_runs=True): s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()] for l in p.splitlines()] if show_runs: print "Horizontal runs:", s[0] print "Vertical runs:", s[1] deduce(s[0], s[1]) def main(): fn = "nonogram_problems.txt" for p in (x for x in open(fn).read().split("\n\n") if x): solve(p) print "Extra example not solvable by deduction alone:" solve("B B A A\nB B A A") print "Extra example where there is no solution:" solve("B A A\nA A A") main()
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "strings" ) type BitSet []bool func (bs BitSet) and(other BitSet) { for i := range bs { if bs[i] && other[i] { bs[i] = true } else { bs[i] = false } } } func (bs BitSet) or(other BitSet) { for i := range bs { if bs[i] || other[i] { bs[i] = true } else { bs[i] = false } } } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func newPuzzle(data [2]string) { rowData := strings.Fields(data[0]) colData := strings.Fields(data[1]) rows := getCandidates(rowData, len(colData)) cols := getCandidates(colData, len(rowData)) for { numChanged := reduceMutual(cols, rows) if numChanged == -1 { fmt.Println("No solution") return } if numChanged == 0 { break } } for _, row := range rows { for i := 0; i < len(cols); i++ { fmt.Printf(iff(row[0][i], "# ", ". ")) } fmt.Println() } fmt.Println() } func getCandidates(data []string, le int) [][]BitSet { var result [][]BitSet for _, s := range data { var lst []BitSet a := []byte(s) sumBytes := 0 for _, b := range a { sumBytes += int(b - 'A' + 1) } prep := make([]string, len(a)) for i, b := range a { prep[i] = strings.Repeat("1", int(b-'A'+1)) } for _, r := range genSequence(prep, le-sumBytes+1) { bits := []byte(r[1:]) bitset := make(BitSet, len(bits)) for i, b := range bits { bitset[i] = b == '1' } lst = append(lst, bitset) } result = append(result, lst) } return result } func genSequence(ones []string, numZeros int) []string { le := len(ones) if le == 0 { return []string{strings.Repeat("0", numZeros)} } var result []string for x := 1; x < numZeros-le+2; x++ { skipOne := ones[1:] for _, tail := range genSequence(skipOne, numZeros-x) { result = append(result, strings.Repeat("0", x)+ones[0]+tail) } } return result } func reduceMutual(cols, rows [][]BitSet) int { countRemoved1 := reduce(cols, rows) if countRemoved1 == -1 { return -1 } countRemoved2 := reduce(rows, cols) if countRemoved2 == -1 { return -1 } return countRemoved1 + countRemoved2 } func reduce(a, b [][]BitSet) int { countRemoved := 0 for i := 0; i < len(a); i++ { commonOn := make(BitSet, len(b)) for j := 0; j < len(b); j++ { commonOn[j] = true } commonOff := make(BitSet, len(b)) for _, candidate := range a[i] { commonOn.and(candidate) commonOff.or(candidate) } for j := 0; j < len(b); j++ { fi, fj := i, j for k := len(b[j]) - 1; k >= 0; k-- { cnd := b[j][k] if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) { lb := len(b[j]) copy(b[j][k:], b[j][k+1:]) b[j][lb-1] = nil b[j] = b[j][:lb-1] countRemoved++ } } if len(b[j]) == 0 { return -1 } } } return countRemoved } func main() { p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"} p2 := [2]string{ "F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA", } p3 := [2]string{ "CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " + "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " + "AAAAD BDG CEF CBDB BBB FC", } p4 := [2]string{ "E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " + "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM", } for _, puzzleData := range [][2]string{p1, p2, p3, p4} { newPuzzle(puzzleData) } }
from itertools import izip def gen_row(w, s): def gen_seg(o, sp): if not o: return [[2] * sp] return [[2] * x + o[0] + tail for x in xrange(1, sp - len(o) + 2) for tail in gen_seg(o[1:], sp - x)] return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))] def deduce(hr, vr): def allowable(row): return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row) def fits(a, b): return all(x & y for x, y in izip(a, b)) def fix_col(n): c = [x[n] for x in can_do] cols[n] = [x for x in cols[n] if fits(x, c)] for i, x in enumerate(allowable(cols[n])): if x != can_do[i][n]: mod_rows.add(i) can_do[i][n] &= x def fix_row(n): c = can_do[n] rows[n] = [x for x in rows[n] if fits(x, c)] for i, x in enumerate(allowable(rows[n])): if x != can_do[n][i]: mod_cols.add(i) can_do[n][i] &= x def show_gram(m): for x in m: print " ".join("x print w, h = len(vr), len(hr) rows = [gen_row(w, x) for x in hr] cols = [gen_row(h, x) for x in vr] can_do = map(allowable, rows) mod_rows, mod_cols = set(), set(xrange(w)) while mod_cols: for i in mod_cols: fix_col(i) mod_cols = set() for i in mod_rows: fix_row(i) mod_rows = set() if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)): print "Solution would be unique" else: print "Solution may not be unique, doing exhaustive search:" out = [0] * h def try_all(n = 0): if n >= h: for j in xrange(w): if [x[j] for x in out] not in cols[j]: return 0 show_gram(out) return 1 sol = 0 for x in rows[n]: out[n] = x sol += try_all(n + 1) return sol n = try_all() if not n: print "No solution." elif n == 1: print "Unique solution." else: print n, "solutions." print def solve(p, show_runs=True): s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()] for l in p.splitlines()] if show_runs: print "Horizontal runs:", s[0] print "Vertical runs:", s[1] deduce(s[0], s[1]) def main(): fn = "nonogram_problems.txt" for p in (x for x in open(fn).read().split("\n\n") if x): solve(p) print "Extra example not solvable by deduction alone:" solve("B B A A\nB B A A") print "Extra example where there is no solution:" solve("B A A\nA A A") main()
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "bufio" "fmt" "log" "math/rand" "os" "regexp" "strings" "time" ) var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}} const ( nRows = 10 nCols = nRows gridSize = nRows * nCols minWords = 25 ) var ( re1 = regexp.MustCompile(fmt.Sprintf("^[a-z]{3,%d}$", nRows)) re2 = regexp.MustCompile("[^A-Z]") ) type grid struct { numAttempts int cells [nRows][nCols]byte solutions []string } func check(err error) { if err != nil { log.Fatal(err) } } func readWords(fileName string) []string { file, err := os.Open(fileName) check(err) defer file.Close() var words []string scanner := bufio.NewScanner(file) for scanner.Scan() { word := strings.ToLower(strings.TrimSpace(scanner.Text())) if re1.MatchString(word) { words = append(words, word) } } check(scanner.Err()) return words } func createWordSearch(words []string) *grid { var gr *grid outer: for i := 1; i < 100; i++ { gr = new(grid) messageLen := gr.placeMessage("Rosetta Code") target := gridSize - messageLen cellsFilled := 0 rand.Shuffle(len(words), func(i, j int) { words[i], words[j] = words[j], words[i] }) for _, word := range words { cellsFilled += gr.tryPlaceWord(word) if cellsFilled == target { if len(gr.solutions) >= minWords { gr.numAttempts = i break outer } else { break } } } } return gr } func (gr *grid) placeMessage(msg string) int { msg = strings.ToUpper(msg) msg = re2.ReplaceAllLiteralString(msg, "") messageLen := len(msg) if messageLen > 0 && messageLen < gridSize { gapSize := gridSize / messageLen for i := 0; i < messageLen; i++ { pos := i*gapSize + rand.Intn(gapSize) gr.cells[pos/nCols][pos%nCols] = msg[i] } return messageLen } return 0 } func (gr *grid) tryPlaceWord(word string) int { randDir := rand.Intn(len(dirs)) randPos := rand.Intn(gridSize) for dir := 0; dir < len(dirs); dir++ { dir = (dir + randDir) % len(dirs) for pos := 0; pos < gridSize; pos++ { pos = (pos + randPos) % gridSize lettersPlaced := gr.tryLocation(word, dir, pos) if lettersPlaced > 0 { return lettersPlaced } } } return 0 } func (gr *grid) tryLocation(word string, dir, pos int) int { r := pos / nCols c := pos % nCols le := len(word) if (dirs[dir][0] == 1 && (le+c) > nCols) || (dirs[dir][0] == -1 && (le-1) > c) || (dirs[dir][1] == 1 && (le+r) > nRows) || (dirs[dir][1] == -1 && (le-1) > r) { return 0 } overlaps := 0 rr := r cc := c for i := 0; i < le; i++ { if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] { return 0 } cc += dirs[dir][0] rr += dirs[dir][1] } rr = r cc = c for i := 0; i < le; i++ { if gr.cells[rr][cc] == word[i] { overlaps++ } else { gr.cells[rr][cc] = word[i] } if i < le-1 { cc += dirs[dir][0] rr += dirs[dir][1] } } lettersPlaced := le - overlaps if lettersPlaced > 0 { sol := fmt.Sprintf("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr) gr.solutions = append(gr.solutions, sol) } return lettersPlaced } func printResult(gr *grid) { if gr.numAttempts == 0 { fmt.Println("No grid to display") return } size := len(gr.solutions) fmt.Println("Attempts:", gr.numAttempts) fmt.Println("Number of words:", size) fmt.Println("\n 0 1 2 3 4 5 6 7 8 9") for r := 0; r < nRows; r++ { fmt.Printf("\n%d ", r) for c := 0; c < nCols; c++ { fmt.Printf(" %c ", gr.cells[r][c]) } } fmt.Println("\n") for i := 0; i < size-1; i += 2 { fmt.Printf("%s %s\n", gr.solutions[i], gr.solutions[i+1]) } if size%2 == 1 { fmt.Println(gr.solutions[size-1]) } } func main() { rand.Seed(time.Now().UnixNano()) unixDictPath := "/usr/share/dict/words" printResult(createWordSearch(readWords(unixDictPath))) }
import re from random import shuffle, randint dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]] n_rows = 10 n_cols = 10 grid_size = n_rows * n_cols min_words = 25 class Grid: def __init__(self): self.num_attempts = 0 self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)] self.solutions = [] def read_words(filename): max_len = max(n_rows, n_cols) words = [] with open(filename, "r") as file: for line in file: s = line.strip().lower() if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None: words.append(s) return words def place_message(grid, msg): msg = re.sub(r'[^A-Z]', "", msg.upper()) message_len = len(msg) if 0 < message_len < grid_size: gap_size = grid_size // message_len for i in range(0, message_len): pos = i * gap_size + randint(0, gap_size) grid.cells[pos // n_cols][pos % n_cols] = msg[i] return message_len return 0 def try_location(grid, word, direction, pos): r = pos // n_cols c = pos % n_cols length = len(word) if (dirs[direction][0] == 1 and (length + c) > n_cols) or \ (dirs[direction][0] == -1 and (length - 1) > c) or \ (dirs[direction][1] == 1 and (length + r) > n_rows) or \ (dirs[direction][1] == -1 and (length - 1) > r): return 0 rr = r cc = c i = 0 overlaps = 0 while i < length: if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]: return 0 cc += dirs[direction][0] rr += dirs[direction][1] i += 1 rr = r cc = c i = 0 while i < length: if grid.cells[rr][cc] == word[i]: overlaps += 1 else: grid.cells[rr][cc] = word[i] if i < length - 1: cc += dirs[direction][0] rr += dirs[direction][1] i += 1 letters_placed = length - overlaps if letters_placed > 0: grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr)) return letters_placed def try_place_word(grid, word): rand_dir = randint(0, len(dirs)) rand_pos = randint(0, grid_size) for direction in range(0, len(dirs)): direction = (direction + rand_dir) % len(dirs) for pos in range(0, grid_size): pos = (pos + rand_pos) % grid_size letters_placed = try_location(grid, word, direction, pos) if letters_placed > 0: return letters_placed return 0 def create_word_search(words): grid = None num_attempts = 0 while num_attempts < 100: num_attempts += 1 shuffle(words) grid = Grid() message_len = place_message(grid, "Rosetta Code") target = grid_size - message_len cells_filled = 0 for word in words: cells_filled += try_place_word(grid, word) if cells_filled == target: if len(grid.solutions) >= min_words: grid.num_attempts = num_attempts return grid else: break return grid def print_result(grid): if grid is None or grid.num_attempts == 0: print("No grid to display") return size = len(grid.solutions) print("Attempts: {0}".format(grid.num_attempts)) print("Number of words: {0}".format(size)) print("\n 0 1 2 3 4 5 6 7 8 9\n") for r in range(0, n_rows): print("{0} ".format(r), end='') for c in range(0, n_cols): print(" %c " % grid.cells[r][c], end='') print() print() for i in range(0, size - 1, 2): print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1])) if size % 2 == 1: print(grid.solutions[size - 1]) if __name__ == "__main__": print_result(create_word_search(read_words("unixdict.txt")))
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v := reflect.ValueOf(any) v = v.Elem() fmt.Println(" v:", v, "=", v.Interface()) t := v.Type() fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") for i := 0; i < v.NumField(); i++ { f := v.Field(i) fmt.Printf(" %2d: %-10s %-4s %t\n", i, t.Field(i).Name, f.Type(), f.CanSet()) } v.Field(0).SetInt(16) vp := v.Field(1).Addr() up := unsafe.Pointer(vp.Pointer()) p := (*int)(up) fmt.Printf(" vp has type %-14T = %v\n", vp, vp) fmt.Printf(" up has type %-14T = %#0x\n", up, up) fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) *p = 43 *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ } func anotherExample() { r := bufio.NewReader(os.Stdin) errp := (*error)(unsafe.Pointer( reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) *errp = errors.New("unsafely injected error value into bufio inner workings") _, err := r.ReadByte() fmt.Println("bufio.ReadByte returned error:", err) }
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v := reflect.ValueOf(any) v = v.Elem() fmt.Println(" v:", v, "=", v.Interface()) t := v.Type() fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") for i := 0; i < v.NumField(); i++ { f := v.Field(i) fmt.Printf(" %2d: %-10s %-4s %t\n", i, t.Field(i).Name, f.Type(), f.CanSet()) } v.Field(0).SetInt(16) vp := v.Field(1).Addr() up := unsafe.Pointer(vp.Pointer()) p := (*int)(up) fmt.Printf(" vp has type %-14T = %v\n", vp, vp) fmt.Printf(" up has type %-14T = %#0x\n", up, up) fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) *p = 43 *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ } func anotherExample() { r := bufio.NewReader(os.Stdin) errp := (*error)(unsafe.Pointer( reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) *errp = errors.New("unsafely injected error value into bufio inner workings") _, err := r.ReadByte() fmt.Println("bufio.ReadByte returned error:", err) }
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "encoding/gob" "fmt" "os" ) type printable interface { print() } func main() { animals := []printable{ &Animal{Alive: true}, &Cat{}, &Lab{ Dog: Dog{Animal: Animal{Alive: true}}, Color: "yellow", }, &Collie{Dog: Dog{ Animal: Animal{Alive: true}, ObedienceTrained: true, }}, } fmt.Println("created:") for _, a := range animals { a.print() } f, err := os.Create("objects.dat") if err != nil { fmt.Println(err) return } for _, a := range animals { gob.Register(a) } err = gob.NewEncoder(f).Encode(animals) if err != nil { fmt.Println(err) return } f.Close() f, err = os.Open("objects.dat") if err != nil { fmt.Println(err) return } var clones []printable gob.NewDecoder(f).Decode(&clones) if err != nil { fmt.Println(err) return } fmt.Println("\nloaded from objects.dat:") for _, c := range clones { c.print() } } type Animal struct { Alive bool } func (a *Animal) print() { if a.Alive { fmt.Println(" live animal, unspecified type") } else { fmt.Println(" dead animal, unspecified type") } } type Dog struct { Animal ObedienceTrained bool } func (d *Dog) print() { switch { case !d.Alive: fmt.Println(" dead dog") case d.ObedienceTrained: fmt.Println(" trained dog") default: fmt.Println(" dog, not trained") } } type Cat struct { Animal LitterBoxTrained bool } func (c *Cat) print() { switch { case !c.Alive: fmt.Println(" dead cat") case c.LitterBoxTrained: fmt.Println(" litter box trained cat") default: fmt.Println(" cat, not litter box trained") } } type Lab struct { Dog Color string } func (l *Lab) print() { var r string if l.Color == "" { r = "lab, color unspecified" } else { r = l.Color + " lab" } switch { case !l.Alive: fmt.Println(" dead", r) case l.ObedienceTrained: fmt.Println(" trained", r) default: fmt.Printf(" %s, not trained\n", r) } } type Collie struct { Dog CatchesFrisbee bool } func (c *Collie) print() { switch { case !c.Alive: fmt.Println(" dead collie") case c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" trained collie, catches frisbee") case c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" trained collie, but doesn't catch frisbee") case !c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" collie, not trained, but catches frisbee") case !c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" collie, not trained, doesn't catch frisbee") } }
import pickle class Entity: def __init__(self): self.name = "Entity" def printName(self): print self.name class Person(Entity): def __init__(self): self.name = "Cletus" instance1 = Person() instance1.printName() instance2 = Entity() instance2.printName() target = file("objects.dat", "w") pickle.dump((instance1, instance2), target) target.close() print "Serialized..." target = file("objects.dat") i1, i2 = pickle.load(target) print "Unserialized..." i1.printName() i2.printName()
Translate this program into Python but keep the logic exactly as in Go.
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {length: 0, suffix: oddRoot, edges: edges{}}, oddRoot: {length: -1, suffix: oddRoot, edges: edges{}}, } suffix := oddRoot var n, k int for i, c := range s { for n = suffix; ; n = tree[n].suffix { k = tree[n].length if b := i - k - 1; b >= 0 && s[b] == c { break } } if e, ok := tree[n].edges[c]; ok { suffix = e continue } suffix = len(tree) tree = append(tree, node{length: k + 2, edges: edges{}}) tree[n].edges[c] = suffix if tree[suffix].length == 1 { tree[suffix].suffix = 0 continue } for { n = tree[n].suffix if b := i - tree[n].length - 1; b >= 0 && s[b] == c { break } } tree[suffix].suffix = tree[n].edges[c] } return tree } func subPalindromes(tree []node) (s []string) { var children func(int, string) children = func(n int, p string) { for c, n := range tree[n].edges { c := string(c) p := c + p + c s = append(s, p) children(n, p) } } children(0, "") for c, n := range tree[1].edges { c := string(c) s = append(s, c) children(n, c) } return }
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)
Write a version of this Go function in Python with identical behavior.
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {length: 0, suffix: oddRoot, edges: edges{}}, oddRoot: {length: -1, suffix: oddRoot, edges: edges{}}, } suffix := oddRoot var n, k int for i, c := range s { for n = suffix; ; n = tree[n].suffix { k = tree[n].length if b := i - k - 1; b >= 0 && s[b] == c { break } } if e, ok := tree[n].edges[c]; ok { suffix = e continue } suffix = len(tree) tree = append(tree, node{length: k + 2, edges: edges{}}) tree[n].edges[c] = suffix if tree[suffix].length == 1 { tree[suffix].suffix = 0 continue } for { n = tree[n].suffix if b := i - tree[n].length - 1; b >= 0 && s[b] == c { break } } tree[suffix].suffix = tree[n].edges[c] } return tree } func subPalindromes(tree []node) (s []string) { var children func(int, string) children = func(n int, p string) { for c, n := range tree[n].edges { c := string(c) p := c + p + c s = append(s, p) children(n, p) } } children(0, "") for c, n := range tree[1].edges { c := string(c) s = append(s, c) children(n, c) } return }
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "time" ) func main() { centuries := []string{"20th", "21st", "22nd"} starts := []int{1900, 2000, 2100} for i := 0; i < len(centuries); i++ { var longYears []int fmt.Printf("\nLong years in the %s century:\n", centuries[i]) for j := starts[i]; j < starts[i] + 100; j++ { t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC) if _, week := t.ISOWeek(); week == 53 { longYears = append(longYears, j) } } fmt.Println(longYears) } }
from datetime import date def longYear(y): return 52 < date(y, 12, 28).isocalendar()[1] def main(): for year in [ x for x in range(2000, 1 + 2100) if longYear(x) ]: print(year) if __name__ == '__main__': main()
Change the following Go code into Python without altering its purpose.
package main import "fmt" func getDivisors(n int) []int { divs := []int{1, n} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs = append(divs, j) } } } return divs } func sum(divs []int) int { sum := 0 for _, div := range divs { sum += div } return sum } func isPartSum(divs []int, sum int) bool { if sum == 0 { return true } le := len(divs) if le == 0 { return false } last := divs[le-1] divs = divs[0 : le-1] if last > sum { return isPartSum(divs, sum) } return isPartSum(divs, sum) || isPartSum(divs, sum-last) } func isZumkeller(n int) bool { divs := getDivisors(n) sum := sum(divs) if sum%2 == 1 { return false } if n%2 == 1 { abundance := sum - 2*n return abundance > 0 && abundance%2 == 0 } return isPartSum(divs, sum/2) } func main() { fmt.Println("The first 220 Zumkeller numbers are:") for i, count := 2, 0; count < 220; i++ { if isZumkeller(i) { fmt.Printf("%3d ", i) count++ if count%20 == 0 { fmt.Println() } } } fmt.Println("\nThe first 40 odd Zumkeller numbers are:") for i, count := 3, 0; count < 40; i += 2 { if isZumkeller(i) { fmt.Printf("%5d ", i) count++ if count%10 == 0 { fmt.Println() } } } fmt.Println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:") for i, count := 3, 0; count < 40; i += 2 { if (i % 10 != 5) && isZumkeller(i) { fmt.Printf("%7d ", i) count++ if count%8 == 0 { fmt.Println() } } } fmt.Println() }
from sympy import divisors from sympy.combinatorics.subsets import Subset def isZumkeller(n): d = divisors(n) s = sum(d) if not s % 2 and max(d) <= s/2: for x in range(1, 2**len(d)): if sum(Subset.unrank_binary(x, d).subset) == s/2: return True return False def printZumkellers(N, oddonly=False): nprinted = 0 for n in range(1, 10**5): if (oddonly == False or n % 2) and isZumkeller(n): print(f'{n:>8}', end='') nprinted += 1 if nprinted % 10 == 0: print() if nprinted >= N: return print("220 Zumkeller numbers:") printZumkellers(220) print("\n\n40 odd Zumkeller numbers:") printZumkellers(40, True)
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
Please provide an equivalent version of this Go code in Python.
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "math/big" ) var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"} func lucas(b int64) { fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b) fmt.Print("First 15 elements: ") var x0, x1 int64 = 1, 1 fmt.Printf("%d, %d", x0, x1) for i := 1; i <= 13; i++ { x2 := b*x1 + x0 fmt.Printf(", %d", x2) x0, x1 = x1, x2 } fmt.Println() } func metallic(b int64, dp int) { x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b) ratio := big.NewRat(1, 1) iters := 0 prev := ratio.FloatString(dp) for { iters++ x2.Mul(bb, x1) x2.Add(x2, x0) this := ratio.SetFrac(x2, x1).FloatString(dp) if prev == this { plural := "s" if iters == 1 { plural = " " } fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this) return } prev = this x0.Set(x1) x1.Set(x2) } } func main() { for b := int64(0); b < 10; b++ { lucas(b) metallic(b, 32) } fmt.Println("Golden ratio, where b = 1:") metallic(1, 256) }
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext().prec = prec last = 0 for i,x in zip(count(), to_decimal(b)): if x == last: print(f'after {i} iterations:\n\t{x}') break last = x for b in range(4): coefs = [n for _,n in islice(metallic_ratio(b), 15)] print(f'\nb = {b}: {coefs}') stable(b, 32) print(f'\nb = 1 with 256 digits:') stable(1, 256)
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "math/big" ) var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"} func lucas(b int64) { fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b) fmt.Print("First 15 elements: ") var x0, x1 int64 = 1, 1 fmt.Printf("%d, %d", x0, x1) for i := 1; i <= 13; i++ { x2 := b*x1 + x0 fmt.Printf(", %d", x2) x0, x1 = x1, x2 } fmt.Println() } func metallic(b int64, dp int) { x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b) ratio := big.NewRat(1, 1) iters := 0 prev := ratio.FloatString(dp) for { iters++ x2.Mul(bb, x1) x2.Add(x2, x0) this := ratio.SetFrac(x2, x1).FloatString(dp) if prev == this { plural := "s" if iters == 1 { plural = " " } fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this) return } prev = this x0.Set(x1) x1.Set(x2) } } func main() { for b := int64(0); b < 10; b++ { lucas(b) metallic(b, 32) } fmt.Println("Golden ratio, where b = 1:") metallic(1, 256) }
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext().prec = prec last = 0 for i,x in zip(count(), to_decimal(b)): if x == last: print(f'after {i} iterations:\n\t{x}') break last = x for b in range(4): coefs = [n for _,n in islice(metallic_ratio(b), 15)] print(f'\nb = {b}: {coefs}') stable(b, 32) print(f'\nb = 1 with 256 digits:') stable(1, 256)
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "bufio" "flag" "fmt" "io" "log" "math/rand" "os" "strings" "time" "unicode" "unicode/utf8" ) func main() { log.SetFlags(0) log.SetPrefix("markov: ") input := flag.String("in", "alice_oz.txt", "input file") n := flag.Int("n", 2, "number of words to use as prefix") runs := flag.Int("runs", 1, "number of runs to generate") wordsPerRun := flag.Int("words", 300, "number of words per run") startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix") stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMarkovFromFile(*input, *n) if err != nil { log.Fatal(err) } for i := 0; i < *runs; i++ { err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence) if err != nil { log.Fatal(err) } fmt.Println() } } type Markov struct { n int capitalized int suffix map[string][]string } func NewMarkovFromFile(filename string, n int) (*Markov, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() return NewMarkov(f, n) } func NewMarkov(r io.Reader, n int) (*Markov, error) { m := &Markov{ n: n, suffix: make(map[string][]string), } sc := bufio.NewScanner(r) sc.Split(bufio.ScanWords) window := make([]string, 0, n) for sc.Scan() { word := sc.Text() if len(window) > 0 { prefix := strings.Join(window, " ") m.suffix[prefix] = append(m.suffix[prefix], word) if isCapitalized(prefix) { m.capitalized++ } } window = appendMax(n, window, word) } if err := sc.Err(); err != nil { return nil, err } return m, nil } func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error { bw := bufio.NewWriter(w) var i int if startCapital { i = rand.Intn(m.capitalized) } else { i = rand.Intn(len(m.suffix)) } var prefix string for prefix = range m.suffix { if startCapital && !isCapitalized(prefix) { continue } if i == 0 { break } i-- } bw.WriteString(prefix) prefixWords := strings.Fields(prefix) n -= len(prefixWords) for { suffixChoices := m.suffix[prefix] if len(suffixChoices) == 0 { break } i = rand.Intn(len(suffixChoices)) suffix := suffixChoices[i] bw.WriteByte(' ') if _, err := bw.WriteString(suffix); err != nil { break } n-- if n < 0 && (!stopSentence || isSentenceEnd(suffix)) { break } prefixWords = appendMax(m.n, prefixWords, suffix) prefix = strings.Join(prefixWords, " ") } return bw.Flush() } func isCapitalized(s string) bool { r, _ := utf8.DecodeRuneInString(s) return unicode.IsUpper(r) } func isSentenceEnd(s string) bool { r, _ := utf8.DecodeLastRuneInString(s) return r == '.' || r == '?' || r == '!' } func appendMax(max int, slice []string, value string) []string { if len(slice)+1 > max { n := copy(slice, slice[1:]) slice = slice[:n] } return append(slice, value) }
import random, sys def makerule(data, context): rule = {} words = data.split(' ') index = context for word in words[index:]: key = ' '.join(words[index-context:index]) if key in rule: rule[key].append(word) else: rule[key] = [word] index += 1 return rule def makestring(rule, length): oldwords = random.choice(list(rule.keys())).split(' ') string = ' '.join(oldwords) + ' ' for i in range(length): try: key = ' '.join(oldwords) newword = random.choice(rule[key]) string += newword + ' ' for word in range(len(oldwords)): oldwords[word] = oldwords[(word + 1) % len(oldwords)] oldwords[-1] = newword except KeyError: return string return string if __name__ == '__main__': with open(sys.argv[1], encoding='utf8') as f: data = f.read() rule = makerule(data, int(sys.argv[2])) string = makestring(rule, int(sys.argv[3])) print(string)
Write the same code in Python as shown below in Go.
package main import ( "container/heap" "fmt" ) type PriorityQueue struct { items []Vertex m map[Vertex]int pr map[Vertex]int } func (pq *PriorityQueue) Len() int { return len(pq.items) } func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] } func (pq *PriorityQueue) Swap(i, j int) { pq.items[i], pq.items[j] = pq.items[j], pq.items[i] pq.m[pq.items[i]] = i pq.m[pq.items[j]] = j } func (pq *PriorityQueue) Push(x interface{}) { n := len(pq.items) item := x.(Vertex) pq.m[item] = n pq.items = append(pq.items, item) } func (pq *PriorityQueue) Pop() interface{} { old := pq.items n := len(old) item := old[n-1] pq.m[item] = -1 pq.items = old[0 : n-1] return item } func (pq *PriorityQueue) update(item Vertex, priority int) { pq.pr[item] = priority heap.Fix(pq, pq.m[item]) } func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) { heap.Push(pq, item) pq.update(item, priority) } const ( Infinity = int(^uint(0) >> 1) Uninitialized = -1 ) func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) { vs := g.Vertices() dist = make(map[Vertex]int, len(vs)) prev = make(map[Vertex]Vertex, len(vs)) sid := source dist[sid] = 0 q := &PriorityQueue{ items: make([]Vertex, 0, len(vs)), m: make(map[Vertex]int, len(vs)), pr: make(map[Vertex]int, len(vs)), } for _, v := range vs { if v != sid { dist[v] = Infinity } prev[v] = Uninitialized q.addWithPriority(v, dist[v]) } for len(q.items) != 0 { u := heap.Pop(q).(Vertex) for _, v := range g.Neighbors(u) { alt := dist[u] + g.Weight(u, v) if alt < dist[v] { dist[v] = alt prev[v] = u q.update(v, alt) } } } return dist, prev } type Graph interface { Vertices() []Vertex Neighbors(v Vertex) []Vertex Weight(u, v Vertex) int } type Vertex int type sg struct { ids map[string]Vertex names map[Vertex]string edges map[Vertex]map[Vertex]int } func newsg(ids map[string]Vertex) sg { g := sg{ids: ids} g.names = make(map[Vertex]string, len(ids)) for k, v := range ids { g.names[v] = k } g.edges = make(map[Vertex]map[Vertex]int) return g } func (g sg) edge(u, v string, w int) { if _, ok := g.edges[g.ids[u]]; !ok { g.edges[g.ids[u]] = make(map[Vertex]int) } g.edges[g.ids[u]][g.ids[v]] = w } func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) { s = g.names[v] for prev[v] >= 0 { v = prev[v] s = g.names[v] + s } return s } func (g sg) Vertices() []Vertex { vs := make([]Vertex, 0, len(g.ids)) for _, v := range g.ids { vs = append(vs, v) } return vs } func (g sg) Neighbors(u Vertex) []Vertex { vs := make([]Vertex, 0, len(g.edges[u])) for v := range g.edges[u] { vs = append(vs, v) } return vs } func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] } func main() { g := newsg(map[string]Vertex{ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, }) g.edge("a", "b", 7) g.edge("a", "c", 9) g.edge("a", "f", 14) g.edge("b", "c", 10) g.edge("b", "d", 15) g.edge("c", "d", 11) g.edge("c", "f", 2) g.edge("d", "e", 6) g.edge("e", "f", 9) dist, prev := Dijkstra(g, g.ids["a"]) fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev)) fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev)) }
from collections import namedtuple, deque from pprint import pprint as pp inf = float('inf') Edge = namedtuple('Edge', ['start', 'end', 'cost']) class Graph(): def __init__(self, edges): self.edges = [Edge(*edge) for edge in edges] self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges} def dijkstra(self, source, dest): assert source in self.vertices dist = {vertex: inf for vertex in self.vertices} previous = {vertex: None for vertex in self.vertices} dist[source] = 0 q = self.vertices.copy() neighbours = {vertex: set() for vertex in self.vertices} for start, end, cost in self.edges: neighbours[start].add((end, cost)) neighbours[end].add((start, cost)) while q: u = min(q, key=lambda vertex: dist[vertex]) q.remove(u) if dist[u] == inf or u == dest: break for v, cost in neighbours[u]: alt = dist[u] + cost if alt < dist[v]: dist[v] = alt previous[v] = u s, u = deque(), dest while previous[u]: s.appendleft(u) u = previous[u] s.appendleft(u) return s graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10), ("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6), ("e", "f", 9)]) pp(graph.dijkstra("a", "e"))
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/rand" "time" ) type vector []float64 func e(n uint) vector { if n > 4 { panic("n must be less than 5") } result := make(vector, 32) result[1<<n] = 1.0 return result } func cdot(a, b vector) vector { return mul(vector{0.5}, add(mul(a, b), mul(b, a))) } func neg(x vector) vector { return mul(vector{-1}, x) } func bitCount(i int) int { i = i - ((i >> 1) & 0x55555555) i = (i & 0x33333333) + ((i >> 2) & 0x33333333) i = (i + (i >> 4)) & 0x0F0F0F0F i = i + (i >> 8) i = i + (i >> 16) return i & 0x0000003F } func reorderingSign(i, j int) float64 { i >>= 1 sum := 0 for i != 0 { sum += bitCount(i & j) i >>= 1 } cond := (sum & 1) == 0 if cond { return 1.0 } return -1.0 } func add(a, b vector) vector { result := make(vector, 32) copy(result, a) for i, _ := range b { result[i] += b[i] } return result } func mul(a, b vector) vector { result := make(vector, 32) for i, _ := range a { if a[i] != 0 { for j, _ := range b { if b[j] != 0 { s := reorderingSign(i, j) * a[i] * b[j] k := i ^ j result[k] += s } } } } return result } func randomVector() vector { result := make(vector, 32) for i := uint(0); i < 5; i++ { result = add(result, mul(vector{rand.Float64()}, e(i))) } return result } func randomMultiVector() vector { result := make(vector, 32) for i := 0; i < 32; i++ { result[i] = rand.Float64() } return result } func main() { rand.Seed(time.Now().UnixNano()) for i := uint(0); i < 5; i++ { for j := uint(0); j < 5; j++ { if i < j { if cdot(e(i), e(j))[0] != 0 { fmt.Println("Unexpected non-null scalar product.") return } } else if i == j { if cdot(e(i), e(j))[0] == 0 { fmt.Println("Unexpected null scalar product.") } } } } a := randomMultiVector() b := randomMultiVector() c := randomMultiVector() x := randomVector() fmt.Println(mul(mul(a, b), c)) fmt.Println(mul(a, mul(b, c))) fmt.Println(mul(a, add(b, c))) fmt.Println(add(mul(a, b), mul(a, c))) fmt.Println(mul(add(a, b), c)) fmt.Println(add(mul(a, c), mul(b, c))) fmt.Println(mul(x, x)) }
import copy, random def bitcount(n): return bin(n).count("1") def reoderingSign(i, j): k = i >> 1 sum = 0 while k != 0: sum += bitcount(k & j) k = k >> 1 return 1.0 if ((sum & 1) == 0) else -1.0 class Vector: def __init__(self, da): self.dims = da def dot(self, other): return (self * other + other * self) * 0.5 def __getitem__(self, i): return self.dims[i] def __setitem__(self, i, v): self.dims[i] = v def __neg__(self): return self * -1.0 def __add__(self, other): result = copy.copy(other.dims) for i in xrange(0, len(self.dims)): result[i] += self.dims[i] return Vector(result) def __mul__(self, other): if isinstance(other, Vector): result = [0.0] * 32 for i in xrange(0, len(self.dims)): if self.dims[i] != 0.0: for j in xrange(0, len(self.dims)): if other.dims[j] != 0.0: s = reoderingSign(i, j) * self.dims[i] * other.dims[j] k = i ^ j result[k] += s return Vector(result) else: result = copy.copy(self.dims) for i in xrange(0, len(self.dims)): self.dims[i] *= other return Vector(result) def __str__(self): return str(self.dims) def e(n): assert n <= 4, "n must be less than 5" result = Vector([0.0] * 32) result[1 << n] = 1.0 return result def randomVector(): result = Vector([0.0] * 32) for i in xrange(0, 5): result += Vector([random.uniform(0, 1)]) * e(i) return result def randomMultiVector(): result = Vector([0.0] * 32) for i in xrange(0, 32): result[i] = random.uniform(0, 1) return result def main(): for i in xrange(0, 5): for j in xrange(0, 5): if i < j: if e(i).dot(e(j))[0] != 0.0: print "Unexpected non-null scalar product" return elif i == j: if e(i).dot(e(j))[0] == 0.0: print "Unexpected non-null scalar product" a = randomMultiVector() b = randomMultiVector() c = randomMultiVector() x = randomVector() print (a * b) * c print a * (b * c) print print a * (b + c) print a * b + a * c print print (a + b) * c print a * c + b * c print print x * x main()
Generate an equivalent Python version of this Go code.
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree { n := 0 for i := 0; i < len(suf); { b := suf[i] ch := t[n].ch var x2, n2 int for ; ; x2++ { if x2 == len(ch) { n2 = len(t) t = append(t, node{sub: suf[i:]}) t[n].ch = append(t[n].ch, n2) return t } n2 = ch[x2] if t[n2].sub[0] == b { break } } sub2 := t[n2].sub j := 0 for ; j < len(sub2); j++ { if suf[i+j] != sub2[j] { n3 := n2 n2 = len(t) t = append(t, node{sub2[:j], []int{n3}}) t[n3].sub = sub2[j:] t[n].ch[x2] = n2 break } } i += j n = n2 } return t } func vis(t tree) { if len(t) == 0 { fmt.Println("<empty>") return } var f func(int, string) f = func(n int, pre string) { children := t[n].ch if len(children) == 0 { fmt.Println("╴", t[n].sub) return } fmt.Println("┐", t[n].sub) last := len(children) - 1 for _, ch := range children[:last] { fmt.Print(pre, "├─") f(ch, pre+"│ ") } fmt.Print(pre, "└─") f(children[last], pre+" ") } f(0, "") }
class Node: def __init__(self, sub="", children=None): self.sub = sub self.ch = children or [] class SuffixTree: def __init__(self, str): self.nodes = [Node()] for i in range(len(str)): self.addSuffix(str[i:]) def addSuffix(self, suf): n = 0 i = 0 while i < len(suf): b = suf[i] x2 = 0 while True: children = self.nodes[n].ch if x2 == len(children): n2 = len(self.nodes) self.nodes.append(Node(suf[i:], [])) self.nodes[n].ch.append(n2) return n2 = children[x2] if self.nodes[n2].sub[0] == b: break x2 = x2 + 1 sub2 = self.nodes[n2].sub j = 0 while j < len(sub2): if suf[i + j] != sub2[j]: n3 = n2 n2 = len(self.nodes) self.nodes.append(Node(sub2[:j], [n3])) self.nodes[n3].sub = sub2[j:] self.nodes[n].ch[x2] = n2 break j = j + 1 i = i + j n = n2 def visualize(self): if len(self.nodes) == 0: print "<empty>" return def f(n, pre): children = self.nodes[n].ch if len(children) == 0: print "--", self.nodes[n].sub return print "+-", self.nodes[n].sub for c in children[:-1]: print pre, "+-", f(c, pre + " | ") print pre, "+-", f(children[-1], pre + " ") f(0, "") SuffixTree("banana$").visualize()
Port the provided Go code into Python while preserving the original functionality.
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree { n := 0 for i := 0; i < len(suf); { b := suf[i] ch := t[n].ch var x2, n2 int for ; ; x2++ { if x2 == len(ch) { n2 = len(t) t = append(t, node{sub: suf[i:]}) t[n].ch = append(t[n].ch, n2) return t } n2 = ch[x2] if t[n2].sub[0] == b { break } } sub2 := t[n2].sub j := 0 for ; j < len(sub2); j++ { if suf[i+j] != sub2[j] { n3 := n2 n2 = len(t) t = append(t, node{sub2[:j], []int{n3}}) t[n3].sub = sub2[j:] t[n].ch[x2] = n2 break } } i += j n = n2 } return t } func vis(t tree) { if len(t) == 0 { fmt.Println("<empty>") return } var f func(int, string) f = func(n int, pre string) { children := t[n].ch if len(children) == 0 { fmt.Println("╴", t[n].sub) return } fmt.Println("┐", t[n].sub) last := len(children) - 1 for _, ch := range children[:last] { fmt.Print(pre, "├─") f(ch, pre+"│ ") } fmt.Print(pre, "└─") f(children[last], pre+" ") } f(0, "") }
class Node: def __init__(self, sub="", children=None): self.sub = sub self.ch = children or [] class SuffixTree: def __init__(self, str): self.nodes = [Node()] for i in range(len(str)): self.addSuffix(str[i:]) def addSuffix(self, suf): n = 0 i = 0 while i < len(suf): b = suf[i] x2 = 0 while True: children = self.nodes[n].ch if x2 == len(children): n2 = len(self.nodes) self.nodes.append(Node(suf[i:], [])) self.nodes[n].ch.append(n2) return n2 = children[x2] if self.nodes[n2].sub[0] == b: break x2 = x2 + 1 sub2 = self.nodes[n2].sub j = 0 while j < len(sub2): if suf[i + j] != sub2[j]: n3 = n2 n2 = len(self.nodes) self.nodes.append(Node(sub2[:j], [n3])) self.nodes[n3].sub = sub2[j:] self.nodes[n].ch[x2] = n2 break j = j + 1 i = i + j n = n2 def visualize(self): if len(self.nodes) == 0: print "<empty>" return def f(n, pre): children = self.nodes[n].ch if len(children) == 0: print "--", self.nodes[n].sub return print "+-", self.nodes[n].sub for c in children[:-1]: print pre, "+-", f(c, pre + " | ") print pre, "+-", f(children[-1], pre + " ") f(0, "") SuffixTree("banana$").visualize()
Convert this Go block to Python, preserving its control flow and logic.
myMap := map[string]int { "hello": 13, "world": 31, "!" : 71 } for key, value := range myMap { fmt.Printf("key = %s, value = %d\n", key, value) } for key := range myMap { fmt.Printf("key = %s\n", key) } for _, value := range myMap { fmt.Printf("value = %d\n", value) }
myDict = { "hello": 13, "world": 31, "!" : 71 } for key, value in myDict.items(): print ("key = %s, value = %s" % (key, value)) for key in myDict: print ("key = %s" % key) for key in myDict.keys(): print ("key = %s" % key) for value in myDict.values(): print ("value = %s" % value)
Generate a Python translation of this Go snippet without changing its computational steps.
package main import "fmt" type TinyInt int func NewTinyInt(i int) TinyInt { if i < 1 { i = 1 } else if i > 10 { i = 10 } return TinyInt(i) } func (t1 TinyInt) Add(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) + int(t2)) } func (t1 TinyInt) Sub(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) - int(t2)) } func (t1 TinyInt) Mul(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) * int(t2)) } func (t1 TinyInt) Div(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) / int(t2)) } func (t1 TinyInt) Rem(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) % int(t2)) } func (t TinyInt) Inc() TinyInt { return t.Add(TinyInt(1)) } func (t TinyInt) Dec() TinyInt { return t.Sub(TinyInt(1)) } func main() { t1 := NewTinyInt(6) t2 := NewTinyInt(3) fmt.Println("t1 =", t1) fmt.Println("t2 =", t2) fmt.Println("t1 + t2 =", t1.Add(t2)) fmt.Println("t1 - t2 =", t1.Sub(t2)) fmt.Println("t1 * t2 =", t1.Mul(t2)) fmt.Println("t1 / t2 =", t1.Div(t2)) fmt.Println("t1 % t2 =", t1.Rem(t2)) fmt.Println("t1 + 1 =", t1.Inc()) fmt.Println("t1 - 1 =", t1.Dec()) }
>>> class num(int): def __init__(self, b): if 1 <= b <= 10: return int.__init__(self+0) else: raise ValueError,"Value %s should be >=0 and <= 10" % b >>> x = num(3) >>> x = num(11) Traceback (most recent call last): File "<pyshell x = num(11) File "<pyshell raise ValueError,"Value %s should be >=0 and <= 10" % b ValueError: Value 11 should be >=0 and <= 10 >>> x 3 >>> type(x) <class '__main__.num'> >>>
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "rcu" ) func D(n float64) float64 { if n < 0 { return -D(-n) } if n < 2 { return 0 } var f []int if n < 1e19 { f = rcu.PrimeFactors(int(n)) } else { g := int(n / 100) f = rcu.PrimeFactors(g) f = append(f, []int{2, 2, 5, 5}...) } c := len(f) if c == 1 { return 1 } if c == 2 { return float64(f[0] + f[1]) } d := n / float64(f[0]) return D(d)*float64(f[0]) + d } func main() { ad := make([]int, 200) for n := -99; n < 101; n++ { ad[n+99] = int(D(float64(n))) } rcu.PrintTable(ad, 10, 4, false) fmt.Println() pow := 1.0 for m := 1; m < 21; m++ { pow *= 10 fmt.Printf("D(10^%-2d) / 7 = %.0f\n", m, D(pow)/7) } }
from sympy.ntheory import factorint def D(n): if n < 0: return -D(-n) elif n < 2: return 0 else: fdict = factorint(n) if len(fdict) == 1 and 1 in fdict: return 1 return sum([n * e // p for p, e in fdict.items()]) for n in range(-99, 101): print('{:5}'.format(D(n)), end='\n' if n % 10 == 0 else '') print() for m in range(1, 21): print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import "fmt" func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func createSlice(nums []int, charSet string) []byte { var chars []byte for i := 0; i < len(nums); i++ { for j := 0; j < nums[i]; j++ { chars = append(chars, charSet[i]) } } return chars } func main() { var res, res2, res3 []string nums := []int{2, 1} s := createSlice(nums, "12") findPerms(s, 0, len(s), &res) fmt.Println(res) fmt.Println() nums = []int{2, 3, 1} s = createSlice(nums, "123") findPerms(s, 0, len(s), &res2) fmt.Println(res2) fmt.Println() s = createSlice(nums, "ABC") findPerms(s, 0, len(s), &res3) fmt.Println(res3) }
from itertools import permutations numList = [2,3,1] baseList = [] for i in numList: for j in range(0,i): baseList.append(i) stringDict = {'A':2,'B':3,'C':1} baseString="" for i in stringDict: for j in range(0,stringDict[i]): baseString+=i print("Permutations for " + str(baseList) + " : ") [print(i) for i in set(permutations(baseList))] print("Permutations for " + baseString + " : ") [print(i) for i in set(permutations(baseString))]
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "github.com/fogleman/gg" "math" ) type tiletype int const ( kite tiletype = iota dart ) type tile struct { tt tiletype x, y float64 angle, size float64 } var gr = (1 + math.Sqrt(5)) / 2 const theta = math.Pi / 5 func setupPrototiles(w, h int) []tile { var proto []tile for a := math.Pi/2 + theta; a < 3*math.Pi; a += 2 * theta { ww := float64(w / 2) hh := float64(h / 2) proto = append(proto, tile{kite, ww, hh, a, float64(w) / 2.5}) } return proto } func distinctTiles(tls []tile) []tile { tileset := make(map[tile]bool) for _, tl := range tls { tileset[tl] = true } distinct := make([]tile, len(tileset)) for tl, _ := range tileset { distinct = append(distinct, tl) } return distinct } func deflateTiles(tls []tile, gen int) []tile { if gen <= 0 { return tls } var next []tile for _, tl := range tls { x, y, a, size := tl.x, tl.y, tl.angle, tl.size/gr var nx, ny float64 if tl.tt == dart { next = append(next, tile{kite, x, y, a + 5*theta, size}) for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign { nx = x + math.Cos(a-4*theta*sign)*gr*tl.size ny = y - math.Sin(a-4*theta*sign)*gr*tl.size next = append(next, tile{dart, nx, ny, a - 4*theta*sign, size}) } } else { for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign { next = append(next, tile{dart, x, y, a - 4*theta*sign, size}) nx = x + math.Cos(a-theta*sign)*gr*tl.size ny = y - math.Sin(a-theta*sign)*gr*tl.size next = append(next, tile{kite, nx, ny, a + 3*theta*sign, size}) } } } tls = distinctTiles(next) return deflateTiles(tls, gen-1) } func drawTiles(dc *gg.Context, tls []tile) { dist := [2][3]float64{{gr, gr, gr}, {-gr, -1, -gr}} for _, tl := range tls { angle := tl.angle - theta dc.MoveTo(tl.x, tl.y) ord := tl.tt for i := 0; i < 3; i++ { x := tl.x + dist[ord][i]*tl.size*math.Cos(angle) y := tl.y - dist[ord][i]*tl.size*math.Sin(angle) dc.LineTo(x, y) angle += theta } dc.ClosePath() if ord == kite { dc.SetHexColor("FFA500") } else { dc.SetHexColor("FFFF00") } dc.FillPreserve() dc.SetHexColor("A9A9A9") dc.SetLineWidth(1) dc.Stroke() } } func main() { w, h := 700, 450 dc := gg.NewContext(w, h) dc.SetRGB(1, 1, 1) dc.Clear() tiles := deflateTiles(setupPrototiles(w, h), 5) drawTiles(dc, tiles) dc.SavePNG("penrose_tiling.png") }
def penrose(depth): print( <g id="A{d+1}" transform="translate(100, 0) scale(0.6180339887498949)"> <use href=" <use href=" </g> <g id="B{d+1}"> <use href=" <use href=" </g> <g id="G"> <use href=" <use href=" </g> </defs> <g transform="scale(2, 2)"> <use href=" <use href=" <use href=" <use href=" <use href=" </g> </svg>''') penrose(6)
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "math" "rcu" "sort" ) func main() { const limit = 1000000 limit2 := int(math.Cbrt(limit)) primes := rcu.Primes(limit / 6) pc := len(primes) var sphenic []int fmt.Println("Sphenic numbers less than 1,000:") for i := 0; i < pc-2; i++ { if primes[i] > limit2 { break } for j := i + 1; j < pc-1; j++ { prod := primes[i] * primes[j] if prod+primes[j+1] >= limit { break } for k := j + 1; k < pc; k++ { res := prod * primes[k] if res >= limit { break } sphenic = append(sphenic, res) } } } sort.Ints(sphenic) ix := sort.Search(len(sphenic), func(i int) bool { return sphenic[i] >= 1000 }) rcu.PrintTable(sphenic[:ix], 15, 3, false) fmt.Println("\nSphenic triplets less than 10,000:") var triplets [][3]int for i := 0; i < len(sphenic)-2; i++ { s := sphenic[i] if sphenic[i+1] == s+1 && sphenic[i+2] == s+2 { triplets = append(triplets, [3]int{s, s + 1, s + 2}) } } ix = sort.Search(len(triplets), func(i int) bool { return triplets[i][2] >= 10000 }) for i := 0; i < ix; i++ { fmt.Printf("%4d ", triplets[i]) if (i+1)%3 == 0 { fmt.Println() } } fmt.Printf("\nThere are %s sphenic numbers less than 1,000,000.\n", rcu.Commatize(len(sphenic))) fmt.Printf("There are %s sphenic triplets less than 1,000,000.\n", rcu.Commatize(len(triplets))) s := sphenic[199999] pf := rcu.PrimeFactors(s) fmt.Printf("The 200,000th sphenic number is %s (%d*%d*%d).\n", rcu.Commatize(s), pf[0], pf[1], pf[2]) fmt.Printf("The 5,000th sphenic triplet is %v.\n.", triplets[4999]) }
from sympy import factorint sphenics1m, sphenic_triplets1m = [], [] for i in range(3, 1_000_000): d = factorint(i) if len(d) == 3 and sum(d.values()) == 3: sphenics1m.append(i) if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1: sphenic_triplets1m.append(i) print('Sphenic numbers less than 1000:') for i, n in enumerate(sphenics1m): if n < 1000: print(f'{n : 5}', end='\n' if (i + 1) % 15 == 0 else '') else: break print('\n\nSphenic triplets less than 10_000:') for i, n in enumerate(sphenic_triplets1m): if n < 10_000: print(f'({n - 2} {n - 1} {n})', end='\n' if (i + 1) % 3 == 0 else ' ') else: break print('\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m), 'sphenic triplets less than 1 million.') S2HK = sphenics1m[200_000 - 1] T5K = sphenic_triplets1m[5000 - 1] print(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.') print(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')
Convert this Go snippet to Python and keep its semantics consistent.
package main import "fmt" type any = interface{} func toTree(list []int) any { s := []any{[]any{}} for _, n := range list { for n != len(s) { if n > len(s) { inner := []any{} s[len(s)-1] = append(s[len(s)-1].([]any), inner) s = append(s, inner) } else { s = s[0 : len(s)-1] } } s[len(s)-1] = append(s[len(s)-1].([]any), n) for i := len(s) - 2; i >= 0; i-- { le := len(s[i].([]any)) s[i].([]any)[le-1] = s[i+1] } } return s[0] } func main() { tests := [][]int{ {}, {1, 2, 4}, {3, 1, 3, 1}, {1, 2, 3, 1}, {3, 2, 1, 3}, {3, 3, 3, 1, 1, 3, 3, 3}, } for _, test := range tests { nest := toTree(test) fmt.Printf("%17s => %v\n", fmt.Sprintf("%v", test), nest) } }
def to_tree(x, index=0, depth=1): so_far = [] while index < len(x): this = x[index] if this == depth: so_far.append(this) elif this > depth: index, deeper = to_tree(x, index, depth + 1) so_far.append(deeper) else: index -=1 break index += 1 return (index, so_far) if depth > 1 else so_far if __name__ == "__main__": from pprint import pformat def pnest(nest:list, width: int=9) -> str: text = pformat(nest, width=width).replace('\n', '\n ') print(f" OR {text}\n") exercises = [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], [3, 3, 3, 1, 1, 3, 3, 3], ] for flat in exercises: nest = to_tree(flat) print(f"{flat} NESTS TO: {nest}") pnest(nest)
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import "fmt" type any = interface{} func toTree(list []int) any { s := []any{[]any{}} for _, n := range list { for n != len(s) { if n > len(s) { inner := []any{} s[len(s)-1] = append(s[len(s)-1].([]any), inner) s = append(s, inner) } else { s = s[0 : len(s)-1] } } s[len(s)-1] = append(s[len(s)-1].([]any), n) for i := len(s) - 2; i >= 0; i-- { le := len(s[i].([]any)) s[i].([]any)[le-1] = s[i+1] } } return s[0] } func main() { tests := [][]int{ {}, {1, 2, 4}, {3, 1, 3, 1}, {1, 2, 3, 1}, {3, 2, 1, 3}, {3, 3, 3, 1, 1, 3, 3, 3}, } for _, test := range tests { nest := toTree(test) fmt.Printf("%17s => %v\n", fmt.Sprintf("%v", test), nest) } }
def to_tree(x, index=0, depth=1): so_far = [] while index < len(x): this = x[index] if this == depth: so_far.append(this) elif this > depth: index, deeper = to_tree(x, index, depth + 1) so_far.append(deeper) else: index -=1 break index += 1 return (index, so_far) if depth > 1 else so_far if __name__ == "__main__": from pprint import pformat def pnest(nest:list, width: int=9) -> str: text = pformat(nest, width=width).replace('\n', '\n ') print(f" OR {text}\n") exercises = [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], [3, 3, 3, 1, 1, 3, 3, 3], ] for flat in exercises: nest = to_tree(flat) print(f"{flat} NESTS TO: {nest}") pnest(nest)
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "crypto/md5" "io/ioutil" "log" "os" "path/filepath" "sort" "time" ) type fileData struct { filePath string info os.FileInfo } type hash [16]byte func check(err error) { if err != nil { log.Fatal(err) } } func checksum(filePath string) hash { bytes, err := ioutil.ReadFile(filePath) check(err) return hash(md5.Sum(bytes)) } func findDuplicates(dirPath string, minSize int64) [][2]fileData { var dups [][2]fileData m := make(map[hash]fileData) werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() && info.Size() >= minSize { h := checksum(path) fd, ok := m[h] fd2 := fileData{path, info} if !ok { m[h] = fd2 } else { dups = append(dups, [2]fileData{fd, fd2}) } } return nil }) check(werr) return dups } func main() { dups := findDuplicates(".", 1) fmt.Println("The following pairs of files have the same size and the same hash:\n") fmt.Println("File name Size Date last modified") fmt.Println("==========================================================") sort.Slice(dups, func(i, j int) bool { return dups[i][0].info.Size() > dups[j][0].info.Size() }) for _, dup := range dups { for i := 0; i < 2; i++ { d := dup[i] fmt.Printf("%-20s %8d %v\n", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC)) } fmt.Println() } }
from __future__ import print_function import os import hashlib import datetime def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"): knownFiles = {} for root, dirs, files in os.walk(pth): for fina in files: fullFina = os.path.join(root, fina) isSymLink = os.path.islink(fullFina) if isSymLink: continue si = os.path.getsize(fullFina) if si < minSize: continue if si not in knownFiles: knownFiles[si] = {} h = hashlib.new(hashName) h.update(open(fullFina, "rb").read()) hashed = h.digest() if hashed in knownFiles[si]: fileRec = knownFiles[si][hashed] fileRec.append(fullFina) else: knownFiles[si][hashed] = [fullFina] sizeList = list(knownFiles.keys()) sizeList.sort(reverse=True) for si in sizeList: filesAtThisSize = knownFiles[si] for hashVal in filesAtThisSize: if len(filesAtThisSize[hashVal]) < 2: continue fullFinaLi = filesAtThisSize[hashVal] print ("=======Duplicate=======") for fullFina in fullFinaLi: st = os.stat(fullFina) isHardLink = st.st_nlink > 1 infoStr = [] if isHardLink: infoStr.append("(Hard linked)") fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ') print (fmtModTime, si, os.path.relpath(fullFina, pth), " ".join(infoStr)) if __name__=="__main__": FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math/big" ) func main() { one := big.NewInt(1) two := big.NewInt(2) next := new(big.Int) sylvester := []*big.Int{two} prod := new(big.Int).Set(two) count := 1 for count < 10 { next.Add(prod, one) sylvester = append(sylvester, new(big.Int).Set(next)) count++ prod.Mul(prod, next) } fmt.Println("The first 10 terms in the Sylvester sequence are:") for i := 0; i < 10; i++ { fmt.Println(sylvester[i]) } sumRecip := new(big.Rat) for _, s := range sylvester { sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s)) } fmt.Println("\nThe sum of their reciprocals as a rational number is:") fmt.Println(sumRecip) fmt.Println("\nThe sum of their reciprocals as a decimal number (to 211 places) is:") fmt.Println(sumRecip.FloatString(211)) }
from functools import reduce from itertools import count, islice def sylvester(): def go(n): return 1 + reduce( lambda a, x: a * go(x), range(0, n), 1 ) if 0 != n else 2 return map(go, count(0)) def main(): print("First 10 terms of OEIS A000058:") xs = list(islice(sylvester(), 10)) print('\n'.join([ str(x) for x in xs ])) print("\nSum of the reciprocals of the first 10 terms:") print( reduce(lambda a, x: a + 1 / x, xs, 0) ) if __name__ == '__main__': main()
Translate this program into Python but keep the logic exactly as in Go.
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Please provide an equivalent version of this Go code in Python.
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Write a version of this Go function in Python with identical behavior.
package main import ( "fmt" "sort" "strings" ) type indexSort struct { val sort.Interface ind []int } func (s indexSort) Len() int { return len(s.ind) } func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] } func (s indexSort) Swap(i, j int) { s.val.Swap(s.ind[i], s.ind[j]) s.ind[i], s.ind[j] = s.ind[j], s.ind[i] } func disjointSliceSort(m, n []string) []string { s := indexSort{sort.StringSlice(m), make([]int, 0, len(n))} used := make(map[int]bool) for _, nw := range n { for i, mw := range m { if used[i] || mw != nw { continue } used[i] = true s.ind = append(s.ind, i) break } } sort.Sort(s) return s.val.(sort.StringSlice) } func disjointStringSort(m, n string) string { return strings.Join( disjointSliceSort(strings.Fields(m), strings.Fields(n)), " ") } func main() { for _, data := range []struct{ m, n string }{ {"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, {"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"}, {"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, } { mp := disjointStringSort(data.m, data.n) fmt.Printf("%s → %s » %s\n", data.m, data.n, mp) } }
from __future__ import print_function def order_disjoint_list_items(data, items): itemindices = [] for item in set(items): itemcount = items.count(item) lastindex = [-1] for i in range(itemcount): lastindex.append(data.index(item, lastindex[-1] + 1)) itemindices += lastindex[1:] itemindices.sort() for index, item in zip(itemindices, items): data[index] = item if __name__ == '__main__': tostring = ' '.join for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')), (str.split('the cat sat on the mat'), str.split('cat mat')), (list('ABCABCABC'), list('CACA')), (list('ABCABDABE'), list('EADA')), (list('AB'), list('B')), (list('AB'), list('BA')), (list('ABBA'), list('BA')), (list(''), list('')), (list('A'), list('A')), (list('AB'), list('')), (list('ABBA'), list('AB')), (list('ABAB'), list('AB')), (list('ABAB'), list('BABA')), (list('ABCCBA'), list('ACAC')), (list('ABCCBA'), list('CACA')), ]: print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ') order_disjoint_list_items(data, items) print("-> M' %r" % tostring(data))
Produce a functionally identical Python code for the snippet given in Go.
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, } h := map[string][]int{} for i, r := range tableA { h[r.key] = append(h[r.key], i) } for _, x := range tableB { for _, a := range h[x.key] { fmt.Println(tableA[a], x) } } }
from collections import defaultdict def hashJoin(table1, index1, table2, index2): h = defaultdict(list) for s in table1: h[s[index1]].append(s) return [(s, r) for r in table2 for s in h[r[index2]]] table1 = [(27, "Jonah"), (18, "Alan"), (28, "Glory"), (18, "Popeye"), (28, "Alan")] table2 = [("Jonah", "Whales"), ("Jonah", "Spiders"), ("Alan", "Ghosts"), ("Alan", "Zombies"), ("Glory", "Buffy")] for row in hashJoin(table1, 1, table2, 0): print(row)
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "math" "sort" ) func totient(n int) int { tot := n i := 2 for i*i <= n { if n%i == 0 { for n%i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } if n > 1 { tot -= tot / n } return tot } var pps = make(map[int]bool) func getPerfectPowers(maxExp int) { upper := math.Pow(10, float64(maxExp)) for i := 2; i <= int(math.Sqrt(upper)); i++ { fi := float64(i) p := fi for { p *= fi if p >= upper { break } pps[int(p)] = true } } } func getAchilles(minExp, maxExp int) map[int]bool { lower := math.Pow(10, float64(minExp)) upper := math.Pow(10, float64(maxExp)) achilles := make(map[int]bool) for b := 1; b <= int(math.Cbrt(upper)); b++ { b3 := b * b * b for a := 1; a <= int(math.Sqrt(upper)); a++ { p := b3 * a * a if p >= int(upper) { break } if p >= int(lower) { if _, ok := pps[p]; !ok { achilles[p] = true } } } } return achilles } func main() { maxDigits := 15 getPerfectPowers(maxDigits) achillesSet := getAchilles(1, 5) achilles := make([]int, len(achillesSet)) i := 0 for k := range achillesSet { achilles[i] = k i++ } sort.Ints(achilles) fmt.Println("First 50 Achilles numbers:") for i = 0; i < 50; i++ { fmt.Printf("%4d ", achilles[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 strong Achilles numbers:") var strongAchilles []int count := 0 for n := 0; count < 30; n++ { tot := totient(achilles[n]) if _, ok := achillesSet[tot]; ok { strongAchilles = append(strongAchilles, achilles[n]) count++ } } for i = 0; i < 30; i++ { fmt.Printf("%5d ", strongAchilles[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\nNumber of Achilles numbers with:") for d := 2; d <= maxDigits; d++ { ac := len(getAchilles(d-1, d)) fmt.Printf("%2d digits: %d\n", d, ac) } }
from math import gcd from sympy import factorint def is_Achilles(n): p = factorint(n).values() return all(i > 1 for i in p) and gcd(*p) == 1 def is_strong_Achilles(n): return is_Achilles(n) and is_Achilles(totient(n)) def test_strong_Achilles(nachilles, nstrongachilles): print('First', nachilles, 'Achilles numbers:') n, found = 0, 0 while found < nachilles: if is_Achilles(n): found += 1 print(f'{n: 8,}', end='\n' if found % 10 == 0 else '') n += 1 print('\nFirst', nstrongachilles, 'strong Achilles numbers:') n, found = 0, 0 while found < nstrongachilles: if is_strong_Achilles(n): found += 1 print(f'{n: 9,}', end='\n' if found % 10 == 0 else '') n += 1 print('\nCount of Achilles numbers for various intervals:') intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]] for interval in intervals: print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval))) test_strong_Achilles(50, 100)
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" "sort" ) func totient(n int) int { tot := n i := 2 for i*i <= n { if n%i == 0 { for n%i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } if n > 1 { tot -= tot / n } return tot } var pps = make(map[int]bool) func getPerfectPowers(maxExp int) { upper := math.Pow(10, float64(maxExp)) for i := 2; i <= int(math.Sqrt(upper)); i++ { fi := float64(i) p := fi for { p *= fi if p >= upper { break } pps[int(p)] = true } } } func getAchilles(minExp, maxExp int) map[int]bool { lower := math.Pow(10, float64(minExp)) upper := math.Pow(10, float64(maxExp)) achilles := make(map[int]bool) for b := 1; b <= int(math.Cbrt(upper)); b++ { b3 := b * b * b for a := 1; a <= int(math.Sqrt(upper)); a++ { p := b3 * a * a if p >= int(upper) { break } if p >= int(lower) { if _, ok := pps[p]; !ok { achilles[p] = true } } } } return achilles } func main() { maxDigits := 15 getPerfectPowers(maxDigits) achillesSet := getAchilles(1, 5) achilles := make([]int, len(achillesSet)) i := 0 for k := range achillesSet { achilles[i] = k i++ } sort.Ints(achilles) fmt.Println("First 50 Achilles numbers:") for i = 0; i < 50; i++ { fmt.Printf("%4d ", achilles[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 strong Achilles numbers:") var strongAchilles []int count := 0 for n := 0; count < 30; n++ { tot := totient(achilles[n]) if _, ok := achillesSet[tot]; ok { strongAchilles = append(strongAchilles, achilles[n]) count++ } } for i = 0; i < 30; i++ { fmt.Printf("%5d ", strongAchilles[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\nNumber of Achilles numbers with:") for d := 2; d <= maxDigits; d++ { ac := len(getAchilles(d-1, d)) fmt.Printf("%2d digits: %d\n", d, ac) } }
from math import gcd from sympy import factorint def is_Achilles(n): p = factorint(n).values() return all(i > 1 for i in p) and gcd(*p) == 1 def is_strong_Achilles(n): return is_Achilles(n) and is_Achilles(totient(n)) def test_strong_Achilles(nachilles, nstrongachilles): print('First', nachilles, 'Achilles numbers:') n, found = 0, 0 while found < nachilles: if is_Achilles(n): found += 1 print(f'{n: 8,}', end='\n' if found % 10 == 0 else '') n += 1 print('\nFirst', nstrongachilles, 'strong Achilles numbers:') n, found = 0, 0 while found < nstrongachilles: if is_strong_Achilles(n): found += 1 print(f'{n: 9,}', end='\n' if found % 10 == 0 else '') n += 1 print('\nCount of Achilles numbers for various intervals:') intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]] for interval in intervals: print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval))) test_strong_Achilles(50, 100)
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "rcu" "sort" ) func main() { primes := rcu.Primes(333) var oss []int for i := 1; i < len(primes)-1; i++ { for j := i + 1; j < len(primes); j++ { n := primes[i] * primes[j] if n >= 1000 { break } oss = append(oss, n) } } sort.Ints(oss) fmt.Println("Odd squarefree semiprimes under 1,000:") for i, n := range oss { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such numbers found.\n", len(oss)) }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 999): if not isPrime(p): continue for q in range(p+1, 1000//p): if not isPrime(q): continue print(p*q, end = " ");
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "rcu" "sort" ) func main() { primes := rcu.Primes(333) var oss []int for i := 1; i < len(primes)-1; i++ { for j := i + 1; j < len(primes); j++ { n := primes[i] * primes[j] if n >= 1000 { break } oss = append(oss, n) } } sort.Ints(oss) fmt.Println("Odd squarefree semiprimes under 1,000:") for i, n := range oss { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such numbers found.\n", len(oss)) }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 999): if not isPrime(p): continue for q in range(p+1, 1000//p): if not isPrime(q): continue print(p*q, end = " ");
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx, cy-2*h) } func lineS() { lineTo(cx, cy+2*h) } func lineE() { lineTo(cx+2*h, cy) } func lineW() { lineTo(cx-2*h, cy) } func lineNW() { lineTo(cx-h, cy-h) } func lineNE() { lineTo(cx+h, cy-h) } func lineSE() { lineTo(cx+h, cy+h) } func lineSW() { lineTo(cx-h, cy+h) } func sierN(level int) { if level == 1 { lineNE() lineN() lineNW() } else { sierN(level - 1) lineNE() sierE(level - 1) lineN() sierW(level - 1) lineNW() sierN(level - 1) } } func sierE(level int) { if level == 1 { lineSE() lineE() lineNE() } else { sierE(level - 1) lineSE() sierS(level - 1) lineE() sierN(level - 1) lineNE() sierE(level - 1) } } func sierS(level int) { if level == 1 { lineSW() lineS() lineSE() } else { sierS(level - 1) lineSW() sierW(level - 1) lineS() sierE(level - 1) lineSE() sierS(level - 1) } } func sierW(level int) { if level == 1 { lineNW() lineW() lineSW() } else { sierW(level - 1) lineNW() sierN(level - 1) lineW() sierS(level - 1) lineSW() sierW(level - 1) } } func squareCurve(level int) { sierN(level) lineNE() sierE(level) lineSE() sierS(level) lineSW() sierW(level) lineNW() lineNE() } func main() { dc.SetRGB(0, 0, 1) dc.Clear() level := 5 cx, cy = width/2, height h = cx / math.Pow(2, float64(level+1)) squareCurve(level) dc.SetRGB255(255, 255, 0) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_curve.png") }
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import hsv_to_rgb as hsv def curve(axiom, rules, angle, depth): for _ in range(depth): axiom = ''.join(rules[c] if c in rules else c for c in axiom) a, x, y = 0, [0], [0] for c in axiom: match c: case '+': a += 1 case '-': a -= 1 case 'F' | 'G': x.append(x[-1] + np.cos(a*angle*np.pi/180)) y.append(y[-1] + np.sin(a*angle*np.pi/180)) l = len(x) for i in range(l - 1): plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7])) plt.gca().set_aspect(1) plt.show() curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
Change the following Go code into Python without altering its purpose.
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx, cy-2*h) } func lineS() { lineTo(cx, cy+2*h) } func lineE() { lineTo(cx+2*h, cy) } func lineW() { lineTo(cx-2*h, cy) } func lineNW() { lineTo(cx-h, cy-h) } func lineNE() { lineTo(cx+h, cy-h) } func lineSE() { lineTo(cx+h, cy+h) } func lineSW() { lineTo(cx-h, cy+h) } func sierN(level int) { if level == 1 { lineNE() lineN() lineNW() } else { sierN(level - 1) lineNE() sierE(level - 1) lineN() sierW(level - 1) lineNW() sierN(level - 1) } } func sierE(level int) { if level == 1 { lineSE() lineE() lineNE() } else { sierE(level - 1) lineSE() sierS(level - 1) lineE() sierN(level - 1) lineNE() sierE(level - 1) } } func sierS(level int) { if level == 1 { lineSW() lineS() lineSE() } else { sierS(level - 1) lineSW() sierW(level - 1) lineS() sierE(level - 1) lineSE() sierS(level - 1) } } func sierW(level int) { if level == 1 { lineNW() lineW() lineSW() } else { sierW(level - 1) lineNW() sierN(level - 1) lineW() sierS(level - 1) lineSW() sierW(level - 1) } } func squareCurve(level int) { sierN(level) lineNE() sierE(level) lineSE() sierS(level) lineSW() sierW(level) lineNW() lineNE() } func main() { dc.SetRGB(0, 0, 1) dc.Clear() level := 5 cx, cy = width/2, height h = cx / math.Pow(2, float64(level+1)) squareCurve(level) dc.SetRGB255(255, 255, 0) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_curve.png") }
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import hsv_to_rgb as hsv def curve(axiom, rules, angle, depth): for _ in range(depth): axiom = ''.join(rules[c] if c in rules else c for c in axiom) a, x, y = 0, [0], [0] for c in axiom: match c: case '+': a += 1 case '-': a -= 1 case 'F' | 'G': x.append(x[-1] + np.cos(a*angle*np.pi/180)) y.append(y[-1] + np.sin(a*angle*np.pi/180)) l = len(x) for i in range(l - 1): plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7])) plt.gca().set_aspect(1) plt.show() curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "fmt" "sort" ) type cf struct { c rune f int } func reverseStr(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func indexOfCf(cfs []cf, r rune) int { for i, cf := range cfs { if cf.c == r { return i } } return -1 } func minOf(i, j int) int { if i < j { return i } return j } func mostFreqKHashing(input string, k int) string { var cfs []cf for _, r := range input { ix := indexOfCf(cfs, r) if ix >= 0 { cfs[ix].f++ } else { cfs = append(cfs, cf{r, 1}) } } sort.SliceStable(cfs, func(i, j int) bool { return cfs[i].f > cfs[j].f }) acc := "" min := minOf(len(cfs), k) for _, cf := range cfs[:min] { acc += fmt.Sprintf("%c%c", cf.c, cf.f) } return acc } func mostFreqKSimilarity(input1, input2 string) int { similarity := 0 runes1, runes2 := []rune(input1), []rune(input2) for i := 0; i < len(runes1); i += 2 { for j := 0; j < len(runes2); j += 2 { if runes1[i] == runes2[j] { freq1, freq2 := runes1[i+1], runes2[j+1] if freq1 != freq2 { continue } similarity += int(freq1) } } } return similarity } func mostFreqKSDF(input1, input2 string, k, maxDistance int) { fmt.Println("input1 :", input1) fmt.Println("input2 :", input2) s1 := mostFreqKHashing(input1, k) s2 := mostFreqKHashing(input2, k) fmt.Printf("mfkh(input1, %d) = ", k) for i, c := range s1 { if i%2 == 0 { fmt.Printf("%c", c) } else { fmt.Printf("%d", c) } } fmt.Printf("\nmfkh(input2, %d) = ", k) for i, c := range s2 { if i%2 == 0 { fmt.Printf("%c", c) } else { fmt.Printf("%d", c) } } result := maxDistance - mostFreqKSimilarity(s1, s2) fmt.Printf("\nSDF(input1, input2, %d, %d) = %d\n\n", k, maxDistance, result) } func main() { pairs := [][2]string{ {"research", "seeking"}, {"night", "nacht"}, {"my", "a"}, {"research", "research"}, {"aaaaabbbb", "ababababa"}, {"significant", "capabilities"}, } for _, pair := range pairs { mostFreqKSDF(pair[0], pair[1], 2, 10) } s1 := "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV" s2 := "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG" mostFreqKSDF(s1, s2, 2, 100) s1 = "abracadabra12121212121abracadabra12121212121" s2 = reverseStr(s1) mostFreqKSDF(s1, s2, 2, 100) }
import collections def MostFreqKHashing(inputString, K): occuDict = collections.defaultdict(int) for c in inputString: occuDict[c] += 1 occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True) outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K]) return outputStr def MostFreqKSimilarity(inputStr1, inputStr2): similarity = 0 for i in range(0, len(inputStr1), 2): c = inputStr1[i] cnt1 = int(inputStr1[i + 1]) for j in range(0, len(inputStr2), 2): if inputStr2[j] == c: cnt2 = int(inputStr2[j + 1]) similarity += cnt1 + cnt2 break return similarity def MostFreqKSDF(inputStr1, inputStr2, K, maxDistance): return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "sort" ) type cf struct { c rune f int } func reverseStr(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func indexOfCf(cfs []cf, r rune) int { for i, cf := range cfs { if cf.c == r { return i } } return -1 } func minOf(i, j int) int { if i < j { return i } return j } func mostFreqKHashing(input string, k int) string { var cfs []cf for _, r := range input { ix := indexOfCf(cfs, r) if ix >= 0 { cfs[ix].f++ } else { cfs = append(cfs, cf{r, 1}) } } sort.SliceStable(cfs, func(i, j int) bool { return cfs[i].f > cfs[j].f }) acc := "" min := minOf(len(cfs), k) for _, cf := range cfs[:min] { acc += fmt.Sprintf("%c%c", cf.c, cf.f) } return acc } func mostFreqKSimilarity(input1, input2 string) int { similarity := 0 runes1, runes2 := []rune(input1), []rune(input2) for i := 0; i < len(runes1); i += 2 { for j := 0; j < len(runes2); j += 2 { if runes1[i] == runes2[j] { freq1, freq2 := runes1[i+1], runes2[j+1] if freq1 != freq2 { continue } similarity += int(freq1) } } } return similarity } func mostFreqKSDF(input1, input2 string, k, maxDistance int) { fmt.Println("input1 :", input1) fmt.Println("input2 :", input2) s1 := mostFreqKHashing(input1, k) s2 := mostFreqKHashing(input2, k) fmt.Printf("mfkh(input1, %d) = ", k) for i, c := range s1 { if i%2 == 0 { fmt.Printf("%c", c) } else { fmt.Printf("%d", c) } } fmt.Printf("\nmfkh(input2, %d) = ", k) for i, c := range s2 { if i%2 == 0 { fmt.Printf("%c", c) } else { fmt.Printf("%d", c) } } result := maxDistance - mostFreqKSimilarity(s1, s2) fmt.Printf("\nSDF(input1, input2, %d, %d) = %d\n\n", k, maxDistance, result) } func main() { pairs := [][2]string{ {"research", "seeking"}, {"night", "nacht"}, {"my", "a"}, {"research", "research"}, {"aaaaabbbb", "ababababa"}, {"significant", "capabilities"}, } for _, pair := range pairs { mostFreqKSDF(pair[0], pair[1], 2, 10) } s1 := "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV" s2 := "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG" mostFreqKSDF(s1, s2, 2, 100) s1 = "abracadabra12121212121abracadabra12121212121" s2 = reverseStr(s1) mostFreqKSDF(s1, s2, 2, 100) }
import collections def MostFreqKHashing(inputString, K): occuDict = collections.defaultdict(int) for c in inputString: occuDict[c] += 1 occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True) outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K]) return outputStr def MostFreqKSimilarity(inputStr1, inputStr2): similarity = 0 for i in range(0, len(inputStr1), 2): c = inputStr1[i] cnt1 = int(inputStr1[i + 1]) for j in range(0, len(inputStr2), 2): if inputStr2[j] == c: cnt2 = int(inputStr2[j + 1]) similarity += cnt1 + cnt2 break return similarity def MostFreqKSDF(inputStr1, inputStr2, K, maxDistance): return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "rcu" ) func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n /= 10 } return rev } func main() { primes := rcu.Primes(99999) var pals []int for _, p := range primes { if p == reversed(p) { pals = append(pals, p) } } fmt.Println("Palindromic primes under 1,000:") var smallPals, bigPals []int for _, p := range pals { if p < 1000 { smallPals = append(smallPals, p) } else { bigPals = append(bigPals, p) } } rcu.PrintTable(smallPals, 10, 3, false) fmt.Println() fmt.Println(len(smallPals), "such primes found.") fmt.Println("\nAdditional palindromic primes under 100,000:") rcu.PrintTable(bigPals, 10, 6, true) fmt.Println() fmt.Println(len(bigPals), "such primes found,", len(pals), "in all.") }
from itertools import takewhile def palindromicPrimes(): def p(n): s = str(n) return s == s[::-1] return (n for n in primes() if p(n)) def main(): print('\n'.join( str(x) for x in takewhile( lambda n: 1000 > n, palindromicPrimes() ) )) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n if __name__ == '__main__': main()
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "rcu" ) func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n /= 10 } return rev } func main() { primes := rcu.Primes(99999) var pals []int for _, p := range primes { if p == reversed(p) { pals = append(pals, p) } } fmt.Println("Palindromic primes under 1,000:") var smallPals, bigPals []int for _, p := range pals { if p < 1000 { smallPals = append(smallPals, p) } else { bigPals = append(bigPals, p) } } rcu.PrintTable(smallPals, 10, 3, false) fmt.Println() fmt.Println(len(smallPals), "such primes found.") fmt.Println("\nAdditional palindromic primes under 100,000:") rcu.PrintTable(bigPals, 10, 6, true) fmt.Println() fmt.Println(len(bigPals), "such primes found,", len(pals), "in all.") }
from itertools import takewhile def palindromicPrimes(): def p(n): s = str(n) return s == s[::-1] return (n for n in primes() if p(n)) def main(): print('\n'.join( str(x) for x in takewhile( lambda n: 1000 > n, palindromicPrimes() ) )) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n if __name__ == '__main__': main()
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) > 10 { words = append(words, s) } } count := 0 fmt.Println("Words which contain all 5 vowels once in", wordList, "\b:\n") for _, word := range words { ca, ce, ci, co, cu := 0, 0, 0, 0, 0 for _, r := range word { switch r { case 'a': ca++ case 'e': ce++ case 'i': ci++ case 'o': co++ case 'u': cu++ } } if ca == 1 && ce == 1 && ci == 1 && co == 1 && cu == 1 { count++ fmt.Printf("%2d: %s\n", count, word) } } }
import urllib.request from collections import Counter urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() for word in wordList: if len(word)>10: frequency = Counter(word.lower()) if frequency['a']==frequency['e']==frequency['i']==frequency['o']==frequency['u']==1: print(word)
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "log" "math" ) var MinusInf = math.Inf(-1) type MaxTropical struct{ r float64 } func newMaxTropical(r float64) MaxTropical { if math.IsInf(r, 1) || math.IsNaN(r) { log.Fatal("Argument must be a real number or negative infinity.") } return MaxTropical{r} } func (t MaxTropical) eq(other MaxTropical) bool { return t.r == other.r } func (t MaxTropical) add(other MaxTropical) MaxTropical { if t.r == MinusInf { return other } if other.r == MinusInf { return t } return newMaxTropical(math.Max(t.r, other.r)) } func (t MaxTropical) mul(other MaxTropical) MaxTropical { if t.r == 0 { return other } if other.r == 0 { return t } return newMaxTropical(t.r + other.r) } func (t MaxTropical) pow(e int) MaxTropical { if e < 1 { log.Fatal("Exponent must be a positive integer.") } if e == 1 { return t } p := t for i := 2; i <= e; i++ { p = p.mul(t) } return p } func (t MaxTropical) String() string { return fmt.Sprintf("%g", t.r) } func main() { data := [][]float64{ {2, -2, 1}, {-0.001, MinusInf, 0}, {0, MinusInf, 1}, {1.5, -1, 0}, {-0.5, 0, 1}, } for _, d := range data { a := newMaxTropical(d[0]) b := newMaxTropical(d[1]) if d[2] == 0 { fmt.Printf("%s ⊕ %s = %s\n", a, b, a.add(b)) } else { fmt.Printf("%s ⊗ %s = %s\n", a, b, a.mul(b)) } } c := newMaxTropical(5) fmt.Printf("%s ^ 7 = %s\n", c, c.pow(7)) d := newMaxTropical(8) e := newMaxTropical(7) f := c.mul(d.add(e)) g := c.mul(d).add(c.mul(e)) fmt.Printf("%s ⊗ (%s ⊕ %s) = %s\n", c, d, e, f) fmt.Printf("%s ⊗ %s ⊕ %s ⊗ %s = %s\n", c, d, c, e, g) fmt.Printf("%s ⊗ (%s ⊕ %s) == %s ⊗ %s ⊕ %s ⊗ %s is %t\n", c, d, e, c, d, c, e, f.eq(g)) }
from numpy import Inf class MaxTropical: def __init__(self, x=0): self.x = x def __str__(self): return str(self.x) def __add__(self, other): return MaxTropical(max(self.x, other.x)) def __mul__(self, other): return MaxTropical(self.x + other.x) def __pow__(self, other): assert other.x // 1 == other.x and other.x > 0, "Invalid Operation" return MaxTropical(self.x * other.x) def __eq__(self, other): return self.x == other.x if __name__ == "__main__": a = MaxTropical(-2) b = MaxTropical(-1) c = MaxTropical(-0.5) d = MaxTropical(-0.001) e = MaxTropical(0) f = MaxTropical(0.5) g = MaxTropical(1) h = MaxTropical(1.5) i = MaxTropical(2) j = MaxTropical(5) k = MaxTropical(7) l = MaxTropical(8) m = MaxTropical(-Inf) print("2 * -2 == ", i * a) print("-0.001 + -Inf == ", d + m) print("0 * -Inf == ", e * m) print("1.5 + -1 == ", h + b) print("-0.5 * 0 == ", c * e) print("5**7 == ", j**k) print("5 * (8 + 7)) == ", j * (l + k)) print("5 * 8 + 5 * 7 == ", j * l + j * k) print("5 * (8 + 7) == 5 * 8 + 5 * 7", j * (l + k) == j * l + j * k)
Generate an equivalent Python version of this Go code.
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota piggedOut rolls pointSpending holds turn gameOverSummary player1 = PlayerID(0) player2 = PlayerID(1) noPlayer = PlayerID(-1) maxScore = 100 scoreChaseStrat = iota rollCountStrat ) func pluralS(n int) string { if n != 1 { return "s" } return "" } func New() *PigGameData { return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false} } func (pg *PigGameData) statusMessage(id MessageID) string { var msg string switch id { case gameOver: msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount) case piggedOut: msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount)) case rolls: msg = fmt.Sprintf(" Rolls %d", pg.lastRoll) case pointSpending: msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore)) case holds: msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer)) case turn: msg = fmt.Sprintf("Player %d's turn:", pg.player+1) case gameOverSummary: msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2)) } return msg } func (pg *PigGameData) PrintStatus(id MessageID) { if pg.verbose { fmt.Println(pg.statusMessage(id)) } } func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) { if pg.GameOver() { pg.PrintStatus(gameOver) return false } if pg.turnCount == 0 { pg.player = player2 pg.NextPlayer() } pg.lastRoll = rand.Intn(6) + 1 pg.PrintStatus(rolls) pg.turnRollCount++ if pg.lastRoll == 1 { pg.PrintStatus(piggedOut) pg.NextPlayer() } else { pg.turnScore += pg.lastRoll pg.PrintStatus(pointSpending) success := false switch id { case scoreChaseStrat: success = pg.scoreChaseStrategy() case rollCountStrat: success = pg.rollCountStrategy() } if success { pg.Hold() pg.NextPlayer() } } return true } func (pg *PigGameData) PlayerScore(id PlayerID) int { if id == noPlayer { return pg.scores[pg.player] } return pg.scores[id] } func (pg *PigGameData) GameOver() bool { return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore } func (pg *PigGameData) Winner() PlayerID { for index, score := range pg.scores { if score >= maxScore { return PlayerID(index) } } return noPlayer } func (pg *PigGameData) otherPlayer() PlayerID { return 1 - pg.player } func (pg *PigGameData) Hold() { pg.scores[pg.player] += pg.turnScore pg.PrintStatus(holds) pg.turnRollCount, pg.turnScore = 0, 0 } func (pg *PigGameData) NextPlayer() { pg.turnCount++ pg.turnRollCount, pg.turnScore = 0, 0 pg.player = pg.otherPlayer() pg.PrintStatus(turn) } func (pg *PigGameData) rollCountStrategy() bool { return pg.turnRollCount >= 3 } func (pg *PigGameData) scoreChaseStrategy() bool { myScore := pg.PlayerScore(pg.player) otherScore := pg.PlayerScore(pg.otherPlayer()) myPendingScore := pg.turnScore + myScore return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5 } func main() { rand.Seed(time.Now().UnixNano()) pg := New() pg.verbose = true strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat} for !pg.GameOver() { pg.Play(strategies[pg.player]) } pg.PrintStatus(gameOverSummary) }
from random import randint from collections import namedtuple import random from pprint import pprint as pp from collections import Counter playercount = 2 maxscore = 100 maxgames = 100000 Game = namedtuple('Game', 'players, maxscore, rounds') Round = namedtuple('Round', 'who, start, scores, safe') class Player(): def __init__(self, player_index): self.player_index = player_index def __repr__(self): return '%s(%i)' % (self.__class__.__name__, self.player_index) def __call__(self, safescore, scores, game): 'Returns boolean True to roll again' pass class RandPlay(Player): def __call__(self, safe, scores, game): 'Returns random boolean choice of whether to roll again' return bool(random.randint(0, 1)) class RollTo20(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20' return (((sum(scores) + safe[self.player_index]) < maxscore) and(sum(scores) < 20)) class Desparat(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20 or someone is within 20 of winning' return (((sum(scores) + safe[self.player_index]) < maxscore) and( (sum(scores) < 20) or max(safe) >= (maxscore - 20))) def game__str__(self): 'Pretty printer for Game class' return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])" % (self.players, self.maxscore, ',\n '.join(repr(round) for round in self.rounds))) Game.__str__ = game__str__ def winningorder(players, safescores): 'Return (players in winning order, their scores)' return tuple(zip(*sorted(zip(players, safescores), key=lambda x: x[1], reverse=True))) def playpig(game): players, maxscore, rounds = game playercount = len(players) safescore = [0] * playercount player = 0 scores=[] while max(safescore) < maxscore: startscore = safescore[player] rolling = players[player](safescore, scores, game) if rolling: rolled = randint(1, 6) scores.append(rolled) if rolled == 1: round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) scores, player = [], (player + 1) % playercount else: safescore[player] += sum(scores) round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) if safescore[player] >= maxscore: break scores, player = [], (player + 1) % playercount return winningorder(players, safescore) if __name__ == '__main__': game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=20, rounds=[]) print('ONE GAME') print('Winning order: %r; Respective scores: %r\n' % playpig(game)) print(game) game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=maxscore, rounds=[]) algos = (RollTo20, RandPlay, Desparat) print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES' % (', '.join(p.__name__ for p in algos), maxgames,)) winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i) for i in range(playercount)), rounds=[]))[0]) for i in range(maxgames)) print(' Players(position) winning on left; occurrences on right:\n %s' % ',\n '.join(str(w) for w in winners.most_common()))
Write the same code in Python as shown below in Go.
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota piggedOut rolls pointSpending holds turn gameOverSummary player1 = PlayerID(0) player2 = PlayerID(1) noPlayer = PlayerID(-1) maxScore = 100 scoreChaseStrat = iota rollCountStrat ) func pluralS(n int) string { if n != 1 { return "s" } return "" } func New() *PigGameData { return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false} } func (pg *PigGameData) statusMessage(id MessageID) string { var msg string switch id { case gameOver: msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount) case piggedOut: msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount)) case rolls: msg = fmt.Sprintf(" Rolls %d", pg.lastRoll) case pointSpending: msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore)) case holds: msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer)) case turn: msg = fmt.Sprintf("Player %d's turn:", pg.player+1) case gameOverSummary: msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2)) } return msg } func (pg *PigGameData) PrintStatus(id MessageID) { if pg.verbose { fmt.Println(pg.statusMessage(id)) } } func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) { if pg.GameOver() { pg.PrintStatus(gameOver) return false } if pg.turnCount == 0 { pg.player = player2 pg.NextPlayer() } pg.lastRoll = rand.Intn(6) + 1 pg.PrintStatus(rolls) pg.turnRollCount++ if pg.lastRoll == 1 { pg.PrintStatus(piggedOut) pg.NextPlayer() } else { pg.turnScore += pg.lastRoll pg.PrintStatus(pointSpending) success := false switch id { case scoreChaseStrat: success = pg.scoreChaseStrategy() case rollCountStrat: success = pg.rollCountStrategy() } if success { pg.Hold() pg.NextPlayer() } } return true } func (pg *PigGameData) PlayerScore(id PlayerID) int { if id == noPlayer { return pg.scores[pg.player] } return pg.scores[id] } func (pg *PigGameData) GameOver() bool { return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore } func (pg *PigGameData) Winner() PlayerID { for index, score := range pg.scores { if score >= maxScore { return PlayerID(index) } } return noPlayer } func (pg *PigGameData) otherPlayer() PlayerID { return 1 - pg.player } func (pg *PigGameData) Hold() { pg.scores[pg.player] += pg.turnScore pg.PrintStatus(holds) pg.turnRollCount, pg.turnScore = 0, 0 } func (pg *PigGameData) NextPlayer() { pg.turnCount++ pg.turnRollCount, pg.turnScore = 0, 0 pg.player = pg.otherPlayer() pg.PrintStatus(turn) } func (pg *PigGameData) rollCountStrategy() bool { return pg.turnRollCount >= 3 } func (pg *PigGameData) scoreChaseStrategy() bool { myScore := pg.PlayerScore(pg.player) otherScore := pg.PlayerScore(pg.otherPlayer()) myPendingScore := pg.turnScore + myScore return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5 } func main() { rand.Seed(time.Now().UnixNano()) pg := New() pg.verbose = true strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat} for !pg.GameOver() { pg.Play(strategies[pg.player]) } pg.PrintStatus(gameOverSummary) }
from random import randint from collections import namedtuple import random from pprint import pprint as pp from collections import Counter playercount = 2 maxscore = 100 maxgames = 100000 Game = namedtuple('Game', 'players, maxscore, rounds') Round = namedtuple('Round', 'who, start, scores, safe') class Player(): def __init__(self, player_index): self.player_index = player_index def __repr__(self): return '%s(%i)' % (self.__class__.__name__, self.player_index) def __call__(self, safescore, scores, game): 'Returns boolean True to roll again' pass class RandPlay(Player): def __call__(self, safe, scores, game): 'Returns random boolean choice of whether to roll again' return bool(random.randint(0, 1)) class RollTo20(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20' return (((sum(scores) + safe[self.player_index]) < maxscore) and(sum(scores) < 20)) class Desparat(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20 or someone is within 20 of winning' return (((sum(scores) + safe[self.player_index]) < maxscore) and( (sum(scores) < 20) or max(safe) >= (maxscore - 20))) def game__str__(self): 'Pretty printer for Game class' return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])" % (self.players, self.maxscore, ',\n '.join(repr(round) for round in self.rounds))) Game.__str__ = game__str__ def winningorder(players, safescores): 'Return (players in winning order, their scores)' return tuple(zip(*sorted(zip(players, safescores), key=lambda x: x[1], reverse=True))) def playpig(game): players, maxscore, rounds = game playercount = len(players) safescore = [0] * playercount player = 0 scores=[] while max(safescore) < maxscore: startscore = safescore[player] rolling = players[player](safescore, scores, game) if rolling: rolled = randint(1, 6) scores.append(rolled) if rolled == 1: round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) scores, player = [], (player + 1) % playercount else: safescore[player] += sum(scores) round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) if safescore[player] >= maxscore: break scores, player = [], (player + 1) % playercount return winningorder(players, safescore) if __name__ == '__main__': game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=20, rounds=[]) print('ONE GAME') print('Winning order: %r; Respective scores: %r\n' % playpig(game)) print(game) game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=maxscore, rounds=[]) algos = (RollTo20, RandPlay, Desparat) print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES' % (', '.join(p.__name__ for p in algos), maxgames,)) winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i) for i in range(playercount)), rounds=[]))[0]) for i in range(maxgames)) print(' Players(position) winning on left; occurrences on right:\n %s' % ',\n '.join(str(w) for w in winners.most_common()))
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(v.String()) result.SetString(s, 10) } else { v := new(big.Int).Set(v) digit := new(big.Int) result.SetUint64(0) for v.BitLen() > 0 { v.QuoRem(v, ten, digit) result.Mul(result, ten) result.Add(result, digit) } } } return result } func reverseUint64(v uint64) uint64 { var r uint64 for v > 0 { r *= 10 r += v % 10 v /= 10 } return r } func reverseString(s string) string { b := make([]byte, len(s)) for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 { b[i] = s[j] } return string(b) } var known = make(map[string]bool) func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) { v, r := new(big.Int).SetUint64(n), new(big.Int) reverseInt(v, r) seen := make(map[string]bool) isLychrel = true isSeed = true for i := iter; i > 0; i-- { str := v.String() if seen[str] { isLychrel = true break } if ans, ok := known[str]; ok { isLychrel = ans isSeed = false break } seen[str] = true v = v.Add(v, r) reverseInt(v, r) if v.Cmp(r) == 0 { isLychrel = false isSeed = false break } } for k := range seen { known[k] = isLychrel } return isLychrel, isSeed } func main() { max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive") iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter) var seeds []uint64 var related int var pals []uint64 for i := uint64(1); i <= *max; i++ { if l, s := Lychrel(i, *iter); l { if s { seeds = append(seeds, i) } else { related++ } if i == reverseUint64(i) { pals = append(pals, i) } } } fmt.Println(" Number of Lychrel seeds:", len(seeds)) fmt.Println(" Lychrel seeds:", seeds) fmt.Println(" Number of related:", related) fmt.Println("Number of Lychrel palindromes:", len(pals)) fmt.Println(" Lychrel palindromes:", pals) }
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)[::-1]) def split_roots_from_relateds(roots_and_relateds): roots = roots_and_relateds[::] i = 1 while i < len(roots): this = roots[i] if any(this.intersection(prev) for prev in roots[:i]): del roots[i] else: i += 1 root = [min(each_set) for each_set in roots] related = [min(each_set) for each_set in roots_and_relateds] related = [n for n in related if n not in root] return root, related def find_lychrel(maxn, max_reversions): 'Lychrel number generator' series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)] roots_and_relateds = [s for s in series if len(s) > max_reversions] return split_roots_from_relateds(roots_and_relateds) if __name__ == '__main__': maxn, reversion_limit = 10000, 500 print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds" % (maxn, reversion_limit)) lychrel, l_related = find_lychrel(maxn, reversion_limit) print(' Number of Lychrel numbers:', len(lychrel)) print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel)) print(' Number of Lychrel related:', len(l_related)) pals = [x for x in lychrel + l_related if x == reverse_int(x)] print(' Number of Lychrel palindromes:', len(pals)) print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(v.String()) result.SetString(s, 10) } else { v := new(big.Int).Set(v) digit := new(big.Int) result.SetUint64(0) for v.BitLen() > 0 { v.QuoRem(v, ten, digit) result.Mul(result, ten) result.Add(result, digit) } } } return result } func reverseUint64(v uint64) uint64 { var r uint64 for v > 0 { r *= 10 r += v % 10 v /= 10 } return r } func reverseString(s string) string { b := make([]byte, len(s)) for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 { b[i] = s[j] } return string(b) } var known = make(map[string]bool) func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) { v, r := new(big.Int).SetUint64(n), new(big.Int) reverseInt(v, r) seen := make(map[string]bool) isLychrel = true isSeed = true for i := iter; i > 0; i-- { str := v.String() if seen[str] { isLychrel = true break } if ans, ok := known[str]; ok { isLychrel = ans isSeed = false break } seen[str] = true v = v.Add(v, r) reverseInt(v, r) if v.Cmp(r) == 0 { isLychrel = false isSeed = false break } } for k := range seen { known[k] = isLychrel } return isLychrel, isSeed } func main() { max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive") iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter) var seeds []uint64 var related int var pals []uint64 for i := uint64(1); i <= *max; i++ { if l, s := Lychrel(i, *iter); l { if s { seeds = append(seeds, i) } else { related++ } if i == reverseUint64(i) { pals = append(pals, i) } } } fmt.Println(" Number of Lychrel seeds:", len(seeds)) fmt.Println(" Lychrel seeds:", seeds) fmt.Println(" Number of related:", related) fmt.Println("Number of Lychrel palindromes:", len(pals)) fmt.Println(" Lychrel palindromes:", pals) }
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)[::-1]) def split_roots_from_relateds(roots_and_relateds): roots = roots_and_relateds[::] i = 1 while i < len(roots): this = roots[i] if any(this.intersection(prev) for prev in roots[:i]): del roots[i] else: i += 1 root = [min(each_set) for each_set in roots] related = [min(each_set) for each_set in roots_and_relateds] related = [n for n in related if n not in root] return root, related def find_lychrel(maxn, max_reversions): 'Lychrel number generator' series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)] roots_and_relateds = [s for s in series if len(s) > max_reversions] return split_roots_from_relateds(roots_and_relateds) if __name__ == '__main__': maxn, reversion_limit = 10000, 500 print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds" % (maxn, reversion_limit)) lychrel, l_related = find_lychrel(maxn, reversion_limit) print(' Number of Lychrel numbers:', len(lychrel)) print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel)) print(' Number of Lychrel related:', len(l_related)) pals = [x for x in lychrel + l_related if x == reverse_int(x)] print(' Number of Lychrel palindromes:', len(pals)) print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
Keep all operations the same but rewrite the snippet in Python.
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(v.String()) result.SetString(s, 10) } else { v := new(big.Int).Set(v) digit := new(big.Int) result.SetUint64(0) for v.BitLen() > 0 { v.QuoRem(v, ten, digit) result.Mul(result, ten) result.Add(result, digit) } } } return result } func reverseUint64(v uint64) uint64 { var r uint64 for v > 0 { r *= 10 r += v % 10 v /= 10 } return r } func reverseString(s string) string { b := make([]byte, len(s)) for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 { b[i] = s[j] } return string(b) } var known = make(map[string]bool) func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) { v, r := new(big.Int).SetUint64(n), new(big.Int) reverseInt(v, r) seen := make(map[string]bool) isLychrel = true isSeed = true for i := iter; i > 0; i-- { str := v.String() if seen[str] { isLychrel = true break } if ans, ok := known[str]; ok { isLychrel = ans isSeed = false break } seen[str] = true v = v.Add(v, r) reverseInt(v, r) if v.Cmp(r) == 0 { isLychrel = false isSeed = false break } } for k := range seen { known[k] = isLychrel } return isLychrel, isSeed } func main() { max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive") iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter) var seeds []uint64 var related int var pals []uint64 for i := uint64(1); i <= *max; i++ { if l, s := Lychrel(i, *iter); l { if s { seeds = append(seeds, i) } else { related++ } if i == reverseUint64(i) { pals = append(pals, i) } } } fmt.Println(" Number of Lychrel seeds:", len(seeds)) fmt.Println(" Lychrel seeds:", seeds) fmt.Println(" Number of related:", related) fmt.Println("Number of Lychrel palindromes:", len(pals)) fmt.Println(" Lychrel palindromes:", pals) }
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)[::-1]) def split_roots_from_relateds(roots_and_relateds): roots = roots_and_relateds[::] i = 1 while i < len(roots): this = roots[i] if any(this.intersection(prev) for prev in roots[:i]): del roots[i] else: i += 1 root = [min(each_set) for each_set in roots] related = [min(each_set) for each_set in roots_and_relateds] related = [n for n in related if n not in root] return root, related def find_lychrel(maxn, max_reversions): 'Lychrel number generator' series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)] roots_and_relateds = [s for s in series if len(s) > max_reversions] return split_roots_from_relateds(roots_and_relateds) if __name__ == '__main__': maxn, reversion_limit = 10000, 500 print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds" % (maxn, reversion_limit)) lychrel, l_related = find_lychrel(maxn, reversion_limit) print(' Number of Lychrel numbers:', len(lychrel)) print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel)) print(' Number of Lychrel related:', len(l_related)) pals = [x for x in lychrel + l_related if x == reverse_int(x)] print(' Number of Lychrel palindromes:', len(pals)) print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "strconv" "strings" ) func main() { const nondecimal = "abcdef" c := 0 for i := int64(0); i <= 500; i++ { hex := strconv.FormatInt(i, 16) if strings.ContainsAny(nondecimal, hex) { fmt.Printf("%3d ", i) c++ if c%15 == 0 { fmt.Println() } } } fmt.Printf("\n\n%d such numbers found.\n", c) }
def p(n): return 9 < n and (9 < n % 16 or p(n // 16)) def main(): xs = [ str(n) for n in range(1, 1 + 500) if p(n) ] print(f'{len(xs)} matches for the predicate:\n') print( table(6)(xs) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
Generate an equivalent Python version of this Go code.
package main import ( "fmt" "strconv" "strings" ) func main() { const nondecimal = "abcdef" c := 0 for i := int64(0); i <= 500; i++ { hex := strconv.FormatInt(i, 16) if strings.ContainsAny(nondecimal, hex) { fmt.Printf("%3d ", i) c++ if c%15 == 0 { fmt.Println() } } } fmt.Printf("\n\n%d such numbers found.\n", c) }
def p(n): return 9 < n and (9 < n % 16 or p(n // 16)) def main(): xs = [ str(n) for n in range(1, 1 + 500) if p(n) ] print(f'{len(xs)} matches for the predicate:\n') print( table(6)(xs) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
Write a version of this Go function in Python with identical behavior.
package main import ( "fmt" "strings" ) type rng struct{ from, to int } type fn func(rngs *[]rng, n int) func (r rng) String() string { return fmt.Sprintf("%d-%d", r.from, r.to) } func rangesAdd(rngs []rng, n int) []rng { if len(rngs) == 0 { rngs = append(rngs, rng{n, n}) return rngs } for i, r := range rngs { if n < r.from-1 { rngs = append(rngs, rng{}) copy(rngs[i+1:], rngs[i:]) rngs[i] = rng{n, n} return rngs } else if n == r.from-1 { rngs[i] = rng{n, r.to} return rngs } else if n <= r.to { return rngs } else if n == r.to+1 { rngs[i] = rng{r.from, n} if i < len(rngs)-1 && (n == rngs[i+1].from || n+1 == rngs[i+1].from) { rngs[i] = rng{r.from, rngs[i+1].to} copy(rngs[i+1:], rngs[i+2:]) rngs[len(rngs)-1] = rng{} rngs = rngs[:len(rngs)-1] } return rngs } else if i == len(rngs)-1 { rngs = append(rngs, rng{n, n}) return rngs } } return rngs } func rangesRemove(rngs []rng, n int) []rng { if len(rngs) == 0 { return rngs } for i, r := range rngs { if n <= r.from-1 { return rngs } else if n == r.from && n == r.to { copy(rngs[i:], rngs[i+1:]) rngs[len(rngs)-1] = rng{} rngs = rngs[:len(rngs)-1] return rngs } else if n == r.from { rngs[i] = rng{n + 1, r.to} return rngs } else if n < r.to { rngs[i] = rng{r.from, n - 1} rngs = append(rngs, rng{}) copy(rngs[i+2:], rngs[i+1:]) rngs[i+1] = rng{n + 1, r.to} return rngs } else if n == r.to { rngs[i] = rng{r.from, n - 1} return rngs } } return rngs } func standard(rngs []rng) string { if len(rngs) == 0 { return "" } var sb strings.Builder for _, r := range rngs { sb.WriteString(fmt.Sprintf("%s,", r)) } s := sb.String() return s[:len(s)-1] } func main() { const add = 0 const remove = 1 fns := []fn{ func(prngs *[]rng, n int) { *prngs = rangesAdd(*prngs, n) fmt.Printf(" add %2d => %s\n", n, standard(*prngs)) }, func(prngs *[]rng, n int) { *prngs = rangesRemove(*prngs, n) fmt.Printf(" remove %2d => %s\n", n, standard(*prngs)) }, } var rngs []rng ops := [][2]int{{add, 77}, {add, 79}, {add, 78}, {remove, 77}, {remove, 78}, {remove, 79}} fmt.Printf("Start: %q\n", standard(rngs)) for _, op := range ops { fns[op[0]](&rngs, op[1]) } rngs = []rng{{1, 3}, {5, 5}} ops = [][2]int{{add, 1}, {remove, 4}, {add, 7}, {add, 8}, {add, 6}, {remove, 7}} fmt.Printf("\nStart: %q\n", standard(rngs)) for _, op := range ops { fns[op[0]](&rngs, op[1]) } rngs = []rng{{1, 5}, {10, 25}, {27, 30}} ops = [][2]int{{add, 26}, {add, 9}, {add, 7}, {remove, 26}, {remove, 9}, {remove, 7}} fmt.Printf("\nStart: %q\n", standard(rngs)) for _, op := range ops { fns[op[0]](&rngs, op[1]) } }
class Sequence(): def __init__(self, sequence_string): self.ranges = self.to_ranges(sequence_string) assert self.ranges == sorted(self.ranges), "Sequence order error" def to_ranges(self, txt): return [[int(x) for x in r.strip().split('-')] for r in txt.strip().split(',') if r] def remove(self, rem): ranges = self.ranges for i, r in enumerate(ranges): if r[0] <= rem <= r[1]: if r[0] == rem: if r[1] > rem: r[0] += 1 else: del ranges[i] elif r[1] == rem: if r[0] < rem: r[1] -= 1 else: del ranges[i] else: r[1], splitrange = rem - 1, [rem + 1, r[1]] ranges.insert(i + 1, splitrange) break if r[0] > rem: break return self def add(self, add): ranges = self.ranges for i, r in enumerate(ranges): if r[0] <= add <= r[1]: break elif r[0] - 1 == add: r[0] = add break elif r[1] + 1 == add: r[1] = add break elif r[0] > add: ranges.insert(i, [add, add]) break else: ranges.append([add, add]) return self return self.consolidate() def consolidate(self): "Combine overlapping ranges" ranges = self.ranges for this, that in zip(ranges, ranges[1:]): if this[1] + 1 >= that[0]: if this[1] >= that[1]: this[:], that[:] = [], this else: this[:], that[:] = [], [this[0], that[1]] ranges[:] = [r for r in ranges if r] return self def __repr__(self): rr = self.ranges return ",".join(f"{r[0]}-{r[1]}" for r in rr) def demo(opp_txt): by_line = opp_txt.strip().split('\n') start = by_line.pop(0) ex = Sequence(start.strip().split()[-1][1:-1]) lines = [line.strip().split() for line in by_line] opps = [((ex.add if word[0] == "add" else ex.remove), int(word[1])) for word in lines] print(f"Start: \"{ex}\"") for op, val in opps: print(f" {op.__name__:>6} {val:2} => {op(val)}") print() if __name__ == '__main__': demo() demo() demo()
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "log" big "github.com/ncw/gmp" "rcu" ) var zero = new(big.Int) var one = big.NewInt(1) var two = big.NewInt(2) func juggler(n int64) (int, int, *big.Int, int) { if n < 1 { log.Fatal("Starting value must be a positive integer.") } count := 0 maxCount := 0 a := big.NewInt(n) max := big.NewInt(n) tmp := new(big.Int) for a.Cmp(one) != 0 { if tmp.Rem(a, two).Cmp(zero) == 0 { a.Sqrt(a) } else { tmp.Mul(a, a) tmp.Mul(tmp, a) a.Sqrt(tmp) } count++ if a.Cmp(max) > 0 { max.Set(a) maxCount = count } } return count, maxCount, max, len(max.String()) } func main() { fmt.Println("n l[n] i[n] h[n]") fmt.Println("-----------------------------------") for n := int64(20); n < 40; n++ { count, maxCount, max, _ := juggler(n) cmax := rcu.Commatize(int(max.Int64())) fmt.Printf("%2d %2d %2d %s\n", n, count, maxCount, cmax) } fmt.Println() nums := []int64{ 113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963, } fmt.Println(" n l[n] i[n] d[n]") fmt.Println("-------------------------------------") for _, n := range nums { count, maxCount, _, digits := juggler(n) cn := rcu.Commatize(int(n)) fmt.Printf("%11s %3d %3d %s\n", cn, count, maxCount, rcu.Commatize(digits)) } }
from math import isqrt def juggler(k, countdig=True, maxiters=1000): m, maxj, maxjpos = k, k, 0 for i in range(1, maxiters): m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m) if m >= maxj: maxj, maxjpos = m, i if m == 1: print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}") return i print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations") print(" n l(n) i(n) h(n) or d(n)\n-------------------------------------------") for k in range(20, 40): juggler(k, False) for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]: juggler(k)
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "log" big "github.com/ncw/gmp" "rcu" ) var zero = new(big.Int) var one = big.NewInt(1) var two = big.NewInt(2) func juggler(n int64) (int, int, *big.Int, int) { if n < 1 { log.Fatal("Starting value must be a positive integer.") } count := 0 maxCount := 0 a := big.NewInt(n) max := big.NewInt(n) tmp := new(big.Int) for a.Cmp(one) != 0 { if tmp.Rem(a, two).Cmp(zero) == 0 { a.Sqrt(a) } else { tmp.Mul(a, a) tmp.Mul(tmp, a) a.Sqrt(tmp) } count++ if a.Cmp(max) > 0 { max.Set(a) maxCount = count } } return count, maxCount, max, len(max.String()) } func main() { fmt.Println("n l[n] i[n] h[n]") fmt.Println("-----------------------------------") for n := int64(20); n < 40; n++ { count, maxCount, max, _ := juggler(n) cmax := rcu.Commatize(int(max.Int64())) fmt.Printf("%2d %2d %2d %s\n", n, count, maxCount, cmax) } fmt.Println() nums := []int64{ 113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963, } fmt.Println(" n l[n] i[n] d[n]") fmt.Println("-------------------------------------") for _, n := range nums { count, maxCount, _, digits := juggler(n) cn := rcu.Commatize(int(n)) fmt.Printf("%11s %3d %3d %s\n", cn, count, maxCount, rcu.Commatize(digits)) } }
from math import isqrt def juggler(k, countdig=True, maxiters=1000): m, maxj, maxjpos = k, k, 0 for i in range(1, maxiters): m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m) if m >= maxj: maxj, maxjpos = m, i if m == 1: print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}") return i print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations") print(" n l(n) i(n) h(n) or d(n)\n-------------------------------------------") for k in range(20, 40): juggler(k, False) for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]: juggler(k)
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "github.com/fogleman/gg" "github.com/trubitsyn/go-lindenmayer" "log" "math" ) const twoPi = 2 * math.Pi var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h, theta float64 func main() { dc.SetRGB(0, 0, 1) dc.Clear() cx, cy = 10, height/2+5 h = 6 sys := lindenmayer.Lsystem{ Variables: []rune{'X'}, Constants: []rune{'F', '+', '-'}, Axiom: "F+XF+F+XF", Rules: []lindenmayer.Rule{ {"X", "XF-F+F-XF+F+XF-F+F-X"}, }, Angle: math.Pi / 2, } result := lindenmayer.Iterate(&sys, 5) operations := map[rune]func(){ 'F': func() { newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta) dc.LineTo(newX, newY) cx, cy = newX, newY }, '+': func() { theta = math.Mod(theta+sys.Angle, twoPi) }, '-': func() { theta = math.Mod(theta-sys.Angle, twoPi) }, } if err := lindenmayer.Process(result, operations); err != nil { log.Fatal(err) } operations['+']() operations['F']() dc.SetRGB255(255, 255, 0) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_square_curve.png") }
import matplotlib.pyplot as plt import math def nextPoint(x, y, angle): a = math.pi * angle / 180 x2 = (int)(round(x + (1 * math.cos(a)))) y2 = (int)(round(y + (1 * math.sin(a)))) return x2, y2 def expand(axiom, rules, level): for l in range(0, level): a2 = "" for c in axiom: if c in rules: a2 += rules[c] else: a2 += c axiom = a2 return axiom def draw_lsystem(axiom, rules, angle, iterations): xp = [1] yp = [1] direction = 0 for c in expand(axiom, rules, iterations): if c == "F": xn, yn = nextPoint(xp[-1], yp[-1], direction) xp.append(xn) yp.append(yn) elif c == "-": direction = direction - angle if direction < 0: direction = 360 + direction elif c == "+": direction = (direction + angle) % 360 plt.plot(xp, yp) plt.show() if __name__ == '__main__': s_axiom = "F+XF+F+XF" s_rules = {"X": "XF-F+F-XF+F+XF-F+F-X"} s_angle = 90 draw_lsystem(s_axiom, s_rules, s_angle, 3)
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "math" "sort" ) const adj = 0.0001 var primes = []uint64{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } func isSquareFree(x uint64) bool { for _, p := range primes { p2 := p * p if p2 > x { break } if x%p2 == 0 { return false } } return true } func iroot(x, p uint64) uint64 { return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj) } func ipow(x, p uint64) uint64 { prod := uint64(1) for p > 0 { if p&1 != 0 { prod *= x } p >>= 1 x *= x } return prod } func powerful(n, k uint64) []uint64 { set := make(map[uint64]bool) var f func(m, r uint64) f = func(m, r uint64) { if r < k { set[m] = true return } for v := uint64(1); v <= iroot(n/m, r); v++ { if r > k { if !isSquareFree(v) || gcd(m, v) != 1 { continue } } f(m*ipow(v, r), r-1) } } f(1, (1<<k)-1) list := make([]uint64, 0, len(set)) for key := range set { list = append(list, key) } sort.Slice(list, func(i, j int) bool { return list[i] < list[j] }) return list } func main() { power := uint64(10) for k := uint64(2); k <= 10; k++ { power *= 10 a := powerful(power, k) le := len(a) h, t := a[0:5], a[le-5:] fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t) } fmt.Println() for k := uint64(2); k <= 10; k++ { power := uint64(1) var counts []int for j := uint64(0); j < k+10; j++ { a := powerful(power, k) counts = append(counts, len(a)) power *= 10 } j := k + 10 fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts) } }
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) return res def kpowerful(k, upper_bound, count_only=True): ps = primepowers(k, upper_bound) def accu(i, ub): c = 0 if count_only else [] for p in ps[i]: u = ub//p if not u: break c += 1 if count_only else [p] for j in range(i + 1, len(ps)): if u < ps[j][0]: break c += accu(j, u) if count_only else [p*x for x in accu(j, u)] return c res = accu(0, upper_bound) return res if count_only else sorted(res) for k in range(2, 11): res = kpowerful(k, 10**k, count_only=False) print(f'{len(res)} {k}-powerfuls up to 10^{k}:', ' '.join(str(x) for x in res[:5]), '...', ' '.join(str(x) for x in res[-5:]) ) for k in range(2, 11): res = [kpowerful(k, 10**n) for n in range(k+10)] print(f'{k}-powerful up to 10^{k+10}:', ' '.join(str(x) for x in res))
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "fmt" "math" "sort" ) const adj = 0.0001 var primes = []uint64{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } func isSquareFree(x uint64) bool { for _, p := range primes { p2 := p * p if p2 > x { break } if x%p2 == 0 { return false } } return true } func iroot(x, p uint64) uint64 { return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj) } func ipow(x, p uint64) uint64 { prod := uint64(1) for p > 0 { if p&1 != 0 { prod *= x } p >>= 1 x *= x } return prod } func powerful(n, k uint64) []uint64 { set := make(map[uint64]bool) var f func(m, r uint64) f = func(m, r uint64) { if r < k { set[m] = true return } for v := uint64(1); v <= iroot(n/m, r); v++ { if r > k { if !isSquareFree(v) || gcd(m, v) != 1 { continue } } f(m*ipow(v, r), r-1) } } f(1, (1<<k)-1) list := make([]uint64, 0, len(set)) for key := range set { list = append(list, key) } sort.Slice(list, func(i, j int) bool { return list[i] < list[j] }) return list } func main() { power := uint64(10) for k := uint64(2); k <= 10; k++ { power *= 10 a := powerful(power, k) le := len(a) h, t := a[0:5], a[le-5:] fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t) } fmt.Println() for k := uint64(2); k <= 10; k++ { power := uint64(1) var counts []int for j := uint64(0); j < k+10; j++ { a := powerful(power, k) counts = append(counts, len(a)) power *= 10 } j := k + 10 fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts) } }
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) return res def kpowerful(k, upper_bound, count_only=True): ps = primepowers(k, upper_bound) def accu(i, ub): c = 0 if count_only else [] for p in ps[i]: u = ub//p if not u: break c += 1 if count_only else [p] for j in range(i + 1, len(ps)): if u < ps[j][0]: break c += accu(j, u) if count_only else [p*x for x in accu(j, u)] return c res = accu(0, upper_bound) return res if count_only else sorted(res) for k in range(2, 11): res = kpowerful(k, 10**k, count_only=False) print(f'{len(res)} {k}-powerfuls up to 10^{k}:', ' '.join(str(x) for x in res[:5]), '...', ' '.join(str(x) for x in res[-5:]) ) for k in range(2, 11): res = [kpowerful(k, 10**n) for n in range(k+10)] print(f'{k}-powerful up to 10^{k+10}:', ' '.join(str(x) for x in res))
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "log" "os" "os/exec" ) func reverseBytes(bytes []byte) { for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 { bytes[i], bytes[j] = bytes[j], bytes[i] } } func check(err error) { if err != nil { log.Fatal(err) } } func main() { in, err := os.Open("infile.dat") check(err) defer in.Close() out, err := os.Create("outfile.dat") check(err) record := make([]byte, 80) empty := make([]byte, 80) for { n, err := in.Read(record) if err != nil { if n == 0 { break } else { out.Close() log.Fatal(err) } } reverseBytes(record) out.Write(record) copy(record, empty) } out.Close() cmd := exec.Command("dd", "if=outfile.dat", "cbs=80", "conv=unblock") bytes, err := cmd.Output() check(err) fmt.Println(string(bytes)) }
infile = open('infile.dat', 'rb') outfile = open('outfile.dat', 'wb') while True: onerecord = infile.read(80) if len(onerecord) < 80: break onerecordreversed = bytes(reversed(onerecord)) outfile.write(onerecordreversed) infile.close() outfile.close()
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) count := 0 for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) { count++ fmt.Printf("%d: %s\n", count, s) } } }
import urllib.request urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() for word in wordList: if len(word)>5 and word[:3].lower()==word[-3:].lower(): print(word)
Convert this Go block to Python, preserving its control flow and logic.
package main import "fmt" var factors []int var inc = []int{4, 2, 4, 2, 4, 6, 2, 6} func primeFactors(n int) { factors = factors[:0] factors = append(factors, 2) last := 2 n /= 2 for n%3 == 0 { if last == 3 { factors = factors[:0] return } last = 3 factors = append(factors, 3) n /= 3 } for n%5 == 0 { if last == 5 { factors = factors[:0] return } last = 5 factors = append(factors, 5) n /= 5 } for k, i := 7, 0; k*k <= n; { if n%k == 0 { if last == k { factors = factors[:0] return } last = k factors = append(factors, k) n /= k } else { k += inc[i] i = (i + 1) % 8 } } if n > 1 { factors = append(factors, n) } } func main() { const limit = 5 var giuga []int for n := 6; len(giuga) < limit; n += 4 { primeFactors(n) if len(factors) > 2 { isGiuga := true for _, f := range factors { if (n/f-1)%f != 0 { isGiuga = false break } } if isGiuga { giuga = append(giuga, n) } } } fmt.Println("The first", limit, "Giuga numbers are:") fmt.Println(giuga) }
from math import sqrt def isGiuga(m): n = m f = 2 l = sqrt(n) while True: if n % f == 0: if ((m / f) - 1) % f != 0: return False n /= f if f > n: return True else: f += 1 if f > l: return False if __name__ == '__main__': n = 3 c = 0 print("The first 4 Giuga numbers are: ") while c < 4: if isGiuga(n): c += 1 print(n) n += 1
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo(out[i], divisor[0]) if coef := out[i]; coef.Sign() != 0 { var a big.Rat for j := 1; j < len(divisor); j++ { out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef)) } } } separator := len(out) - (len(divisor) - 1) return out[:separator], out[separator:] } func main() { N := []*big.Rat{ big.NewRat(1, 1), big.NewRat(-12, 1), big.NewRat(0, 1), big.NewRat(-42, 1)} D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)} Q, R := div(N, D) fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R) }
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef = out[i] if coef != 0: for j in xrange(1, len(divisor)): out[i + j] += -divisor[j] * coef separator = -(len(divisor)-1) return out[:separator], out[separator:] if __name__ == '__main__': print("POLYNOMIAL SYNTHETIC DIVISION") N = [1, -12, 0, -42] D = [1, -3] print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo(out[i], divisor[0]) if coef := out[i]; coef.Sign() != 0 { var a big.Rat for j := 1; j < len(divisor); j++ { out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef)) } } } separator := len(out) - (len(divisor) - 1) return out[:separator], out[separator:] } func main() { N := []*big.Rat{ big.NewRat(1, 1), big.NewRat(-12, 1), big.NewRat(0, 1), big.NewRat(-42, 1)} D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)} Q, R := div(N, D) fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R) }
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef = out[i] if coef != 0: for j in xrange(1, len(divisor)): out[i + j] += -divisor[j] * coef separator = -(len(divisor)-1) return out[:separator], out[separator:] if __name__ == '__main__': print("POLYNOMIAL SYNTHETIC DIVISION") N = [1, -12, 0, -42] D = [1, -3] print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
Change the following Go code into Python without altering its purpose.
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords)) for i, bword := range bwords { words[i] = string(bword) } count := 0 fmt.Println("The odd words with length > 4 in", wordList, "are:") for _, word := range words { rword := []rune(word) if len(rword) > 8 { var sb strings.Builder for i := 0; i < len(rword); i += 2 { sb.WriteRune(rword[i]) } s := sb.String() idx := sort.SearchStrings(words, s) if idx < len(words) && words[idx] == s { count = count + 1 fmt.Printf("%2d: %-12s -> %s\n", count, word, s) } } } }
import urllib.request urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() oddWordSet = set({}) for word in wordList: if len(word)>=9 and word[::2] in wordList: oddWordSet.add(word[::2]) [print(i) for i in sorted(oddWordSet)]
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords)) for i, bword := range bwords { words[i] = string(bword) } count := 0 fmt.Println("The odd words with length > 4 in", wordList, "are:") for _, word := range words { rword := []rune(word) if len(rword) > 8 { var sb strings.Builder for i := 0; i < len(rword); i += 2 { sb.WriteRune(rword[i]) } s := sb.String() idx := sort.SearchStrings(words, s) if idx < len(words) && words[idx] == s { count = count + 1 fmt.Printf("%2d: %-12s -> %s\n", count, word, s) } } } }
import urllib.request urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() oddWordSet = set({}) for word in wordList: if len(word)>=9 and word[::2] in wordList: oddWordSet.add(word[::2]) [print(i) for i in sorted(oddWordSet)]
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "io" "os" "strings" ) type nNode struct { name string children []nNode } type iNode struct { level int name string } func printNest(n nNode, level int, w io.Writer) { if level == 0 { fmt.Fprintln(w, "\n==Nest form==\n") } fmt.Fprintf(w, "%s%s\n", strings.Repeat(" ", level), n.name) for _, c := range n.children { fmt.Fprintf(w, "%s", strings.Repeat(" ", level+1)) printNest(c, level+1, w) } } func toNest(iNodes []iNode, start, level int, n *nNode) { if level == 0 { n.name = iNodes[0].name } for i := start + 1; i < len(iNodes); i++ { if iNodes[i].level == level+1 { c := nNode{iNodes[i].name, nil} toNest(iNodes, i, level+1, &c) n.children = append(n.children, c) } else if iNodes[i].level <= level { return } } } func printIndent(iNodes []iNode, w io.Writer) { fmt.Fprintln(w, "\n==Indent form==\n") for _, n := range iNodes { fmt.Fprintf(w, "%d %s\n", n.level, n.name) } } func toIndent(n nNode, level int, iNodes *[]iNode) { *iNodes = append(*iNodes, iNode{level, n.name}) for _, c := range n.children { toIndent(c, level+1, iNodes) } } func main() { n1 := nNode{"RosettaCode", nil} n2 := nNode{"rocks", []nNode{{"code", nil}, {"comparison", nil}, {"wiki", nil}}} n3 := nNode{"mocks", []nNode{{"trolling", nil}}} n1.children = append(n1.children, n2, n3) var sb strings.Builder printNest(n1, 0, &sb) s1 := sb.String() fmt.Print(s1) var iNodes []iNode toIndent(n1, 0, &iNodes) printIndent(iNodes, os.Stdout) var n nNode toNest(iNodes, 0, 0, &n) sb.Reset() printNest(n, 0, &sb) s2 := sb.String() fmt.Print(s2) fmt.Println("\nRound trip test satisfied? ", s1 == s2) }
from pprint import pprint as pp def to_indent(node, depth=0, flat=None): if flat is None: flat = [] if node: flat.append((depth, node[0])) for child in node[1]: to_indent(child, depth + 1, flat) return flat def to_nest(lst, depth=0, level=None): if level is None: level = [] while lst: d, name = lst[0] if d == depth: children = [] level.append((name, children)) lst.pop(0) elif d > depth: to_nest(lst, d, children) elif d < depth: return return level[0] if level else None if __name__ == '__main__': print('Start Nest format:') nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), ('mocks', [('trolling', [])])]) pp(nest, width=25) print('\n... To Indent format:') as_ind = to_indent(nest) pp(as_ind, width=25) print('\n... To Nest format:') as_nest = to_nest(as_ind) pp(as_nest, width=25) if nest != as_nest: print("Whoops round-trip issues")
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "io" "os" "strings" ) type nNode struct { name string children []nNode } type iNode struct { level int name string } func printNest(n nNode, level int, w io.Writer) { if level == 0 { fmt.Fprintln(w, "\n==Nest form==\n") } fmt.Fprintf(w, "%s%s\n", strings.Repeat(" ", level), n.name) for _, c := range n.children { fmt.Fprintf(w, "%s", strings.Repeat(" ", level+1)) printNest(c, level+1, w) } } func toNest(iNodes []iNode, start, level int, n *nNode) { if level == 0 { n.name = iNodes[0].name } for i := start + 1; i < len(iNodes); i++ { if iNodes[i].level == level+1 { c := nNode{iNodes[i].name, nil} toNest(iNodes, i, level+1, &c) n.children = append(n.children, c) } else if iNodes[i].level <= level { return } } } func printIndent(iNodes []iNode, w io.Writer) { fmt.Fprintln(w, "\n==Indent form==\n") for _, n := range iNodes { fmt.Fprintf(w, "%d %s\n", n.level, n.name) } } func toIndent(n nNode, level int, iNodes *[]iNode) { *iNodes = append(*iNodes, iNode{level, n.name}) for _, c := range n.children { toIndent(c, level+1, iNodes) } } func main() { n1 := nNode{"RosettaCode", nil} n2 := nNode{"rocks", []nNode{{"code", nil}, {"comparison", nil}, {"wiki", nil}}} n3 := nNode{"mocks", []nNode{{"trolling", nil}}} n1.children = append(n1.children, n2, n3) var sb strings.Builder printNest(n1, 0, &sb) s1 := sb.String() fmt.Print(s1) var iNodes []iNode toIndent(n1, 0, &iNodes) printIndent(iNodes, os.Stdout) var n nNode toNest(iNodes, 0, 0, &n) sb.Reset() printNest(n, 0, &sb) s2 := sb.String() fmt.Print(s2) fmt.Println("\nRound trip test satisfied? ", s1 == s2) }
from pprint import pprint as pp def to_indent(node, depth=0, flat=None): if flat is None: flat = [] if node: flat.append((depth, node[0])) for child in node[1]: to_indent(child, depth + 1, flat) return flat def to_nest(lst, depth=0, level=None): if level is None: level = [] while lst: d, name = lst[0] if d == depth: children = [] level.append((name, children)) lst.pop(0) elif d > depth: to_nest(lst, d, children) elif d < depth: return return level[0] if level else None if __name__ == '__main__': print('Start Nest format:') nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), ('mocks', [('trolling', [])])]) pp(nest, width=25) print('\n... To Indent format:') as_ind = to_indent(nest) pp(as_ind, width=25) print('\n... To Nest format:') as_nest = to_nest(as_ind) pp(as_nest, width=25) if nest != as_nest: print("Whoops round-trip issues")
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "strings" ) func main() { s := "abracadabra" ss := []byte(s) var ixs []int for ix, c := range s { if c == 'a' { ixs = append(ixs, ix) } } repl := "ABaCD" for i := 0; i < 5; i++ { ss[ixs[i]] = repl[i] } s = string(ss) s = strings.Replace(s, "b", "E", 1) s = strings.Replace(s, "r", "F", 2) s = strings.Replace(s, "F", "r", 1) fmt.Println(s) }
from collections import defaultdict rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}} def trstring(oldstring, repdict): seen, newchars = defaultdict(lambda:1, {}), [] for c in oldstring: i = seen[c] newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c) seen[c] += 1 return ''.join(newchars) print('abracadabra ->', trstring('abracadabra', rep))
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "strings" ) func main() { s := "abracadabra" ss := []byte(s) var ixs []int for ix, c := range s { if c == 'a' { ixs = append(ixs, ix) } } repl := "ABaCD" for i := 0; i < 5; i++ { ss[ixs[i]] = repl[i] } s = string(ss) s = strings.Replace(s, "b", "E", 1) s = strings.Replace(s, "r", "F", 2) s = strings.Replace(s, "F", "r", 1) fmt.Println(s) }
from collections import defaultdict rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}} def trstring(oldstring, repdict): seen, newchars = defaultdict(lambda:1, {}), [] for c in oldstring: i = seen[c] newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c) seen[c] += 1 return ''.join(newchars) print('abracadabra ->', trstring('abracadabra', rep))
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" "strings" ) func main() { limit := 2700 primes := rcu.Primes(limit) s := new(big.Int) for b := 2; b <= 36; b++ { var rPrimes []int for _, p := range primes { s.SetString(strings.Repeat("1", p), b) if s.ProbablyPrime(15) { rPrimes = append(rPrimes, p) } } fmt.Printf("Base %2d: %v\n", b, rPrimes) } }
from sympy import isprime for b in range(2, 17): print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
Generate an equivalent Python version of this Go code.
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" "strings" ) func main() { limit := 2700 primes := rcu.Primes(limit) s := new(big.Int) for b := 2; b <= 36; b++ { var rPrimes []int for _, p := range primes { s.SetString(strings.Repeat("1", p), b) if s.ProbablyPrime(15) { rPrimes = append(rPrimes, p) } } fmt.Printf("Base %2d: %v\n", b, rPrimes) } }
from sympy import isprime for b in range(2, 17): print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/big" ) func main() { zero := big.NewInt(0) one := big.NewInt(1) for k := int64(2); k <= 10; k += 2 { bk := big.NewInt(k) fmt.Println("The first 50 Curzon numbers using a base of", k, ":") count := 0 n := int64(1) pow := big.NewInt(k) z := new(big.Int) var curzon50 []int64 for { z.Add(pow, one) d := k*n + 1 bd := big.NewInt(d) if z.Rem(z, bd).Cmp(zero) == 0 { if count < 50 { curzon50 = append(curzon50, n) } count++ if count == 50 { for i := 0; i < len(curzon50); i++ { fmt.Printf("%4d ", curzon50[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Print("\nOne thousandth: ") } if count == 1000 { fmt.Println(n) break } } n++ pow.Mul(pow, bk) } fmt.Println() } }
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '') print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math/big" ) func main() { zero := big.NewInt(0) one := big.NewInt(1) for k := int64(2); k <= 10; k += 2 { bk := big.NewInt(k) fmt.Println("The first 50 Curzon numbers using a base of", k, ":") count := 0 n := int64(1) pow := big.NewInt(k) z := new(big.Int) var curzon50 []int64 for { z.Add(pow, one) d := k*n + 1 bd := big.NewInt(d) if z.Rem(z, bd).Cmp(zero) == 0 { if count < 50 { curzon50 = append(curzon50, n) } count++ if count == 50 { for i := 0; i < len(curzon50); i++ { fmt.Printf("%4d ", curzon50[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Print("\nOne thousandth: ") } if count == 1000 { fmt.Println(n) break } } n++ pow.Mul(pow, bk) } fmt.Println() } }
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '') print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
Write the same code in Python as shown below in Go.
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" ) const ( prec = 256 ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" ) func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec).SetInt64(d) t.Sqrt(t) t.Mul(pi, t) return bigfloat.Exp(t) } func main() { fmt.Println("Ramanujan's constant to 32 decimal places is:") fmt.Printf("%.32f\n", q(163)) heegners := [4][2]int64{ {19, 96}, {43, 960}, {67, 5280}, {163, 640320}, } fmt.Println("\nHeegner numbers yielding 'almost' integers:") t := new(big.Float).SetPrec(prec) for _, h := range heegners { qh := q(h[0]) c := h[1]*h[1]*h[1] + 744 t.SetInt64(c) t.Sub(t, qh) fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t) } }
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" ) const ( prec = 256 ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" ) func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec).SetInt64(d) t.Sqrt(t) t.Mul(pi, t) return bigfloat.Exp(t) } func main() { fmt.Println("Ramanujan's constant to 32 decimal places is:") fmt.Printf("%.32f\n", q(163)) heegners := [4][2]int64{ {19, 96}, {43, 960}, {67, 5280}, {163, 640320}, } fmt.Println("\nHeegner numbers yielding 'almost' integers:") t := new(big.Float).SetPrec(prec) for _, h := range heegners { qh := q(h[0]) c := h[1]*h[1]*h[1] + 744 t.SetInt64(c) t.Sub(t, qh) fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t) } }
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" ) const ( prec = 256 ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" ) func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec).SetInt64(d) t.Sqrt(t) t.Mul(pi, t) return bigfloat.Exp(t) } func main() { fmt.Println("Ramanujan's constant to 32 decimal places is:") fmt.Printf("%.32f\n", q(163)) heegners := [4][2]int64{ {19, 96}, {43, 960}, {67, 5280}, {163, 640320}, } fmt.Println("\nHeegner numbers yielding 'almost' integers:") t := new(big.Float).SetPrec(prec) for _, h := range heegners { qh := q(h[0]) c := h[1]*h[1]*h[1] + 744 t.SetInt64(c) t.Sub(t, qh) fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t) } }
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func (e example) CallMethod(n string) int { if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() { return int(m.Call(nil)[0].Int()) } fmt.Println("Unknown method:", n) return 0 } func main() { var e example fmt.Println(e.CallMethod("Foo")) fmt.Println(e.CallMethod("Bar")) }
class Example(object): def foo(self): print("this is foo") def bar(self): print("this is bar") def __getattr__(self, name): def method(*args): print("tried to handle unknown method " + name) if args: print("it had arguments: " + str(args)) return method example = Example() example.foo() example.bar() example.grill() example.ding("dong")
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "strings" ) type dict map[string]bool func newDict(words ...string) dict { d := dict{} for _, w := range words { d[w] = true } return d } func (d dict) wordBreak(s string) (broken []string, ok bool) { if s == "" { return nil, true } type prefix struct { length int broken []string } bp := []prefix{{0, nil}} for end := 1; end <= len(s); end++ { for i := len(bp) - 1; i >= 0; i-- { w := s[bp[i].length:end] if d[w] { b := append(bp[i].broken, w) if end == len(s) { return b, true } bp = append(bp, prefix{end, b}) break } } } return nil, false } func main() { d := newDict("a", "bc", "abc", "cd", "b") for _, s := range []string{"abcd", "abbc", "abcbcd", "acdbc", "abcdd"} { if b, ok := d.wordBreak(s); ok { fmt.Printf("%s: %s\n", s, strings.Join(b, " ")) } else { fmt.Println("can't break") } } }
from itertools import (chain) def stringParse(lexicon): return lambda s: Node(s)( tokenTrees(lexicon)(s) ) def tokenTrees(wds): def go(s): return [Node(s)([])] if s in wds else ( concatMap(nxt(s))(wds) ) def nxt(s): return lambda w: parse( w, go(s[len(w):]) ) if s.startswith(w) else [] def parse(w, xs): return [Node(w)(xs)] if xs else xs return lambda s: go(s) def showParse(tree): def showTokens(x): xs = x['nest'] return ' ' + x['root'] + (showTokens(xs[0]) if xs else '') parses = tree['nest'] return tree['root'] + ':\n' + ( '\n'.join( map(showTokens, parses) ) if parses else ' ( Not parseable in terms of these words )' ) def main(): lexicon = 'a bc abc cd b'.split() testSamples = 'abcd abbc abcbcd acdbc abcdd'.split() print(unlines( map( showParse, map( stringParse(lexicon), testSamples ) ) )) def Node(v): return lambda xs: {'type': 'Node', 'root': v, 'nest': xs} def concatMap(f): return lambda xs: list( chain.from_iterable(map(f, xs)) ) def unlines(xs): return '\n'.join(xs) if __name__ == '__main__': main()
Write a version of this Go function in Python with identical behavior.
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits; k++ { var s []int for _, p := range primes { if p >= pow*10 { break } if p > pow { s = append(s, p) } } for i := 0; i < len(s); i++ { for j := i; j < len(s); j++ { prod := s[i] * s[j] if prod < limit { if countOnly { count++ } else { brilliant = append(brilliant, prod) } } else { if next > prod { next = prod } break } } } pow *= 10 } if countOnly { return res{count, next} } return res{brilliant, next} } func main() { fmt.Println("First 100 brilliant numbers:") brilliant := getBrilliant(2, 10000, false).bc.([]int) sort.Ints(brilliant) brilliant = brilliant[0:100] for i := 0; i < len(brilliant); i++ { fmt.Printf("%4d ", brilliant[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() for k := 1; k <= 13; k++ { limit := int(math.Pow(10, float64(k))) r := getBrilliant(k, limit, true) total := r.bc.(int) next := r.next climit := rcu.Commatize(limit) ctotal := rcu.Commatize(total + 1) cnext := rcu.Commatize(next) fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext) } }
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n + 1)//2 continue i = np.searchsorted(blk, root, 'left') i += blk[i]*blk[i] < lb if not i: return blk[0]*blk[0], pos p = blk[:i + 1] q = (lb - 1)//p idx = np.searchsorted(blk, q, 'right') sel = idx < n p, idx = p[sel], idx[sel] q = blk[idx] sel = q >= p p, q, idx = p[sel], q[sel], idx[sel] pos += np.sum(idx - np.arange(len(idx))) return np.min(p*q), pos res = [] p = 0 for i in range(100): p, _ = smallest_brilliant(p + 1) res.append(p) print(f'first 100 are {res}') for i in range(max_order*2): thresh = 10**i p, pos = smallest_brilliant(thresh) print(f'Above 10^{i:2d}: {p:20d} at
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits; k++ { var s []int for _, p := range primes { if p >= pow*10 { break } if p > pow { s = append(s, p) } } for i := 0; i < len(s); i++ { for j := i; j < len(s); j++ { prod := s[i] * s[j] if prod < limit { if countOnly { count++ } else { brilliant = append(brilliant, prod) } } else { if next > prod { next = prod } break } } } pow *= 10 } if countOnly { return res{count, next} } return res{brilliant, next} } func main() { fmt.Println("First 100 brilliant numbers:") brilliant := getBrilliant(2, 10000, false).bc.([]int) sort.Ints(brilliant) brilliant = brilliant[0:100] for i := 0; i < len(brilliant); i++ { fmt.Printf("%4d ", brilliant[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() for k := 1; k <= 13; k++ { limit := int(math.Pow(10, float64(k))) r := getBrilliant(k, limit, true) total := r.bc.(int) next := r.next climit := rcu.Commatize(limit) ctotal := rcu.Commatize(total + 1) cnext := rcu.Commatize(next) fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext) } }
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n + 1)//2 continue i = np.searchsorted(blk, root, 'left') i += blk[i]*blk[i] < lb if not i: return blk[0]*blk[0], pos p = blk[:i + 1] q = (lb - 1)//p idx = np.searchsorted(blk, q, 'right') sel = idx < n p, idx = p[sel], idx[sel] q = blk[idx] sel = q >= p p, q, idx = p[sel], q[sel], idx[sel] pos += np.sum(idx - np.arange(len(idx))) return np.min(p*q), pos res = [] p = 0 for i in range(100): p, _ = smallest_brilliant(p + 1) res.append(p) print(f'first 100 are {res}') for i in range(max_order*2): thresh = 10**i p, pos = smallest_brilliant(thresh) print(f'Above 10^{i:2d}: {p:20d} at