Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } } func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } } func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } } func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } } var draw map[int]func() func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() }, 10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() }, 100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() }, 1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } } func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() } func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
def _init(): "digit sections for forming numbers" digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f"{int(n):04}"][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])), ''.join((_digits[0][ 0], '┃', _digits[0][ 0])), ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] if __name__ == '__main__': for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
Maintain the same structure and functionality when rewriting this code in Python.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } } func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } } func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } } func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } } var draw map[int]func() func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() }, 10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() }, 100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() }, 1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } } func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() } func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
def _init(): "digit sections for forming numbers" digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f"{int(n):04}"][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])), ''.join((_digits[0][ 0], '┃', _digits[0][ 0])), ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] if __name__ == '__main__': for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/big" ) func main() { x := big.NewInt(2) x = x.Exp(big.NewInt(3), x, nil) x = x.Exp(big.NewInt(4), x, nil) x = x.Exp(big.NewInt(5), x, nil) str := x.String() fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n", len(str), str[:20], str[len(str)-20:], ) }
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } func drawSphere(r int, k, amb float64, dir *vector) *image.Gray { w, h := r*4, r*3 img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2)) vec := new(vector) for x := -r; x < r; x++ { for y := -r; y < r; y++ { if z := r*r - x*x - y*y; z >= 0 { vec[0] = float64(x) vec[1] = float64(y) vec[2] = math.Sqrt(float64(z)) normalize(vec) s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } } return img } func main() { dir := &vector{-30, -30, 50} normalize(dir) img := drawSphere(200, 1.5, .2, dir) f, err := os.Create("sphere.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
import math shades = ('.',':','!','*','o','e','&',' def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(math.ceil(r)+1)): x = i + 0.5 line = '' for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)): y = j/2 + 0.5 if x*x + y*y <= r*r: vec = normalize((x,y,math.sqrt(r*r - x*x - y*y))) b = dot(light,vec)**k + ambient intensity = int((1-b)*(len(shades)-1)) line += shades[intensity] if 0 <= intensity < len(shades) else shades[0] else: line += ' ' print(line) light = normalize((30,30,-50)) draw_sphere(20,4,0.1, light) draw_sphere(10,2,0.4, light)
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } func drawSphere(r int, k, amb float64, dir *vector) *image.Gray { w, h := r*4, r*3 img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2)) vec := new(vector) for x := -r; x < r; x++ { for y := -r; y < r; y++ { if z := r*r - x*x - y*y; z >= 0 { vec[0] = float64(x) vec[1] = float64(y) vec[2] = math.Sqrt(float64(z)) normalize(vec) s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } } return img } func main() { dir := &vector{-30, -30, 50} normalize(dir) img := drawSphere(200, 1.5, .2, dir) f, err := os.Create("sphere.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
import math shades = ('.',':','!','*','o','e','&',' def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(math.ceil(r)+1)): x = i + 0.5 line = '' for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)): y = j/2 + 0.5 if x*x + y*y <= r*r: vec = normalize((x,y,math.sqrt(r*r - x*x - y*y))) b = dot(light,vec)**k + ambient intensity = int((1-b)*(len(shades)-1)) line += shades[intensity] if 0 <= intensity < len(shades) else shades[0] else: line += ' ' print(line) light = normalize((30,30,-50)) draw_sphere(20,4,0.1, light) draw_sphere(10,2,0.4, light)
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "bufio" "bytes" "errors" "fmt" "io" "os" ) var index map[string][]int var indexed []doc type doc struct { file string title string } func main() { index = make(map[string][]int) if err := indexDir("docs"); err != nil { fmt.Println(err) return } ui() } func indexDir(dir string) error { df, err := os.Open(dir) if err != nil { return err } fis, err := df.Readdir(-1) if err != nil { return err } if len(fis) == 0 { return errors.New(fmt.Sprintf("no files in %s", dir)) } indexed := 0 for _, fi := range fis { if !fi.IsDir() { if indexFile(dir + "/" + fi.Name()) { indexed++ } } } return nil } func indexFile(fn string) bool { f, err := os.Open(fn) if err != nil { fmt.Println(err) return false } x := len(indexed) indexed = append(indexed, doc{fn, fn}) pdoc := &indexed[x] r := bufio.NewReader(f) lines := 0 for { b, isPrefix, err := r.ReadLine() switch { case err == io.EOF: return true case err != nil: fmt.Println(err) return true case isPrefix: fmt.Printf("%s: unexpected long line\n", fn) return true case lines < 20 && bytes.HasPrefix(b, []byte("Title:")): pdoc.title = string(b[7:]) } wordLoop: for _, bword := range bytes.Fields(b) { bword := bytes.Trim(bword, ".,-~?!\"'`;:()<>[]{}\\|/=_+*&^%$#@") if len(bword) > 0 { word := string(bword) dl := index[word] for _, d := range dl { if d == x { continue wordLoop } } index[word] = append(dl, x) } } } return true } func ui() { fmt.Println(len(index), "words indexed in", len(indexed), "files") fmt.Println("enter single words to search for") fmt.Println("enter a blank line when done") var word string for { fmt.Print("search word: ") wc, _ := fmt.Scanln(&word) if wc == 0 { return } switch dl := index[word]; len(dl) { case 0: fmt.Println("no match") case 1: fmt.Println("one match:") fmt.Println(" ", indexed[dl[0]].file, indexed[dl[0]].title) default: fmt.Println(len(dl), "matches:") for _, d := range dl { fmt.Println(" ", indexed[d].file, indexed[d].title) } } } }
from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for txtfile in glob(fileglob): with open(txtfile, 'r') as f: txt = f.read().split() words |= set(txt) texts[txtfile.split('\\')[-1]] = txt return texts, words def termsearch(terms): return reduce(set.intersection, (invindex[term] for term in terms), set(texts.keys())) texts, words = parsetexts() print('\nTexts') pp(texts) print('\nWords') pp(sorted(words)) invindex = {word:set(txt for txt, wrds in texts.items() if word in wrds) for word in words} print('\nInverted Index') pp({k:sorted(v) for k,v in invindex.items()}) terms = ["what", "is", "it"] print('\nTerm Search for: ' + repr(terms)) pp(sorted(termsearch(terms)))
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "math/big" ) var m, n, z big.Int func init() { m.SetString("2562047788015215500854906332309589561", 10) n.SetString("6795454494268282920431565661684282819", 10) } func main() { fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n)) }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "math/big" ) var m, n, z big.Int func init() { m.SetString("2562047788015215500854906332309589561", 10) n.SetString("6795454494268282920431565661684282819", 10) } func main() { fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n)) }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Generate an equivalent Python version of this Go code.
package main import ( "fmt" "github.com/jbarham/primegen" "math" "math/big" "math/rand" "sort" "time" ) const ( maxCurves = 10000 maxRnd = 1 << 31 maxB1 = uint64(43 * 1e7) maxB2 = uint64(2 * 1e10) ) var ( zero = big.NewInt(0) one = big.NewInt(1) two = big.NewInt(2) three = big.NewInt(3) four = big.NewInt(4) five = big.NewInt(5) ) func pollardRho(n *big.Int) (*big.Int, error) { g := func(x, n *big.Int) *big.Int { x2 := new(big.Int) x2.Mul(x, x) x2.Add(x2, one) return x2.Mod(x2, n) } x, y, d := new(big.Int).Set(two), new(big.Int).Set(two), new(big.Int).Set(one) t, z := new(big.Int), new(big.Int).Set(one) count := 0 for { x = g(x, n) y = g(g(y, n), n) t.Sub(x, y) t.Abs(t) t.Mod(t, n) z.Mul(z, t) count++ if count == 100 { d.GCD(nil, nil, z, n) if d.Cmp(one) != 0 { break } z.Set(one) count = 0 } } if d.Cmp(n) == 0 { return nil, fmt.Errorf("Pollard's rho failure") } return d, nil } func getPrimes(n uint64) []uint64 { pg := primegen.New() var primes []uint64 for { prime := pg.Next() if prime < n { primes = append(primes, prime) } else { break } } return primes } func computeBounds(n *big.Int) (uint64, uint64) { le := len(n.String()) var b1, b2 uint64 switch { case le <= 30: b1, b2 = 2000, 147396 case le <= 40: b1, b2 = 11000, 1873422 case le <= 50: b1, b2 = 50000, 12746592 case le <= 60: b1, b2 = 250000, 128992510 case le <= 70: b1, b2 = 1000000, 1045563762 case le <= 80: b1, b2 = 3000000, 5706890290 default: b1, b2 = maxB1, maxB2 } return b1, b2 } func pointAdd(px, pz, qx, qz, rx, rz, n *big.Int) (*big.Int, *big.Int) { t := new(big.Int).Sub(px, pz) u := new(big.Int).Add(qx, qz) u.Mul(t, u) t.Add(px, pz) v := new(big.Int).Sub(qx, qz) v.Mul(t, v) upv := new(big.Int).Add(u, v) umv := new(big.Int).Sub(u, v) x := new(big.Int).Mul(upv, upv) x.Mul(x, rz) if x.Cmp(n) >= 0 { x.Mod(x, n) } z := new(big.Int).Mul(umv, umv) z.Mul(z, rx) if z.Cmp(n) >= 0 { z.Mod(z, n) } return x, z } func pointDouble(px, pz, n, a24 *big.Int) (*big.Int, *big.Int) { u2 := new(big.Int).Add(px, pz) u2.Mul(u2, u2) v2 := new(big.Int).Sub(px, pz) v2.Mul(v2, v2) t := new(big.Int).Sub(u2, v2) x := new(big.Int).Mul(u2, v2) if x.Cmp(n) >= 0 { x.Mod(x, n) } z := new(big.Int).Mul(a24, t) z.Add(v2, z) z.Mul(t, z) if z.Cmp(n) >= 0 { z.Mod(z, n) } return x, z } func scalarMultiply(k, px, pz, n, a24 *big.Int) (*big.Int, *big.Int) { sk := fmt.Sprintf("%b", k) lk := len(sk) qx := new(big.Int).Set(px) qz := new(big.Int).Set(pz) rx, rz := pointDouble(px, pz, n, a24) for i := 1; i < lk; i++ { if sk[i] == '1' { qx, qz = pointAdd(rx, rz, qx, qz, px, pz, n) rx, rz = pointDouble(rx, rz, n, a24) } else { rx, rz = pointAdd(qx, qz, rx, rz, px, pz, n) qx, qz = pointDouble(qx, qz, n, a24) } } return qx, qz } func ecm(n *big.Int) (*big.Int, error) { if n.Cmp(one) == 0 || n.ProbablyPrime(10) { return n, nil } b1, b2 := computeBounds(n) dd := uint64(math.Sqrt(float64(b2))) beta := make([]*big.Int, dd+1) for i := 0; i < len(beta); i++ { beta[i] = new(big.Int) } s := make([]*big.Int, 2*dd+2) for i := 0; i < len(s); i++ { s[i] = new(big.Int) } curves := 0 logB1 := math.Log(float64(b1)) primes := getPrimes(b2) numPrimes := len(primes) idxB1 := sort.Search(len(primes), func(i int) bool { return primes[i] >= b1 }) k := big.NewInt(1) for i := 0; i < idxB1; i++ { p := primes[i] bp := new(big.Int).SetUint64(p) t := uint64(logB1 / math.Log(float64(p))) bt := new(big.Int).SetUint64(t) bt.Exp(bp, bt, nil) k.Mul(k, bt) } g := big.NewInt(1) for (g.Cmp(one) == 0 || g.Cmp(n) == 0) && curves <= maxCurves { curves++ st := int64(6 + rand.Intn(maxRnd-5)) sigma := big.NewInt(st) u := new(big.Int).Mul(sigma, sigma) u.Sub(u, five) u.Mod(u, n) v := new(big.Int).Mul(four, sigma) v.Mod(v, n) vmu := new(big.Int).Sub(v, u) a := new(big.Int).Mul(vmu, vmu) a.Mul(a, vmu) t := new(big.Int).Mul(three, u) t.Add(t, v) a.Mul(a, t) t.Mul(four, u) t.Mul(t, u) t.Mul(t, u) t.Mul(t, v) a.Quo(a, t) a.Sub(a, two) a.Mod(a, n) a24 := new(big.Int).Add(a, two) a24.Quo(a24, four) px := new(big.Int).Mul(u, u) px.Mul(px, u) t.Mul(v, v) t.Mul(t, v) px.Quo(px, t) px.Mod(px, n) pz := big.NewInt(1) qx, qz := scalarMultiply(k, px, pz, n, a24) g.GCD(nil, nil, n, qz) if g.Cmp(one) != 0 && g.Cmp(n) != 0 { return g, nil } s[1], s[2] = pointDouble(qx, qz, n, a24) s[3], s[4] = pointDouble(s[1], s[2], n, a24) beta[1].Mul(s[1], s[2]) beta[1].Mod(beta[1], n) beta[2].Mul(s[3], s[4]) beta[2].Mod(beta[2], n) for d := uint64(3); d <= dd; d++ { d2 := 2 * d s[d2-1], s[d2] = pointAdd(s[d2-3], s[d2-2], s[1], s[2], s[d2-5], s[d2-4], n) beta[d].Mul(s[d2-1], s[d2]) beta[d].Mod(beta[d], n) } g.SetUint64(1) b := new(big.Int).SetUint64(b1 - 1) rx, rz := scalarMultiply(b, qx, qz, n, a24) t.Mul(two, new(big.Int).SetUint64(dd)) t.Sub(b, t) tx, tz := scalarMultiply(t, qx, qz, n, a24) q, step := idxB1, 2*dd for r := b1 - 1; r < b2; r += step { alpha := new(big.Int).Mul(rx, rz) alpha.Mod(alpha, n) limit := r + step for q < numPrimes && primes[q] <= limit { d := (primes[q] - r) / 2 t := new(big.Int).Sub(rx, s[2*d-1]) f := new(big.Int).Add(rz, s[2*d]) f.Mul(t, f) f.Sub(f, alpha) f.Add(f, beta[d]) g.Mul(g, f) g.Mod(g, n) q++ } trx := new(big.Int).Set(rx) trz := new(big.Int).Set(rz) rx, rz = pointAdd(rx, rz, s[2*dd-1], s[2*dd], tx, tz, n) tx.Set(trx) tz.Set(trz) } g.GCD(nil, nil, n, g) } if curves > maxCurves { return zero, fmt.Errorf("maximum curves exceeded before a factor was found") } return g, nil } func primeFactors(n *big.Int) ([]*big.Int, error) { var res []*big.Int if n.ProbablyPrime(10) { return append(res, n), nil } le := len(n.String()) var factor1 *big.Int var err error if le > 20 && le <= 60 { factor1, err = ecm(n) } else { factor1, err = pollardRho(n) } if err != nil { return nil, err } if !factor1.ProbablyPrime(10) { return nil, fmt.Errorf("first factor is not prime") } factor2 := new(big.Int) factor2.Quo(n, factor1) if !factor2.ProbablyPrime(10) { return nil, fmt.Errorf("%d (second factor is not prime)", factor1) } return append(res, factor1, factor2), nil } func fermatNumbers(n int) (res []*big.Int) { f := new(big.Int).SetUint64(3) for i := 0; i < n; i++ { t := new(big.Int).Set(f) res = append(res, t) f.Sub(f, one) f.Mul(f, f) f.Add(f, one) } return res } func main() { start := time.Now() rand.Seed(time.Now().UnixNano()) fns := fermatNumbers(10) fmt.Println("First 10 Fermat numbers:") for i, f := range fns { fmt.Printf("F%c = %d\n", 0x2080+i, f) } fmt.Println("\nFactors of first 10 Fermat numbers:") for i, f := range fns { fmt.Printf("F%c = ", 0x2080+i) factors, err := primeFactors(f) if err != nil { fmt.Println(err) continue } for _, factor := range factors { fmt.Printf("%d ", factor) } if len(factors) == 1 { fmt.Println("- prime") } else { fmt.Println() } } fmt.Printf("\nTook %s\n", time.Since(start)) }
def factors(x): factors = [] i = 2 s = int(x ** 0.5) while i < s: if x % i == 0: factors.append(i) x = int(x / i) s = int(x ** 0.5) i += 1 factors.append(x) return factors print("First 10 Fermat numbers:") for i in range(10): fermat = 2 ** 2 ** i + 1 print("F{} = {}".format(chr(i + 0x2080) , fermat)) print("\nFactors of first few Fermat numbers:") for i in range(10): fermat = 2 ** 2 ** i + 1 fac = factors(fermat) if len(fac) == 1: print("F{} -> IS PRIME".format(chr(i + 0x2080))) else: print("F{} -> FACTORS: {}".format(chr(i + 0x2080), fac))
Write the same code in Python as shown below in Go.
package main import "fmt" import "math/rand" import "time" func main() { rand.Seed(time.Now().UnixNano()) for { a := rand.Intn(20) fmt.Println(a) if a == 10 { break } b := rand.Intn(20) fmt.Println(b) } }
from random import randrange while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "os" ) func main() { lp0, err := os.Create("/dev/lp0") if err != nil { panic(err) } defer lp0.Close() fmt.Fprintln(lp0, "Hello World!") }
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "os" ) func main() { lp0, err := os.Create("/dev/lp0") if err != nil { panic(err) } defer lp0.Close() fmt.Fprintln(lp0, "Hello World!") }
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import "fmt" func maxl(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := 0; i < len(hm);i++{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func maxr(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := len(hm) - 1 ; i >= 0;i--{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func min(a,b []int) []int { res := make([]int,len(a)) for i := 0; i < len(a);i++{ if a[i] >= b[i]{ res[i] = b[i] }else { res[i] = a[i] } } return res } func diff(hm, min []int) []int { res := make([]int,len(hm)) for i := 0; i < len(hm);i++{ if min[i] > hm[i]{ res[i] = min[i] - hm[i] } } return res } func sum(a []int) int { res := 0 for i := 0; i < len(a);i++{ res += a[i] } return res } func waterCollected(hm []int) int { maxr := maxr(hm) maxl := maxl(hm) min := min(maxr,maxl) diff := diff(hm,min) sum := sum(diff) return sum } func main() { fmt.Println(waterCollected([]int{1, 5, 3, 7, 2})) fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2})) fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1})) fmt.Println(waterCollected([]int{5, 5, 5, 5})) fmt.Println(waterCollected([]int{5, 6, 7, 8})) fmt.Println(waterCollected([]int{8, 7, 7, 6})) fmt.Println(waterCollected([]int{6, 7, 10, 7, 6})) }
def water_collected(tower): N = len(tower) highest_left = [0] + [max(tower[:n]) for n in range(1,N)] highest_right = [max(tower[n:N]) for n in range(1,N)] + [0] water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0) for n in range(N)] print("highest_left: ", highest_left) print("highest_right: ", highest_right) print("water_level: ", water_level) print("tower_level: ", tower) print("total_water: ", sum(water_level)) print("") return sum(water_level) towers = [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] [water_collected(tower) for tower in towers]
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "rcu" "sort" "strconv" ) func combinations(a []int, k int) [][]int { n := len(a) c := make([]int, k) var combs [][]int var combine func(start, end, index int) combine = func(start, end, index int) { if index == k { t := make([]int, len(c)) copy(t, c) combs = append(combs, t) return } for i := start; i <= end && end-i+1 >= k-index; i++ { c[index] = a[i] combine(i+1, end, index+1) } } combine(0, n-1, 0) return combs } func powerset(a []int) (res [][]int) { if len(a) == 0 { return } for i := 1; i <= len(a); i++ { res = append(res, combinations(a, i)...) } return } func main() { ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}) var descPrimes []int for i := 1; i < len(ps); i++ { s := "" for _, e := range ps[i] { s += string(e + '0') } p, _ := strconv.Atoi(s) if rcu.IsPrime(p) { descPrimes = append(descPrimes, p) } } sort.Ints(descPrimes) fmt.Println("There are", len(descPrimes), "descending primes, namely:") for i := 0; i < len(descPrimes); i++ { fmt.Printf("%8d ", descPrimes[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() }
from sympy import isprime def descending(xs=range(10)): for x in xs: yield x yield from descending(x*10 + d for d in range(x%10)) for i, p in enumerate(sorted(filter(isprime, descending()))): print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n') print()
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "math" ) func sieve(limit uint64) []uint64 { primes := []uint64{2} c := make([]bool, limit+1) p := uint64(3) for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } for i := uint64(3); i <= limit; i += 2 { if !c[i] { primes = append(primes, i) } } return primes } func squareFree(from, to uint64) (results []uint64) { limit := uint64(math.Sqrt(float64(to))) primes := sieve(limit) outer: for i := from; i <= to; i++ { for _, p := range primes { p2 := p * p if p2 > i { break } if i%p2 == 0 { continue outer } } results = append(results, i) } return } const trillion uint64 = 1000000000000 func main() { fmt.Println("Square-free integers from 1 to 145:") sf := squareFree(1, 145) for i := 0; i < len(sf); i++ { if i > 0 && i%20 == 0 { fmt.Println() } fmt.Printf("%4d", sf[i]) } fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145) sf = squareFree(trillion, trillion+145) for i := 0; i < len(sf); i++ { if i > 0 && i%5 == 0 { fmt.Println() } fmt.Printf("%14d", sf[i]) } fmt.Println("\n\nNumber of square-free integers:\n") a := [...]uint64{100, 1000, 10000, 100000, 1000000} for _, n := range a { fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n))) } }
import math def SquareFree ( _number ) : max = (int) (math.sqrt ( _number )) for root in range ( 2, max+1 ): if 0 == _number % ( root * root ): return False return True def ListSquareFrees( _start, _end ): count = 0 for i in range ( _start, _end+1 ): if True == SquareFree( i ): print ( "{}\t".format(i), end="" ) count += 1 print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count)) ListSquareFrees( 1, 100 ) ListSquareFrees( 1000000000000, 1000000000145 )
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import "fmt" func jaro(str1, str2 string) float64 { if len(str1) == 0 && len(str2) == 0 { return 1 } if len(str1) == 0 || len(str2) == 0 { return 0 } match_distance := len(str1) if len(str2) > match_distance { match_distance = len(str2) } match_distance = match_distance/2 - 1 str1_matches := make([]bool, len(str1)) str2_matches := make([]bool, len(str2)) matches := 0. transpositions := 0. for i := range str1 { start := i - match_distance if start < 0 { start = 0 } end := i + match_distance + 1 if end > len(str2) { end = len(str2) } for k := start; k < end; k++ { if str2_matches[k] { continue } if str1[i] != str2[k] { continue } str1_matches[i] = true str2_matches[k] = true matches++ break } } if matches == 0 { return 0 } k := 0 for i := range str1 { if !str1_matches[i] { continue } for !str2_matches[k] { k++ } if str1[i] != str2[k] { transpositions++ } k++ } transpositions /= 2 return (matches/float64(len(str1)) + matches/float64(len(str2)) + (matches-transpositions)/matches) / 3 } func main() { fmt.Printf("%f\n", jaro("MARTHA", "MARHTA")) fmt.Printf("%f\n", jaro("DIXON", "DICKSONX")) fmt.Printf("%f\n", jaro("JELLYFISH", "SMELLYFISH")) }
from __future__ import division def jaro(s, t): s_len = len(s) t_len = len(t) if s_len == 0 and t_len == 0: return 1 match_distance = (max(s_len, t_len) // 2) - 1 s_matches = [False] * s_len t_matches = [False] * t_len matches = 0 transpositions = 0 for i in range(s_len): start = max(0, i - match_distance) end = min(i + match_distance + 1, t_len) for j in range(start, end): if t_matches[j]: continue if s[i] != t[j]: continue s_matches[i] = True t_matches[j] = True matches += 1 break if matches == 0: return 0 k = 0 for i in range(s_len): if not s_matches[i]: continue while not t_matches[k]: k += 1 if s[i] != t[k]: transpositions += 1 k += 1 return ((matches / s_len) + (matches / t_len) + ((matches - transpositions / 2) / matches)) / 3 def main(): for s, t in [('MARTHA', 'MARHTA'), ('DIXON', 'DICKSONX'), ('JELLYFISH', 'SMELLYFISH')]: print("jaro(%r, %r) = %.10f" % (s, t, jaro(s, t))) if __name__ == '__main__': main()
Port the provided Go code into Python while preserving the original functionality.
package main import "fmt" type pair struct{ x, y int } func main() { const max = 1685 var all []pair for a := 2; a < max; a++ { for b := a + 1; b < max-a; b++ { all = append(all, pair{a, b}) } } fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)") products := countProducts(all) var sPairs []pair pairs: for _, p := range all { s := p.x + p.y for a := 2; a < s/2+s&1; a++ { b := s - a if products[a*b] == 1 { continue pairs } } sPairs = append(sPairs, p) } fmt.Println("S starts with", len(sPairs), "possible pairs.") sProducts := countProducts(sPairs) var pPairs []pair for _, p := range sPairs { if sProducts[p.x*p.y] == 1 { pPairs = append(pPairs, p) } } fmt.Println("P then has", len(pPairs), "possible pairs.") pSums := countSums(pPairs) var final []pair for _, p := range pPairs { if pSums[p.x+p.y] == 1 { final = append(final, p) } } switch len(final) { case 1: fmt.Println("Answer:", final[0].x, "and", final[0].y) case 0: fmt.Println("No possible answer.") default: fmt.Println(len(final), "possible answers:", final) } } func countProducts(list []pair) map[int]int { m := make(map[int]int) for _, p := range list { m[p.x*p.y]++ } return m } func countSums(list []pair) map[int]int { m := make(map[int]int) for _, p := range list { m[p.x+p.y]++ } return m } func decomposeSum(s int) []pair { pairs := make([]pair, 0, s/2) for a := 2; a < s/2+s&1; a++ { pairs = append(pairs, pair{a, s - a}) } return pairs }
from collections import Counter def decompose_sum(s): return [(a,s-a) for a in range(2,int(s/2+1))] all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100) product_counts = Counter(c*d for c,d in all_pairs) unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1) s_pairs = [(a,b) for a,b in all_pairs if all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))] product_counts = Counter(c*d for c,d in s_pairs) p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1] sum_counts = Counter(c+d for c,d in p_pairs) final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1] print(final_pairs)
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "sort" "strconv" "strings" ) func fairshare(n, base int) []int { res := make([]int, n) for i := 0; i < n; i++ { j := i sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } return res } func turns(n int, fss []int) string { m := make(map[int]int) for _, fs := range fss { m[fs]++ } m2 := make(map[int]int) for _, v := range m { m2[v]++ } res := []int{} sum := 0 for k, v := range m2 { sum += v res = append(res, k) } if sum != n { return fmt.Sprintf("only %d have a turn", sum) } sort.Ints(res) res2 := make([]string, len(res)) for i := range res { res2[i] = strconv.Itoa(res[i]) } return strings.Join(res2, " or ") } func main() { for _, base := range []int{2, 3, 5, 11} { fmt.Printf("%2d : %2d\n", base, fairshare(25, base)) } fmt.Println("\nHow many times does each get a turn in 50000 iterations?") for _, base := range []int{191, 1377, 49999, 50000, 50001} { t := turns(base, fairshare(50000, base)) fmt.Printf(" With %d people: %s\n", base, t) } }
from itertools import count, islice def _basechange_int(num, b): if num == 0: return [0] result = [] while num != 0: num, d = divmod(num, b) result.append(d) return result[::-1] def fairshare(b=2): for i in count(): yield sum(_basechange_int(i, b)) % b if __name__ == '__main__': for b in (2, 3, 5, 11): print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math/rand" "strings" "time" ) var cylinder = [6]bool{} func rshift() { t := cylinder[5] for i := 4; i >= 0; i-- { cylinder[i+1] = cylinder[i] } cylinder[0] = t } func unload() { for i := 0; i < 6; i++ { cylinder[i] = false } } func load() { for cylinder[0] { rshift() } cylinder[0] = true rshift() } func spin() { var lim = 1 + rand.Intn(6) for i := 1; i < lim; i++ { rshift() } } func fire() bool { shot := cylinder[0] rshift() return shot } func method(s string) int { unload() for _, c := range s { switch c { case 'L': load() case 'S': spin() case 'F': if fire() { return 1 } } } return 0 } func mstring(s string) string { var l []string for _, c := range s { switch c { case 'L': l = append(l, "load") case 'S': l = append(l, "spin") case 'F': l = append(l, "fire") } } return strings.Join(l, ", ") } func main() { rand.Seed(time.Now().UnixNano()) tests := 100000 for _, m := range []string{"LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"} { sum := 0 for t := 1; t <= tests; t++ { sum += method(m) } pc := float64(sum) * 100 / float64(tests) fmt.Printf("%-40s produces %6.3f%% deaths.\n", mstring(m), pc) } }
import numpy as np class Revolver: def __init__(self): self.cylinder = np.array([False] * 6) def unload(self): self.cylinder[:] = False def load(self): while self.cylinder[1]: self.cylinder[:] = np.roll(self.cylinder, 1) self.cylinder[1] = True def spin(self): self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7)) def fire(self): shot = self.cylinder[0] self.cylinder[:] = np.roll(self.cylinder, 1) return shot def LSLSFSF(self): self.unload() self.load() self.spin() self.load() self.spin() if self.fire(): return True self.spin() if self.fire(): return True return False def LSLSFF(self): self.unload() self.load() self.spin() self.load() self.spin() if self.fire(): return True if self.fire(): return True return False def LLSFSF(self): self.unload() self.load() self.load() self.spin() if self.fire(): return True self.spin() if self.fire(): return True return False def LLSFF(self): self.unload() self.load() self.load() self.spin() if self.fire(): return True if self.fire(): return True return False if __name__ == '__main__': REV = Revolver() TESTCOUNT = 100000 for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF], ['load, spin, load, spin, fire, fire', REV.LSLSFF], ['load, load, spin, fire, spin, fire', REV.LLSFSF], ['load, load, spin, fire, fire', REV.LLSFF]]: percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT print("Method", name, "produces", percentage, "per cent deaths.")
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) fmt.Println("postfix:", parseInfix(input)) } func parseInfix(e string) (rpn string) { var stack []string for _, tok := range strings.Fields(e) { switch tok { case "(": stack = append(stack, tok) case ")": var op string for { op, stack = stack[len(stack)-1], stack[:len(stack)-1] if op == "(" { break } rpn += " " + op } default: if o1, isOp := opa[tok]; isOp { for len(stack) > 0 { op := stack[len(stack)-1] if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec || o1.prec == o2.prec && o1.rAssoc { break } stack = stack[:len(stack)-1] rpn += " " + op } stack = append(stack, tok) } else { if rpn > "" { rpn += " " } rpn += tok } } } for len(stack) > 0 { rpn += " " + stack[len(stack)-1] stack = stack[:len(stack)-1] } return }
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(prec=9, assoc=L), ')': OpInfo(prec=0, assoc=L), } NUM, LPAREN, RPAREN = 'NUMBER ( )'.split() def get_input(inp = None): 'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)' if inp is None: inp = input('expression: ') tokens = inp.strip().split() tokenvals = [] for token in tokens: if token in ops: tokenvals.append((token, ops[token])) else: tokenvals.append((NUM, token)) return tokenvals def shunting(tokenvals): outq, stack = [], [] table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')] for token, val in tokenvals: note = action = '' if token is NUM: action = 'Add number to output' outq.append(val) table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) elif token in ops: t1, (p1, a1) = token, val v = t1 note = 'Pop ops from stack to output' while stack: t2, (p2, a2) = stack[-1] if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2): if t1 != RPAREN: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: break else: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: stack.pop() action = '(Pop & discard "(")' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) break table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' else: note = '' break note = '' note = '' if t1 != RPAREN: stack.append((token, val)) action = 'Push op token to stack' else: action = 'Discard ")"' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) note = 'Drain stack to output' while stack: v = '' t2, (p2, a2) = stack[-1] action = '(Pop op)' stack.pop() outq.append(t2) table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' return table if __name__ == '__main__': infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' print( 'For infix expression: %r\n' % infix ) rp = shunting(get_input(infix)) maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)] row = rp[0] print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) for row in rp[1:]: print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) print('\n The final output RPN is: %r' % rp[-1][2])
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) fmt.Println("postfix:", parseInfix(input)) } func parseInfix(e string) (rpn string) { var stack []string for _, tok := range strings.Fields(e) { switch tok { case "(": stack = append(stack, tok) case ")": var op string for { op, stack = stack[len(stack)-1], stack[:len(stack)-1] if op == "(" { break } rpn += " " + op } default: if o1, isOp := opa[tok]; isOp { for len(stack) > 0 { op := stack[len(stack)-1] if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec || o1.prec == o2.prec && o1.rAssoc { break } stack = stack[:len(stack)-1] rpn += " " + op } stack = append(stack, tok) } else { if rpn > "" { rpn += " " } rpn += tok } } } for len(stack) > 0 { rpn += " " + stack[len(stack)-1] stack = stack[:len(stack)-1] } return }
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(prec=9, assoc=L), ')': OpInfo(prec=0, assoc=L), } NUM, LPAREN, RPAREN = 'NUMBER ( )'.split() def get_input(inp = None): 'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)' if inp is None: inp = input('expression: ') tokens = inp.strip().split() tokenvals = [] for token in tokens: if token in ops: tokenvals.append((token, ops[token])) else: tokenvals.append((NUM, token)) return tokenvals def shunting(tokenvals): outq, stack = [], [] table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')] for token, val in tokenvals: note = action = '' if token is NUM: action = 'Add number to output' outq.append(val) table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) elif token in ops: t1, (p1, a1) = token, val v = t1 note = 'Pop ops from stack to output' while stack: t2, (p2, a2) = stack[-1] if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2): if t1 != RPAREN: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: break else: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: stack.pop() action = '(Pop & discard "(")' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) break table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' else: note = '' break note = '' note = '' if t1 != RPAREN: stack.append((token, val)) action = 'Push op token to stack' else: action = 'Discard ")"' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) note = 'Drain stack to output' while stack: v = '' t2, (p2, a2) = stack[-1] action = '(Pop op)' stack.pop() outq.append(t2) table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' return table if __name__ == '__main__': infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' print( 'For infix expression: %r\n' % infix ) rp = shunting(get_input(infix)) maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)] row = rp[0] print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) for row in rp[1:]: print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) print('\n The final output RPN is: %r' % rp[-1][2])
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "log" "math" ) func main() { fmt.Print("Enter 11 numbers: ") var s [11]float64 for i := 0; i < 11; { if n, _ := fmt.Scan(&s[i]); n > 0 { i++ } } for i, item := range s[:5] { s[i], s[10-i] = s[10-i], item } for _, item := range s { if result, overflow := f(item); overflow { log.Printf("f(%g) overflow", item) } else { fmt.Printf("f(%g) = %g\n", item, result) } } } func f(x float64) (float64, bool) { result := math.Sqrt(math.Abs(x)) + 5*x*x*x return result, result > 400 }
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def f(x): return abs(x) ** 0.5 + 5 * x**3 >>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!") for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1]))) 11 numbers: 1 2 3 4 5 6 7 8 9 10 11 11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0 >>>
Please provide an equivalent version of this Go code in Python.
package m3 import ( "errors" "strconv" ) var ( ErrorLT3 = errors.New("N of at least three digits required.") ErrorEven = errors.New("N with odd number of digits required.") ) func Digits(i int) (string, error) { if i < 0 { i = -i } if i < 100 { return "", ErrorLT3 } s := strconv.Itoa(i) if len(s)%2 == 0 { return "", ErrorEven } m := len(s) / 2 return s[m-1 : m+2], nil }
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer)) middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "math" "math/big" ) var bi = new(big.Int) func isPrime(n int) bool { bi.SetUint64(uint64(n)) return bi.ProbablyPrime(0) } func generateSmallPrimes(n int) []int { primes := make([]int, n) primes[0] = 2 for i, count := 3, 1; count < n; i += 2 { if isPrime(i) { primes[count] = i count++ } } return primes } func countDivisors(n int) int { count := 1 for n%2 == 0 { n >>= 1 count++ } for d := 3; d*d <= n; d += 2 { q, r := n/d, n%d if r == 0 { dc := 0 for r == 0 { dc += count n = q q, r = n/d, n%d } count += dc } } if n != 1 { count *= 2 } return count } func main() { const max = 33 primes := generateSmallPrimes(max) z := new(big.Int) p := new(big.Int) fmt.Println("The first", max, "terms in the sequence are:") for i := 1; i <= max; i++ { if isPrime(i) { z.SetUint64(uint64(primes[i-1])) p.SetUint64(uint64(i - 1)) z.Exp(z, p, nil) fmt.Printf("%2d : %d\n", i, z) } else { count := 0 for j := 1; ; j++ { if i%2 == 1 { sq := int(math.Sqrt(float64(j))) if sq*sq != j { continue } } if countDivisors(j) == i { count++ if count == i { fmt.Printf("%2d : %d\n", i, j) break } } } } } }
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def primes(): ii = 1 while True: ii += 1 if is_prime(ii): yield ii def prime(n): generator = primes() for ii in range(n - 1): generator.__next__() return generator.__next__() def n_divisors(n): ii = 0 while True: ii += 1 if len(divisors(ii)) == n: yield ii def sequence(max_n=None): if max_n is not None: for ii in range(1, max_n + 1): if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() else: ii = 1 while True: ii += 1 if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() if __name__ == '__main__': for item in sequence(15): print(item)
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import "fmt" func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count } func main() { const max = 15 seq := make([]int, max) fmt.Println("The first", max, "terms of the sequence are:") for i, n := 1, 0; n < max; i++ { if k := countDivisors(i); k <= max && seq[k-1] == 0 { seq[k-1] = i n++ } } fmt.Println(seq) }
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): n = 0 while True: n += 1 ii = 0 if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii break if __name__ == '__main__': for item in sequence(15): print(item)
Translate the given Go code snippet into Python without altering its behavior.
package main import "fmt" func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj } func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d) = %2d ", n, pancake(n)) } fmt.Println() } }
import time from collections import deque from operator import itemgetter from typing import Tuple Pancakes = Tuple[int, ...] def flip(pancakes: Pancakes, position: int) -> Pancakes: return tuple([*reversed(pancakes[:position]), *pancakes[position:]]) def pancake(n: int) -> Tuple[Pancakes, int]: init_stack = tuple(range(1, n + 1)) stack_flips = {init_stack: 0} queue = deque([init_stack]) while queue: stack = queue.popleft() flips = stack_flips[stack] + 1 for i in range(2, n + 1): flipped = flip(stack, i) if flipped not in stack_flips: stack_flips[flipped] = flips queue.append(flipped) return max(stack_flips.items(), key=itemgetter(1)) if __name__ == "__main__": start = time.time() for n in range(1, 10): pancakes, p = pancake(n) print(f"pancake({n}) = {p:>2}. Example: {list(pancakes)}") print(f"\nTook {time.time() - start:.3} seconds.")
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) var grid [8][8]byte func abs(i int) int { if i >= 0 { return i } else { return -i } } func createFen() string { placeKings() placePieces("PPPPPPPP", true) placePieces("pppppppp", true) placePieces("RNBQBNR", false) placePieces("rnbqbnr", false) return toFen() } func placeKings() { for { r1 := rand.Intn(8) c1 := rand.Intn(8) r2 := rand.Intn(8) c2 := rand.Intn(8) if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 { grid[r1][c1] = 'K' grid[r2][c2] = 'k' return } } } func placePieces(pieces string, isPawn bool) { numToPlace := rand.Intn(len(pieces)) for n := 0; n < numToPlace; n++ { var r, c int for { r = rand.Intn(8) c = rand.Intn(8) if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) { break } } grid[r][c] = pieces[n] } } func toFen() string { var fen strings.Builder countEmpty := 0 for r := 0; r < 8; r++ { for c := 0; c < 8; c++ { ch := grid[r][c] if ch == '\000' { ch = '.' } fmt.Printf("%2c ", ch) if ch == '.' { countEmpty++ } else { if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteByte(ch) } } if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteString("/") fmt.Println() } fen.WriteString(" w - - 0 1") return fen.String() } func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(createFen()) }
import random board = [[" " for x in range(8)] for y in range(8)] piece_list = ["R", "N", "B", "Q", "P"] def place_kings(brd): while True: rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7) diff_list = [abs(rank_white - rank_black), abs(file_white - file_black)] if sum(diff_list) > 2 or set(diff_list) == set([0, 2]): brd[rank_white][file_white], brd[rank_black][file_black] = "K", "k" break def populate_board(brd, wp, bp): for x in range(2): if x == 0: piece_amount = wp pieces = piece_list else: piece_amount = bp pieces = [s.lower() for s in piece_list] while piece_amount != 0: piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7) piece = random.choice(pieces) if brd[piece_rank][piece_file] == " " and pawn_on_promotion_square(piece, piece_rank) == False: brd[piece_rank][piece_file] = piece piece_amount -= 1 def fen_from_board(brd): fen = "" for x in brd: n = 0 for y in x: if y == " ": n += 1 else: if n != 0: fen += str(n) fen += y n = 0 if n != 0: fen += str(n) fen += "/" if fen.count("/") < 7 else "" fen += " w - - 0 1\n" return fen def pawn_on_promotion_square(pc, pr): if pc == "P" and pr == 0: return True elif pc == "p" and pr == 7: return True return False def start(): piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15) place_kings(board) populate_board(board, piece_amount_white, piece_amount_black) print(fen_from_board(board)) for x in board: print(x) start()
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "strconv" ) func uabs(a, b uint64) uint64 { if a > b { return a - b } return b - a } func isEsthetic(n, b uint64) bool { if n == 0 { return false } i := n % b n /= b for n > 0 { j := n % b if uabs(i, j) != 1 { return false } n /= b i = j } return true } var esths []uint64 func dfs(n, m, i uint64) { if i >= n && i <= m { esths = append(esths, i) } if i == 0 || i > m { return } d := i % 10 i1 := i*10 + d - 1 i2 := i1 + 2 if d == 0 { dfs(n, m, i2) } else if d == 9 { dfs(n, m, i1) } else { dfs(n, m, i1) dfs(n, m, i2) } } func listEsths(n, n2, m, m2 uint64, perLine int, all bool) { esths = esths[:0] for i := uint64(0); i < 10; i++ { dfs(n2, m2, i) } le := len(esths) fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n", commatize(uint64(le)), commatize(n), commatize(m)) if all { for c, esth := range esths { fmt.Printf("%d ", esth) if (c+1)%perLine == 0 { fmt.Println() } } } else { for i := 0; i < perLine; i++ { fmt.Printf("%d ", esths[i]) } fmt.Println("\n............\n") for i := le - perLine; i < le; i++ { fmt.Printf("%d ", esths[i]) } } fmt.Println("\n") } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { for b := uint64(2); b <= 16; b++ { fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b) for n, c := uint64(1), uint64(0); c < 6*b; n++ { if isEsthetic(n, b) { c++ if c >= 4*b { fmt.Printf("%s ", strconv.FormatUint(n, int(b))) } } } fmt.Println("\n") } listEsths(1000, 1010, 9999, 9898, 16, true) listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true) listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false) listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false) listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false) }
from collections import deque from itertools import dropwhile, islice, takewhile from textwrap import wrap from typing import Iterable, Iterator Digits = str def esthetic_nums(base: int) -> Iterator[int]: queue: deque[tuple[int, int]] = deque() queue.extendleft((d, d) for d in range(1, base)) while True: num, lsd = queue.pop() yield num new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base) num *= base queue.extendleft((num + d, d) for d in new_lsds) def to_digits(num: int, base: int) -> Digits: digits: list[str] = [] while num: num, d = divmod(num, base) digits.append("0123456789abcdef"[d]) return "".join(reversed(digits)) if digits else "0" def pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None: joined = ", ".join(it) lines = wrap(joined, width=width - indent) for line in lines: print(f"{indent*' '}{line}") print() def task_2() -> None: nums: Iterator[int] for base in range(2, 16 + 1): start, stop = 4 * base, 6 * base nums = esthetic_nums(base) nums = islice(nums, start - 1, stop) print( f"Base-{base} esthetic numbers from " f"index {start} through index {stop} inclusive:\n" ) pprint_it(to_digits(num, base) for num in nums) def task_3(lower: int, upper: int, base: int = 10) -> None: nums: Iterator[int] = esthetic_nums(base) nums = dropwhile(lambda num: num < lower, nums) nums = takewhile(lambda num: num <= upper, nums) print( f"Base-{base} esthetic numbers with " f"magnitude between {lower:,} and {upper:,}:\n" ) pprint_it(to_digits(num, base) for num in nums) if __name__ == "__main__": print("======\nTask 2\n======\n") task_2() print("======\nTask 3\n======\n") task_3(1_000, 9_999) print("======\nTask 4\n======\n") task_3(100_000_000, 130_000_000)
Maintain the same structure and functionality when rewriting this code in Python.
package main import "fmt" const ( maxn = 10 maxl = 50 ) func main() { for i := 1; i <= maxn; i++ { fmt.Printf("%d: %d\n", i, steps(i)) } } func steps(n int) int { var a, b [maxl][maxn + 1]int var x [maxl]int a[0][0] = 1 var m int for l := 0; ; { x[l]++ k := int(x[l]) if k >= n { if l <= 0 { break } l-- continue } if a[l][k] == 0 { if b[l][k+1] != 0 { continue } } else if a[l][k] != k+1 { continue } a[l+1] = a[l] for j := 1; j <= k; j++ { a[l+1][j] = a[l][k-j] } b[l+1] = b[l] a[l+1][0] = k + 1 b[l+1][k+1] = 1 if l > m-1 { m = l + 1 } l++ x[l] = 0 } return m }
>>> from itertools import permutations >>> def f1(p): i = 0 while True: p0 = p[0] if p0 == 1: break p[:p0] = p[:p0][::-1] i += 1 return i >>> def fannkuch(n): return max(f1(list(p)) for p in permutations(range(1, n+1))) >>> for n in range(1, 11): print(n,fannkuch(n)) 1 0 2 1 3 2 4 4 5 7 6 10 7 16 8 22 9 30 10 38 >>>
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { units := []string{ "tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer", } convs := []float32{ 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000, } scanner := bufio.NewScanner(os.Stdin) for { for i, u := range units { fmt.Printf("%2d %s\n", i+1, u) } fmt.Println() var unit int var err error for { fmt.Print("Please choose a unit 1 to 13 : ") scanner.Scan() unit, err = strconv.Atoi(scanner.Text()) if err == nil && unit >= 1 && unit <= 13 { break } } unit-- var value float64 for { fmt.Print("Now enter a value in that unit : ") scanner.Scan() value, err = strconv.ParseFloat(scanner.Text(), 32) if err == nil && value >= 0 { break } } fmt.Println("\nThe equivalent in the remaining units is:\n") for i, u := range units { if i == unit { continue } fmt.Printf(" %10s : %g\n", u, float32(value)*convs[unit]/convs[i]) } fmt.Println() yn := "" for yn != "y" && yn != "n" { fmt.Print("Do another one y/n : ") scanner.Scan() yn = strings.ToLower(scanner.Text()) } if yn == "n" { return } } }
from sys import argv unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254, "fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254, "meter": 1.0, "milia": 7467.6, "piad": 0.1778, "sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445, "versta": 1066.8} if __name__ == '__main__': assert len(argv) == 3, 'ERROR. Need two arguments - number then units' try: value = float(argv[1]) except: print('ERROR. First argument must be a (float) number') raise unit = argv[2] assert unit in unit2mult, ( 'ERROR. Only know the following units: ' + ' '.join(unit2mult.keys()) ) print("%g %s to:" % (value, unit)) for unt, mlt in sorted(unit2mult.items()): print(' %10s: %g' % (unt, value * unit2mult[unit] / mlt))
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math/rand" "time" ) type rateStateS struct { lastFlush time.Time period time.Duration tickCount int } func ticRate(pRate *rateStateS) { pRate.tickCount++ now := time.Now() if now.Sub(pRate.lastFlush) >= pRate.period { tps := 0. if pRate.tickCount > 0 { tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds() } fmt.Println(tps, "tics per second.") pRate.tickCount = 0 pRate.lastFlush = now } } func somethingWeDo() { time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) } func main() { start := time.Now() rateWatch := rateStateS{ lastFlush: start, period: 5 * time.Second, } latest := start for latest.Sub(start) < 20*time.Second { somethingWeDo() ticRate(&rateWatch) latest = time.Now() } }
import subprocess import time class Tlogger(object): def __init__(self): self.counts = 0 self.tottime = 0.0 self.laststart = 0.0 self.lastreport = time.time() def logstart(self): self.laststart = time.time() def logend(self): self.counts +=1 self.tottime += (time.time()-self.laststart) if (time.time()-self.lastreport)>5.0: self.report() def report(self): if ( self.counts > 4*self.tottime): print "Subtask execution rate: %f times/second"% (self.counts/self.tottime); else: print "Average execution time: %f seconds"%(self.tottime/self.counts); self.lastreport = time.time() def taskTimer( n, subproc_args ): logger = Tlogger() for x in range(n): logger.logstart() p = subprocess.Popen(subproc_args) p.wait() logger.logend() logger.report() import timeit import sys def main( ): s = timer = timeit.Timer(s) rzlts = timer.repeat(5, 5000) for t in rzlts: print "Time for 5000 executions of statement = ",t print " print "Command:",sys.argv[2:] print "" for k in range(3): taskTimer( int(sys.argv[1]), sys.argv[2:]) main()
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import "fmt" func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count } func main() { const max = 15 fmt.Println("The first", max, "terms of the sequence are:") for i, next := 1, 1; next <= max; i++ { if next == countDivisors(i) { fmt.Printf("%d ", i) next++ } } fmt.Println() }
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): previous = 0 n = 0 while True: n += 1 ii = previous if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii previous = ii break if __name__ == '__main__': for item in sequence(15): print(item)
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "math" "math/big" "strings" ) func padovanRecur(n int) []int { p := make([]int, n) p[0], p[1], p[2] = 1, 1, 1 for i := 3; i < n; i++ { p[i] = p[i-2] + p[i-3] } return p } func padovanFloor(n int) []int { var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat) p, _ = p.SetString("1.324717957244746025960908854") s, _ = s.SetString("1.0453567932525329623") f := make([]int, n) pow := new(big.Rat).SetInt64(1) u = u.SetFrac64(1, 2) t.Quo(pow, p) t.Quo(t, s) t.Add(t, u) v, _ := t.Float64() f[0] = int(math.Floor(v)) for i := 1; i < n; i++ { t.Quo(pow, s) t.Add(t, u) v, _ = t.Float64() f[i] = int(math.Floor(v)) pow.Mul(pow, p) } return f } type LSystem struct { rules map[string]string init, current string } func step(lsys *LSystem) string { var sb strings.Builder if lsys.current == "" { lsys.current = lsys.init } else { for _, c := range lsys.current { sb.WriteString(lsys.rules[string(c)]) } lsys.current = sb.String() } return lsys.current } func padovanLSys(n int) []string { rules := map[string]string{"A": "B", "B": "C", "C": "AB"} lsys := &LSystem{rules, "A", ""} p := make([]string, n) for i := 0; i < n; i++ { p[i] = step(lsys) } return p } func areSame(l1, l2 []int) bool { for i := 0; i < len(l1); i++ { if l1[i] != l2[i] { return false } } return true } func main() { fmt.Println("First 20 members of the Padovan sequence:") fmt.Println(padovanRecur(20)) recur := padovanRecur(64) floor := padovanFloor(64) same := areSame(recur, floor) s := "give" if !same { s = "do not give" } fmt.Println("\nThe recurrence and floor based functions", s, "the same results for 64 terms.") p := padovanLSys(32) lsyst := make([]int, 32) for i := 0; i < 32; i++ { lsyst[i] = len(p[i]) } fmt.Println("\nFirst 10 members of the Padovan L-System:") fmt.Println(p[:10]) fmt.Println("\nand their lengths:") fmt.Println(lsyst[:10]) same = areSame(recur[:32], lsyst) s = "give" if !same { s = "do not give" } fmt.Println("\nThe recurrence and L-system based functions", s, "the same results for 32 terms.")
from math import floor from collections import deque from typing import Dict, Generator def padovan_r() -> Generator[int, None, None]: last = deque([1, 1, 1], 4) while True: last.append(last[-2] + last[-3]) yield last.popleft() _p, _s = 1.324717957244746025960908854, 1.0453567932525329623 def padovan_f(n: int) -> int: return floor(_p**(n-1) / _s + .5) def padovan_l(start: str='A', rules: Dict[str, str]=dict(A='B', B='C', C='AB') ) -> Generator[str, None, None]: axiom = start while True: yield axiom axiom = ''.join(rules[ch] for ch in axiom) if __name__ == "__main__": from itertools import islice print("The first twenty terms of the sequence.") print(str([padovan_f(n) for n in range(20)])[1:-1]) r_generator = padovan_r() if all(next(r_generator) == padovan_f(n) for n in range(64)): print("\nThe recurrence and floor based algorithms match to n=63 .") else: print("\nThe recurrence and floor based algorithms DIFFER!") print("\nThe first 10 L-system string-lengths and strings") l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) print('\n'.join(f" {len(string):3} {repr(string)}" for string in islice(l_generator, 10))) r_generator = padovan_r() l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) if all(len(next(l_generator)) == padovan_f(n) == next(r_generator) for n in range(32)): print("\nThe L-system, recurrence and floor based algorithms match to n=31 .") else: print("\nThe L-system, recurrence and floor based algorithms DIFFER!")
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "image" "image/color" "image/draw" "image/png" "log" "os" ) const ( width, height = 800, 600 maxDepth = 11 colFactor = uint8(255 / maxDepth) fileName = "pythagorasTree.png" ) func main() { img := image.NewNRGBA(image.Rect(0, 0, width, height)) bg := image.NewUniform(color.RGBA{255, 255, 255, 255}) draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src) drawSquares(340, 550, 460, 550, img, 0) imgFile, err := os.Create(fileName) if err != nil { log.Fatal(err) } defer imgFile.Close() if err := png.Encode(imgFile, img); err != nil { imgFile.Close() log.Fatal(err) } } func drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) { if depth > maxDepth { return } dx, dy := bx-ax, ay-by x3, y3 := bx-dy, by-dx x4, y4 := ax-dy, ay-dx x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2 col := color.RGBA{0, uint8(depth) * colFactor, 0, 255} drawLine(ax, ay, bx, by, img, col) drawLine(bx, by, x3, y3, img, col) drawLine(x3, y3, x4, y4, img, col) drawLine(x4, y4, ax, ay, img, col) drawSquares(x4, y4, x5, y5, img, depth+1) drawSquares(x5, y5, x3, y3, img, depth+1) } func drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) { dx := abs(x1 - x0) dy := abs(y1 - y0) var sx, sy int = -1, -1 if x0 < x1 { sx = 1 } if y0 < y1 { sy = 1 } err := dx - dy for { img.Set(x0, y0, col) if x0 == x1 && y0 == y1 { break } e2 := 2 * err if e2 > -dy { err -= dy x0 += sx } if e2 < dx { err += dx y0 += sy } } } func abs(x int) int { if x < 0 { return -x } return x }
def setup(): size(800, 400) background(255) stroke(0, 255, 0) tree(width / 2.3, height, width / 1.8, height, 10) def tree(x1, y1, x2, y2, depth): if depth <= 0: return dx = (x2 - x1) dy = (y1 - y2) x3 = (x2 - dy) y3 = (y2 - dx) x4 = (x1 - dy) y4 = (y1 - dx) x5 = (x4 + 0.5 * (dx - dy)) y5 = (y4 - 0.5 * (dx + dy)) beginShape() fill(0.0, 255.0 / depth, 0.0) vertex(x1, y1) vertex(x2, y2) vertex(x3, y3) vertex(x4, y4) vertex(x1, y1) endShape() beginShape() fill(0.0, 255.0 / depth, 0.0) vertex(x3, y3) vertex(x4, y4) vertex(x5, y5) vertex(x3, y3) endShape() tree(x4, y4, x5, y5, depth - 1) tree(x5, y5, x3, y3, depth - 1)
Generate an equivalent Python version of this Go code.
package main import ( "bytes" "fmt" "io" "os" "unicode" ) func main() { owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life.")) fmt.Println() owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more.")) fmt.Println() } func owp(dst io.Writer, src io.Reader) { byte_in := func () byte { bs := make([]byte, 1) src.Read(bs) return bs[0] } byte_out := func (b byte) { dst.Write([]byte{b}) } var odd func() byte odd = func() byte { s := byte_in() if unicode.IsPunct(rune(s)) { return s } b := odd() byte_out(s) return b } for { for { b := byte_in() byte_out(b) if b == '.' { return } if unicode.IsPunct(rune(b)) { break } } b := odd() byte_out(b) if b == '.' { return } } }
from sys import stdin, stdout def char_in(): return stdin.read(1) def char_out(c): stdout.write(c) def odd(prev = lambda: None): a = char_in() if not a.isalpha(): prev() char_out(a) return a != '.' def clos(): char_out(a) prev() return odd(clos) def even(): while True: c = char_in() char_out(c) if not c.isalpha(): return c != '.' e = False while odd() if e else even(): e = not e
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "log" "math" ) var a1 = []int64{0, 1403580, -810728} var a2 = []int64{527612, 0, -1370589} const m1 = int64((1 << 32) - 209) const m2 = int64((1 << 32) - 22853) const d = m1 + 1 func mod(x, y int64) int64 { m := x % y if m < 0 { if y < 0 { return m - y } else { return m + y } } return m } type MRG32k3a struct{ x1, x2 [3]int64 } func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} } func (mrg *MRG32k3a) seed(seedState int64) { if seedState <= 0 || seedState >= d { log.Fatalf("Argument must be in the range [0, %d].\n", d) } mrg.x1 = [3]int64{seedState, 0, 0} mrg.x2 = [3]int64{seedState, 0, 0} } func (mrg *MRG32k3a) nextInt() int64 { x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1) x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2) mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} return mod(x1i-x2i, m1) + 1 } func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) } func main() { randomGen := MRG32k3aNew() randomGen.seed(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
a1 = [0, 1403580, -810728] m1 = 2**32 - 209 a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a(): def __init__(self, seed_state=123): self.seed(seed_state) def seed(self, seed_state): assert 0 <seed_state < d, f"Out of Range 0 x < {d}" self.x1 = [seed_state, 0, 0] self.x2 = [seed_state, 0, 0] def next_int(self): "return random int in range 0..d" x1i = sum(aa * xx for aa, xx in zip(a1, self.x1)) % m1 x2i = sum(aa * xx for aa, xx in zip(a2, self.x2)) % m2 self.x1 = [x1i] + self.x1[:2] self.x2 = [x2i] + self.x2[:2] z = (x1i - x2i) % m1 answer = (z + 1) return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / d if __name__ == '__main__': random_gen = MRG32k3a() random_gen.seed(1234567) for i in range(5): print(random_gen.next_int()) random_gen.seed(987654321) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "rcu" "strconv" ) func isColorful(n int) bool { if n < 0 { return false } if n < 10 { return true } digits := rcu.Digits(n, 10) for _, d := range digits { if d == 0 || d == 1 { return false } } set := make(map[int]bool) for _, d := range digits { set[d] = true } dc := len(digits) if len(set) < dc { return false } for k := 2; k <= dc; k++ { for i := 0; i <= dc-k; i++ { prod := 1 for j := i; j <= i+k-1; j++ { prod *= digits[j] } if ok := set[prod]; ok { return false } set[prod] = true } } return true } var count = make([]int, 9) var used = make([]bool, 11) var largest = 0 func countColorful(taken int, n string) { if taken == 0 { for digit := 0; digit < 10; digit++ { dx := digit + 1 used[dx] = true t := 1 if digit < 2 { t = 9 } countColorful(t, string(digit+48)) used[dx] = false } } else { nn, _ := strconv.Atoi(n) if isColorful(nn) { ln := len(n) count[ln]++ if nn > largest { largest = nn } } if taken < 9 { for digit := 2; digit < 10; digit++ { dx := digit + 1 if !used[dx] { used[dx] = true countColorful(taken+1, n+string(digit+48)) used[dx] = false } } } } } func main() { var cn []int for i := 0; i < 100; i++ { if isColorful(i) { cn = append(cn, i) } } fmt.Println("The", len(cn), "colorful numbers less than 100 are:") for i := 0; i < len(cn); i++ { fmt.Printf("%2d ", cn[i]) if (i+1)%10 == 0 { fmt.Println() } } countColorful(0, "") fmt.Println("\n\nThe largest possible colorful number is:") fmt.Println(rcu.Commatize(largest)) fmt.Println("\nCount of colorful numbers for each order of magnitude:") pow := 10 for dc := 1; dc < len(count); dc++ { cdc := rcu.Commatize(count[dc]) pc := 100 * float64(count[dc]) / float64(pow) fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc) if pow == 10 { pow = 90 } else { pow *= 10 } } sum := 0 for _, c := range count { sum += c } fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum)) }
from math import prod largest = [0] def iscolorful(n): if 0 <= n < 10: return True dig = [int(c) for c in str(n)] if 1 in dig or 0 in dig or len(dig) > len(set(dig)): return False products = list(set(dig)) for i in range(len(dig)): for j in range(i+2, len(dig)+1): p = prod(dig[i:j]) if p in products: return False products.append(p) largest[0] = max(n, largest[0]) return True print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:') for i in range(1, 101, 25): for j in range(25): if iscolorful(i + j): print(f'{i + j: 5,}', end='') print() csum = 0 for i in range(8): j = 0 if i == 0 else 10**i k = 10**(i+1) - 1 n = sum(iscolorful(x) for x in range(j, k+1)) csum += n print(f'The count of colorful numbers between {j} and {k} is {n}.') print(f'The largest possible colorful number is {largest[0]}.') print(f'The total number of colorful numbers is {csum}.')
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "rcu" "strconv" ) func isColorful(n int) bool { if n < 0 { return false } if n < 10 { return true } digits := rcu.Digits(n, 10) for _, d := range digits { if d == 0 || d == 1 { return false } } set := make(map[int]bool) for _, d := range digits { set[d] = true } dc := len(digits) if len(set) < dc { return false } for k := 2; k <= dc; k++ { for i := 0; i <= dc-k; i++ { prod := 1 for j := i; j <= i+k-1; j++ { prod *= digits[j] } if ok := set[prod]; ok { return false } set[prod] = true } } return true } var count = make([]int, 9) var used = make([]bool, 11) var largest = 0 func countColorful(taken int, n string) { if taken == 0 { for digit := 0; digit < 10; digit++ { dx := digit + 1 used[dx] = true t := 1 if digit < 2 { t = 9 } countColorful(t, string(digit+48)) used[dx] = false } } else { nn, _ := strconv.Atoi(n) if isColorful(nn) { ln := len(n) count[ln]++ if nn > largest { largest = nn } } if taken < 9 { for digit := 2; digit < 10; digit++ { dx := digit + 1 if !used[dx] { used[dx] = true countColorful(taken+1, n+string(digit+48)) used[dx] = false } } } } } func main() { var cn []int for i := 0; i < 100; i++ { if isColorful(i) { cn = append(cn, i) } } fmt.Println("The", len(cn), "colorful numbers less than 100 are:") for i := 0; i < len(cn); i++ { fmt.Printf("%2d ", cn[i]) if (i+1)%10 == 0 { fmt.Println() } } countColorful(0, "") fmt.Println("\n\nThe largest possible colorful number is:") fmt.Println(rcu.Commatize(largest)) fmt.Println("\nCount of colorful numbers for each order of magnitude:") pow := 10 for dc := 1; dc < len(count); dc++ { cdc := rcu.Commatize(count[dc]) pc := 100 * float64(count[dc]) / float64(pow) fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc) if pow == 10 { pow = 90 } else { pow *= 10 } } sum := 0 for _, c := range count { sum += c } fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum)) }
from math import prod largest = [0] def iscolorful(n): if 0 <= n < 10: return True dig = [int(c) for c in str(n)] if 1 in dig or 0 in dig or len(dig) > len(set(dig)): return False products = list(set(dig)) for i in range(len(dig)): for j in range(i+2, len(dig)+1): p = prod(dig[i:j]) if p in products: return False products.append(p) largest[0] = max(n, largest[0]) return True print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:') for i in range(1, 101, 25): for j in range(25): if iscolorful(i + j): print(f'{i + j: 5,}', end='') print() csum = 0 for i in range(8): j = 0 if i == 0 else 10**i k = 10**(i+1) - 1 n = sum(iscolorful(x) for x in range(j, k+1)) csum += n print(f'The count of colorful numbers between {j} and {k} is {n}.') print(f'The largest possible colorful number is {largest[0]}.') print(f'The total number of colorful numbers is {csum}.')
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02" var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "} var lengths = [3]int{23, 28, 33} var quadrants = [4][2]string{ {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and falling", "valley"}, {"down but rising", "transition"}, } func check(err error) { if err != nil { log.Fatal(err) } } func biorhythms(birthDate, targetDate string) { bd, err := time.Parse(layout, birthDate) check(err) td, err := time.Parse(layout, targetDate) check(err) days := int(td.Sub(bd).Hours() / 24) fmt.Printf("Born %s, Target %s\n", birthDate, targetDate) fmt.Println("Day", days) for i := 0; i < 3; i++ { length := lengths[i] cycle := cycles[i] position := days % length quadrant := position * 4 / length percent := math.Sin(2 * math.Pi * float64(position) / float64(length)) percent = math.Floor(percent*1000) / 10 descript := "" if percent > 95 { descript = " peak" } else if percent < -95 { descript = " valley" } else if math.Abs(percent) < 5 { descript = " critical transition" } else { daysToAdd := (quadrant+1)*length/4 - position transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd)) trend := quadrants[quadrant][0] next := quadrants[quadrant][1] transStr := transition.Format(layout) descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr) } fmt.Printf("%s %2d : %s\n", cycle, position, descript) } fmt.Println() } func main() { datePairs := [][2]string{ {"1943-03-09", "1972-07-11"}, {"1809-01-12", "1863-11-19"}, {"1809-02-12", "1863-11-19"}, } for _, datePair := range datePairs { biorhythms(datePair[0], datePair[1]) } }
from datetime import date, timedelta from math import floor, sin, pi def biorhythms(birthdate,targetdate): print("Born: "+birthdate+" Target: "+targetdate) birthdate = date.fromisoformat(birthdate) targetdate = date.fromisoformat(targetdate) days = (targetdate - birthdate).days print("Day: "+str(days)) cycle_labels = ["Physical", "Emotional", "Mental"] cycle_lengths = [23, 28, 33] quadrants = [("up and rising", "peak"), ("up but falling", "transition"), ("down and falling", "valley"), ("down but rising", "transition")] for i in range(3): label = cycle_labels[i] length = cycle_lengths[i] position = days % length quadrant = int(floor((4 * position) / length)) percentage = int(round(100 * sin(2 * pi * position / length),0)) transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position) trend, next = quadrants[quadrant] if percentage > 95: description = "peak" elif percentage < -95: description = "valley" elif abs(percentage) < 5: description = "critical transition" else: description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")" print(label+" day "+str(position)+": "+description) biorhythms("1943-03-09","1972-07-11")
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02" var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "} var lengths = [3]int{23, 28, 33} var quadrants = [4][2]string{ {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and falling", "valley"}, {"down but rising", "transition"}, } func check(err error) { if err != nil { log.Fatal(err) } } func biorhythms(birthDate, targetDate string) { bd, err := time.Parse(layout, birthDate) check(err) td, err := time.Parse(layout, targetDate) check(err) days := int(td.Sub(bd).Hours() / 24) fmt.Printf("Born %s, Target %s\n", birthDate, targetDate) fmt.Println("Day", days) for i := 0; i < 3; i++ { length := lengths[i] cycle := cycles[i] position := days % length quadrant := position * 4 / length percent := math.Sin(2 * math.Pi * float64(position) / float64(length)) percent = math.Floor(percent*1000) / 10 descript := "" if percent > 95 { descript = " peak" } else if percent < -95 { descript = " valley" } else if math.Abs(percent) < 5 { descript = " critical transition" } else { daysToAdd := (quadrant+1)*length/4 - position transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd)) trend := quadrants[quadrant][0] next := quadrants[quadrant][1] transStr := transition.Format(layout) descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr) } fmt.Printf("%s %2d : %s\n", cycle, position, descript) } fmt.Println() } func main() { datePairs := [][2]string{ {"1943-03-09", "1972-07-11"}, {"1809-01-12", "1863-11-19"}, {"1809-02-12", "1863-11-19"}, } for _, datePair := range datePairs { biorhythms(datePair[0], datePair[1]) } }
from datetime import date, timedelta from math import floor, sin, pi def biorhythms(birthdate,targetdate): print("Born: "+birthdate+" Target: "+targetdate) birthdate = date.fromisoformat(birthdate) targetdate = date.fromisoformat(targetdate) days = (targetdate - birthdate).days print("Day: "+str(days)) cycle_labels = ["Physical", "Emotional", "Mental"] cycle_lengths = [23, 28, 33] quadrants = [("up and rising", "peak"), ("up but falling", "transition"), ("down and falling", "valley"), ("down but rising", "transition")] for i in range(3): label = cycle_labels[i] length = cycle_lengths[i] position = days % length quadrant = int(floor((4 * position) / length)) percentage = int(round(100 * sin(2 * pi * position / length),0)) transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position) trend, next = quadrants[quadrant] if percentage > 95: description = "peak" elif percentage < -95: description = "valley" elif abs(percentage) < 5: description = "critical transition" else: description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")" print(label+" day "+str(position)+": "+description) biorhythms("1943-03-09","1972-07-11")
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "database/sql" "fmt" "log" _ "github.com/mattn/go-sqlite3" ) func main() { db, err := sql.Open("sqlite3", "rc.db") if err != nil { log.Print(err) return } defer db.Close() _, err = db.Exec(`create table addr ( id int unique, street text, city text, state text, zip text )`) if err != nil { log.Print(err) return } rows, err := db.Query(`pragma table_info(addr)`) if err != nil { log.Print(err) return } var field, storage string var ignore sql.RawBytes for rows.Next() { err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore) if err != nil { log.Print(err) return } fmt.Println(field, storage) } }
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> conn.execute() <sqlite3.Cursor object at 0x013265C0> >>>
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "os/exec" ) func main() { synthType := "sine" duration := "5" frequency := "440" cmd := exec.Command("play", "-n", "synth", duration, synthType, frequency) err := cmd.Run() if err != nil { fmt.Println(err) } }
import os from math import pi, sin au_header = bytearray( [46, 115, 110, 100, 0, 0, 0, 24, 255, 255, 255, 255, 0, 0, 0, 3, 0, 0, 172, 68, 0, 0, 0, 1]) def f(x, freq): "Compute sine wave as 16-bit integer" return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536 def play_sine(freq=440, duration=5, oname="pysine.au"): "Play a sine wave for `duration` seconds" out = open(oname, 'wb') out.write(au_header) v = [f(x, freq) for x in range(duration * 44100 + 1)] s = [] for i in v: s.append(i >> 8) s.append(i % 256) out.write(bytearray(s)) out.close() os.system("vlc " + oname) play_sine()
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "bufio" "encoding/binary" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type code = byte const ( fetch code = iota store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt ) type Tree struct { nodeType NodeType left *Tree right *Tree value string } type atr struct { enumText string nodeType NodeType opcode code } var atrs = []atr{ {"Identifier", ndIdent, 255}, {"String", ndString, 255}, {"Integer", ndInteger, 255}, {"Sequence", ndSequence, 255}, {"If", ndIf, 255}, {"Prtc", ndPrtc, 255}, {"Prts", ndPrts, 255}, {"Prti", ndPrti, 255}, {"While", ndWhile, 255}, {"Assign", ndAssign, 255}, {"Negate", ndNegate, neg}, {"Not", ndNot, not}, {"Multiply", ndMul, mul}, {"Divide", ndDiv, div}, {"Mod", ndMod, mod}, {"Add", ndAdd, add}, {"Subtract", ndSub, sub}, {"Less", ndLss, lt}, {"LessEqual", ndLeq, le}, {"Greater", ndGtr, gt}, {"GreaterEqual", ndGeq, ge}, {"Equal", ndEql, eq}, {"NotEqual", ndNeq, ne}, {"And", ndAnd, and}, {"Or", ndOr, or}, } var ( stringPool []string globals []string object []code ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func nodeType2Op(nodeType NodeType) code { return atrs[nodeType].opcode } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, ""} } func makeLeaf(nodeType NodeType, value string) *Tree { return &Tree{nodeType, nil, nil, value} } func emitByte(c code) { object = append(object, c) } func emitWord(n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for _, b := range bs { emitByte(code(b)) } } func emitWordAt(at, n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for i := at; i < at+4; i++ { object[i] = code(bs[i-at]) } } func hole() int { t := len(object) emitWord(0) return t } func fetchVarOffset(id string) int { for i := 0; i < len(globals); i++ { if globals[i] == id { return i } } globals = append(globals, id) return len(globals) - 1 } func fetchStringOffset(st string) int { for i := 0; i < len(stringPool); i++ { if stringPool[i] == st { return i } } stringPool = append(stringPool, st) return len(stringPool) - 1 } func codeGen(x *Tree) { if x == nil { return } var n, p1, p2 int switch x.nodeType { case ndIdent: emitByte(fetch) n = fetchVarOffset(x.value) emitWord(n) case ndInteger: emitByte(push) n, err = strconv.Atoi(x.value) check(err) emitWord(n) case ndString: emitByte(push) n = fetchStringOffset(x.value) emitWord(n) case ndAssign: n = fetchVarOffset(x.left.value) codeGen(x.right) emitByte(store) emitWord(n) case ndIf: codeGen(x.left) emitByte(jz) p1 = hole() codeGen(x.right.left) if x.right.right != nil { emitByte(jmp) p2 = hole() } emitWordAt(p1, len(object)-p1) if x.right.right != nil { codeGen(x.right.right) emitWordAt(p2, len(object)-p2) } case ndWhile: p1 = len(object) codeGen(x.left) emitByte(jz) p2 = hole() codeGen(x.right) emitByte(jmp) emitWord(p1 - len(object)) emitWordAt(p2, len(object)-p2) case ndSequence: codeGen(x.left) codeGen(x.right) case ndPrtc: codeGen(x.left) emitByte(prtc) case ndPrti: codeGen(x.left) emitByte(prti) case ndPrts: codeGen(x.left) emitByte(prts) case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq, ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod: codeGen(x.left) codeGen(x.right) emitByte(nodeType2Op(x.nodeType)) case ndNegate, ndNot: codeGen(x.left) emitByte(nodeType2Op(x.nodeType)) default: msg := fmt.Sprintf("error in code generator - found %d, expecting operator\n", x.nodeType) reportError(msg) } } func codeFinish() { emitByte(halt) } func listCode() { fmt.Printf("Datasize: %d Strings: %d\n", len(globals), len(stringPool)) for _, s := range stringPool { fmt.Println(s) } pc := 0 for pc < len(object) { fmt.Printf("%5d ", pc) op := object[pc] pc++ switch op { case fetch: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("fetch [%d]\n", x) pc += 4 case store: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("store [%d]\n", x) pc += 4 case push: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("push %d\n", x) pc += 4 case add: fmt.Println("add") case sub: fmt.Println("sub") case mul: fmt.Println("mul") case div: fmt.Println("div") case mod: fmt.Println("mod") case lt: fmt.Println("lt") case gt: fmt.Println("gt") case le: fmt.Println("le") case ge: fmt.Println("ge") case eq: fmt.Println("eq") case ne: fmt.Println("ne") case and: fmt.Println("and") case or: fmt.Println("or") case neg: fmt.Println("neg") case not: fmt.Println("not") case jmp: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("jmp (%d) %d\n", x, int32(pc)+x) pc += 4 case jz: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("jz (%d) %d\n", x, int32(pc)+x) pc += 4 case prtc: fmt.Println("prtc") case prti: fmt.Println("prti") case prts: fmt.Println("prts") case halt: fmt.Println("halt") default: reportError(fmt.Sprintf("listCode: Unknown opcode %d", op)) } } } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { return makeLeaf(nodeType, s) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) codeGen(loadAst()) codeFinish() listCode() }
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Change the following Go code into Python without altering its purpose.
package main import ( "bufio" "encoding/binary" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type code = byte const ( fetch code = iota store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt ) type Tree struct { nodeType NodeType left *Tree right *Tree value string } type atr struct { enumText string nodeType NodeType opcode code } var atrs = []atr{ {"Identifier", ndIdent, 255}, {"String", ndString, 255}, {"Integer", ndInteger, 255}, {"Sequence", ndSequence, 255}, {"If", ndIf, 255}, {"Prtc", ndPrtc, 255}, {"Prts", ndPrts, 255}, {"Prti", ndPrti, 255}, {"While", ndWhile, 255}, {"Assign", ndAssign, 255}, {"Negate", ndNegate, neg}, {"Not", ndNot, not}, {"Multiply", ndMul, mul}, {"Divide", ndDiv, div}, {"Mod", ndMod, mod}, {"Add", ndAdd, add}, {"Subtract", ndSub, sub}, {"Less", ndLss, lt}, {"LessEqual", ndLeq, le}, {"Greater", ndGtr, gt}, {"GreaterEqual", ndGeq, ge}, {"Equal", ndEql, eq}, {"NotEqual", ndNeq, ne}, {"And", ndAnd, and}, {"Or", ndOr, or}, } var ( stringPool []string globals []string object []code ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func nodeType2Op(nodeType NodeType) code { return atrs[nodeType].opcode } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, ""} } func makeLeaf(nodeType NodeType, value string) *Tree { return &Tree{nodeType, nil, nil, value} } func emitByte(c code) { object = append(object, c) } func emitWord(n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for _, b := range bs { emitByte(code(b)) } } func emitWordAt(at, n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for i := at; i < at+4; i++ { object[i] = code(bs[i-at]) } } func hole() int { t := len(object) emitWord(0) return t } func fetchVarOffset(id string) int { for i := 0; i < len(globals); i++ { if globals[i] == id { return i } } globals = append(globals, id) return len(globals) - 1 } func fetchStringOffset(st string) int { for i := 0; i < len(stringPool); i++ { if stringPool[i] == st { return i } } stringPool = append(stringPool, st) return len(stringPool) - 1 } func codeGen(x *Tree) { if x == nil { return } var n, p1, p2 int switch x.nodeType { case ndIdent: emitByte(fetch) n = fetchVarOffset(x.value) emitWord(n) case ndInteger: emitByte(push) n, err = strconv.Atoi(x.value) check(err) emitWord(n) case ndString: emitByte(push) n = fetchStringOffset(x.value) emitWord(n) case ndAssign: n = fetchVarOffset(x.left.value) codeGen(x.right) emitByte(store) emitWord(n) case ndIf: codeGen(x.left) emitByte(jz) p1 = hole() codeGen(x.right.left) if x.right.right != nil { emitByte(jmp) p2 = hole() } emitWordAt(p1, len(object)-p1) if x.right.right != nil { codeGen(x.right.right) emitWordAt(p2, len(object)-p2) } case ndWhile: p1 = len(object) codeGen(x.left) emitByte(jz) p2 = hole() codeGen(x.right) emitByte(jmp) emitWord(p1 - len(object)) emitWordAt(p2, len(object)-p2) case ndSequence: codeGen(x.left) codeGen(x.right) case ndPrtc: codeGen(x.left) emitByte(prtc) case ndPrti: codeGen(x.left) emitByte(prti) case ndPrts: codeGen(x.left) emitByte(prts) case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq, ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod: codeGen(x.left) codeGen(x.right) emitByte(nodeType2Op(x.nodeType)) case ndNegate, ndNot: codeGen(x.left) emitByte(nodeType2Op(x.nodeType)) default: msg := fmt.Sprintf("error in code generator - found %d, expecting operator\n", x.nodeType) reportError(msg) } } func codeFinish() { emitByte(halt) } func listCode() { fmt.Printf("Datasize: %d Strings: %d\n", len(globals), len(stringPool)) for _, s := range stringPool { fmt.Println(s) } pc := 0 for pc < len(object) { fmt.Printf("%5d ", pc) op := object[pc] pc++ switch op { case fetch: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("fetch [%d]\n", x) pc += 4 case store: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("store [%d]\n", x) pc += 4 case push: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("push %d\n", x) pc += 4 case add: fmt.Println("add") case sub: fmt.Println("sub") case mul: fmt.Println("mul") case div: fmt.Println("div") case mod: fmt.Println("mod") case lt: fmt.Println("lt") case gt: fmt.Println("gt") case le: fmt.Println("le") case ge: fmt.Println("ge") case eq: fmt.Println("eq") case ne: fmt.Println("ne") case and: fmt.Println("and") case or: fmt.Println("or") case neg: fmt.Println("neg") case not: fmt.Println("not") case jmp: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("jmp (%d) %d\n", x, int32(pc)+x) pc += 4 case jz: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("jz (%d) %d\n", x, int32(pc)+x) pc += 4 case prtc: fmt.Println("prtc") case prti: fmt.Println("prti") case prts: fmt.Println("prts") case halt: fmt.Println("halt") default: reportError(fmt.Sprintf("listCode: Unknown opcode %d", op)) } } } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { return makeLeaf(nodeType, s) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) codeGen(loadAst()) codeFinish() listCode() }
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Produce a functionally identical Python code for the snippet given in Go.
package main import "fmt" func hello() { fmt.Println("Hello from main.go") } func main() { hello() hello2() }
import one
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import "fmt" func hello() { fmt.Println("Hello from main.go") } func main() { hello() hello2() }
import one
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "sternbrocot" ) func main() { g := sb.Generator() fmt.Println("First 15:") for i := 1; i <= 15; i++ { fmt.Printf("%2d: %d\n", i, g()) } s := sb.New() fmt.Println("First 15:", s.FirstN(15)) for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} { fmt.Printf("%3d at 1-based index %d\n", x, 1+s.Find(x)) } fmt.Println("1-based indexes: gcd") for n, f := range s.FirstN(1000)[:999] { g := gcd(f, (*s)[n+1]) fmt.Printf("%d,%d: gcd(%d, %d) = %d\n", n+1, n+2, f, (*s)[n+1], g) if g != 1 { panic("oh no!") return } } } func gcd(x, y int) int { for y != 0 { x, y = y, x%y } return x }
def stern_brocot(predicate=lambda series: len(series) < 20): sb, i = [1, 1], 0 while predicate(sb): sb += [sum(sb[i:i + 2]), sb[i + 1]] i += 1 return sb if __name__ == '__main__': from fractions import gcd n_first = 15 print('The first %i values:\n ' % n_first, stern_brocot(lambda series: len(series) < n_first)[:n_first]) print() n_max = 10 for n_occur in list(range(1, n_max + 1)) + [100]: print('1-based index of the first occurrence of %3i in the series:' % n_occur, stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1) print() n_gcd = 1000 s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd] assert all(gcd(prev, this) == 1 for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "math" ) type unc struct { n float64 s float64 } func newUnc(n, s float64) *unc { return &unc{n, s * s} } func (z *unc) errorTerm() float64 { return math.Sqrt(z.s) } func (z *unc) addC(a *unc, c float64) *unc { *z = *a z.n += c return z } func (z *unc) subC(a *unc, c float64) *unc { *z = *a z.n -= c return z } func (z *unc) addU(a, b *unc) *unc { z.n = a.n + b.n z.s = a.s + b.s return z } func (z *unc) subU(a, b *unc) *unc { z.n = a.n - b.n z.s = a.s + b.s return z } func (z *unc) mulC(a *unc, c float64) *unc { z.n = a.n * c z.s = a.s * c * c return z } func (z *unc) divC(a *unc, c float64) *unc { z.n = a.n / c z.s = a.s / (c * c) return z } func (z *unc) mulU(a, b *unc) *unc { prod := a.n * b.n z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n)) return z } func (z *unc) divU(a, b *unc) *unc { quot := a.n / b.n z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n)) return z } func (z *unc) expC(a *unc, c float64) *unc { f := math.Pow(a.n, c) g := f * c / a.n z.n = f z.s = a.s * g * g return z } func main() { x1 := newUnc(100, 1.1) x2 := newUnc(200, 2.2) y1 := newUnc(50, 1.2) y2 := newUnc(100, 2.3) var d, d2 unc d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5) fmt.Println("d: ", d.n) fmt.Println("error:", d.errorTerm()) }
from collections import namedtuple import math class I(namedtuple('Imprecise', 'value, delta')): 'Imprecise type: I(value=0.0, delta=0.0)' __slots__ = () def __new__(_cls, value=0.0, delta=0.0): 'Defaults to 0.0 ± delta' return super().__new__(_cls, float(value), abs(float(delta))) def reciprocal(self): return I(1. / self.value, self.delta / (self.value**2)) def __str__(self): 'Shorter form of Imprecise as string' return 'I(%g, %g)' % self def __neg__(self): return I(-self.value, self.delta) def __add__(self, other): if type(other) == I: return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value + c, self.delta) def __sub__(self, other): return self + (-other) def __radd__(self, other): return I.__add__(self, other) def __mul__(self, other): if type(other) == I: a1,b1 = self a2,b2 = other f = a1 * a2 return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value * c, self.delta * c) def __pow__(self, other): if type(other) == I: return NotImplemented try: c = float(other) except: return NotImplemented f = self.value ** c return I(f, f * c * (self.delta / self.value)) def __rmul__(self, other): return I.__mul__(self, other) def __truediv__(self, other): if type(other) == I: return self.__mul__(other.reciprocal()) try: c = float(other) except: return NotImplemented return I(self.value / c, self.delta / c) def __rtruediv__(self, other): return other * self.reciprocal() __div__, __rdiv__ = __truediv__, __rtruediv__ Imprecise = I def distance(p1, p2): x1, y1 = p1 x2, y2 = p2 return ((x1 - x2)**2 + (y1 - y2)**2)**0.5 x1 = I(100, 1.1) x2 = I(200, 2.2) y1 = I( 50, 1.2) y2 = I(100, 2.3) p1, p2 = (x1, y1), (x2, y2) print("Distance between points\n p1: %s\n and p2: %s\n = %r" % ( p1, p2, distance(p1, p2)))
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "errors" "fmt" "unicode" ) var code = []byte("01230127022455012623017202") func soundex(s string) (string, error) { var sx [4]byte var sxi int var cx, lastCode byte for i, c := range s { switch { case !unicode.IsLetter(c): if c < ' ' || c == 127 { return "", errors.New("ASCII control characters disallowed") } if i == 0 { return "", errors.New("initial character must be a letter") } lastCode = '0' continue case c >= 'A' && c <= 'Z': cx = byte(c - 'A') case c >= 'a' && c <= 'z': cx = byte(c - 'a') default: return "", errors.New("non-ASCII letters unsupported") } if i == 0 { sx[0] = cx + 'A' sxi = 1 continue } switch x := code[cx]; x { case '7', lastCode: case '0': lastCode = '0' default: sx[sxi] = x if sxi == 3 { return string(sx[:]), nil } sxi++ lastCode = x } } if sxi == 0 { return "", errors.New("no letters present") } for ; sxi < 4; sxi++ { sx[sxi] = '0' } return string(sx[:]), nil } func main() { for _, s := range []string{ "Robert", "Rupert", "Rubin", "ashcroft", "ashcraft", "moses", "O'Mally", "d jay", "R2-D2", "12p2", "naïve", "", "bump\t", } { if x, err := soundex(s); err == nil { fmt.Println("soundex", s, "=", x) } else { fmt.Printf("\"%s\" fail. %s\n", s, err) } } }
from itertools import groupby def soundex(word): codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r") soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod) cmap2 = lambda kar: soundDict.get(kar, '9') sdx = ''.join(cmap2(kar) for kar in word.lower()) sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9') sdx3 = sdx2[0:4].ljust(4,'0') return sdx3
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "log" "os" "strconv" ) type tree uint64 var ( list []tree offset = [32]uint{1: 1} ) func add(t tree) { list = append(list, 1|t<<1) } func show(t tree, l uint) { for ; l > 0; t >>= 1 { l-- var paren byte if (t & 1) != 0 { paren = '(' } else { paren = ')' } fmt.Printf("%c", paren) } } func listTrees(n uint) { for i := offset[n]; i < offset[n+1]; i++ { show(list[i], n*2) fmt.Println() } } func assemble(n uint, t tree, sl, pos, rem uint) { if rem == 0 { add(t) return } if sl > rem { sl = rem pos = offset[sl] } else if pos >= offset[sl+1] { sl-- if sl == 0 { return } pos = offset[sl] } assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl) assemble(n, t, sl, pos+1, rem) } func mktrees(n uint) { if offset[n+1] > 0 { return } if n > 0 { mktrees(n - 1) } assemble(n, 0, n-1, offset[n-1], n-1) offset[n+1] = uint(len(list)) } func main() { if len(os.Args) != 2 { log.Fatal("There must be exactly 1 command line argument") } n, err := strconv.Atoi(os.Args[1]) if err != nil { log.Fatal("Argument is not a valid number") } if n <= 0 || n > 19 { n = 5 } add(0) mktrees(uint(n)) fmt.Fprintf(os.Stderr, "Number of %d-trees: %d\n", n, offset[n+1]-offset[n]) listTrees(uint(n)) }
def bags(n,cache={}): if not n: return [(0, "")] upto = sum([bags(x) for x in range(n-1, 0, -1)], []) return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)] def bagchain(x, n, bb, start=0): if not n: return [x] out = [] for i in range(start, len(bb)): c,s = bb[i] if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i) return out def replace_brackets(s): depth,out = 0,[] for c in s: if c == '(': out.append("([{"[depth%3]) depth += 1 else: depth -= 1 out.append(")]}"[depth%3]) return "".join(out) for x in bags(5): print(replace_brackets(x[1]))
Generate an equivalent Python version of this Go code.
package example var ( X, Y, Z int ) func XP() { } func nonXP() {} var MEMEME int
class Doc(object): def method(self, num): pass
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "encoding/binary" "encoding/json" "fmt" "github.com/boltdb/bolt" "log" ) type StockTrans struct { Id int Date string Trans string Symbol string Quantity int Price float32 Settled bool } func (st *StockTrans) save(db *bolt.DB, bucket string) error { err := db.Update(func(tx *bolt.Tx) error { b := tx.Bucket([]byte(bucket)) id, _ := b.NextSequence() st.Id = int(id) encoded, err := json.Marshal(st) if err != nil { return err } return b.Put(itob(st.Id), encoded) }) return err } func itob(i int) []byte { b := make([]byte, 8) binary.BigEndian.PutUint64(b, uint64(i)) return b } func check(err error) { if err != nil { log.Fatal(err) } } func main() { db, err := bolt.Open("store.db", 0600, nil) check(err) defer db.Close() err = db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists([]byte("stocks")) return err }) check(err) transactions := []*StockTrans{ {0, "2006-01-05", "BUY", "RHAT", 100, 35.14, true}, {0, "2006-03-28", "BUY", "IBM", 1000, 45, true}, {0, "2006-04-06", "SELL", "IBM", 500, 53, true}, {0, "2006-04-05", "BUY", "MSOFT", 1000, 72, false}, } for _, trans := range transactions { err := trans.save(db, "stocks") check(err) } fmt.Println("Id Date Trans Sym Qty Price Settled") fmt.Println("------------------------------------------------") db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("stocks")) b.ForEach(func(k, v []byte) error { st := new(StockTrans) err := json.Unmarshal(v, st) check(err) fmt.Printf("%d %s  %-4s  %-5s %4d %2.2f %t\n", st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled) return nil }) return nil }) }
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> c = conn.cursor() >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ]: c.execute('insert into stocks values (?,?,?,?,?)', t) <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> >>> >>> c = conn.cursor() >>> c.execute('select * from stocks order by price') <sqlite3.Cursor object at 0x01326530> >>> for row in c: print row (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001) (u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0) (u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0) (u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0) >>>
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "encoding/binary" "encoding/json" "fmt" "github.com/boltdb/bolt" "log" ) type StockTrans struct { Id int Date string Trans string Symbol string Quantity int Price float32 Settled bool } func (st *StockTrans) save(db *bolt.DB, bucket string) error { err := db.Update(func(tx *bolt.Tx) error { b := tx.Bucket([]byte(bucket)) id, _ := b.NextSequence() st.Id = int(id) encoded, err := json.Marshal(st) if err != nil { return err } return b.Put(itob(st.Id), encoded) }) return err } func itob(i int) []byte { b := make([]byte, 8) binary.BigEndian.PutUint64(b, uint64(i)) return b } func check(err error) { if err != nil { log.Fatal(err) } } func main() { db, err := bolt.Open("store.db", 0600, nil) check(err) defer db.Close() err = db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists([]byte("stocks")) return err }) check(err) transactions := []*StockTrans{ {0, "2006-01-05", "BUY", "RHAT", 100, 35.14, true}, {0, "2006-03-28", "BUY", "IBM", 1000, 45, true}, {0, "2006-04-06", "SELL", "IBM", 500, 53, true}, {0, "2006-04-05", "BUY", "MSOFT", 1000, 72, false}, } for _, trans := range transactions { err := trans.save(db, "stocks") check(err) } fmt.Println("Id Date Trans Sym Qty Price Settled") fmt.Println("------------------------------------------------") db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("stocks")) b.ForEach(func(k, v []byte) error { st := new(StockTrans) err := json.Unmarshal(v, st) check(err) fmt.Printf("%d %s  %-4s  %-5s %4d %2.2f %t\n", st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled) return nil }) return nil }) }
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> c = conn.cursor() >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> c.execute() <sqlite3.Cursor object at 0x013263B0> >>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ]: c.execute('insert into stocks values (?,?,?,?,?)', t) <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> <sqlite3.Cursor object at 0x013263B0> >>> >>> c = conn.cursor() >>> c.execute('select * from stocks order by price') <sqlite3.Cursor object at 0x01326530> >>> for row in c: print row (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001) (u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0) (u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0) (u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0) >>>
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math" ) type circle struct { x, y, r float64 } func main() { c1 := circle{0, 0, 1} c2 := circle{4, 0, 1} c3 := circle{2, 4, 2} fmt.Println(ap(c1, c2, c3, true)) fmt.Println(ap(c1, c2, c3, false)) } func ap(c1, c2, c3 circle, s bool) circle { x1sq := c1.x * c1.x y1sq := c1.y * c1.y r1sq := c1.r * c1.r x2sq := c2.x * c2.x y2sq := c2.y * c2.y r2sq := c2.r * c2.r x3sq := c3.x * c3.x y3sq := c3.y * c3.y r3sq := c3.r * c3.r v11 := 2 * (c2.x - c1.x) v12 := 2 * (c2.y - c1.y) v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq v14 := 2 * (c2.r - c1.r) v21 := 2 * (c3.x - c2.x) v22 := 2 * (c3.y - c2.y) v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq v24 := 2 * (c3.r - c2.r) if s { v14 = -v14 v24 = -v24 } w12 := v12 / v11 w13 := v13 / v11 w14 := v14 / v11 w22 := v22/v21 - w12 w23 := v23/v21 - w13 w24 := v24/v21 - w14 p := -w23 / w22 q := w24 / w22 m := -w12*p - w13 n := w14 - w12*q a := n*n + q*q - 1 b := m*n - n*c1.x + p*q - q*c1.y if s { b -= c1.r } else { b += c1.r } b *= 2 c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq d := b*b - 4*a*c rs := (-b - math.Sqrt(d)) / (2 * a) return circle{m + n*rs, p + q*rs, rs} }
from collections import namedtuple import math Circle = namedtuple('Circle', 'x, y, r') def solveApollonius(c1, c2, c3, s1, s2, s3): x1, y1, r1 = c1 x2, y2, r2 = c2 x3, y3, r3 = c3 v11 = 2*x2 - 2*x1 v12 = 2*y2 - 2*y1 v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 v14 = 2*s2*r2 - 2*s1*r1 v21 = 2*x3 - 2*x2 v22 = 2*y3 - 2*y2 v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 v24 = 2*s3*r3 - 2*s2*r2 w12 = v12/v11 w13 = v13/v11 w14 = v14/v11 w22 = v22/v21-w12 w23 = v23/v21-w13 w24 = v24/v21-w14 P = -w23/w22 Q = w24/w22 M = -w12*P-w13 N = w14 - w12*Q a = N*N + Q*Q - 1 b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1 c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1 D = b*b-4*a*c rs = (-b-math.sqrt(D))/(2*a) xs = M+N*rs ys = P+Q*rs return Circle(xs, ys, rs) if __name__ == '__main__': c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2) print(solveApollonius(c1, c2, c3, 1, 1, 1)) print(solveApollonius(c1, c2, c3, -1, -1, -1))
Write the same code in Python as shown below in Go.
package main import "fmt" func main() { list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9} list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18} list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27} var list [9]int for i := 0; i < 9; i++ { list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i] } fmt.Println(list) }
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18] list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27] print([ ''.join(str(n) for n in z) for z in zip(list1, list2, list3) ])
Keep all operations the same but rewrite the snippet in Python.
package main import "fmt" func main() { list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9} list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18} list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27} var list [9]int for i := 0; i < 9; i++ { list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i] } fmt.Println(list) }
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18] list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27] print([ ''.join(str(n) for n in z) for z in zip(list1, list2, list3) ])
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "strings" ) func lcs(a []string) string { le := len(a) if le == 0 { return "" } if le == 1 { return a[0] } le0 := len(a[0]) minLen := le0 for i := 1; i < le; i++ { if len(a[i]) < minLen { minLen = len(a[i]) } } if minLen == 0 { return "" } res := "" a1 := a[1:] for i := 1; i <= minLen; i++ { suffix := a[0][le0-i:] for _, e := range a1 { if !strings.HasSuffix(e, suffix) { return res } } res = suffix } return res } func main() { tests := [][]string{ {"baabababc", "baabc", "bbbabc"}, {"baabababc", "baabc", "bbbazc"}, {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}, {"longest", "common", "suffix"}, {"suffix"}, {""}, } for _, test := range tests { fmt.Printf("%v -> \"%s\"\n", test, lcs(test)) } }
from itertools import takewhile from functools import reduce def longestCommonSuffix(xs): def allSame(cs): h = cs[0] return all(h == c for c in cs[1:]) def firstCharPrepended(s, cs): return cs[0] + s return reduce( firstCharPrepended, takewhile( allSame, zip(*(reversed(x) for x in xs)) ), '' ) def main(): samples = [ [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], [ "Sondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrydag", "Saterdag" ] ] for xs in samples: print( longestCommonSuffix(xs) ) if __name__ == '__main__': main()
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Write a version of this Go function in Python with identical behavior.
package main import ( "fmt" "unicode" ) const ( lcASCII = "abcdefghijklmnopqrstuvwxyz" ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) func main() { fmt.Println("ASCII lower case:") fmt.Println(lcASCII) for l := 'a'; l <= 'z'; l++ { fmt.Print(string(l)) } fmt.Println() fmt.Println("\nASCII upper case:") fmt.Println(ucASCII) for l := 'A'; l <= 'Z'; l++ { fmt.Print(string(l)) } fmt.Println() fmt.Println("\nUnicode version " + unicode.Version) showRange16("Lower case 16-bit code points:", unicode.Lower.R16) showRange32("Lower case 32-bit code points:", unicode.Lower.R32) showRange16("Upper case 16-bit code points:", unicode.Upper.R16) showRange32("Upper case 32-bit code points:", unicode.Upper.R32) } func showRange16(hdr string, rList []unicode.Range16) { fmt.Print("\n", hdr, "\n") fmt.Printf("%d ranges:\n", len(rList)) for _, rng := range rList { fmt.Printf("%U: ", rng.Lo) for r := rng.Lo; r <= rng.Hi; r += rng.Stride { fmt.Printf("%c", r) } fmt.Println() } } func showRange32(hdr string, rList []unicode.Range32) { fmt.Print("\n", hdr, "\n") fmt.Printf("%d ranges:\n", len(rList)) for _, rng := range rList { fmt.Printf("%U: ", rng.Lo) for r := rng.Lo; r <= rng.Hi; r += rng.Stride { fmt.Printf("%c", r) } fmt.Println() } }
classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal, str.isdigit, str.isidentifier, str.isnumeric, str.isprintable, str.isspace, str.istitle) for stringclass in classes: chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i))) print('\nString class %s has %i characters the first of which are:\n %r' % (stringclass.__name__, len(chars), chars[:100]))
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "log" ) func main() { m := [][]int{ {1, 3, 7, 8, 10}, {2, 4, 16, 14, 4}, {3, 1, 9, 18, 11}, {12, 14, 17, 18, 20}, {7, 1, 3, 9, 5}, } if len(m) != len(m[0]) { log.Fatal("Matrix must be square.") } sum := 0 for i := 1; i < len(m); i++ { for j := 0; j < i; j++ { sum = sum + m[i][j] } } fmt.Println("Sum of elements below main diagonal is", sum) }
from numpy import array, tril, sum A = [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]] print(sum(tril(A, -1)))
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "strings" "time" ) func get(url string) (res string, err error) { resp, err := http.Get(url) if err != nil { return "", err } buf, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(buf), nil } func grep(needle string, haystack string) (res []string) { for _, line := range strings.Split(haystack, "\n") { if strings.Contains(line, needle) { res = append(res, line) } } return res } func genUrl(i int, loc *time.Location) string { date := time.Now().In(loc).AddDate(0, 0, i) return date.Format("http: } func main() { needle := os.Args[1] back := -10 serverLoc, err := time.LoadLocation("Europe/Berlin") if err != nil { log.Fatal(err) } for i := back; i <= 0; i++ { url := genUrl(i, serverLoc) contents, err := get(url) if err != nil { log.Fatal(err) } found := grep(needle, contents) if len(found) > 0 { fmt.Printf("%v\n------\n", url) for _, line := range found { fmt.Printf("%v\n", line) } fmt.Printf("------\n\n") } } }
import datetime import re import urllib.request import sys def get(url): with urllib.request.urlopen(url) as response: html = response.read().decode('utf-8') if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html): return None return html def main(): template = 'http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl' today = datetime.datetime.utcnow() back = 10 needle = sys.argv[1] for i in range(-back, 2): day = today + datetime.timedelta(days=i) url = day.strftime(template) haystack = get(url) if haystack: mentions = [x for x in haystack.split('\n') if needle in x] if mentions: print('{}\n------\n{}\n------\n' .format(url, '\n'.join(mentions))) main()
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "io/ioutil" "net/http" "regexp" "sort" "strconv" ) type Result struct { lang string users int } func main() { const minimum = 25 ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)` re := regexp.MustCompile(ex) page := "http: action := "action=query" format := "format=json" fversion := "formatversion=2" generator := "generator=categorymembers" gcmTitle := "gcmtitle=Category:Language%20users" gcmLimit := "gcmlimit=500" prop := "prop=categoryinfo" rawContinue := "rawcontinue=" page += fmt.Sprintf("%s&%s&%s&%s&%s&%s&%s&%s", action, format, fversion, generator, gcmTitle, gcmLimit, prop, rawContinue) resp, _ := http.Get(page) body, _ := ioutil.ReadAll(resp.Body) matches := re.FindAllStringSubmatch(string(body), -1) resp.Body.Close() var results []Result for _, match := range matches { if len(match) == 5 { users, _ := strconv.Atoi(match[4]) if users >= minimum { result := Result{match[1], users} results = append(results, result) } } } sort.Slice(results, func(i, j int) bool { return results[j].users < results[i].users }) fmt.Println("Rank Users Language") fmt.Println("---- ----- --------") rank := 0 lastUsers := 0 lastRank := 0 for i, result := range results { eq := " " rank = i + 1 if lastUsers == result.users { eq = "=" rank = lastRank } else { lastUsers = result.users lastRank = rank } fmt.Printf(" %-2d%s %3d %s\n", rank, eq, result.users, result.lang) } }
import requests URL = "http://rosettacode.org/mw/api.php" PARAMS = { "action": "query", "format": "json", "formatversion": 2, "generator": "categorymembers", "gcmtitle": "Category:Language users", "gcmlimit": 500, "prop": "categoryinfo", } def fetch_data(): counts = {} continue_ = {"continue": ""} while continue_: resp = requests.get(URL, params={**PARAMS, **continue_}) resp.raise_for_status() data = resp.json() counts.update( { p["title"]: p.get("categoryinfo", {}).get("size", 0) for p in data["query"]["pages"] } ) continue_ = data.get("continue", {}) return counts if __name__ == "__main__": counts = fetch_data() at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100] top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True) for i, lang in enumerate(top_languages): print(f"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}")
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "io/ioutil" "net/http" "regexp" "sort" "strconv" ) type Result struct { lang string users int } func main() { const minimum = 25 ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)` re := regexp.MustCompile(ex) page := "http: action := "action=query" format := "format=json" fversion := "formatversion=2" generator := "generator=categorymembers" gcmTitle := "gcmtitle=Category:Language%20users" gcmLimit := "gcmlimit=500" prop := "prop=categoryinfo" rawContinue := "rawcontinue=" page += fmt.Sprintf("%s&%s&%s&%s&%s&%s&%s&%s", action, format, fversion, generator, gcmTitle, gcmLimit, prop, rawContinue) resp, _ := http.Get(page) body, _ := ioutil.ReadAll(resp.Body) matches := re.FindAllStringSubmatch(string(body), -1) resp.Body.Close() var results []Result for _, match := range matches { if len(match) == 5 { users, _ := strconv.Atoi(match[4]) if users >= minimum { result := Result{match[1], users} results = append(results, result) } } } sort.Slice(results, func(i, j int) bool { return results[j].users < results[i].users }) fmt.Println("Rank Users Language") fmt.Println("---- ----- --------") rank := 0 lastUsers := 0 lastRank := 0 for i, result := range results { eq := " " rank = i + 1 if lastUsers == result.users { eq = "=" rank = lastRank } else { lastUsers = result.users lastRank = rank } fmt.Printf(" %-2d%s %3d %s\n", rank, eq, result.users, result.lang) } }
import requests URL = "http://rosettacode.org/mw/api.php" PARAMS = { "action": "query", "format": "json", "formatversion": 2, "generator": "categorymembers", "gcmtitle": "Category:Language users", "gcmlimit": 500, "prop": "categoryinfo", } def fetch_data(): counts = {} continue_ = {"continue": ""} while continue_: resp = requests.get(URL, params={**PARAMS, **continue_}) resp.raise_for_status() data = resp.json() counts.update( { p["title"]: p.get("categoryinfo", {}).get("size", 0) for p in data["query"]["pages"] } ) continue_ = data.get("continue", {}) return counts if __name__ == "__main__": counts = fetch_data() at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100] top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True) for i, lang in enumerate(top_languages): print(f"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}")
Transform the following Go implementation into Python, maintaining the same output and logic.
#!/bin/bash sed -n -e '12,$p' < "$0" > ttmmpp.go go build ttmmpp.go rm ttmmpp.go binfile="${0%.*}" mv ttmmpp $binfile $binfile "$@" STATUS=$? rm $binfile exit $STATUS ######## Go Code start on line 12 package main import ( "fmt" "os" ) func main() { for i, x := range os.Args { if i == 0 { fmt.Printf("This program is named %s.\n", x) } else { fmt.Printf("the argument #%d is %s\n", i, x) } } }
"exec" "python" "$0" print "Hello World"
Transform the following Go implementation into Python, maintaining the same output and logic.
#!/bin/bash sed -n -e '12,$p' < "$0" > ttmmpp.go go build ttmmpp.go rm ttmmpp.go binfile="${0%.*}" mv ttmmpp $binfile $binfile "$@" STATUS=$? rm $binfile exit $STATUS ######## Go Code start on line 12 package main import ( "fmt" "os" ) func main() { for i, x := range os.Args { if i == 0 { fmt.Printf("This program is named %s.\n", x) } else { fmt.Printf("the argument #%d is %s\n", i, x) } } }
"exec" "python" "$0" print "Hello World"
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "fmt" "os" "strings" ) func main() { lang := strings.ToUpper(os.Getenv("LANG")) if strings.Contains(lang, "UTF") { fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3') } else { fmt.Println("This terminal does not support unicode") } }
import sys if "UTF-8" in sys.stdout.encoding: print("△") else: raise Exception("Terminal can't handle UTF-8")
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "os" "strings" ) func main() { lang := strings.ToUpper(os.Getenv("LANG")) if strings.Contains(lang, "UTF") { fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3') } else { fmt.Println("This terminal does not support unicode") } }
import sys if "UTF-8" in sys.stdout.encoding: print("△") else: raise Exception("Terminal can't handle UTF-8")
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "math" "rcu" ) func main() { limit := 999999 primes := rcu.Primes(limit) fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:") for i := 1; i < len(primes); i++ { diff := primes[i] - primes[i-1] if diff > 36 { s := int(math.Sqrt(float64(diff))) if diff == s*s { cp1 := rcu.Commatize(primes[i]) cp2 := rcu.Commatize(primes[i-1]) fmt.Printf("%7s - %7s = %3d = %2d x %2d\n", cp1, cp2, diff, s, s) } } } }
import math print("working...") limit = 1000000 Primes = [] oldPrime = 0 newPrime = 0 x = 0 def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issquare(x): for n in range(x): if (x == n*n): return 1 return 0 for n in range(limit): if isPrime(n): Primes.append(n) for n in range(2,len(Primes)): pr1 = Primes[n] pr2 = Primes[n-1] diff = pr1 - pr2 flag = issquare(diff) if (flag == 1 and diff > 36): print(str(pr1) + " " + str(pr2) + " diff = " + str(diff)) print("done...")
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math" "rcu" ) func main() { limit := 999999 primes := rcu.Primes(limit) fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:") for i := 1; i < len(primes); i++ { diff := primes[i] - primes[i-1] if diff > 36 { s := int(math.Sqrt(float64(diff))) if diff == s*s { cp1 := rcu.Commatize(primes[i]) cp2 := rcu.Commatize(primes[i-1]) fmt.Printf("%7s - %7s = %3d = %2d x %2d\n", cp1, cp2, diff, s, s) } } } }
import math print("working...") limit = 1000000 Primes = [] oldPrime = 0 newPrime = 0 x = 0 def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issquare(x): for n in range(x): if (x == n*n): return 1 return 0 for n in range(limit): if isPrime(n): Primes.append(n) for n in range(2,len(Primes)): pr1 = Primes[n] pr2 = Primes[n-1] diff = pr1 - pr2 flag = issquare(diff) if (flag == 1 and diff > 36): print(str(pr1) + " " + str(pr2) + " diff = " + str(diff)) print("done...")
Preserve the algorithm and functionality while converting the code from Go to Python.
import ( "fmt" "os" ) if err := os.Truncate("filename", newSize); err != nil { fmt.Println(err) }
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
Preserve the algorithm and functionality while converting the code from Go to Python.
import ( "fmt" "os" ) if err := os.Truncate("filename", newSize); err != nil { fmt.Println(err) }
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "log" "os/exec" "time" ) func main() { out, err := exec.Command("xrandr", "-q").Output() if err != nil { log.Fatal(err) } fmt.Println(string(out)) time.Sleep(3 * time.Second) err = exec.Command("xrandr", "-s", "1024x768").Run() if err != nil { log.Fatal(err) } time.Sleep(3 * time.Second) err = exec.Command("xrandr", "-s", "1366x768").Run() if err != nil { log.Fatal(err) } }
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "log" "os/exec" "time" ) func main() { out, err := exec.Command("xrandr", "-q").Output() if err != nil { log.Fatal(err) } fmt.Println(string(out)) time.Sleep(3 * time.Second) err = exec.Command("xrandr", "-s", "1024x768").Run() if err != nil { log.Fatal(err) } time.Sleep(3 * time.Second) err = exec.Command("xrandr", "-s", "1366x768").Run() if err != nil { log.Fatal(err) } }
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
Write the same code in Python as shown below in Go.
package main import ( "log" gc "code.google.com/p/goncurses" ) func main() { _, err := gc.Init() if err != nil { log.Fatal("init:", err) } defer gc.End() gc.FlushInput() }
def flush_input(): try: import msvcrt while msvcrt.kbhit(): msvcrt.getch() except ImportError: import sys, termios termios.tcflush(sys.stdin, termios.TCIOFLUSH)
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math" ) type F = func(float64) float64 func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) { m = (a + b) / 2 fm = f(m) simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb) return } func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 { lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm) rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb) delta := left + right - whole if math.Abs(delta) <= eps*15 { return left + right + delta/15 } return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) + quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm) } func quadAsr(f F, a, b, eps float64) float64 { fa, fb := f(a), f(b) m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb) return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm) } func main() { a, b := 0.0, 1.0 sinx := quadAsr(math.Sin, a, b, 1e-09) fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx) }
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float: lt = _quad_simpsons_mem(f, a, fa, m, fm) rt = _quad_simpsons_mem(f, m, fm, b, fb) delta = lt.simp + rt.simp - whole return (lt.simp + rt.simp + delta/15 if (abs(delta) <= eps * 15) else _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) + _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm) ) def quad_asr(f: callable, a: float, b: float, eps: float)->float: fa = f(a) fb = f(b) t = _quad_simpsons_mem(f, a, fa, b, fb) return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm) def main(): (a, b,) = (0.0, 1.0,) sinx = quad_asr(math.sin, a, b, 1e-09); print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx)) main()
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "fmt" "math" ) type F = func(float64) float64 func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) { m = (a + b) / 2 fm = f(m) simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb) return } func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 { lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm) rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb) delta := left + right - whole if math.Abs(delta) <= eps*15 { return left + right + delta/15 } return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) + quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm) } func quadAsr(f F, a, b, eps float64) float64 { fa, fb := f(a), f(b) m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb) return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm) } func main() { a, b := 0.0, 1.0 sinx := quadAsr(math.Sin, a, b, 1e-09) fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx) }
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float: lt = _quad_simpsons_mem(f, a, fa, m, fm) rt = _quad_simpsons_mem(f, m, fm, b, fb) delta = lt.simp + rt.simp - whole return (lt.simp + rt.simp + delta/15 if (abs(delta) <= eps * 15) else _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) + _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm) ) def quad_asr(f: callable, a: float, b: float, eps: float)->float: fa = f(a) fb = f(b) t = _quad_simpsons_mem(f, a, fa, b, fb) return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm) def main(): (a, b,) = (0.0, 1.0,) sinx = quad_asr(math.sin, a, b, 1e-09); print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx)) main()
Write the same code in Python as shown below in Go.
package main import ( "fmt" "math" ) type F = func(float64) float64 func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) { m = (a + b) / 2 fm = f(m) simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb) return } func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 { lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm) rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb) delta := left + right - whole if math.Abs(delta) <= eps*15 { return left + right + delta/15 } return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) + quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm) } func quadAsr(f F, a, b, eps float64) float64 { fa, fb := f(a), f(b) m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb) return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm) } func main() { a, b := 0.0, 1.0 sinx := quadAsr(math.Sin, a, b, 1e-09) fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx) }
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float: lt = _quad_simpsons_mem(f, a, fa, m, fm) rt = _quad_simpsons_mem(f, m, fm, b, fb) delta = lt.simp + rt.simp - whole return (lt.simp + rt.simp + delta/15 if (abs(delta) <= eps * 15) else _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) + _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm) ) def quad_asr(f: callable, a: float, b: float, eps: float)->float: fa = f(a) fb = f(b) t = _quad_simpsons_mem(f, a, fa, b, fb) return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm) def main(): (a, b,) = (0.0, 1.0,) sinx = quad_asr(math.sin, a, b, 1e-09); print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx)) main()
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "bufio" "fmt" "os" ) func main() { f, err := os.Open("rc.fasta") if err != nil { fmt.Println(err) return } defer f.Close() s := bufio.NewScanner(f) headerFound := false for s.Scan() { line := s.Text() switch { case line == "": continue case line[0] != '>': if !headerFound { fmt.Println("missing header") return } fmt.Print(line) case headerFound: fmt.Println() fallthrough default: fmt.Printf("%s: ", line[1:]) headerFound = true } } if headerFound { fmt.Println() } if err := s.Err(); err != nil { fmt.Println(err) } }
import io FASTA= infile = io.StringIO(FASTA) def fasta_parse(infile): key = '' for line in infile: if line.startswith('>'): if key: yield key, val key, val = line[1:].rstrip().split()[0], '' elif key: val += line.rstrip() if key: yield key, val print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
Generate an equivalent Python version of this Go code.
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func main() { count := 0 fmt.Println("Cousin prime pairs whose elements are less than 1,000:") for i := 3; i <= 995; i += 2 { if isPrime(i) && isPrime(i+4) { fmt.Printf("%3d:%3d ", i, i+4) count++ if count%7 == 0 { fmt.Println() } if i != 3 { i += 4 } else { i += 2 } } } fmt.Printf("\n\n%d pairs found\n", count) }
from itertools import chain, takewhile def cousinPrimes(): def go(x): n = 4 + x return [(x, n)] if isPrime(n) else [] return chain.from_iterable( map(go, primes()) ) def main(): pairs = list( takewhile( lambda ab: 1000 > ab[1], cousinPrimes() ) ) print(f'{len(pairs)} cousin pairs below 1000:\n') print( spacedTable(list( chunksOf(4)([ repr(x) for x in pairs ]) )) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def 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 def listTranspose(xss): def go(xss): if xss: h, *t = xss return ( [[h[0]] + [xs[0] for xs in t if xs]] + ( go([h[1:]] + [xs[1:] for xs in t]) ) ) if h and isinstance(h, list) else go(t) else: return [] return go(xss) def spacedTable(rows): columnWidths = [ len(str(row[-1])) for row in listTranspose(rows) ] return '\n'.join([ ' '.join( map( lambda w, s: s.rjust(w, ' '), columnWidths, row ) ) for row in rows ]) if __name__ == '__main__': main()
Convert this Go block to Python, preserving its control flow and logic.
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func main() { count := 0 fmt.Println("Cousin prime pairs whose elements are less than 1,000:") for i := 3; i <= 995; i += 2 { if isPrime(i) && isPrime(i+4) { fmt.Printf("%3d:%3d ", i, i+4) count++ if count%7 == 0 { fmt.Println() } if i != 3 { i += 4 } else { i += 2 } } } fmt.Printf("\n\n%d pairs found\n", count) }
from itertools import chain, takewhile def cousinPrimes(): def go(x): n = 4 + x return [(x, n)] if isPrime(n) else [] return chain.from_iterable( map(go, primes()) ) def main(): pairs = list( takewhile( lambda ab: 1000 > ab[1], cousinPrimes() ) ) print(f'{len(pairs)} cousin pairs below 1000:\n') print( spacedTable(list( chunksOf(4)([ repr(x) for x in pairs ]) )) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def 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 def listTranspose(xss): def go(xss): if xss: h, *t = xss return ( [[h[0]] + [xs[0] for xs in t if xs]] + ( go([h[1:]] + [xs[1:] for xs in t]) ) ) if h and isinstance(h, list) else go(t) else: return [] return go(xss) def spacedTable(rows): columnWidths = [ len(str(row[-1])) for row in listTranspose(rows) ] return '\n'.join([ ' '.join( map( lambda w, s: s.rjust(w, ' '), columnWidths, row ) ) for row in rows ]) if __name__ == '__main__': main()
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "strconv" "time" ) func isPalindrome2(n uint64) bool { x := uint64(0) if (n & 1) == 0 { return n == 0 } for x < n { x = (x << 1) | (n & 1) n >>= 1 } return n == x || n == (x>>1) } func reverse3(n uint64) uint64 { x := uint64(0) for n != 0 { x = x*3 + (n % 3) n /= 3 } return x } func show(n uint64) { fmt.Println("Decimal :", n) fmt.Println("Binary  :", strconv.FormatUint(n, 2)) fmt.Println("Ternary :", strconv.FormatUint(n, 3)) fmt.Println("Time  :", time.Since(start)) fmt.Println() } func min(a, b uint64) uint64 { if a < b { return a } return b } func max(a, b uint64) uint64 { if a > b { return a } return b } var start time.Time func main() { start = time.Now() fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n") show(0) cnt := 1 var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1 for { i := lo for ; i < hi; i++ { n := (i*3+1)*pow3 + reverse3(i) if !isPalindrome2(n) { continue } show(n) cnt++ if cnt >= 7 { return } } if i == pow3 { pow3 *= 3 } else { pow2 *= 4 } for { for pow2 <= pow3 { pow2 *= 4 } lo2 := (pow2/pow3 - 1) / 3 hi2 := (pow2*2/pow3-1)/3 + 1 lo3 := pow3 / 3 hi3 := pow3 if lo2 >= hi3 { pow3 *= 3 } else if lo3 >= hi2 { pow2 *= 4 } else { lo = max(lo2, lo3) hi = min(hi2, hi3) break } } } }
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] return based == based[::-1] def pal_23(): yield 0 yield 1 n = 1 while True: n += 1 b = baseN(n, 3) revb = b[::-1] for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb), '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)): t = int(trial, 3) if pal2(t): yield t for pal23 in islice(pal_23(), 6): print(pal23, baseN(pal23, 3), baseN(pal23, 2))
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "strconv" "time" ) func isPalindrome2(n uint64) bool { x := uint64(0) if (n & 1) == 0 { return n == 0 } for x < n { x = (x << 1) | (n & 1) n >>= 1 } return n == x || n == (x>>1) } func reverse3(n uint64) uint64 { x := uint64(0) for n != 0 { x = x*3 + (n % 3) n /= 3 } return x } func show(n uint64) { fmt.Println("Decimal :", n) fmt.Println("Binary  :", strconv.FormatUint(n, 2)) fmt.Println("Ternary :", strconv.FormatUint(n, 3)) fmt.Println("Time  :", time.Since(start)) fmt.Println() } func min(a, b uint64) uint64 { if a < b { return a } return b } func max(a, b uint64) uint64 { if a > b { return a } return b } var start time.Time func main() { start = time.Now() fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n") show(0) cnt := 1 var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1 for { i := lo for ; i < hi; i++ { n := (i*3+1)*pow3 + reverse3(i) if !isPalindrome2(n) { continue } show(n) cnt++ if cnt >= 7 { return } } if i == pow3 { pow3 *= 3 } else { pow2 *= 4 } for { for pow2 <= pow3 { pow2 *= 4 } lo2 := (pow2/pow3 - 1) / 3 hi2 := (pow2*2/pow3-1)/3 + 1 lo3 := pow3 / 3 hi3 := pow3 if lo2 >= hi3 { pow3 *= 3 } else if lo3 >= hi2 { pow2 *= 4 } else { lo = max(lo2, lo3) hi = min(hi2, hi3) break } } } }
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] return based == based[::-1] def pal_23(): yield 0 yield 1 n = 1 while True: n += 1 b = baseN(n, 3) revb = b[::-1] for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb), '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)): t = int(trial, 3) if pal2(t): yield t for pal23 in islice(pal_23(), 6): print(pal23, baseN(pal23, 3), baseN(pal23, 2))
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "golang.org/x/crypto/ssh/terminal" "fmt" "os" ) func main() { if terminal.IsTerminal(int(os.Stdin.Fd())) { fmt.Println("Hello terminal") } else { fmt.Println("Who are you? You're not a terminal.") } }
from sys import stdin if stdin.isatty(): print("Input comes from tty.") else: print("Input doesn't come from tty.")
Generate an equivalent Python version of this Go code.
package main import ( "golang.org/x/crypto/ssh/terminal" "fmt" "os" ) func main() { if terminal.IsTerminal(int(os.Stdin.Fd())) { fmt.Println("Hello terminal") } else { fmt.Println("Who are you? You're not a terminal.") } }
from sys import stdin if stdin.isatty(): print("Input comes from tty.") else: print("Input doesn't come from tty.")
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "log" "github.com/jezek/xgb" "github.com/jezek/xgb/xproto" ) func main() { X, err := xgb.NewConn() if err != nil { log.Fatal(err) } points := []xproto.Point{ {10, 10}, {10, 20}, {20, 10}, {20, 20}}; polyline := []xproto.Point{ {50, 10}, { 5, 20}, {25,-20}, {10, 10}}; segments := []xproto.Segment{ {100, 10, 140, 30}, {110, 25, 130, 60}}; rectangles := []xproto.Rectangle{ { 10, 50, 40, 20}, { 80, 50, 10, 40}}; arcs := []xproto.Arc{ {10, 100, 60, 40, 0, 90 << 6}, {90, 100, 55, 40, 0, 270 << 6}}; setup := xproto.Setup(X) screen := setup.DefaultScreen(X) foreground, _ := xproto.NewGcontextId(X) mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures) values := []uint32{screen.BlackPixel, 0} xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values) win, _ := xproto.NewWindowId(X) winDrawable := xproto.Drawable(win) mask = uint32(xproto.CwBackPixel | xproto.CwEventMask) values = []uint32{screen.WhitePixel, xproto.EventMaskExposure} xproto.CreateWindow(X, screen.RootDepth, win, screen.Root, 0, 0, 150, 150, 10, xproto.WindowClassInputOutput, screen.RootVisual, mask, values) xproto.MapWindow(X, win) for { evt, err := X.WaitForEvent() switch evt.(type) { case xproto.ExposeEvent: xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points) xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline) xproto.PolySegment(X, winDrawable, foreground, segments) xproto.PolyRectangle(X, winDrawable, foreground, rectangles) xproto.PolyArc(X, winDrawable, foreground, arcs) default: } if err != nil { log.Fatal(err) } } return }
from Xlib import X, display class Window: def __init__(self, display, msg): self.display = display self.msg = msg self.screen = self.display.screen() self.window = self.screen.root.create_window( 10, 10, 100, 100, 1, self.screen.root_depth, background_pixel=self.screen.white_pixel, event_mask=X.ExposureMask | X.KeyPressMask, ) self.gc = self.window.create_gc( foreground = self.screen.black_pixel, background = self.screen.white_pixel, ) self.window.map() def loop(self): while True: e = self.display.next_event() if e.type == X.Expose: self.window.fill_rectangle(self.gc, 20, 20, 10, 10) self.window.draw_text(self.gc, 10, 50, self.msg) elif e.type == X.KeyPress: raise SystemExit if __name__ == "__main__": Window(display.Display(), "Hello, World!").loop()
Translate the given Go code snippet into Python without altering its behavior.
package main import "fmt" const n = 64 func pow2(x uint) uint64 { return uint64(1) << x } func evolve(state uint64, rule int) { for p := 0; p < 10; p++ { b := uint64(0) for q := 7; q >= 0; q-- { st := state b |= (st & 1) << uint(q) state = 0 for i := uint(0); i < n; i++ { var t1, t2, t3 uint64 if i > 0 { t1 = st >> (i - 1) } else { t1 = st >> 63 } if i == 0 { t2 = st << 1 } else if i == 1 { t2 = st << 63 } else { t2 = st << (n + 1 - i) } t3 = 7 & (t1 | t2) if (uint64(rule) & pow2(uint(t3))) != 0 { state |= pow2(i) } } } fmt.Printf("%d ", b) } fmt.Println() } func main() { evolve(1, 30) }
from elementary_cellular_automaton import eca, eca_wrap def rule30bytes(lencells=100): cells = '1' + '0' * (lencells - 1) gen = eca(cells, 30) while True: yield int(''.join(next(gen)[0] for i in range(8)), 2) if __name__ == '__main__': print([b for i,b in zip(range(10), rule30bytes())])
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "os" "golang.org/x/crypto/ssh/terminal" ) func main() { w, h, err := terminal.GetSize(int(os.Stdout.Fd())) if err != nil { fmt.Println(err) return } fmt.Println(h, w) }
import os def get_windows_terminal(): from ctypes import windll, create_string_buffer h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if not res: return 80, 25 import struct (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\ = struct.unpack("hhhhHhhhhhh", csbi.raw) width = right - left + 1 height = bottom - top + 1 return width, height def get_linux_terminal(): width = os.popen('tput cols', 'r').readline() height = os.popen('tput lines', 'r').readline() return int(width), int(height) print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
Generate an equivalent Python version of this Go code.
package main import ( "bufio" "fmt" "log" "os" "strings" ) type state int const ( ready state = iota waiting exit dispense refunding ) func check(err error) { if err != nil { log.Fatal(err) } } func fsm() { fmt.Println("Please enter your option when prompted") fmt.Println("(any characters after the first will be ignored)") state := ready var trans string scanner := bufio.NewScanner(os.Stdin) for { switch state { case ready: for { fmt.Print("\n(D)ispense or (Q)uit : ") scanner.Scan() trans = scanner.Text() check(scanner.Err()) if len(trans) == 0 { continue } option := strings.ToLower(trans)[0] if option == 'd' { state = waiting break } else if option == 'q' { state = exit break } } case waiting: fmt.Println("OK, put your money in the slot") for { fmt.Print("(S)elect product or choose a (R)efund : ") scanner.Scan() trans = scanner.Text() check(scanner.Err()) if len(trans) == 0 { continue } option := strings.ToLower(trans)[0] if option == 's' { state = dispense break } else if option == 'r' { state = refunding break } } case dispense: for { fmt.Print("(R)emove product : ") scanner.Scan() trans = scanner.Text() check(scanner.Err()) if len(trans) == 0 { continue } option := strings.ToLower(trans)[0] if option == 'r' { state = ready break } } case refunding: fmt.Println("OK, refunding your money") state = ready case exit: fmt.Println("OK, quitting") return } } } func main() { fsm() }
states = { 'ready':{ 'prompt' : 'Machine ready: (d)eposit, or (q)uit?', 'responses' : ['d','q']}, 'waiting':{ 'prompt' : 'Machine waiting: (s)elect, or (r)efund?', 'responses' : ['s','r']}, 'dispense' : { 'prompt' : 'Machine dispensing: please (r)emove product', 'responses' : ['r']}, 'refunding' : { 'prompt' : 'Refunding money', 'responses' : []}, 'exit' :{} } transitions = { 'ready': { 'd': 'waiting', 'q': 'exit'}, 'waiting' : { 's' : 'dispense', 'r' : 'refunding'}, 'dispense' : { 'r' : 'ready'}, 'refunding' : { '' : 'ready'}} def Acceptor(prompt, valids): if not valids: print(prompt) return '' else: while True: resp = input(prompt)[0].lower() if resp in valids: return resp def finite_state_machine(initial_state, exit_state): response = True next_state = initial_state current_state = states[next_state] while response != exit_state: response = Acceptor(current_state['prompt'], current_state['responses']) next_state = transitions[next_state][response] current_state = states[next_state] if __name__ == "__main__": finite_state_machine('ready','q')
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "image" "image/color" "image/gif" "log" "os" ) var ( black = color.RGBA{0, 0, 0, 255} red = color.RGBA{255, 0, 0, 255} green = color.RGBA{0, 255, 0, 255} blue = color.RGBA{0, 0, 255, 255} magenta = color.RGBA{255, 0, 255, 255} cyan = color.RGBA{0, 255, 255, 255} yellow = color.RGBA{255, 255, 0, 255} white = color.RGBA{255, 255, 255, 255} ) var palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black} func hline(img *image.Paletted, x1, y, x2 int, ci uint8) { for ; x1 <= x2; x1++ { img.SetColorIndex(x1, y, ci) } } func vline(img *image.Paletted, x, y1, y2 int, ci uint8) { for ; y1 <= y2; y1++ { img.SetColorIndex(x, y1, ci) } } func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) { for x := 0; x < w; x++ { for y := 0; y < h; y++ { img.SetColorIndex(x, y, ci) } } } func drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) { hline(img, x1, y1, x2, ci) hline(img, x1, y2, x2, ci) vline(img, x1, y1, y2, ci) vline(img, x2, y1, y2, ci) } func main() { const nframes = 140 const delay = 10 width, height := 500, 500 anim := gif.GIF{LoopCount: nframes} rect := image.Rect(0, 0, width, height) for c := uint8(0); c < 7; c++ { for f := 0; f < 20; f++ { img := image.NewPaletted(rect, palette) setBackgroundColor(img, width, height, 7) for r := 0; r < 20; r++ { ix := c if r < f { ix = (ix + 1) % 7 } x := width * (r + 1) / 50 y := height * (r + 1) / 50 w := width - x h := height - y drawRectangle(img, x, y, w, h, ix) } anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } } file, err := os.Create("vibrating.gif") if err != nil { log.Fatal(err) } defer file.Close() if err2 := gif.EncodeAll(file, &anim); err != nil { log.Fatal(err2) } }
import turtle from itertools import cycle from time import sleep def rect(t, x, y): x2, y2 = x/2, y/2 t.setpos(-x2, -y2) t.pendown() for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: t.goto(pos) t.penup() def rects(t, colour, wait_between_rect=0.1): for x in range(550, 0, -25): t.color(colour) rect(t, x, x*.75) sleep(wait_between_rect) tl=turtle.Turtle() screen=turtle.Screen() screen.setup(620,620) screen.bgcolor('black') screen.title('Rosetta Code Vibrating Rectangles') tl.pensize(3) tl.speed(0) tl.penup() tl.ht() colours = 'red green blue orange white yellow'.split() for colour in cycle(colours): rects(tl, colour) sleep(0.5)
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "image" "image/color" "image/gif" "log" "os" ) var ( black = color.RGBA{0, 0, 0, 255} red = color.RGBA{255, 0, 0, 255} green = color.RGBA{0, 255, 0, 255} blue = color.RGBA{0, 0, 255, 255} magenta = color.RGBA{255, 0, 255, 255} cyan = color.RGBA{0, 255, 255, 255} yellow = color.RGBA{255, 255, 0, 255} white = color.RGBA{255, 255, 255, 255} ) var palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black} func hline(img *image.Paletted, x1, y, x2 int, ci uint8) { for ; x1 <= x2; x1++ { img.SetColorIndex(x1, y, ci) } } func vline(img *image.Paletted, x, y1, y2 int, ci uint8) { for ; y1 <= y2; y1++ { img.SetColorIndex(x, y1, ci) } } func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) { for x := 0; x < w; x++ { for y := 0; y < h; y++ { img.SetColorIndex(x, y, ci) } } } func drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) { hline(img, x1, y1, x2, ci) hline(img, x1, y2, x2, ci) vline(img, x1, y1, y2, ci) vline(img, x2, y1, y2, ci) } func main() { const nframes = 140 const delay = 10 width, height := 500, 500 anim := gif.GIF{LoopCount: nframes} rect := image.Rect(0, 0, width, height) for c := uint8(0); c < 7; c++ { for f := 0; f < 20; f++ { img := image.NewPaletted(rect, palette) setBackgroundColor(img, width, height, 7) for r := 0; r < 20; r++ { ix := c if r < f { ix = (ix + 1) % 7 } x := width * (r + 1) / 50 y := height * (r + 1) / 50 w := width - x h := height - y drawRectangle(img, x, y, w, h, ix) } anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } } file, err := os.Create("vibrating.gif") if err != nil { log.Fatal(err) } defer file.Close() if err2 := gif.EncodeAll(file, &anim); err != nil { log.Fatal(err2) } }
import turtle from itertools import cycle from time import sleep def rect(t, x, y): x2, y2 = x/2, y/2 t.setpos(-x2, -y2) t.pendown() for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: t.goto(pos) t.penup() def rects(t, colour, wait_between_rect=0.1): for x in range(550, 0, -25): t.color(colour) rect(t, x, x*.75) sleep(wait_between_rect) tl=turtle.Turtle() screen=turtle.Screen() screen.setup(620,620) screen.bgcolor('black') screen.title('Rosetta Code Vibrating Rectangles') tl.pensize(3) tl.speed(0) tl.penup() tl.ht() colours = 'red green blue orange white yellow'.split() for colour in cycle(colours): rects(tl, colour) sleep(0.5)
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "sort" ) func main() { a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11} for len(a) > 1 { sort.Ints(a) fmt.Println("Sorted list:", a) sum := a[0] + a[1] fmt.Printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum) a = append(a, sum) a = a[2:] } fmt.Println("Last item is", a[0], "\b.") }
def add_least_reduce(lis): while len(lis) > 1: lis.append(lis.pop(lis.index(min(lis))) + lis.pop(lis.index(min(lis)))) print('Interim list:', lis) return lis LIST = [6, 81, 243, 14, 25, 49, 123, 69, 11] print(LIST, ' ==> ', add_least_reduce(LIST.copy()))
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "rcu" ) func main() { numbers1 := [5]int{5, 45, 23, 21, 67} numbers2 := [5]int{43, 22, 78, 46, 38} numbers3 := [5]int{9, 98, 12, 98, 53} numbers := [5]int{} for n := 0; n < 5; n++ { numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n]) } fmt.Println(numbers) }
numbers1 = [5,45,23,21,67] numbers2 = [43,22,78,46,38] numbers3 = [9,98,12,98,53] numbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))] print(numbers)
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "rcu" ) func main() { numbers1 := [5]int{5, 45, 23, 21, 67} numbers2 := [5]int{43, 22, 78, 46, 38} numbers3 := [5]int{9, 98, 12, 98, 53} numbers := [5]int{} for n := 0; n < 5; n++ { numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n]) } fmt.Println(numbers) }
numbers1 = [5,45,23,21,67] numbers2 = [43,22,78,46,38] numbers3 = [9,98,12,98,53] numbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))] print(numbers)
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { return } var a, ω2 int for a = 0; ; a++ { ω2 = (a*a + p - n) % p if ls(ω2) == p-1 { break } } type point struct{ x, y int } mul := func(a, b point) point { return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p} } r := point{1, 0} s := point{a, 1} for n := (p + 1) >> 1 % p; n > 0; n >>= 1 { if n&1 == 1 { r = mul(r, s) } s = mul(s, s) } if r.y != 0 { return } if r.x*r.x%p != n { return } return r.x, p - r.x, true } func main() { fmt.Println(c(10, 13)) fmt.Println(c(56, 101)) fmt.Println(c(8218, 10007)) fmt.Println(c(8219, 10007)) fmt.Println(c(331575, 1000003)) }
def convertToBase(n, b): if(n < 2): return [n]; temp = n; ans = []; while(temp != 0): ans = [temp % b]+ ans; temp /= b; return ans; def cipolla(n,p): n %= p if(n == 0 or n == 1): return (n,-n%p) phi = p - 1 if(pow(n, phi/2, p) != 1): return () if(p%4 == 3): ans = pow(n,(p+1)/4,p) return (ans,-ans%p) aa = 0 for i in xrange(1,p): temp = pow((i*i-n)%p,phi/2,p) if(temp == phi): aa = i break; exponent = convertToBase((p+1)/2,2) def cipollaMult((a,b),(c,d),w,p): return ((a*c+b*d*w)%p,(a*d+b*c)%p) x1 = (aa,1) x2 = cipollaMult(x1,x1,aa*aa-n,p) for i in xrange(1,len(exponent)): if(exponent[i] == 0): x2 = cipollaMult(x2,x1,aa*aa-n,p) x1 = cipollaMult(x1,x1,aa*aa-n,p) else: x1 = cipollaMult(x1,x2,aa*aa-n,p) x2 = cipollaMult(x2,x2,aa*aa-n,p) return (x1[0],-x1[0]%p) print "Roots of 2 mod 7: " +str(cipolla(2,7)) print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007)) print "Roots of 56 mod 101: " +str(cipolla(56,101)) print "Roots of 1 mod 11: " +str(cipolla(1,11)) print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { return } var a, ω2 int for a = 0; ; a++ { ω2 = (a*a + p - n) % p if ls(ω2) == p-1 { break } } type point struct{ x, y int } mul := func(a, b point) point { return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p} } r := point{1, 0} s := point{a, 1} for n := (p + 1) >> 1 % p; n > 0; n >>= 1 { if n&1 == 1 { r = mul(r, s) } s = mul(s, s) } if r.y != 0 { return } if r.x*r.x%p != n { return } return r.x, p - r.x, true } func main() { fmt.Println(c(10, 13)) fmt.Println(c(56, 101)) fmt.Println(c(8218, 10007)) fmt.Println(c(8219, 10007)) fmt.Println(c(331575, 1000003)) }
def convertToBase(n, b): if(n < 2): return [n]; temp = n; ans = []; while(temp != 0): ans = [temp % b]+ ans; temp /= b; return ans; def cipolla(n,p): n %= p if(n == 0 or n == 1): return (n,-n%p) phi = p - 1 if(pow(n, phi/2, p) != 1): return () if(p%4 == 3): ans = pow(n,(p+1)/4,p) return (ans,-ans%p) aa = 0 for i in xrange(1,p): temp = pow((i*i-n)%p,phi/2,p) if(temp == phi): aa = i break; exponent = convertToBase((p+1)/2,2) def cipollaMult((a,b),(c,d),w,p): return ((a*c+b*d*w)%p,(a*d+b*c)%p) x1 = (aa,1) x2 = cipollaMult(x1,x1,aa*aa-n,p) for i in xrange(1,len(exponent)): if(exponent[i] == 0): x2 = cipollaMult(x2,x1,aa*aa-n,p) x1 = cipollaMult(x1,x1,aa*aa-n,p) else: x1 = cipollaMult(x1,x2,aa*aa-n,p) x2 = cipollaMult(x2,x2,aa*aa-n,p) return (x1[0],-x1[0]%p) print "Roots of 2 mod 7: " +str(cipolla(2,7)) print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007)) print "Roots of 56 mod 101: " +str(cipolla(56,101)) print "Roots of 1 mod 11: " +str(cipolla(1,11)) print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "math" ) const CONST = 6364136223846793005 type Pcg32 struct{ state, inc uint64 } func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} } func (pcg *Pcg32) seed(seedState, seedSequence uint64) { pcg.state = 0 pcg.inc = (seedSequence << 1) | 1 pcg.nextInt() pcg.state = pcg.state + seedState pcg.nextInt() } func (pcg *Pcg32) nextInt() uint32 { old := pcg.state pcg.state = old*CONST + pcg.inc pcgshifted := uint32(((old >> 18) ^ old) >> 27) rot := uint32(old >> 59) return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31)) } func (pcg *Pcg32) nextFloat() float64 { return float64(pcg.nextInt()) / (1 << 32) } func main() { randomGen := Pcg32New() randomGen.seed(42, 54) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321, 1) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 CONST = 6364136223846793005 class PCG32(): def __init__(self, seed_state=None, seed_sequence=None): if all(type(x) == int for x in (seed_state, seed_sequence)): self.seed(seed_state, seed_sequence) else: self.state = self.inc = 0 def seed(self, seed_state, seed_sequence): self.state = 0 self.inc = ((seed_sequence << 1) | 1) & mask64 self.next_int() self.state = (self.state + seed_state) self.next_int() def next_int(self): "return random 32 bit unsigned int" old = self.state self.state = ((old * CONST) + self.inc) & mask64 xorshifted = (((old >> 18) ^ old) >> 27) & mask32 rot = (old >> 59) & mask32 answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)) answer = answer &mask32 return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / (1 << 32) if __name__ == '__main__': random_gen = PCG32() random_gen.seed(42, 54) for i in range(5): print(random_gen.next_int()) random_gen.seed(987654321, 1) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import "fmt" func main() { h := []float64{-8, -9, -3, -1, -6, 7} f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1} g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7} fmt.Println(h) fmt.Println(deconv(g, f)) fmt.Println(f) fmt.Println(deconv(g, h)) } func deconv(g, f []float64) []float64 { h := make([]float64, len(g)-len(f)+1) for n := range h { h[n] = g[n] var lower int if n >= len(f) { lower = n - len(f) + 1 } for i := lower; i < n; i++ { h[n] -= h[i] * f[n-i] } h[n] /= f[0] } return h }
def ToReducedRowEchelonForm( M ): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / lv for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 return M def pmtx(mtx): print ('\n'.join(''.join(' %4s' % col for col in row) for row in mtx)) def convolve(f, h): g = [0] * (len(f) + len(h) - 1) for hindex, hval in enumerate(h): for findex, fval in enumerate(f): g[hindex + findex] += fval * hval return g def deconvolve(g, f): lenh = len(g) - len(f) + 1 mtx = [[0 for x in range(lenh+1)] for y in g] for hindex in range(lenh): for findex, fval in enumerate(f): gindex = hindex + findex mtx[gindex][hindex] = fval for gindex, gval in enumerate(g): mtx[gindex][lenh] = gval ToReducedRowEchelonForm( mtx ) return [mtx[i][lenh] for i in range(lenh)] if __name__ == '__main__': h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7] assert convolve(f,h) == g assert deconvolve(g, f) == h
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "math/rand" "os/exec" "raster" ) func main() { b := raster.NewBitmap(400, 300) b.FillRgb(0xc08040) for i := 0; i < 2000; i++ { b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020) } for x := 0; x < 400; x++ { for y := 240; y < 245; y++ { b.SetPxRgb(x, y, 0x804020) } for y := 260; y < 265; y++ { b.SetPxRgb(x, y, 0x804020) } } for y := 0; y < 300; y++ { for x := 80; x < 85; x++ { b.SetPxRgb(x, y, 0x804020) } for x := 95; x < 100; x++ { b.SetPxRgb(x, y, 0x804020) } } c := exec.Command("cjpeg", "-outfile", "pipeout.jpg") pipe, err := c.StdinPipe() if err != nil { fmt.Println(err) return } err = c.Start() if err != nil { fmt.Println(err) return } err = b.WritePpmTo(pipe) if err != nil { fmt.Println(err) return } err = pipe.Close() if err != nil { fmt.Println(err) } }
from PIL import Image im = Image.open("boxes_1.ppm") im.save("boxes_1.jpg")
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _, err := hex.Decode(p.x[:], []byte(x)); err != nil { return err } _, err := hex.Decode(p.y[:], []byte(y)) return err } type A25 [25]byte func (a *A25) doubleSHA256() []byte { h := sha256.New() h.Write(a[:21]) d := h.Sum([]byte{}) h = sha256.New() h.Write(d) return h.Sum(d[:0]) } func (a *A25) UpdateChecksum() { copy(a[21:], a.doubleSHA256()) } func (a *A25) SetPoint(p *Point) { c := [65]byte{4} copy(c[1:], p.x[:]) copy(c[33:], p.y[:]) h := sha256.New() h.Write(c[:]) s := h.Sum([]byte{}) h = ripemd160.New() h.Write(s) h.Sum(a[1:1]) a.UpdateChecksum() } var tmpl = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") func (a *A25) A58() []byte { var out [34]byte for n := 33; n >= 0; n-- { c := 0 for i := 0; i < 25; i++ { c = c*256 + int(a[i]) a[i] = byte(c / 58) c %= 58 } out[n] = tmpl[c] } i := 1 for i < 34 && out[i] == '1' { i++ } return out[i-1:] } func main() { var p Point err := p.SetHex( "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352", "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6") if err != nil { fmt.Println(err) return } var a A25 a.SetPoint(&p) fmt.Println(string(a.A58())) }
import binascii import functools import hashlib digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def b58(n): return b58(n//58) + digits58[n%58:n%58+1] if n else b'' def public_point_to_address(x, y): c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y) r = hashlib.new('ripemd160') r.update(hashlib.sha256(c).digest()) c = b'\x00' + r.digest() d = hashlib.sha256(hashlib.sha256(c).digest()).digest() return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4])) if __name__ == '__main__': print(public_point_to_address( b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352', b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _, err := hex.Decode(p.x[:], []byte(x)); err != nil { return err } _, err := hex.Decode(p.y[:], []byte(y)) return err } type A25 [25]byte func (a *A25) doubleSHA256() []byte { h := sha256.New() h.Write(a[:21]) d := h.Sum([]byte{}) h = sha256.New() h.Write(d) return h.Sum(d[:0]) } func (a *A25) UpdateChecksum() { copy(a[21:], a.doubleSHA256()) } func (a *A25) SetPoint(p *Point) { c := [65]byte{4} copy(c[1:], p.x[:]) copy(c[33:], p.y[:]) h := sha256.New() h.Write(c[:]) s := h.Sum([]byte{}) h = ripemd160.New() h.Write(s) h.Sum(a[1:1]) a.UpdateChecksum() } var tmpl = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") func (a *A25) A58() []byte { var out [34]byte for n := 33; n >= 0; n-- { c := 0 for i := 0; i < 25; i++ { c = c*256 + int(a[i]) a[i] = byte(c / 58) c %= 58 } out[n] = tmpl[c] } i := 1 for i < 34 && out[i] == '1' { i++ } return out[i-1:] } func main() { var p Point err := p.SetHex( "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352", "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6") if err != nil { fmt.Println(err) return } var a A25 a.SetPoint(&p) fmt.Println(string(a.A58())) }
import binascii import functools import hashlib digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def b58(n): return b58(n//58) + digits58[n%58:n%58+1] if n else b'' def public_point_to_address(x, y): c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y) r = hashlib.new('ripemd160') r.update(hashlib.sha256(c).digest()) c = b'\x00' + r.digest() d = hashlib.sha256(hashlib.sha256(c).digest()).digest() return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4])) if __name__ == '__main__': print(public_point_to_address( b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352', b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))