Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same algorithm in Python as shown in this Go implementation.
package main import "fmt" const jobs = 12 type environment struct{ seq, cnt int } var ( env [jobs]environment seq, cnt *int ) func hail() { fmt.Printf("% 4d", *seq) if *seq == 1 { return } (*cnt)++ if *seq&1 != 0 { *seq = 3*(*seq) + 1 } else { *seq /= 2 } } func switchTo(id int) { seq = &env[id].seq cnt = &env[id].cnt } func main() { for i := 0; i < jobs; i++ { switchTo(i) env[i].seq = i + 1 } again: for i := 0; i < jobs; i++ { switchTo(i) hail() } fmt.Println() for j := 0; j < jobs; j++ { switchTo(j) if *seq != 1 { goto again } } fmt.Println() fmt.Println("COUNTS:") for i := 0; i < jobs; i++ { switchTo(i) fmt.Printf("% 4d", *cnt) } fmt.Println() }
environments = [{'cnt':0, 'seq':i+1} for i in range(12)] code = while any(env['seq'] > 1 for env in environments): for env in environments: exec(code, globals(), env) print() print('Counts') for env in environments: print('% 4d' % env['cnt'], end='') print()
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "bytes" "encoding/hex" "fmt" "log" "strings" ) var testCases = []struct { rune string }{ {'A', "41"}, {'ö', "C3 B6"}, {'Ж', "D0 96"}, {'€', "E2 82 AC"}, {'𝄞', "F0 9D 84 9E"}, } func main() { for _, tc := range testCases { u := fmt.Sprintf("U+%04X", tc.rune) b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1)) if err != nil { log.Fatal("bad test data") } e := encodeUTF8(tc.rune) d := decodeUTF8(b) fmt.Printf("%c  %-7s %X\n", d, u, e) if !bytes.Equal(e, b) { log.Fatal("encodeUTF8 wrong") } if d != tc.rune { log.Fatal("decodeUTF8 wrong") } } } const ( b2Lead = 0xC0 b2Mask = 0x1F b3Lead = 0xE0 b3Mask = 0x0F b4Lead = 0xF0 b4Mask = 0x07 mbLead = 0x80 mbMask = 0x3F ) func encodeUTF8(r rune) []byte { switch i := uint32(r); { case i <= 1<<7-1: return []byte{byte(r)} case i <= 1<<11-1: return []byte{ b2Lead | byte(r>>6), mbLead | byte(r)&mbMask} case i <= 1<<16-1: return []byte{ b3Lead | byte(r>>12), mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} default: return []byte{ b4Lead | byte(r>>18), mbLead | byte(r>>12)&mbMask, mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} } } func decodeUTF8(b []byte) rune { switch b0 := b[0]; { case b0 < 0x80: return rune(b0) case b0 < 0xE0: return rune(b0&b2Mask)<<6 | rune(b[1]&mbMask) case b0 < 0xF0: return rune(b0&b3Mask)<<12 | rune(b[1]&mbMask)<<6 | rune(b[2]&mbMask) default: return rune(b0&b4Mask)<<18 | rune(b[1]&mbMask)<<12 | rune(b[2]&mbMask)<<6 | rune(b[3]&mbMask) } }
from unicodedata import name def unicode_code(ch): return 'U+{:04x}'.format(ord(ch)) def utf8hex(ch): return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper() if __name__ == "__main__": print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)')) chars = ['A', 'ö', 'Ж', '€', '𝄞'] for char in chars: print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
Please provide an equivalent version of this Go code in Python.
package main import ( "bytes" "encoding/hex" "fmt" "log" "strings" ) var testCases = []struct { rune string }{ {'A', "41"}, {'ö', "C3 B6"}, {'Ж', "D0 96"}, {'€', "E2 82 AC"}, {'𝄞', "F0 9D 84 9E"}, } func main() { for _, tc := range testCases { u := fmt.Sprintf("U+%04X", tc.rune) b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1)) if err != nil { log.Fatal("bad test data") } e := encodeUTF8(tc.rune) d := decodeUTF8(b) fmt.Printf("%c  %-7s %X\n", d, u, e) if !bytes.Equal(e, b) { log.Fatal("encodeUTF8 wrong") } if d != tc.rune { log.Fatal("decodeUTF8 wrong") } } } const ( b2Lead = 0xC0 b2Mask = 0x1F b3Lead = 0xE0 b3Mask = 0x0F b4Lead = 0xF0 b4Mask = 0x07 mbLead = 0x80 mbMask = 0x3F ) func encodeUTF8(r rune) []byte { switch i := uint32(r); { case i <= 1<<7-1: return []byte{byte(r)} case i <= 1<<11-1: return []byte{ b2Lead | byte(r>>6), mbLead | byte(r)&mbMask} case i <= 1<<16-1: return []byte{ b3Lead | byte(r>>12), mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} default: return []byte{ b4Lead | byte(r>>18), mbLead | byte(r>>12)&mbMask, mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} } } func decodeUTF8(b []byte) rune { switch b0 := b[0]; { case b0 < 0x80: return rune(b0) case b0 < 0xE0: return rune(b0&b2Mask)<<6 | rune(b[1]&mbMask) case b0 < 0xF0: return rune(b0&b3Mask)<<12 | rune(b[1]&mbMask)<<6 | rune(b[2]&mbMask) default: return rune(b0&b4Mask)<<18 | rune(b[1]&mbMask)<<12 | rune(b[2]&mbMask)<<6 | rune(b[3]&mbMask) } }
from unicodedata import name def unicode_code(ch): return 'U+{:04x}'.format(ord(ch)) def utf8hex(ch): return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper() if __name__ == "__main__": print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)')) chars = ['A', 'ö', 'Ж', '€', '𝄞'] for char in chars: print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
Produce a language-to-language conversion: from Go to Python, same semantics.
package raster import "math" func ipart(x float64) float64 { return math.Floor(x) } func round(x float64) float64 { return ipart(x + .5) } func fpart(x float64) float64 { return x - ipart(x) } func rfpart(x float64) float64 { return 1 - fpart(x) } func (g *Grmap) AaLine(x1, y1, x2, y2 float64) { dx := x2 - x1 dy := y2 - y1 ax := dx if ax < 0 { ax = -ax } ay := dy if ay < 0 { ay = -ay } var plot func(int, int, float64) if ax < ay { x1, y1 = y1, x1 x2, y2 = y2, x2 dx, dy = dy, dx plot = func(x, y int, c float64) { g.SetPx(y, x, uint16(c*math.MaxUint16)) } } else { plot = func(x, y int, c float64) { g.SetPx(x, y, uint16(c*math.MaxUint16)) } } if x2 < x1 { x1, x2 = x2, x1 y1, y2 = y2, y1 } gradient := dy / dx xend := round(x1) yend := y1 + gradient*(xend-x1) xgap := rfpart(x1 + .5) xpxl1 := int(xend) ypxl1 := int(ipart(yend)) plot(xpxl1, ypxl1, rfpart(yend)*xgap) plot(xpxl1, ypxl1+1, fpart(yend)*xgap) intery := yend + gradient xend = round(x2) yend = y2 + gradient*(xend-x2) xgap = fpart(x2 + 0.5) xpxl2 := int(xend) ypxl2 := int(ipart(yend)) plot(xpxl2, ypxl2, rfpart(yend)*xgap) plot(xpxl2, ypxl2+1, fpart(yend)*xgap) for x := xpxl1 + 1; x <= xpxl2-1; x++ { plot(x, int(ipart(intery)), rfpart(intery)) plot(x, int(ipart(intery))+1, fpart(intery)) intery = intery + gradient } }
from __future__ import division import sys from PIL import Image def _fpart(x): return x - int(x) def _rfpart(x): return 1 - _fpart(x) def putpixel(img, xy, color, alpha=1): compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg)) c = compose_color(img.getpixel(xy), color) img.putpixel(xy, c) def draw_line(img, p1, p2, color): x1, y1 = p1 x2, y2 = p2 dx, dy = x2-x1, y2-y1 steep = abs(dx) < abs(dy) p = lambda px, py: ((px,py), (py,px))[steep] if steep: x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx if x2 < x1: x1, x2, y1, y2 = x2, x1, y2, y1 grad = dy/dx intery = y1 + _rfpart(x1) * grad def draw_endpoint(pt): x, y = pt xend = round(x) yend = y + grad * (xend - x) xgap = _rfpart(x + 0.5) px, py = int(xend), int(yend) putpixel(img, p(px, py), color, _rfpart(yend) * xgap) putpixel(img, p(px, py+1), color, _fpart(yend) * xgap) return px xstart = draw_endpoint(p(*p1)) + 1 xend = draw_endpoint(p(*p2)) for x in range(xstart, xend): y = int(intery) putpixel(img, p(x, y), color, _rfpart(intery)) putpixel(img, p(x, y+1), color, _fpart(intery)) intery += grad if __name__ == '__main__': if len(sys.argv) != 2: print 'usage: python xiaolinwu.py [output-file]' sys.exit(-1) blue = (0, 0, 255) yellow = (255, 255, 0) img = Image.new("RGB", (500,500), blue) for a in range(10, 431, 60): draw_line(img, (10, 10), (490, a), yellow) draw_line(img, (10, 10), (a, 490), yellow) draw_line(img, (10, 10), (490, 490), yellow) filename = sys.argv[1] img.save(filename) print 'image saved to', filename
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import "C" import "fmt" import "unsafe" func main() { d := C.XOpenDisplay(nil) f7, f6 := C.CString("F7"), C.CString("F6") defer C.free(unsafe.Pointer(f7)) defer C.free(unsafe.Pointer(f6)) if d != nil { C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync) C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync) var event C.XEvent for { C.XNextEvent(d, &event) if C.getXEvent_type(event) == C.KeyPress { xkeyEvent := C.getXEvent_xkey(event) s := C.XLookupKeysym(&xkeyEvent, 0) if s == C.XK_F7 { fmt.Println("something's happened") } else if s == C.XK_F6 { break } } } C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d)) C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d)) } else { fmt.Println("XOpenDisplay did not succeed") } }
import curses def print_message(): stdscr.addstr('This is the message.\n') stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) stdscr.addstr('CTRL+P for message or q to quit.\n') while True: c = stdscr.getch() if c == 16: print_message() elif c == ord('q'): break curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin()
Please provide an equivalent version of this Go code in Python.
package main import "fmt" func mcnugget(limit int) { sv := make([]bool, limit+1) for s := 0; s <= limit; s += 6 { for n := s; n <= limit; n += 9 { for t := n; t <= limit; t += 20 { sv[t] = true } } } for i := limit; i >= 0; i-- { if !sv[i] { fmt.Println("Maximum non-McNuggets number is", i) return } } } func main() { mcnugget(100) }
>>> from itertools import product >>> nuggets = set(range(101)) >>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)): nuggets.discard(6*s + 9*n + 20*t) >>> max(nuggets) 43 >>>
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "log" "strings" ) const dimensions int = 8 func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 size := d * d mult := d / 4 for i, r := 0, 0; r < d; r++ { output = append(output, []int{}) for c := 0; c < d; i, c = i+1, c+1 { bitPos := c/mult + (r/mult)*4 if (bits & (1 << uint(bitPos))) != 0 { output[r] = append(output[r], i+1) } else { output[r] = append(output[r], size-i) } } } return output, nil } func arrayItoa(input []int) []string { var output []string for _, i := range input { output = append(output, fmt.Sprintf("%4d", i)) } return output } func main() { data, err := setupMagicSquareData(dimensions) if err != nil { log.Fatal(err) } magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2 for _, row := range data { fmt.Println(strings.Join(arrayItoa(row), " ")) } fmt.Printf("\nMagic Constant: %d\n", magicConstant) }
def MagicSquareDoublyEven(order): sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ] n1 = order/4 for r in range(n1): r1 = sq[r][n1:-n1] r2 = sq[order -r - 1][n1:-n1] r1.reverse() r2.reverse() sq[r][n1:-n1] = r2 sq[order -r - 1][n1:-n1] = r1 for r in range(n1, order-n1): r1 = sq[r][:n1] r2 = sq[order -r - 1][order-n1:] r1.reverse() r2.reverse() sq[r][:n1] = r2 sq[order -r - 1][order-n1:] = r1 return sq def printsq(s): n = len(s) bl = len(str(n**2))+1 for i in range(n): print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] ) print "\nMagic constant = %d"%sum(s[0]) printsq(MagicSquareDoublyEven(8))
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "math" ) func main() { var zero float64 var negZero, posInf, negInf, nan float64 negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero fmt.Println(negZero, posInf, negInf, nan) fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN()) fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") } func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } } func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } } func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } } func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } } func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
>>> >>> inf = 1e234 * 1e234 >>> _inf = 1e234 * -1e234 >>> _zero = 1 / _inf >>> nan = inf + _inf >>> inf, _inf, _zero, nan (inf, -inf, -0.0, nan) >>> >>> for value in (inf, _inf, _zero, nan): print (value) inf -inf -0.0 nan >>> >>> float('nan') nan >>> float('inf') inf >>> float('-inf') -inf >>> -0. -0.0 >>> >>> nan == nan False >>> nan is nan True >>> 0. == -0. True >>> 0. is -0. False >>> inf + _inf nan >>> 0.0 * nan nan >>> nan * 0.0 nan >>> 0.0 * inf nan >>> inf * 0.0 nan
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math" ) func main() { var zero float64 var negZero, posInf, negInf, nan float64 negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero fmt.Println(negZero, posInf, negInf, nan) fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN()) fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") } func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } } func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } } func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } } func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } } func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
>>> >>> inf = 1e234 * 1e234 >>> _inf = 1e234 * -1e234 >>> _zero = 1 / _inf >>> nan = inf + _inf >>> inf, _inf, _zero, nan (inf, -inf, -0.0, nan) >>> >>> for value in (inf, _inf, _zero, nan): print (value) inf -inf -0.0 nan >>> >>> float('nan') nan >>> float('inf') inf >>> float('-inf') -inf >>> -0. -0.0 >>> >>> nan == nan False >>> nan is nan True >>> 0. == -0. True >>> 0. is -0. False >>> inf + _inf nan >>> 0.0 * nan nan >>> nan * 0.0 nan >>> 0.0 * inf nan >>> inf * 0.0 nan
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "math" ) func main() { var zero float64 var negZero, posInf, negInf, nan float64 negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero fmt.Println(negZero, posInf, negInf, nan) fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN()) fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") } func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } } func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } } func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } } func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } } func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
>>> >>> inf = 1e234 * 1e234 >>> _inf = 1e234 * -1e234 >>> _zero = 1 / _inf >>> nan = inf + _inf >>> inf, _inf, _zero, nan (inf, -inf, -0.0, nan) >>> >>> for value in (inf, _inf, _zero, nan): print (value) inf -inf -0.0 nan >>> >>> float('nan') nan >>> float('inf') inf >>> float('-inf') -inf >>> -0. -0.0 >>> >>> nan == nan False >>> nan is nan True >>> 0. == -0. True >>> 0. is -0. False >>> inf + _inf nan >>> 0.0 * nan nan >>> nan * 0.0 nan >>> 0.0 * inf nan >>> inf * 0.0 nan
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" ) const CONST = 0x2545F4914F6CDD1D type XorshiftStar struct{ state uint64 } func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} } func (xor *XorshiftStar) seed(state uint64) { xor.state = state } func (xor *XorshiftStar) nextInt() uint32 { x := xor.state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) xor.state = x return uint32((x * CONST) >> 32) } func (xor *XorshiftStar) nextFloat() float64 { return float64(xor.nextInt()) / (1 << 32) } func main() { randomGen := XorshiftStarNew(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 const = 0x2545F4914F6CDD1D class Xorshift_star(): def __init__(self, seed=0): self.state = seed & mask64 def seed(self, num): self.state = num & mask64 def next_int(self): "return random int between 0 and 2**32" x = self.state x = (x ^ (x >> 12)) & mask64 x = (x ^ (x << 25)) & mask64 x = (x ^ (x >> 27)) & mask64 self.state = x answer = (((x * const) & mask64) >> 32) & mask32 return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / (1 << 32) if __name__ == '__main__': random_gen = Xorshift_star() random_gen.seed(1234567) for i in range(5): print(random_gen.next_int()) random_gen.seed(987654321) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "strings" "unicode" ) func main() { f := NewFourIsSeq() fmt.Print("The lengths of the first 201 words are:") for i := 1; i <= 201; i++ { if i%25 == 1 { fmt.Printf("\n%3d: ", i) } _, n := f.WordLen(i) fmt.Printf(" %2d", n) } fmt.Println() fmt.Println("Length of sentence so far:", f.TotalLength()) for i := 1000; i <= 1e7; i *= 10 { w, n := f.WordLen(i) fmt.Printf("Word %8d is %q, with %d letters.", i, w, n) fmt.Println(" Length of sentence so far:", f.TotalLength()) } } type FourIsSeq struct { i int words []string } func NewFourIsSeq() *FourIsSeq { return &FourIsSeq{ words: []string{ "Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,", }, } } func (f *FourIsSeq) WordLen(w int) (string, int) { for len(f.words) < w { f.i++ n := countLetters(f.words[f.i]) ns := say(int64(n)) os := sayOrdinal(int64(f.i+1)) + "," f.words = append(f.words, strings.Fields(ns)...) f.words = append(f.words, "in", "the") f.words = append(f.words, strings.Fields(os)...) } word := f.words[w-1] return word, countLetters(word) } func (f FourIsSeq) TotalLength() int { cnt := 0 for _, w := range f.words { cnt += len(w) + 1 } return cnt - 1 } func countLetters(s string) int { cnt := 0 for _, r := range s { if unicode.IsLetter(r) { cnt++ } } return cnt }
import inflect def count_letters(word): count = 0 for letter in word: if letter != ',' and letter !='-' and letter !=' ': count += 1 return count def split_with_spaces(sentence): sentence_list = [] curr_word = "" for c in sentence: if c == " " and curr_word != "": sentence_list.append(curr_word+" ") curr_word = "" else: curr_word += c if len(curr_word) > 0: sentence_list.append(curr_word) return sentence_list def my_num_to_words(p, my_number): number_string_list = p.number_to_words(my_number, wantlist=True, andword='') number_string = number_string_list[0] for i in range(1,len(number_string_list)): number_string += " " + number_string_list[i] return number_string def build_sentence(p, max_words): sentence_list = split_with_spaces("Four is the number of letters in the first word of this sentence,") num_words = 13 word_number = 2 while num_words < max_words: ordinal_string = my_num_to_words(p, p.ordinal(word_number)) word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1])) new_string = " "+word_number_string+" in the "+ordinal_string+"," new_list = split_with_spaces(new_string) sentence_list += new_list num_words += len(new_list) word_number += 1 return sentence_list, num_words def word_and_counts(word_num): sentence_list, num_words = build_sentence(p, word_num) word_str = sentence_list[word_num - 1].strip(' ,') num_letters = len(word_str) num_characters = 0 for word in sentence_list: num_characters += len(word) print('Word {0:8d} is "{1}", with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters)) p = inflect.engine() sentence_list, num_words = build_sentence(p, 201) print(" ") print("The lengths of the first 201 words are:") print(" ") print('{0:3d}: '.format(1),end='') total_characters = 0 for word_index in range(201): word_length = count_letters(sentence_list[word_index]) total_characters += len(sentence_list[word_index]) print('{0:2d}'.format(word_length),end='') if (word_index+1) % 20 == 0: print(" ") print('{0:3d}: '.format(word_index + 2),end='') else: print(" ",end='') print(" ") print(" ") print("Length of the sentence so far: "+str(total_characters)) print(" ") word_and_counts(1000) word_and_counts(10000) word_and_counts(100000) word_and_counts(1000000) word_and_counts(10000000)
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "fmt" "log" "math/big" "strings" ) type result struct { name string size int start int end int } func (r result) String() string { return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end) } func validate(diagram string) []string { var lines []string for _, line := range strings.Split(diagram, "\n") { line = strings.Trim(line, " \t") if line != "" { lines = append(lines, line) } } if len(lines) == 0 { log.Fatal("diagram has no non-empty lines!") } width := len(lines[0]) cols := (width - 1) / 3 if cols != 8 && cols != 16 && cols != 32 && cols != 64 { log.Fatal("number of columns should be 8, 16, 32 or 64") } if len(lines)%2 == 0 { log.Fatal("number of non-empty lines should be odd") } if lines[0] != strings.Repeat("+--", cols)+"+" { log.Fatal("incorrect header line") } for i, line := range lines { if i == 0 { continue } else if i%2 == 0 { if line != lines[0] { log.Fatal("incorrect separator line") } } else if len(line) != width { log.Fatal("inconsistent line widths") } else if line[0] != '|' || line[width-1] != '|' { log.Fatal("non-separator lines must begin and end with '|'") } } return lines } func decode(lines []string) []result { fmt.Println("Name Bits Start End") fmt.Println("======= ==== ===== ===") start := 0 width := len(lines[0]) var results []result for i, line := range lines { if i%2 == 0 { continue } line := line[1 : width-1] for _, name := range strings.Split(line, "|") { size := (len(name) + 1) / 3 name = strings.TrimSpace(name) res := result{name, size, start, start + size - 1} results = append(results, res) fmt.Println(res) start += size } } return results } func unpack(results []result, hex string) { fmt.Println("\nTest string in hex:") fmt.Println(hex) fmt.Println("\nTest string in binary:") bin := hex2bin(hex) fmt.Println(bin) fmt.Println("\nUnpacked:\n") fmt.Println("Name Size Bit pattern") fmt.Println("======= ==== ================") for _, res := range results { fmt.Printf("%-7s %2d %s\n", res.name, res.size, bin[res.start:res.end+1]) } } func hex2bin(hex string) string { z := new(big.Int) z.SetString(hex, 16) return fmt.Sprintf("%0*b", 4*len(hex), z) } func main() { const diagram = ` +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ` lines := validate(diagram) fmt.Println("Diagram after trimming whitespace and removal of blank lines:\n") for _, line := range lines { fmt.Println(line) } fmt.Println("\nDecoded:\n") results := decode(lines) hex := "78477bbf5496e12e1bf169a4" unpack(results, hex) }
def validate(diagram): rawlines = diagram.splitlines() lines = [] for line in rawlines: if line != '': lines.append(line) if len(lines) == 0: print('diagram has no non-empty lines!') return None width = len(lines[0]) cols = (width - 1) // 3 if cols not in [8, 16, 32, 64]: print('number of columns should be 8, 16, 32 or 64') return None if len(lines)%2 == 0: print('number of non-empty lines should be odd') return None if lines[0] != (('+--' * cols)+'+'): print('incorrect header line') return None for i in range(len(lines)): line=lines[i] if i == 0: continue elif i%2 == 0: if line != lines[0]: print('incorrect separator line') return None elif len(line) != width: print('inconsistent line widths') return None elif line[0] != '|' or line[width-1] != '|': print("non-separator lines must begin and end with '|'") return None return lines def decode(lines): print("Name Bits Start End") print("======= ==== ===== ===") startbit = 0 results = [] for line in lines: infield=False for c in line: if not infield and c == '|': infield = True spaces = 0 name = '' elif infield: if c == ' ': spaces += 1 elif c != '|': name += c else: bits = (spaces + len(name) + 1) // 3 endbit = startbit + bits - 1 print('{0:7} {1:2d} {2:2d} {3:2d}'.format(name, bits, startbit, endbit)) reslist = [name, bits, startbit, endbit] results.append(reslist) spaces = 0 name = '' startbit += bits return results def unpack(results, hex): print("\nTest string in hex:") print(hex) print("\nTest string in binary:") bin = f'{int(hex, 16):0>{4*len(hex)}b}' print(bin) print("\nUnpacked:\n") print("Name Size Bit pattern") print("======= ==== ================") for r in results: name = r[0] size = r[1] startbit = r[2] endbit = r[3] bitpattern = bin[startbit:endbit+1] print('{0:7} {1:2d} {2:16}'.format(name, size, bitpattern)) diagram = lines = validate(diagram) if lines == None: print("No lines returned") else: print(" ") print("Diagram after trimming whitespace and removal of blank lines:") print(" ") for line in lines: print(line) print(" ") print("Decoded:") print(" ") results = decode(lines) hex = "78477bbf5496e12e1bf169a4" unpack(results, hex)
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "github.com/biogo/biogo/align" ab "github.com/biogo/biogo/alphabet" "github.com/biogo/biogo/feat" "github.com/biogo/biogo/seq/linear" ) func main() { lc := ab.Must(ab.NewAlphabet("-abcdefghijklmnopqrstuvwxyz", feat.Undefined, '-', 0, true)) nw := make(align.NW, lc.Len()) for i := range nw { r := make([]int, lc.Len()) nw[i] = r for j := range r { if j != i { r[j] = -1 } } } a := &linear.Seq{Seq: ab.BytesToLetters([]byte("rosettacode"))} a.Alpha = lc b := &linear.Seq{Seq: ab.BytesToLetters([]byte("raisethysword"))} b.Alpha = lc aln, err := nw.Align(a, b) if err != nil { fmt.Println(err) return } fa := align.Format(a, b, aln, '-') fmt.Printf("%s\n%s\n", fa[0], fa[1]) aa := fmt.Sprint(fa[0]) ba := fmt.Sprint(fa[1]) ma := make([]byte, len(aa)) for i := range ma { if aa[i] == ba[i] { ma[i] = ' ' } else { ma[i] = '|' } } fmt.Println(string(ma)) }
from difflib import ndiff def levenshtein(str1, str2): result = "" pos, removed = 0, 0 for x in ndiff(str1, str2): if pos<len(str1) and str1[pos] == x[2]: pos += 1 result += x[2] if x[0] == "-": removed += 1 continue else: if removed > 0: removed -=1 else: result += "-" print(result) levenshtein("place","palace") levenshtein("rosettacode","raisethysword")
Port the provided Go code into Python while preserving the original functionality.
package main import ( "log" "math/rand" "testing" "time" "github.com/gonum/plot" "github.com/gonum/plot/plotter" "github.com/gonum/plot/plotutil" "github.com/gonum/plot/vg" ) func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } } func insertionsort(a []int) { for i := 1; i < len(a); i++ { value := a[i] j := i - 1 for j >= 0 && a[j] > value { a[j+1] = a[j] j = j - 1 } a[j+1] = value } } func quicksort(a []int) { var pex func(int, int) pex = func(lower, upper int) { for { switch upper - lower { case -1, 0: return case 1: if a[upper] < a[lower] { a[upper], a[lower] = a[lower], a[upper] } return } bx := (upper + lower) / 2 b := a[bx] lp := lower up := upper outer: for { for lp < upper && !(b < a[lp]) { lp++ } for { if lp > up { break outer } if a[up] < b { break } up-- } a[lp], a[up] = a[up], a[lp] lp++ up-- } if bx < lp { if bx < lp-1 { a[bx], a[lp-1] = a[lp-1], b } up = lp - 2 } else { if bx > lp { a[bx], a[lp] = a[lp], b } up = lp - 1 lp++ } if up-lower < upper-lp { pex(lower, up) lower = lp } else { pex(lp, upper) upper = up } } } pex(0, len(a)-1) } func ones(n int) []int { s := make([]int, n) for i := range s { s[i] = 1 } return s } func ascending(n int) []int { s := make([]int, n) v := 1 for i := 0; i < n; { if rand.Intn(3) == 0 { s[i] = v i++ } v++ } return s } func shuffled(n int) []int { return rand.Perm(n) } const ( nPts = 7 inc = 1000 ) var ( p *plot.Plot sortName = []string{"Bubble sort", "Insertion sort", "Quicksort"} sortFunc = []func([]int){bubblesort, insertionsort, quicksort} dataName = []string{"Ones", "Ascending", "Shuffled"} dataFunc = []func(int) []int{ones, ascending, shuffled} ) func main() { rand.Seed(time.Now().Unix()) var err error p, err = plot.New() if err != nil { log.Fatal(err) } p.X.Label.Text = "Data size" p.Y.Label.Text = "microseconds" p.Y.Scale = plot.LogScale{} p.Y.Tick.Marker = plot.LogTicks{} p.Y.Min = .5 for dx, name := range dataName { s, err := plotter.NewScatter(plotter.XYs{}) if err != nil { log.Fatal(err) } s.Shape = plotutil.DefaultGlyphShapes[dx] p.Legend.Add(name, s) } for sx, name := range sortName { l, err := plotter.NewLine(plotter.XYs{}) if err != nil { log.Fatal(err) } l.Color = plotutil.DarkColors[sx] p.Legend.Add(name, l) } for sx := range sortFunc { bench(sx, 0, 1) bench(sx, 1, 5) bench(sx, 2, 5) } if err := p.Save(5*vg.Inch, 5*vg.Inch, "comp.png"); err != nil { log.Fatal(err) } } func bench(sx, dx, rep int) { log.Println("bench", sortName[sx], dataName[dx], "x", rep) pts := make(plotter.XYs, nPts) sf := sortFunc[sx] for i := range pts { x := (i + 1) * inc s0 := dataFunc[dx](x) s := make([]int, x) var tSort int64 for j := 0; j < rep; j++ { tSort += testing.Benchmark(func(b *testing.B) { for i := 0; i < b.N; i++ { copy(s, s0) sf(s) } }).NsPerOp() } tSort /= int64(rep) log.Println(x, "items", tSort, "ns") pts[i] = struct{ X, Y float64 }{float64(x), float64(tSort) * .001} } pl, ps, err := plotter.NewLinePoints(pts) if err != nil { log.Fatal(err) } pl.Color = plotutil.DarkColors[sx] ps.Color = plotutil.DarkColors[sx] ps.Shape = plotutil.DefaultGlyphShapes[dx] p.Add(pl, ps) }
def builtinsort(x): x.sort() def partition(seq, pivot): low, middle, up = [], [], [] for x in seq: if x < pivot: low.append(x) elif x == pivot: middle.append(x) else: up.append(x) return low, middle, up import random def qsortranpart(seq): size = len(seq) if size < 2: return seq low, middle, up = partition(seq, random.choice(seq)) return qsortranpart(low) + middle + qsortranpart(up)
Maintain the same structure and functionality when rewriting this code in Python.
package main import "fmt" type node struct { int left, right *node } func leaves(t *node) chan int { ch := make(chan int) var f func(*node) f = func(n *node) { if n == nil { return } if n.left == nil && n.right == nil { ch <- n.int } else { f(n.left) f(n.right) } } go func() { f(t) close(ch) }() return ch } func sameFringe(t1, t2 *node) bool { f1 := leaves(t1) f2 := leaves(t2) for l1 := range f1 { if l2, ok := <-f2; !ok || l1 != l2 { return false } } _, ok := <-f2 return !ok } func main() { t1 := &node{3, &node{1, &node{int: 1}, &node{int: 2}}, &node{8, &node{int: 5}, &node{int: 13}}} t2 := &node{-8, &node{-3, &node{-1, &node{int: 1}, &node{int: 2}}, &node{int: 5}}, &node{int: 13}} fmt.Println(sameFringe(t1, t2)) }
try: from itertools import zip_longest as izip_longest except: from itertools import izip_longest def fringe(tree): for node1 in tree: if isinstance(node1, tuple): for node2 in fringe(node1): yield node2 else: yield node1 def same_fringe(tree1, tree2): return all(node1 == node2 for node1, node2 in izip_longest(fringe(tree1), fringe(tree2))) if __name__ == '__main__': a = 1, 2, 3, 4, 5, 6, 7, 8 b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8)))) c = (((1, 2), 3), 4), 5, 6, 7, 8 x = 1, 2, 3, 4, 5, 6, 7, 8, 9 y = 0, 2, 3, 4, 5, 6, 7, 8 z = 1, 2, (4, 3), 5, 6, 7, 8 assert same_fringe(a, a) assert same_fringe(a, b) assert same_fringe(a, c) assert not same_fringe(a, x) assert not same_fringe(a, y) assert not same_fringe(a, z)
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import "fmt" type node struct { int left, right *node } func leaves(t *node) chan int { ch := make(chan int) var f func(*node) f = func(n *node) { if n == nil { return } if n.left == nil && n.right == nil { ch <- n.int } else { f(n.left) f(n.right) } } go func() { f(t) close(ch) }() return ch } func sameFringe(t1, t2 *node) bool { f1 := leaves(t1) f2 := leaves(t2) for l1 := range f1 { if l2, ok := <-f2; !ok || l1 != l2 { return false } } _, ok := <-f2 return !ok } func main() { t1 := &node{3, &node{1, &node{int: 1}, &node{int: 2}}, &node{8, &node{int: 5}, &node{int: 13}}} t2 := &node{-8, &node{-3, &node{-1, &node{int: 1}, &node{int: 2}}, &node{int: 5}}, &node{int: 13}} fmt.Println(sameFringe(t1, t2)) }
try: from itertools import zip_longest as izip_longest except: from itertools import izip_longest def fringe(tree): for node1 in tree: if isinstance(node1, tuple): for node2 in fringe(node1): yield node2 else: yield node1 def same_fringe(tree1, tree2): return all(node1 == node2 for node1, node2 in izip_longest(fringe(tree1), fringe(tree2))) if __name__ == '__main__': a = 1, 2, 3, 4, 5, 6, 7, 8 b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8)))) c = (((1, 2), 3), 4), 5, 6, 7, 8 x = 1, 2, 3, 4, 5, 6, 7, 8, 9 y = 0, 2, 3, 4, 5, 6, 7, 8 z = 1, 2, (4, 3), 5, 6, 7, 8 assert same_fringe(a, a) assert same_fringe(a, b) assert same_fringe(a, c) assert not same_fringe(a, x) assert not same_fringe(a, y) assert not same_fringe(a, z)
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
from optparse import OptionParser [...] parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() example: <yourscript> --file=outfile -q
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
from optparse import OptionParser [...] parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() example: <yourscript> --file=outfile -q
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
from optparse import OptionParser [...] parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() example: <yourscript> --file=outfile -q
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "strconv" "strings" ) func a(n int) { s, _ := strconv.Atoi(strings.Repeat("1", n) + "3") t := s * s fmt.Printf("%d %d\n", s, t) } func main() { for n := 0; n <= 7; n++ { a(n) } }
[print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "strconv" "strings" ) func a(n int) { s, _ := strconv.Atoi(strings.Repeat("1", n) + "3") t := s * s fmt.Printf("%d %d\n", s, t) } func main() { for n := 0; n <= 7; n++ { a(n) } }
[print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "github.com/micmonay/keybd_event" "log" "runtime" "time" ) func main() { kb, err := keybd_event.NewKeyBonding() if err != nil { log.Fatal(err) } if runtime.GOOS == "linux" { time.Sleep(2 * time.Second) } kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER) err = kb.Launching() if err != nil { log.Fatal(err) } }
import autopy autopy.key.type_string("Hello, world!") autopy.key.type_string("Hello, world!", wpm=60) autopy.key.tap(autopy.key.Code.RETURN) autopy.key.tap(autopy.key.Code.F1) autopy.key.tap(autopy.key.Code.LEFT_ARROW)
Port the provided Go code into Python while preserving the original functionality.
package main import "fmt" const ( empty = iota black white ) const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' ) type position struct{ i, j int } func iabs(i int) int { if i < 0 { return -i } return i } func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool { if m == 0 { return true } placingBlack := true for i := 0; i < n; i++ { inner: for j := 0; j < n; j++ { pos := position{i, j} for _, queen := range *pBlackQueens { if queen == pos || !placingBlack && isAttacking(queen, pos) { continue inner } } for _, queen := range *pWhiteQueens { if queen == pos || placingBlack && isAttacking(queen, pos) { continue inner } } if placingBlack { *pBlackQueens = append(*pBlackQueens, pos) placingBlack = false } else { *pWhiteQueens = append(*pWhiteQueens, pos) if place(m-1, n, pBlackQueens, pWhiteQueens) { return true } *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1] placingBlack = true } } } if !placingBlack { *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] } return false } func isAttacking(queen, pos position) bool { if queen.i == pos.i { return true } if queen.j == pos.j { return true } if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) { return true } return false } func printBoard(n int, blackQueens, whiteQueens []position) { board := make([]int, n*n) for _, queen := range blackQueens { board[queen.i*n+queen.j] = black } for _, queen := range whiteQueens { board[queen.i*n+queen.j] = white } for i, b := range board { if i != 0 && i%n == 0 { fmt.Println() } switch b { case black: fmt.Printf("%c ", bqueen) case white: fmt.Printf("%c ", wqueen) case empty: if i%2 == 0 { fmt.Printf("%c ", bbullet) } else { fmt.Printf("%c ", wbullet) } } } fmt.Println("\n") } func main() { nms := [][2]int{ {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, } for _, nm := range nms { n, m := nm[0], nm[1] fmt.Printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n) var blackQueens, whiteQueens []position if place(m, n, &blackQueens, &whiteQueens) { printBoard(n, blackQueens, whiteQueens) } else { fmt.Println("No solution exists.\n") } } }
from itertools import combinations, product, count from functools import lru_cache, reduce _bbullet, _wbullet = '\u2022\u25E6' _or = set.__or__ def place(m, n): "Place m black and white queens, peacefully, on an n-by-n board" board = set(product(range(n), repeat=2)) placements = {frozenset(c) for c in combinations(board, m)} for blacks in placements: black_attacks = reduce(_or, (queen_attacks_from(pos, n) for pos in blacks), set()) for whites in {frozenset(c) for c in combinations(board - black_attacks, m)}: if not black_attacks & whites: return blacks, whites return set(), set() @lru_cache(maxsize=None) def queen_attacks_from(pos, n): x0, y0 = pos a = set([pos]) a.update((x, y0) for x in range(n)) a.update((x0, y) for y in range(n)) for x1 in range(n): y1 = y0 -x0 +x1 if 0 <= y1 < n: a.add((x1, y1)) y1 = y0 +x0 -x1 if 0 <= y1 < n: a.add((x1, y1)) return a def pboard(black_white, n): "Print board" if black_white is None: blk, wht = set(), set() else: blk, wht = black_white print(f" f"on a {n}-by-{n} board:", end='') for x, y in product(range(n), repeat=2): if y == 0: print() xy = (x, y) ch = ('?' if xy in blk and xy in wht else 'B' if xy in blk else 'W' if xy in wht else _bbullet if (x + y)%2 else _wbullet) print('%s' % ch, end='') print() if __name__ == '__main__': n=2 for n in range(2, 7): print() for m in count(1): ans = place(m, n) if ans[0]: pboard(ans, n) else: print (f" break print('\n') m, n = 5, 7 ans = place(m, n) pboard(ans, n)
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import "fmt" func main() { for { fmt.Printf("SPAM\n") } }
while 1: print "SPAM"
Convert this Go block to Python, preserving its control flow and logic.
package main import "fmt" type person struct{ name string age int } func copy(p person) person { return person{p.name, p.age} } func main() { p := person{"Dave", 40} fmt.Println(p) q := copy(p) fmt.Println(q) }
from macropy.core.macros import * from macropy.core.quotes import macros, q, ast, u macros = Macros() @macros.expr def expand(tree, **kw): addition = 10 return q[lambda x: x * ast[tree] + u[addition]]
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "rcu" "strconv" ) func equalSets(s1, s2 map[rune]bool) bool { if len(s1) != len(s2) { return false } for k, _ := range s1 { _, ok := s2[k] if !ok { return false } } return true } func main() { const limit = 100_000 count := 0 fmt.Println("Numbers under 100,000 which use the same digits in decimal or hex:") for n := 0; n < limit; n++ { h := strconv.FormatInt(int64(n), 16) hs := make(map[rune]bool) for _, c := range h { hs[c] = true } ns := make(map[rune]bool) for _, c := range strconv.Itoa(n) { ns[c] = true } if equalSets(hs, ns) { count++ fmt.Printf("%6s ", rcu.Commatize(n)) if count%10 == 0 { fmt.Println() } } } fmt.Printf("\n\n%d such numbers found.\n", count) }
col = 0 for i in range(100000): if set(str(i)) == set(hex(i)[2:]): col += 1 print("{:7}".format(i), end='\n'[:col % 10 == 0]) print()
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import "fmt" func largestPrimeFactor(n uint64) uint64 { if n < 2 { return 1 } inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6} max := uint64(1) for n%2 == 0 { max = 2 n /= 2 } for n%3 == 0 { max = 3 n /= 3 } for n%5 == 0 { max = 5 n /= 5 } k := uint64(7) i := 0 for k*k <= n { if n%k == 0 { max = k n /= k } else { k += inc[i] i = (i + 1) % 8 } } if n > 1 { return n } return max } func main() { n := uint64(600851475143) fmt.Println("The largest prime factor of", n, "is", largestPrimeFactor(n), "\b.") }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': n = 600851475143 j = 3 while not isPrime(n): if n % j == 0: n /= j j += 2 print(n);
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import "fmt" func largestProperDivisor(n int) int { for i := 2; i*i <= n; i++ { if n%i == 0 { return n / i } } return 1 } func main() { fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:") fmt.Print(" 1 ") for n := 2; n <= 100; n++ { if n%2 == 0 { fmt.Printf("%2d ", n/2) } else { fmt.Printf("%2d ", largestProperDivisor(n)) } if n%10 == 0 { fmt.Println() } } }
def lpd(n): for i in range(n-1,0,-1): if n%i==0: return i return 1 for i in range(1,101): print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "bytes" "fmt" ) type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq } func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) } func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad return sequence def move2front_decode(sequence, symboltable): chars, pad = [], symboltable[::] for indx in sequence: char = pad[indx] chars.append(char) pad = [pad.pop(indx)] + pad return ''.join(chars) if __name__ == '__main__': for s in ['broood', 'bananaaa', 'hiphophiphop']: encode = move2front_encode(s, SYMBOLTABLE) print('%14r encodes to %r' % (s, encode), end=', ') decode = move2front_decode(encode, SYMBOLTABLE) print('which decodes back to %r' % decode) assert s == decode, 'Whoops!'
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "bytes" "fmt" ) type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq } func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) } func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad return sequence def move2front_decode(sequence, symboltable): chars, pad = [], symboltable[::] for indx in sequence: char = pad[indx] chars.append(char) pad = [pad.pop(indx)] + pad return ''.join(chars) if __name__ == '__main__': for s in ['broood', 'bananaaa', 'hiphophiphop']: encode = move2front_encode(s, SYMBOLTABLE) print('%14r encodes to %r' % (s, encode), end=', ') decode = move2front_decode(encode, SYMBOLTABLE) print('which decodes back to %r' % decode) assert s == decode, 'Whoops!'
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, GroupFilter: "(memberUid=%s)", } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } groups, err := client.GetGroupsOfUser("username") if err != nil { log.Fatalf("Error getting groups for user %s: %+v", "username", err) } log.Printf("Groups: %+v", groups) }
Import-Module ActiveDirectory $searchData = "user name" $searchBase = "DC=example,DC=com" get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
Rewrite the snippet below in Python so it works the same as the original Go code.
<package main import ( "fmt" "gonum.org/v1/gonum/mat" "log" ) func matPrint(m mat.Matrix) { fa := mat.Formatted(m, mat.Prefix(""), mat.Squeeze()) fmt.Printf("%13.10f\n", fa) } func main() { var svd mat.SVD a := mat.NewDense(2, 2, []float64{3, 0, 4, 5}) ok := svd.Factorize(a, mat.SVDFull) if !ok { log.Fatal("Something went wrong!") } u := mat.NewDense(2, 2, nil) svd.UTo(u) fmt.Println("U:") matPrint(u) values := svd.Values(nil) sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]}) fmt.Println("\nΣ:") matPrint(sigma) vt := mat.NewDense(2, 2, nil) svd.VTo(vt) fmt.Println("\nVT:") matPrint(vt) }
from numpy import * A = matrix([[3, 0], [4, 5]]) U, Sigma, VT = linalg.svd(A) print(U) print(Sigma) print(VT)
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "rcu" ) func main() { fmt.Println("Cumulative sums of the first 50 cubes:") sum := 0 for n := 0; n < 50; n++ { sum += n * n * n fmt.Printf("%9s ", rcu.Commatize(sum)) if n%10 == 9 { fmt.Println() } } fmt.Println()
def main(): fila = 0 lenCubos = 51 print("Suma de N cubos para n = [0..49]\n") for n in range(1, lenCubos): sumCubos = 0 for m in range(1, n): sumCubos = sumCubos + (m ** 3) fila += 1 print(f'{sumCubos:7} ', end='') if fila % 5 == 0: print(" ") print(f"\nEncontrados {fila} cubos.") if __name__ == '__main__': main()
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math" "math/big" "reflect" "strings" "unsafe" ) func Float64IsInt(f float64) bool { _, frac := math.Modf(f) return frac == 0 } func Float32IsInt(f float32) bool { return Float64IsInt(float64(f)) } func Complex128IsInt(c complex128) bool { return imag(c) == 0 && Float64IsInt(real(c)) } func Complex64IsInt(c complex64) bool { return imag(c) == 0 && Float64IsInt(float64(real(c))) } type hasIsInt interface { IsInt() bool } var bigIntT = reflect.TypeOf((*big.Int)(nil)) func IsInt(i interface{}) bool { if ci, ok := i.(hasIsInt); ok { return ci.IsInt() } switch v := reflect.ValueOf(i); v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return true case reflect.Float32, reflect.Float64: return Float64IsInt(v.Float()) case reflect.Complex64, reflect.Complex128: return Complex128IsInt(v.Complex()) case reflect.String: if r, ok := new(big.Rat).SetString(v.String()); ok { return r.IsInt() } case reflect.Ptr: if v.Type() == bigIntT { return true } } return false } type intbased int16 type complexbased complex64 type customIntegerType struct { } func (customIntegerType) IsInt() bool { return true } func (customIntegerType) String() string { return "<…>" } func main() { hdr := fmt.Sprintf("%27s  %-6s %s\n", "Input", "IsInt", "Type") show2 := func(t bool, i interface{}, args ...interface{}) { istr := fmt.Sprint(i) fmt.Printf("%27s  %-6t %T ", istr, t, i) fmt.Println(args...) } show := func(i interface{}, args ...interface{}) { show2(IsInt(i), i, args...) } fmt.Print("Using Float64IsInt with float64:\n", hdr) neg1 := -1. for _, f := range []float64{ 0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3, math.Pi, math.MinInt64, math.MaxUint64, math.SmallestNonzeroFloat64, math.MaxFloat64, math.NaN(), math.Inf(1), math.Inf(-1), } { show2(Float64IsInt(f), f) } fmt.Print("\nUsing Complex128IsInt with complex128:\n", hdr) for _, c := range []complex128{ 3, 1i, 0i, 3.4, } { show2(Complex128IsInt(c), c) } fmt.Println("\nUsing reflection:") fmt.Print(hdr) show("hello") show(math.MaxFloat64) show("9e100") f := new(big.Float) show(f) f.SetString("1e-3000") show(f) show("(4+0i)", "(complex strings not parsed)") show(4 + 0i) show(rune('§'), "or rune") show(byte('A'), "or byte") var t1 intbased = 5200 var t2a, t2b complexbased = 5 + 0i, 5 + 1i show(t1) show(t2a) show(t2b) x := uintptr(unsafe.Pointer(&t2b)) show(x) show(math.MinInt32) show(uint64(math.MaxUint64)) b, _ := new(big.Int).SetString(strings.Repeat("9", 25), 0) show(b) r := new(big.Rat) show(r) r.SetString("2/3") show(r) show(r.SetFrac(b, new(big.Int).SetInt64(9))) show("12345/5") show(new(customIntegerType)) }
>>> def isint(f): return complex(f).imag == 0 and complex(f).real.is_integer() >>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))] [True, True, True, False, False, False] >>> ... >>> isint(25.000000) True >>> isint(24.999999) False >>> isint(25.000100) False >>> isint(-2.1e120) True >>> isint(-5e-2) False >>> isint(float('nan')) False >>> isint(float('inf')) False >>> isint(5.0+0.0j) True >>> isint(5-5j) False
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "log" "os" "os/exec" ) func main() { cmd := exec.Command("ls", "-l") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }
import os exit_code = os.system('ls') output = os.popen('ls').read()
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "fmt" "github.com/lestrrat-go/libxml2" "github.com/lestrrat-go/libxml2/xsd" "io/ioutil" "log" "os" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { xsdfile := "shiporder.xsd" f, err := os.Open(xsdfile) check(err) defer f.Close() buf, err := ioutil.ReadAll(f) check(err) s, err := xsd.Parse(buf) check(err) defer s.Free() xmlfile := "shiporder.xml" f2, err := os.Open(xmlfile) check(err) defer f2.Close() buf2, err := ioutil.ReadAll(f2) check(err) d, err := libxml2.Parse(buf2) check(err) if err := s.Validate(d); err != nil { for _, e := range err.(xsd.SchemaValidationError).Errors() { log.Printf("error: %s", e.Error()) } return } fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!") }
from __future__ import print_function import lxml from lxml import etree if __name__=="__main__": parser = etree.XMLParser(dtd_validation=True) schema_root = etree.XML() schema = etree.XMLSchema(schema_root) parser = etree.XMLParser(schema = schema) try: root = etree.fromstring("<a>5</a>", parser) print ("Finished validating good xml") except lxml.etree.XMLSyntaxError as err: print (err) parser = etree.XMLParser(schema = schema) try: root = etree.fromstring("<a>5<b>foobar</b></a>", parser) except lxml.etree.XMLSyntaxError as err: print (err)
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "sort" ) type Node struct { val int back *Node } func lis (n []int) (result []int) { var pileTops []*Node for _, x := range n { j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) node := &Node{ x, nil } if j != 0 { node.back = pileTops[j-1] } if j != len(pileTops) { pileTops[j] = node } else { pileTops = append(pileTops, node) } } if len(pileTops) == 0 { return []int{} } for node := pileTops[len(pileTops)-1]; node != nil; node = node.back { result = append(result, node.val) } for i := 0; i < len(result)/2; i++ { result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i] } return } func main() { for _, d := range [][]int{{3, 2, 6, 4, 5, 1}, {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} { fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d)) } }
def longest_increasing_subsequence(X): N = len(X) P = [0] * N M = [0] * (N+1) L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): lo = mid+1 else: hi = mid-1 newL = lo P[i] = M[newL-1] M[newL] = i if (newL > L): L = newL S = [] k = M[L] for i in range(L-1, -1, -1): S.append(X[k]) k = P[k] return S[::-1] if __name__ == '__main__': for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]: print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func (v *vector) normalize() { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } type sphere struct { cx, cy, cz int r int } func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) { x -= s.cx y -= s.cy if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 { zsqrt := math.Sqrt(float64(zsq)) return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true } return 0, 0, false } func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray { w, h := pos.r*4, pos.r*3 bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2) img := image.NewGray(bounds) vec := new(vector) for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ { for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ { zb1, zb2, hit := pos.hit(x, y) if !hit { continue } zs1, zs2, hit := neg.hit(x, y) if hit { if zs1 > zb1 { hit = false } else if zs2 > zb2 { continue } } if hit { vec[0] = float64(neg.cx - x) vec[1] = float64(neg.cy - y) vec[2] = float64(neg.cz) - zs2 } else { vec[0] = float64(x - pos.cx) vec[1] = float64(y - pos.cy) vec[2] = zb1 - float64(pos.cz) } vec.normalize() s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } return img } func main() { dir := &vector{20, -40, -10} dir.normalize() pos := &sphere{0, 0, 0, 120} neg := &sphere{-90, -90, -30, 100} img := deathStar(pos, neg, 1.5, .2, dir) f, err := os.Create("dstar.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
import sys, math, collections Sphere = collections.namedtuple("Sphere", "cx cy cz r") V3 = collections.namedtuple("V3", "x y z") def normalize((x, y, z)): len = math.sqrt(x**2 + y**2 + z**2) return V3(x / len, y / len, z / len) def dot(v1, v2): d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z return -d if d < 0 else 0.0 def hit_sphere(sph, x0, y0): x = x0 - sph.cx y = y0 - sph.cy zsq = sph.r ** 2 - (x ** 2 + y ** 2) if zsq < 0: return (False, 0, 0) szsq = math.sqrt(zsq) return (True, sph.cz - szsq, sph.cz + szsq) def draw_sphere(k, ambient, light): shades = ".:!*oe& pos = Sphere(20.0, 20.0, 0.0, 20.0) neg = Sphere(1.0, 1.0, -6.0, 20.0) for i in xrange(int(math.floor(pos.cy - pos.r)), int(math.ceil(pos.cy + pos.r) + 1)): y = i + 0.5 for j in xrange(int(math.floor(pos.cx - 2 * pos.r)), int(math.ceil(pos.cx + 2 * pos.r) + 1)): x = (j - pos.cx) / 2.0 + 0.5 + pos.cx (h, zb1, zb2) = hit_sphere(pos, x, y) if not h: hit_result = 0 else: (h, zs1, zs2) = hit_sphere(neg, x, y) if not h: hit_result = 1 elif zs1 > zb1: hit_result = 1 elif zs2 > zb2: hit_result = 0 elif zs2 > zb1: hit_result = 2 else: hit_result = 1 if hit_result == 0: sys.stdout.write(' ') continue elif hit_result == 1: vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz) elif hit_result == 2: vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2) vec = normalize(vec) b = dot(light, vec) ** k + ambient intensity = int((1 - b) * len(shades)) intensity = min(len(shades), max(0, intensity)) sys.stdout.write(shades[intensity]) print light = normalize(V3(-50, 30, 50)) draw_sphere(2, 0.5, light)
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func (v *vector) normalize() { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } type sphere struct { cx, cy, cz int r int } func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) { x -= s.cx y -= s.cy if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 { zsqrt := math.Sqrt(float64(zsq)) return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true } return 0, 0, false } func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray { w, h := pos.r*4, pos.r*3 bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2) img := image.NewGray(bounds) vec := new(vector) for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ { for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ { zb1, zb2, hit := pos.hit(x, y) if !hit { continue } zs1, zs2, hit := neg.hit(x, y) if hit { if zs1 > zb1 { hit = false } else if zs2 > zb2 { continue } } if hit { vec[0] = float64(neg.cx - x) vec[1] = float64(neg.cy - y) vec[2] = float64(neg.cz) - zs2 } else { vec[0] = float64(x - pos.cx) vec[1] = float64(y - pos.cy) vec[2] = zb1 - float64(pos.cz) } vec.normalize() s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } return img } func main() { dir := &vector{20, -40, -10} dir.normalize() pos := &sphere{0, 0, 0, 120} neg := &sphere{-90, -90, -30, 100} img := deathStar(pos, neg, 1.5, .2, dir) f, err := os.Create("dstar.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
import sys, math, collections Sphere = collections.namedtuple("Sphere", "cx cy cz r") V3 = collections.namedtuple("V3", "x y z") def normalize((x, y, z)): len = math.sqrt(x**2 + y**2 + z**2) return V3(x / len, y / len, z / len) def dot(v1, v2): d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z return -d if d < 0 else 0.0 def hit_sphere(sph, x0, y0): x = x0 - sph.cx y = y0 - sph.cy zsq = sph.r ** 2 - (x ** 2 + y ** 2) if zsq < 0: return (False, 0, 0) szsq = math.sqrt(zsq) return (True, sph.cz - szsq, sph.cz + szsq) def draw_sphere(k, ambient, light): shades = ".:!*oe& pos = Sphere(20.0, 20.0, 0.0, 20.0) neg = Sphere(1.0, 1.0, -6.0, 20.0) for i in xrange(int(math.floor(pos.cy - pos.r)), int(math.ceil(pos.cy + pos.r) + 1)): y = i + 0.5 for j in xrange(int(math.floor(pos.cx - 2 * pos.r)), int(math.ceil(pos.cx + 2 * pos.r) + 1)): x = (j - pos.cx) / 2.0 + 0.5 + pos.cx (h, zb1, zb2) = hit_sphere(pos, x, y) if not h: hit_result = 0 else: (h, zs1, zs2) = hit_sphere(neg, x, y) if not h: hit_result = 1 elif zs1 > zb1: hit_result = 1 elif zs2 > zb2: hit_result = 0 elif zs2 > zb1: hit_result = 2 else: hit_result = 1 if hit_result == 0: sys.stdout.write(' ') continue elif hit_result == 1: vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz) elif hit_result == 2: vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2) vec = normalize(vec) b = dot(light, vec) ** k + ambient intensity = int((1 - b) * len(shades)) intensity = min(len(shades), max(0, intensity)) sys.stdout.write(shades[intensity]) print light = normalize(V3(-50, 30, 50)) draw_sphere(2, 0.5, light)
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "log" "os" "strconv" "strings" ) const luckySize = 60000 var luckyOdd = make([]int, luckySize) var luckyEven = make([]int, luckySize) func init() { for i := 0; i < luckySize; i++ { luckyOdd[i] = i*2 + 1 luckyEven[i] = i*2 + 2 } } func filterLuckyOdd() { for n := 2; n < len(luckyOdd); n++ { m := luckyOdd[n-1] end := (len(luckyOdd)/m)*m - 1 for j := end; j >= m-1; j -= m { copy(luckyOdd[j:], luckyOdd[j+1:]) luckyOdd = luckyOdd[:len(luckyOdd)-1] } } } func filterLuckyEven() { for n := 2; n < len(luckyEven); n++ { m := luckyEven[n-1] end := (len(luckyEven)/m)*m - 1 for j := end; j >= m-1; j -= m { copy(luckyEven[j:], luckyEven[j+1:]) luckyEven = luckyEven[:len(luckyEven)-1] } } } func printSingle(j int, odd bool) error { if odd { if j >= len(luckyOdd) { return fmt.Errorf("the argument, %d, is too big", j) } fmt.Println("Lucky number", j, "=", luckyOdd[j-1]) } else { if j >= len(luckyEven) { return fmt.Errorf("the argument, %d, is too big", j) } fmt.Println("Lucky even number", j, "=", luckyEven[j-1]) } return nil } func printRange(j, k int, odd bool) error { if odd { if k >= len(luckyOdd) { return fmt.Errorf("the argument, %d, is too big", k) } fmt.Println("Lucky numbers", j, "to", k, "are:") fmt.Println(luckyOdd[j-1 : k]) } else { if k >= len(luckyEven) { return fmt.Errorf("the argument, %d, is too big", k) } fmt.Println("Lucky even numbers", j, "to", k, "are:") fmt.Println(luckyEven[j-1 : k]) } return nil } func printBetween(j, k int, odd bool) error { var r []int if odd { max := luckyOdd[len(luckyOdd)-1] if j > max || k > max { return fmt.Errorf("at least one argument, %d or %d, is too big", j, k) } for _, num := range luckyOdd { if num < j { continue } if num > k { break } r = append(r, num) } fmt.Println("Lucky numbers between", j, "and", k, "are:") fmt.Println(r) } else { max := luckyEven[len(luckyEven)-1] if j > max || k > max { return fmt.Errorf("at least one argument, %d or %d, is too big", j, k) } for _, num := range luckyEven { if num < j { continue } if num > k { break } r = append(r, num) } fmt.Println("Lucky even numbers between", j, "and", k, "are:") fmt.Println(r) } return nil } func main() { nargs := len(os.Args) if nargs < 2 || nargs > 4 { log.Fatal("there must be between 1 and 3 command line arguments") } filterLuckyOdd() filterLuckyEven() j, err := strconv.Atoi(os.Args[1]) if err != nil || j < 1 { log.Fatalf("first argument, %s, must be a positive integer", os.Args[1]) } if nargs == 2 { if err := printSingle(j, true); err != nil { log.Fatal(err) } return } if nargs == 3 { k, err := strconv.Atoi(os.Args[2]) if err != nil { log.Fatalf("second argument, %s, must be an integer", os.Args[2]) } if k >= 0 { if j > k { log.Fatalf("second argument, %d, can't be less than first, %d", k, j) } if err := printRange(j, k, true); err != nil { log.Fatal(err) } } else { l := -k if j > l { log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j) } if err := printBetween(j, l, true); err != nil { log.Fatal(err) } } return } var odd bool switch lucky := strings.ToLower(os.Args[3]); lucky { case "lucky": odd = true case "evenlucky": odd = false default: log.Fatalf("third argument, %s, is invalid", os.Args[3]) } if os.Args[2] == "," { if err := printSingle(j, odd); err != nil { log.Fatal(err) } return } k, err := strconv.Atoi(os.Args[2]) if err != nil { log.Fatal("second argument must be an integer or a comma") } if k >= 0 { if j > k { log.Fatalf("second argument, %d, can't be less than first, %d", k, j) } if err := printRange(j, k, odd); err != nil { log.Fatal(err) } } else { l := -k if j > l { log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j) } if err := printBetween(j, l, odd); err != nil { log.Fatal(err) } } }
from __future__ import print_function def lgen(even=False, nmax=1000000): start = 2 if even else 1 n, lst = 1, list(range(start, nmax + 1, 2)) lenlst = len(lst) yield lst[0] while n < lenlst and lst[n] < lenlst: yield lst[n] n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]] lenlst = len(lst) for i in lst[n:]: yield i
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "encoding/json" "fmt" "io" "os" "sort" "strings" "time" "unicode" ) type Item struct { Stamp time.Time Name string Tags []string `json:",omitempty"` Notes string `json:",omitempty"` } func (i *Item) String() string { s := i.Stamp.Format(time.ANSIC) + "\n Name: " + i.Name if len(i.Tags) > 0 { s = fmt.Sprintf("%s\n Tags: %v", s, i.Tags) } if i.Notes > "" { s += "\n Notes: " + i.Notes } return s } type db []*Item func (d db) Len() int { return len(d) } func (d db) Swap(i, j int) { d[i], d[j] = d[j], d[i] } func (d db) Less(i, j int) bool { return d[i].Stamp.Before(d[j].Stamp) } const fn = "sdb.json" func main() { if len(os.Args) == 1 { latest() return } switch os.Args[1] { case "add": add() case "latest": latest() case "tags": tags() case "all": all() case "help": help() default: usage("unrecognized command") } } func usage(err string) { if err > "" { fmt.Println(err) } fmt.Println(`usage: sdb [command] [data] where command is one of add, latest, tags, all, or help.`) } func help() { usage("") fmt.Println(` Commands must be in lower case. If no command is specified, the default command is latest. Latest prints the latest item. All prints all items in chronological order. Tags prints the lastest item for each tag. Help prints this message. Add adds data as a new record. The format is, name [tags] [notes] Name is the name of the item and is required for the add command. Tags are optional. A tag is a single word. A single tag can be specified without enclosing brackets. Multiple tags can be specified by enclosing them in square brackets. Text remaining after tags is taken as notes. Notes do not have to be enclosed in quotes or brackets. The brackets above are only showing that notes are optional. Quotes may be useful however--as recognized by your operating system shell or command line--to allow entry of arbitrary text. In particular, quotes or escape characters may be needed to prevent the shell from trying to interpret brackets or other special characters. Examples: sdb add Bookends sdb add Bookends rock my favorite sdb add Bookends [rock folk] sdb add Bookends [] "Simon & Garfunkel" sdb add "Simon&Garfunkel [artist]" As shown in the last example, if you use features of your shell to pass all data as a single string, the item name and tags will still be identified by separating whitespace. The database is stored in JSON format in the file "sdb.json" `) } func load() (db, bool) { d, f, ok := open() if ok { f.Close() if len(d) == 0 { fmt.Println("no items") ok = false } } return d, ok } func open() (d db, f *os.File, ok bool) { var err error f, err = os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0666) if err != nil { fmt.Println("cant open??") fmt.Println(err) return } jd := json.NewDecoder(f) err = jd.Decode(&d) if err != nil && err != io.EOF { fmt.Println(err) f.Close() return } ok = true return } func latest() { d, ok := load() if !ok { return } sort.Sort(d) fmt.Println(d[len(d)-1]) } func all() { d, ok := load() if !ok { return } sort.Sort(d) for _, i := range d { fmt.Println("-----------------------------------") fmt.Println(i) } fmt.Println("-----------------------------------") } func tags() { d, ok := load() if !ok { return } latest := make(map[string]*Item) for _, item := range d { for _, tag := range item.Tags { li, ok := latest[tag] if !ok || item.Stamp.After(li.Stamp) { latest[tag] = item } } } type itemTags struct { item *Item tags []string } inv := make(map[*Item][]string) for tag, item := range latest { inv[item] = append(inv[item], tag) } li := make(db, len(inv)) i := 0 for item := range inv { li[i] = item i++ } sort.Sort(li) for _, item := range li { tags := inv[item] fmt.Println("-----------------------------------") fmt.Println("Latest item with tags", tags) fmt.Println(item) } fmt.Println("-----------------------------------") } func add() { if len(os.Args) < 3 { usage("add command requires data") return } else if len(os.Args) == 3 { add1() } else { add4() } } func add1() { data := strings.TrimLeftFunc(os.Args[2], unicode.IsSpace) if data == "" { usage("invalid name") return } sep := strings.IndexFunc(data, unicode.IsSpace) if sep < 0 { addItem(data, nil, "") return } name := data[:sep] data = strings.TrimLeftFunc(data[sep:], unicode.IsSpace) if data == "" { addItem(name, nil, "") return } if data[0] == '[' { sep = strings.Index(data, "]") if sep < 0 { addItem(name, strings.Fields(data[1:]), "") } else { addItem(name, strings.Fields(data[1:sep]), strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace)) } return } sep = strings.IndexFunc(data, unicode.IsSpace) if sep < 0 { addItem(name, []string{data}, "") } else { addItem(name, []string{data[:sep]}, strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace)) } } func add4() { name := os.Args[2] tag1 := os.Args[3] if tag1[0] != '[' { addItem(name, []string{tag1}, strings.Join(os.Args[4:], " ")) return } if tag1[len(tag1)-1] == ']' { addItem(name, strings.Fields(tag1[1:len(tag1)-1]), strings.Join(os.Args[4:], " ")) return } var tags []string if tag1 > "[" { tags = []string{tag1[1:]} } for x, tag := range os.Args[4:] { if tag[len(tag)-1] != ']' { tags = append(tags, tag) } else { if tag > "]" { tags = append(tags, tag[:len(tag)-1]) } addItem(name, tags, strings.Join(os.Args[5+x:], " ")) return } } addItem(name, tags, "") } func addItem(name string, tags []string, notes string) { db, f, ok := open() if !ok { return } defer f.Close() db = append(db, &Item{time.Now(), name, tags, notes}) sort.Sort(db) js, err := json.MarshalIndent(db, "", " ") if err != nil { fmt.Println(err) return } if _, err = f.Seek(0, 0); err != nil { fmt.Println(err) return } f.Truncate(0) if _, err = f.Write(js); err != nil { fmt.Println(err) } }
import argparse from argparse import Namespace import datetime import shlex def parse_args(): 'Set up, parse, and return arguments' parser = argparse.ArgumentParser(epilog=globals()['__doc__']) parser.add_argument('command', choices='add pl plc pa'.split(), help=) parser.add_argument('-d', '--description', help='A description of the item. (e.g., title, name)') parser.add_argument('-t', '--tag', help=( )) parser.add_argument('-f', '--field', nargs=2, action='append', help='Other optional fields with value (can be repeated)') return parser def do_add(args, dbname): 'Add a new entry' if args.description is None: args.description = '' if args.tag is None: args.tag = '' del args.command print('Writing record to %s' % dbname) with open(dbname, 'a') as db: db.write('%r\n' % args) def do_pl(args, dbname): 'Print the latest entry' print('Getting last record from %s' % dbname) with open(dbname, 'r') as db: for line in db: pass record = eval(line) del record._date print(str(record)) def do_plc(args, dbname): 'Print the latest entry for each category/tag' print('Getting latest record for each tag from %s' % dbname) with open(dbname, 'r') as db: records = [eval(line) for line in db] tags = set(record.tag for record in records) records.reverse() for record in records: if record.tag in tags: del record._date print(str(record)) tags.discard(record.tag) if not tags: break def do_pa(args, dbname): 'Print all entries sorted by a date' print('Getting all records by date from %s' % dbname) with open(dbname, 'r') as db: records = [eval(line) for line in db] for record in records: del record._date print(str(record)) def test(): import time parser = parse_args() for cmdline in [ , , , , , ]: args = parser.parse_args(shlex.split(cmdline)) now = datetime.datetime.utcnow() args._date = now.isoformat() do_command[args.command](args, dbname) time.sleep(0.5) do_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa) dbname = '_simple_db_db.py' if __name__ == '__main__': if 0: test() else: parser = parse_args() args = parser.parse_args() now = datetime.datetime.utcnow() args._date = now.isoformat() do_command[args.command](args, dbname)
Generate an equivalent Python version of this Go code.
package main import ( "flag" "fmt" "math" "runtime" "sort" ) type Circle struct{ X, Y, R, rsq float64 } func NewCircle(x, y, r float64) Circle { return Circle{x, y, r, r * r} } func (c Circle) ContainsPt(x, y float64) bool { return distSq(x, y, c.X, c.Y) <= c.rsq } func (c Circle) ContainsC(c2 Circle) bool { return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R) } func (c Circle) ContainsR(r Rect) (full, corner bool) { nw := c.ContainsPt(r.NW()) ne := c.ContainsPt(r.NE()) sw := c.ContainsPt(r.SW()) se := c.ContainsPt(r.SE()) return nw && ne && sw && se, nw || ne || sw || se } func (c Circle) North() (float64, float64) { return c.X, c.Y + c.R } func (c Circle) South() (float64, float64) { return c.X, c.Y - c.R } func (c Circle) West() (float64, float64) { return c.X - c.R, c.Y } func (c Circle) East() (float64, float64) { return c.X + c.R, c.Y } type Rect struct{ X1, Y1, X2, Y2 float64 } func (r Rect) Area() float64 { return (r.X2 - r.X1) * (r.Y2 - r.Y1) } func (r Rect) NW() (float64, float64) { return r.X1, r.Y2 } func (r Rect) NE() (float64, float64) { return r.X2, r.Y2 } func (r Rect) SW() (float64, float64) { return r.X1, r.Y1 } func (r Rect) SE() (float64, float64) { return r.X2, r.Y1 } func (r Rect) Centre() (float64, float64) { return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0 } func (r Rect) ContainsPt(x, y float64) bool { return r.X1 <= x && x < r.X2 && r.Y1 <= y && y < r.Y2 } func (r Rect) ContainsPC(c Circle) bool { return r.ContainsPt(c.North()) || r.ContainsPt(c.South()) || r.ContainsPt(c.West()) || r.ContainsPt(c.East()) } func (r Rect) MinSide() float64 { return math.Min(r.X2-r.X1, r.Y2-r.Y1) } func distSq(x1, y1, x2, y2 float64) float64 { Δx, Δy := x2-x1, y2-y1 return (Δx * Δx) + (Δy * Δy) } type CircleSet []Circle func (s CircleSet) Len() int { return len(s) } func (s CircleSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R } func (sp *CircleSet) RemoveContainedC() { s := *sp sort.Sort(s) for i := 0; i < len(s); i++ { for j := i + 1; j < len(s); { if s[i].ContainsC(s[j]) { s[j], s[len(s)-1] = s[len(s)-1], s[j] s = s[:len(s)-1] } else { j++ } } } *sp = s } func (s CircleSet) Bounds() Rect { x1 := s[0].X - s[0].R x2 := s[0].X + s[0].R y1 := s[0].Y - s[0].R y2 := s[0].Y + s[0].R for _, c := range s[1:] { x1 = math.Min(x1, c.X-c.R) x2 = math.Max(x2, c.X+c.R) y1 = math.Min(y1, c.Y-c.R) y2 = math.Max(y2, c.Y+c.R) } return Rect{x1, y1, x2, y2} } var nWorkers = 4 func (s CircleSet) UnionArea(ε float64) (min, max float64) { sort.Sort(s) stop := make(chan bool) inside := make(chan Rect) outside := make(chan Rect) unknown := make(chan Rect, 5e7) for i := 0; i < nWorkers; i++ { go s.worker(stop, unknown, inside, outside) } r := s.Bounds() max = r.Area() unknown <- r for max-min > ε { select { case r = <-inside: min += r.Area() case r = <-outside: max -= r.Area() } } close(stop) return min, max } func (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) { for { select { case <-stop: return case r := <-unk: inside, outside := s.CategorizeR(r) switch { case inside: in <- r case outside: out <- r default: midX, midY := r.Centre() unk <- Rect{r.X1, r.Y1, midX, midY} unk <- Rect{midX, r.Y1, r.X2, midY} unk <- Rect{r.X1, midY, midX, r.Y2} unk <- Rect{midX, midY, r.X2, r.Y2} } } } } func (s CircleSet) CategorizeR(r Rect) (inside, outside bool) { anyCorner := false for _, c := range s { full, corner := c.ContainsR(r) if full { return true, false } anyCorner = anyCorner || corner } if anyCorner { return false, false } for _, c := range s { if r.ContainsPC(c) { return false, false } } return false, true } func main() { flag.IntVar(&nWorkers, "workers", nWorkers, "how many worker go routines to use") maxproc := flag.Int("cpu", runtime.NumCPU(), "GOMAXPROCS setting") flag.Parse() if *maxproc > 0 { runtime.GOMAXPROCS(*maxproc) } else { *maxproc = runtime.GOMAXPROCS(0) } circles := CircleSet{ NewCircle(1.6417233788, 1.6121789534, 0.0848270516), NewCircle(-1.4944608174, 1.2077959613, 1.1039549836), NewCircle(0.6110294452, -0.6907087527, 0.9089162485), NewCircle(0.3844862411, 0.2923344616, 0.2375743054), NewCircle(-0.2495892950, -0.3832854473, 1.0845181219), NewCircle(1.7813504266, 1.6178237031, 0.8162655711), NewCircle(-0.1985249206, -0.8343333301, 0.0538864941), NewCircle(-1.7011985145, -0.1263820964, 0.4776976918), NewCircle(-0.4319462812, 1.4104420482, 0.7886291537), NewCircle(0.2178372997, -0.9499557344, 0.0357871187), NewCircle(-0.6294854565, -1.3078893852, 0.7653357688), NewCircle(1.7952608455, 0.6281269104, 0.2727652452), NewCircle(1.4168575317, 1.0683357171, 1.1016025378), NewCircle(1.4637371396, 0.9463877418, 1.1846214562), NewCircle(-0.5263668798, 1.7315156631, 1.4428514068), NewCircle(-1.2197352481, 0.9144146579, 1.0727263474), NewCircle(-0.1389358881, 0.1092805780, 0.7350208828), NewCircle(1.5293954595, 0.0030278255, 1.2472867347), NewCircle(-0.5258728625, 1.3782633069, 1.3495508831), NewCircle(-0.1403562064, 0.2437382535, 1.3804956588), NewCircle(0.8055826339, -0.0482092025, 0.3327165165), NewCircle(-0.6311979224, 0.7184578971, 0.2491045282), NewCircle(1.4685857879, -0.8347049536, 1.3670667538), NewCircle(-0.6855727502, 1.6465021616, 1.0593087096), NewCircle(0.0152957411, 0.0638919221, 0.9771215985), } fmt.Println("Starting with", len(circles), "circles.") circles.RemoveContainedC() fmt.Println("Removing redundant ones leaves", len(circles), "circles.") fmt.Println("Using", nWorkers, "workers with maxprocs =", *maxproc) const ε = 0.0001 min, max := circles.UnionArea(ε) avg := (min + max) / 2.0 rng := max - min fmt.Printf("Area = %v±%v\n", avg, rng) fmt.Printf("Area ≈ %.*f\n", 5, avg) }
from collections import namedtuple Circle = namedtuple("Circle", "x y r") circles = [ Circle( 1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle( 0.6110294452, -0.6907087527, 0.9089162485), Circle( 0.3844862411, 0.2923344616, 0.2375743054), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "flag" "fmt" "math" "runtime" "sort" ) type Circle struct{ X, Y, R, rsq float64 } func NewCircle(x, y, r float64) Circle { return Circle{x, y, r, r * r} } func (c Circle) ContainsPt(x, y float64) bool { return distSq(x, y, c.X, c.Y) <= c.rsq } func (c Circle) ContainsC(c2 Circle) bool { return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R) } func (c Circle) ContainsR(r Rect) (full, corner bool) { nw := c.ContainsPt(r.NW()) ne := c.ContainsPt(r.NE()) sw := c.ContainsPt(r.SW()) se := c.ContainsPt(r.SE()) return nw && ne && sw && se, nw || ne || sw || se } func (c Circle) North() (float64, float64) { return c.X, c.Y + c.R } func (c Circle) South() (float64, float64) { return c.X, c.Y - c.R } func (c Circle) West() (float64, float64) { return c.X - c.R, c.Y } func (c Circle) East() (float64, float64) { return c.X + c.R, c.Y } type Rect struct{ X1, Y1, X2, Y2 float64 } func (r Rect) Area() float64 { return (r.X2 - r.X1) * (r.Y2 - r.Y1) } func (r Rect) NW() (float64, float64) { return r.X1, r.Y2 } func (r Rect) NE() (float64, float64) { return r.X2, r.Y2 } func (r Rect) SW() (float64, float64) { return r.X1, r.Y1 } func (r Rect) SE() (float64, float64) { return r.X2, r.Y1 } func (r Rect) Centre() (float64, float64) { return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0 } func (r Rect) ContainsPt(x, y float64) bool { return r.X1 <= x && x < r.X2 && r.Y1 <= y && y < r.Y2 } func (r Rect) ContainsPC(c Circle) bool { return r.ContainsPt(c.North()) || r.ContainsPt(c.South()) || r.ContainsPt(c.West()) || r.ContainsPt(c.East()) } func (r Rect) MinSide() float64 { return math.Min(r.X2-r.X1, r.Y2-r.Y1) } func distSq(x1, y1, x2, y2 float64) float64 { Δx, Δy := x2-x1, y2-y1 return (Δx * Δx) + (Δy * Δy) } type CircleSet []Circle func (s CircleSet) Len() int { return len(s) } func (s CircleSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R } func (sp *CircleSet) RemoveContainedC() { s := *sp sort.Sort(s) for i := 0; i < len(s); i++ { for j := i + 1; j < len(s); { if s[i].ContainsC(s[j]) { s[j], s[len(s)-1] = s[len(s)-1], s[j] s = s[:len(s)-1] } else { j++ } } } *sp = s } func (s CircleSet) Bounds() Rect { x1 := s[0].X - s[0].R x2 := s[0].X + s[0].R y1 := s[0].Y - s[0].R y2 := s[0].Y + s[0].R for _, c := range s[1:] { x1 = math.Min(x1, c.X-c.R) x2 = math.Max(x2, c.X+c.R) y1 = math.Min(y1, c.Y-c.R) y2 = math.Max(y2, c.Y+c.R) } return Rect{x1, y1, x2, y2} } var nWorkers = 4 func (s CircleSet) UnionArea(ε float64) (min, max float64) { sort.Sort(s) stop := make(chan bool) inside := make(chan Rect) outside := make(chan Rect) unknown := make(chan Rect, 5e7) for i := 0; i < nWorkers; i++ { go s.worker(stop, unknown, inside, outside) } r := s.Bounds() max = r.Area() unknown <- r for max-min > ε { select { case r = <-inside: min += r.Area() case r = <-outside: max -= r.Area() } } close(stop) return min, max } func (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) { for { select { case <-stop: return case r := <-unk: inside, outside := s.CategorizeR(r) switch { case inside: in <- r case outside: out <- r default: midX, midY := r.Centre() unk <- Rect{r.X1, r.Y1, midX, midY} unk <- Rect{midX, r.Y1, r.X2, midY} unk <- Rect{r.X1, midY, midX, r.Y2} unk <- Rect{midX, midY, r.X2, r.Y2} } } } } func (s CircleSet) CategorizeR(r Rect) (inside, outside bool) { anyCorner := false for _, c := range s { full, corner := c.ContainsR(r) if full { return true, false } anyCorner = anyCorner || corner } if anyCorner { return false, false } for _, c := range s { if r.ContainsPC(c) { return false, false } } return false, true } func main() { flag.IntVar(&nWorkers, "workers", nWorkers, "how many worker go routines to use") maxproc := flag.Int("cpu", runtime.NumCPU(), "GOMAXPROCS setting") flag.Parse() if *maxproc > 0 { runtime.GOMAXPROCS(*maxproc) } else { *maxproc = runtime.GOMAXPROCS(0) } circles := CircleSet{ NewCircle(1.6417233788, 1.6121789534, 0.0848270516), NewCircle(-1.4944608174, 1.2077959613, 1.1039549836), NewCircle(0.6110294452, -0.6907087527, 0.9089162485), NewCircle(0.3844862411, 0.2923344616, 0.2375743054), NewCircle(-0.2495892950, -0.3832854473, 1.0845181219), NewCircle(1.7813504266, 1.6178237031, 0.8162655711), NewCircle(-0.1985249206, -0.8343333301, 0.0538864941), NewCircle(-1.7011985145, -0.1263820964, 0.4776976918), NewCircle(-0.4319462812, 1.4104420482, 0.7886291537), NewCircle(0.2178372997, -0.9499557344, 0.0357871187), NewCircle(-0.6294854565, -1.3078893852, 0.7653357688), NewCircle(1.7952608455, 0.6281269104, 0.2727652452), NewCircle(1.4168575317, 1.0683357171, 1.1016025378), NewCircle(1.4637371396, 0.9463877418, 1.1846214562), NewCircle(-0.5263668798, 1.7315156631, 1.4428514068), NewCircle(-1.2197352481, 0.9144146579, 1.0727263474), NewCircle(-0.1389358881, 0.1092805780, 0.7350208828), NewCircle(1.5293954595, 0.0030278255, 1.2472867347), NewCircle(-0.5258728625, 1.3782633069, 1.3495508831), NewCircle(-0.1403562064, 0.2437382535, 1.3804956588), NewCircle(0.8055826339, -0.0482092025, 0.3327165165), NewCircle(-0.6311979224, 0.7184578971, 0.2491045282), NewCircle(1.4685857879, -0.8347049536, 1.3670667538), NewCircle(-0.6855727502, 1.6465021616, 1.0593087096), NewCircle(0.0152957411, 0.0638919221, 0.9771215985), } fmt.Println("Starting with", len(circles), "circles.") circles.RemoveContainedC() fmt.Println("Removing redundant ones leaves", len(circles), "circles.") fmt.Println("Using", nWorkers, "workers with maxprocs =", *maxproc) const ε = 0.0001 min, max := circles.UnionArea(ε) avg := (min + max) / 2.0 rng := max - min fmt.Printf("Area = %v±%v\n", avg, rng) fmt.Printf("Area ≈ %.*f\n", 5, avg) }
from collections import namedtuple Circle = namedtuple("Circle", "x y r") circles = [ Circle( 1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle( 0.6110294452, -0.6907087527, 0.9089162485), Circle( 0.3844862411, 0.2923344616, 0.2375743054), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "flag" "fmt" "math" "runtime" "sort" ) type Circle struct{ X, Y, R, rsq float64 } func NewCircle(x, y, r float64) Circle { return Circle{x, y, r, r * r} } func (c Circle) ContainsPt(x, y float64) bool { return distSq(x, y, c.X, c.Y) <= c.rsq } func (c Circle) ContainsC(c2 Circle) bool { return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R) } func (c Circle) ContainsR(r Rect) (full, corner bool) { nw := c.ContainsPt(r.NW()) ne := c.ContainsPt(r.NE()) sw := c.ContainsPt(r.SW()) se := c.ContainsPt(r.SE()) return nw && ne && sw && se, nw || ne || sw || se } func (c Circle) North() (float64, float64) { return c.X, c.Y + c.R } func (c Circle) South() (float64, float64) { return c.X, c.Y - c.R } func (c Circle) West() (float64, float64) { return c.X - c.R, c.Y } func (c Circle) East() (float64, float64) { return c.X + c.R, c.Y } type Rect struct{ X1, Y1, X2, Y2 float64 } func (r Rect) Area() float64 { return (r.X2 - r.X1) * (r.Y2 - r.Y1) } func (r Rect) NW() (float64, float64) { return r.X1, r.Y2 } func (r Rect) NE() (float64, float64) { return r.X2, r.Y2 } func (r Rect) SW() (float64, float64) { return r.X1, r.Y1 } func (r Rect) SE() (float64, float64) { return r.X2, r.Y1 } func (r Rect) Centre() (float64, float64) { return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0 } func (r Rect) ContainsPt(x, y float64) bool { return r.X1 <= x && x < r.X2 && r.Y1 <= y && y < r.Y2 } func (r Rect) ContainsPC(c Circle) bool { return r.ContainsPt(c.North()) || r.ContainsPt(c.South()) || r.ContainsPt(c.West()) || r.ContainsPt(c.East()) } func (r Rect) MinSide() float64 { return math.Min(r.X2-r.X1, r.Y2-r.Y1) } func distSq(x1, y1, x2, y2 float64) float64 { Δx, Δy := x2-x1, y2-y1 return (Δx * Δx) + (Δy * Δy) } type CircleSet []Circle func (s CircleSet) Len() int { return len(s) } func (s CircleSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R } func (sp *CircleSet) RemoveContainedC() { s := *sp sort.Sort(s) for i := 0; i < len(s); i++ { for j := i + 1; j < len(s); { if s[i].ContainsC(s[j]) { s[j], s[len(s)-1] = s[len(s)-1], s[j] s = s[:len(s)-1] } else { j++ } } } *sp = s } func (s CircleSet) Bounds() Rect { x1 := s[0].X - s[0].R x2 := s[0].X + s[0].R y1 := s[0].Y - s[0].R y2 := s[0].Y + s[0].R for _, c := range s[1:] { x1 = math.Min(x1, c.X-c.R) x2 = math.Max(x2, c.X+c.R) y1 = math.Min(y1, c.Y-c.R) y2 = math.Max(y2, c.Y+c.R) } return Rect{x1, y1, x2, y2} } var nWorkers = 4 func (s CircleSet) UnionArea(ε float64) (min, max float64) { sort.Sort(s) stop := make(chan bool) inside := make(chan Rect) outside := make(chan Rect) unknown := make(chan Rect, 5e7) for i := 0; i < nWorkers; i++ { go s.worker(stop, unknown, inside, outside) } r := s.Bounds() max = r.Area() unknown <- r for max-min > ε { select { case r = <-inside: min += r.Area() case r = <-outside: max -= r.Area() } } close(stop) return min, max } func (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) { for { select { case <-stop: return case r := <-unk: inside, outside := s.CategorizeR(r) switch { case inside: in <- r case outside: out <- r default: midX, midY := r.Centre() unk <- Rect{r.X1, r.Y1, midX, midY} unk <- Rect{midX, r.Y1, r.X2, midY} unk <- Rect{r.X1, midY, midX, r.Y2} unk <- Rect{midX, midY, r.X2, r.Y2} } } } } func (s CircleSet) CategorizeR(r Rect) (inside, outside bool) { anyCorner := false for _, c := range s { full, corner := c.ContainsR(r) if full { return true, false } anyCorner = anyCorner || corner } if anyCorner { return false, false } for _, c := range s { if r.ContainsPC(c) { return false, false } } return false, true } func main() { flag.IntVar(&nWorkers, "workers", nWorkers, "how many worker go routines to use") maxproc := flag.Int("cpu", runtime.NumCPU(), "GOMAXPROCS setting") flag.Parse() if *maxproc > 0 { runtime.GOMAXPROCS(*maxproc) } else { *maxproc = runtime.GOMAXPROCS(0) } circles := CircleSet{ NewCircle(1.6417233788, 1.6121789534, 0.0848270516), NewCircle(-1.4944608174, 1.2077959613, 1.1039549836), NewCircle(0.6110294452, -0.6907087527, 0.9089162485), NewCircle(0.3844862411, 0.2923344616, 0.2375743054), NewCircle(-0.2495892950, -0.3832854473, 1.0845181219), NewCircle(1.7813504266, 1.6178237031, 0.8162655711), NewCircle(-0.1985249206, -0.8343333301, 0.0538864941), NewCircle(-1.7011985145, -0.1263820964, 0.4776976918), NewCircle(-0.4319462812, 1.4104420482, 0.7886291537), NewCircle(0.2178372997, -0.9499557344, 0.0357871187), NewCircle(-0.6294854565, -1.3078893852, 0.7653357688), NewCircle(1.7952608455, 0.6281269104, 0.2727652452), NewCircle(1.4168575317, 1.0683357171, 1.1016025378), NewCircle(1.4637371396, 0.9463877418, 1.1846214562), NewCircle(-0.5263668798, 1.7315156631, 1.4428514068), NewCircle(-1.2197352481, 0.9144146579, 1.0727263474), NewCircle(-0.1389358881, 0.1092805780, 0.7350208828), NewCircle(1.5293954595, 0.0030278255, 1.2472867347), NewCircle(-0.5258728625, 1.3782633069, 1.3495508831), NewCircle(-0.1403562064, 0.2437382535, 1.3804956588), NewCircle(0.8055826339, -0.0482092025, 0.3327165165), NewCircle(-0.6311979224, 0.7184578971, 0.2491045282), NewCircle(1.4685857879, -0.8347049536, 1.3670667538), NewCircle(-0.6855727502, 1.6465021616, 1.0593087096), NewCircle(0.0152957411, 0.0638919221, 0.9771215985), } fmt.Println("Starting with", len(circles), "circles.") circles.RemoveContainedC() fmt.Println("Removing redundant ones leaves", len(circles), "circles.") fmt.Println("Using", nWorkers, "workers with maxprocs =", *maxproc) const ε = 0.0001 min, max := circles.UnionArea(ε) avg := (min + max) / 2.0 rng := max - min fmt.Printf("Area = %v±%v\n", avg, rng) fmt.Printf("Area ≈ %.*f\n", 5, avg) }
from collections import namedtuple Circle = namedtuple("Circle", "x y r") circles = [ Circle( 1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle( 0.6110294452, -0.6907087527, 0.9089162485), Circle( 0.3844862411, 0.2923344616, 0.2375743054), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" ) func hough(im image.Image, ntx, mry int) draw.Image { nimx := im.Bounds().Max.X mimy := im.Bounds().Max.Y him := image.NewGray(image.Rect(0, 0, ntx, mry)) draw.Draw(him, him.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src) rmax := math.Hypot(float64(nimx), float64(mimy)) dr := rmax / float64(mry/2) dth := math.Pi / float64(ntx) for jx := 0; jx < nimx; jx++ { for iy := 0; iy < mimy; iy++ { col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray) if col.Y == 255 { continue } for jtx := 0; jtx < ntx; jtx++ { th := dth * float64(jtx) r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th) iry := mry/2 - int(math.Floor(r/dr+.5)) col = him.At(jtx, iry).(color.Gray) if col.Y > 0 { col.Y-- him.SetGray(jtx, iry, col) } } } } return him } func main() { f, err := os.Open("Pentagon.png") if err != nil { fmt.Println(err) return } pent, err := png.Decode(f) if err != nil { fmt.Println(err) return } if err = f.Close(); err != nil { fmt.Println(err) } h := hough(pent, 460, 360) if f, err = os.Create("hough.png"); err != nil { fmt.Println(err) return } if err = png.Encode(f, h); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(err) } }
from math import hypot, pi, cos, sin from PIL import Image def hough(im, ntx=460, mry=360): "Calculate Hough transform." pim = im.load() nimx, mimy = im.size mry = int(mry/2)*2 him = Image.new("L", (ntx, mry), 255) phim = him.load() rmax = hypot(nimx, mimy) dr = rmax / (mry/2) dth = pi / ntx for jx in xrange(nimx): for iy in xrange(mimy): col = pim[jx, iy] if col == 255: continue for jtx in xrange(ntx): th = dth * jtx r = jx*cos(th) + iy*sin(th) iry = mry/2 + int(r/dr+0.5) phim[jtx, iry] -= 1 return him def test(): "Test Hough transform with pentagon." im = Image.open("pentagon.png").convert("L") him = hough(im) him.save("ho5.bmp") if __name__ == "__main__": test()
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" ) type ifctn func(float64) float64 func simpson38(f ifctn, a, b float64, n int) float64 { h := (b - a) / float64(n) h1 := h / 3 sum := f(a) + f(b) for j := 3*n - 1; j > 0; j-- { if j%3 == 0 { sum += 2 * f(a+h1*float64(j)) } else { sum += 3 * f(a+h1*float64(j)) } } return h * sum / 8 } func gammaIncQ(a, x float64) float64 { aa1 := a - 1 var f ifctn = func(t float64) float64 { return math.Pow(t, aa1) * math.Exp(-t) } y := aa1 h := 1.5e-2 for f(y)*(x-y) > 2e-8 && y < x { y += .4 } if y > x { y = x } return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a))) } func chi2ud(ds []int) float64 { var sum, expected float64 for _, d := range ds { expected += float64(d) } expected /= float64(len(ds)) for _, d := range ds { x := float64(d) - expected sum += x * x } return sum / expected } func chi2p(dof int, distance float64) float64 { return gammaIncQ(.5*float64(dof), .5*distance) } const sigLevel = .05 func main() { for _, dset := range [][]int{ {199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}, } { utest(dset) } } func utest(dset []int) { fmt.Println("Uniform distribution test") var sum int for _, c := range dset { sum += c } fmt.Println(" dataset:", dset) fmt.Println(" samples: ", sum) fmt.Println(" categories: ", len(dset)) dof := len(dset) - 1 fmt.Println(" degrees of freedom: ", dof) dist := chi2ud(dset) fmt.Println(" chi square test statistic: ", dist) p := chi2p(dof, dist) fmt.Println(" p-value of test statistic: ", p) sig := p < sigLevel fmt.Printf(" significant at %2.0f%% level? %t\n", sigLevel*100, sig) fmt.Println(" uniform? ", !sig, "\n") }
import math import random def GammaInc_Q( a, x): a1 = a-1 a2 = a-2 def f0( t ): return t**a1*math.exp(-t) def df0(t): return (a1-t)*t**a2*math.exp(-t) y = a1 while f0(y)*(x-y) >2.0e-8 and y < x: y += .3 if y > x: y = x h = 3.0e-4 n = int(y/h) h = y/n hh = 0.5*h gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1))) return gamax/gamma_spounge(a) c = None def gamma_spounge( z): global c a = 12 if c is None: k1_factrl = 1.0 c = [] c.append(math.sqrt(2.0*math.pi)) for k in range(1,a): c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl ) k1_factrl *= -k accm = c[0] for k in range(1,a): accm += c[k] / (z+k) accm *= math.exp( -(z+a)) * (z+a)**(z+0.5) return accm/z; def chi2UniformDistance( dataSet ): expected = sum(dataSet)*1.0/len(dataSet) cntrd = (d-expected for d in dataSet) return sum(x*x for x in cntrd)/expected def chi2Probability(dof, distance): return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance) def chi2IsUniform(dataSet, significance): dof = len(dataSet)-1 dist = chi2UniformDistance(dataSet) return chi2Probability( dof, dist ) > significance dset1 = [ 199809, 200665, 199607, 200270, 199649 ] dset2 = [ 522573, 244456, 139979, 71531, 21461 ] for ds in (dset1, dset2): print "Data set:", ds dof = len(ds)-1 distance =chi2UniformDistance(ds) print "dof: %d distance: %.4f" % (dof, distance), prob = chi2Probability( dof, distance) print "probability: %.4f"%prob, print "uniform? ", "Yes"if chi2IsUniform(ds,0.05) else "No"
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math" ) var ( d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6, 23.1, 19.6, 19.0, 21.7, 21.4} d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2, 21.9, 22.1, 22.9, 20.5, 24.4} d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8} d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8, 20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8} d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0} d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7, 23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2} d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99} d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98} x = []float64{3.0, 4.0, 1.0, 2.1} y = []float64{490.2, 340.0, 433.9} ) func main() { fmt.Printf("%.6f\n", pValue(d1, d2)) fmt.Printf("%.6f\n", pValue(d3, d4)) fmt.Printf("%.6f\n", pValue(d5, d6)) fmt.Printf("%.6f\n", pValue(d7, d8)) fmt.Printf("%.6f\n", pValue(x, y)) } func mean(a []float64) float64 { sum := 0. for _, x := range a { sum += x } return sum / float64(len(a)) } func sv(a []float64) float64 { m := mean(a) sum := 0. for _, x := range a { d := x - m sum += d * d } return sum / float64(len(a)-1) } func welch(a, b []float64) float64 { return (mean(a) - mean(b)) / math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b))) } func dof(a, b []float64) float64 { sva := sv(a) svb := sv(b) n := sva/float64(len(a)) + svb/float64(len(b)) return n * n / (sva*sva/float64(len(a)*len(a)*(len(a)-1)) + svb*svb/float64(len(b)*len(b)*(len(b)-1))) } func simpson0(n int, upper float64, f func(float64) float64) float64 { sum := 0. nf := float64(n) dx0 := upper / nf sum += f(0) * dx0 sum += f(dx0*.5) * dx0 * 4 x0 := dx0 for i := 1; i < n; i++ { x1 := float64(i+1) * upper / nf xmid := (x0 + x1) * .5 dx := x1 - x0 sum += f(x0) * dx * 2 sum += f(xmid) * dx * 4 x0 = x1 } return (sum + f(upper)*dx0) / 6 } func pValue(a, b []float64) float64 { ν := dof(a, b) t := welch(a, b) g1, _ := math.Lgamma(ν / 2) g2, _ := math.Lgamma(.5) g3, _ := math.Lgamma(ν/2 + .5) return simpson0(2000, ν/(t*t+ν), func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) / math.Exp(g1+g2-g3) }
import numpy as np import scipy as sp import scipy.stats def welch_ttest(x1, x2): n1 = x1.size n2 = x2.size m1 = np.mean(x1) m2 = np.mean(x2) v1 = np.var(x1, ddof=1) v2 = np.var(x2, ddof=1) t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2) df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1))) p = 2 * sp.stats.t.cdf(-abs(t), df) return t, df, p welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9])) (-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "math" ) var ( d1 = []float64{27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6, 23.1, 19.6, 19.0, 21.7, 21.4} d2 = []float64{27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2, 21.9, 22.1, 22.9, 20.5, 24.4} d3 = []float64{17.2, 20.9, 22.6, 18.1, 21.7, 21.4, 23.5, 24.2, 14.7, 21.8} d4 = []float64{21.5, 22.8, 21.0, 23.0, 21.6, 23.6, 22.5, 20.7, 23.4, 21.8, 20.7, 21.7, 21.5, 22.5, 23.6, 21.5, 22.5, 23.5, 21.5, 21.8} d5 = []float64{19.8, 20.4, 19.6, 17.8, 18.5, 18.9, 18.3, 18.9, 19.5, 22.0} d6 = []float64{28.2, 26.6, 20.1, 23.3, 25.2, 22.1, 17.7, 27.6, 20.6, 13.7, 23.2, 17.5, 20.6, 18.0, 23.9, 21.6, 24.3, 20.4, 24.0, 13.2} d7 = []float64{30.02, 29.99, 30.11, 29.97, 30.01, 29.99} d8 = []float64{29.89, 29.93, 29.72, 29.98, 30.02, 29.98} x = []float64{3.0, 4.0, 1.0, 2.1} y = []float64{490.2, 340.0, 433.9} ) func main() { fmt.Printf("%.6f\n", pValue(d1, d2)) fmt.Printf("%.6f\n", pValue(d3, d4)) fmt.Printf("%.6f\n", pValue(d5, d6)) fmt.Printf("%.6f\n", pValue(d7, d8)) fmt.Printf("%.6f\n", pValue(x, y)) } func mean(a []float64) float64 { sum := 0. for _, x := range a { sum += x } return sum / float64(len(a)) } func sv(a []float64) float64 { m := mean(a) sum := 0. for _, x := range a { d := x - m sum += d * d } return sum / float64(len(a)-1) } func welch(a, b []float64) float64 { return (mean(a) - mean(b)) / math.Sqrt(sv(a)/float64(len(a))+sv(b)/float64(len(b))) } func dof(a, b []float64) float64 { sva := sv(a) svb := sv(b) n := sva/float64(len(a)) + svb/float64(len(b)) return n * n / (sva*sva/float64(len(a)*len(a)*(len(a)-1)) + svb*svb/float64(len(b)*len(b)*(len(b)-1))) } func simpson0(n int, upper float64, f func(float64) float64) float64 { sum := 0. nf := float64(n) dx0 := upper / nf sum += f(0) * dx0 sum += f(dx0*.5) * dx0 * 4 x0 := dx0 for i := 1; i < n; i++ { x1 := float64(i+1) * upper / nf xmid := (x0 + x1) * .5 dx := x1 - x0 sum += f(x0) * dx * 2 sum += f(xmid) * dx * 4 x0 = x1 } return (sum + f(upper)*dx0) / 6 } func pValue(a, b []float64) float64 { ν := dof(a, b) t := welch(a, b) g1, _ := math.Lgamma(ν / 2) g2, _ := math.Lgamma(.5) g3, _ := math.Lgamma(ν/2 + .5) return simpson0(2000, ν/(t*t+ν), func(r float64) float64 { return math.Pow(r, ν/2-1) / math.Sqrt(1-r) }) / math.Exp(g1+g2-g3) }
import numpy as np import scipy as sp import scipy.stats def welch_ttest(x1, x2): n1 = x1.size n2 = x2.size m1 = np.mean(x1) m2 = np.mean(x2) v1 = np.var(x1, ddof=1) v2 = np.var(x2, ddof=1) t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2) df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1))) p = 2 * sp.stats.t.cdf(-abs(t), df) return t, df, p welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9])) (-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
Generate an equivalent Python version of this Go code.
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err := parseLibDep(data) if err != nil { fmt.Println(err) return } var tops []string for n := range g { if !dep[n] { tops = append(tops, n) } } fmt.Println("Top levels:", tops) showOrder(g, "top1") showOrder(g, "top2") showOrder(g, "top1", "top2") fmt.Println("Cycle examples:") g, _, err = parseLibDep(data + ` des1a1 des1`) if err != nil { fmt.Println(err) return } showOrder(g, "top1") showOrder(g, "ip1", "ip2") } func showOrder(g graph, target ...string) { order, cyclic := g.orderFrom(target...) if cyclic == nil { reverse(order) fmt.Println("Target", target, "order:", order) } else { fmt.Println("Target", target, "cyclic dependencies:", cyclic) } } func reverse(s []string) { last := len(s) - 1 for i, e := range s[:len(s)/2] { s[i], s[last-i] = s[last-i], e } } type graph map[string][]string type depList map[string]bool func parseLibDep(data string) (g graph, d depList, err error) { lines := strings.Split(data, "\n") if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") { return nil, nil, fmt.Errorf("data format") } lines = lines[3:] g = graph{} d = depList{} for _, line := range lines { libs := strings.Fields(line) if len(libs) == 0 { continue } lib := libs[0] var deps []string for _, dep := range libs[1:] { g[dep] = g[dep] if dep == lib { continue } for i := 0; ; i++ { if i == len(deps) { deps = append(deps, dep) d[dep] = true break } if dep == deps[i] { break } } } g[lib] = deps } return g, d, nil } func (g graph) orderFrom(start ...string) (order, cyclic []string) { L := make([]string, len(g)) i := len(L) temp := map[string]bool{} perm := map[string]bool{} var cycleFound bool var cycleStart string var visit func(string) visit = func(n string) { switch { case temp[n]: cycleFound = true cycleStart = n return case perm[n]: return } temp[n] = true for _, m := range g[n] { visit(m) if cycleFound { if cycleStart > "" { cyclic = append(cyclic, n) if n == cycleStart { cycleStart = "" } } return } } delete(temp, n) perm[n] = true i-- L[i] = n } for _, n := range start { if perm[n] { continue } visit(n) if cycleFound { return nil, cyclic } } return L[i:], nil }
try: from functools import reduce except: pass def topx(data, tops=None): 'Extract the set of top-level(s) in topological order' for k, v in data.items(): v.discard(k) if tops is None: tops = toplevels(data) return _topx(data, tops, [], set()) def _topx(data, tops, _sofar, _sofar_set): 'Recursive topological extractor' _sofar += [tops] _sofar_set.union(tops) depends = reduce(set.union, (data.get(top, set()) for top in tops)) if depends: _topx(data, depends, _sofar, _sofar_set) ordered, accum = [], set() for s in _sofar[::-1]: ordered += [sorted(s - accum)] accum |= s return ordered def printorder(order): 'Prettyprint topological ordering' if order: print("First: " + ', '.join(str(s) for s in order[0])) for o in order[1:]: print(" Then: " + ', '.join(str(s) for s in o)) def toplevels(data): for k, v in data.items(): v.discard(k) dependents = reduce(set.union, data.values()) return set(data.keys()) - dependents if __name__ == '__main__': data = dict( top1 = set('ip1 des1 ip2'.split()), top2 = set('ip2 des1 ip3'.split()), des1 = set('des1a des1b des1c'.split()), des1a = set('des1a1 des1a2'.split()), des1c = set('des1c1 extra1'.split()), ip2 = set('ip2a ip2b ip2c ipcommon'.split()), ip1 = set('ip1a ipcommon extra1'.split()), ) tops = toplevels(data) print("The top levels of the dependency graph are: " + ' '.join(tops)) for t in sorted(tops): print("\nThe compile order for top level: %s is..." % t) printorder(topx(data, set([t]))) if len(tops) > 1: print("\nThe compile order for top levels: %s is..." % ' and '.join(str(s) for s in sorted(tops)) ) printorder(topx(data, tops))
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err := parseLibDep(data) if err != nil { fmt.Println(err) return } var tops []string for n := range g { if !dep[n] { tops = append(tops, n) } } fmt.Println("Top levels:", tops) showOrder(g, "top1") showOrder(g, "top2") showOrder(g, "top1", "top2") fmt.Println("Cycle examples:") g, _, err = parseLibDep(data + ` des1a1 des1`) if err != nil { fmt.Println(err) return } showOrder(g, "top1") showOrder(g, "ip1", "ip2") } func showOrder(g graph, target ...string) { order, cyclic := g.orderFrom(target...) if cyclic == nil { reverse(order) fmt.Println("Target", target, "order:", order) } else { fmt.Println("Target", target, "cyclic dependencies:", cyclic) } } func reverse(s []string) { last := len(s) - 1 for i, e := range s[:len(s)/2] { s[i], s[last-i] = s[last-i], e } } type graph map[string][]string type depList map[string]bool func parseLibDep(data string) (g graph, d depList, err error) { lines := strings.Split(data, "\n") if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") { return nil, nil, fmt.Errorf("data format") } lines = lines[3:] g = graph{} d = depList{} for _, line := range lines { libs := strings.Fields(line) if len(libs) == 0 { continue } lib := libs[0] var deps []string for _, dep := range libs[1:] { g[dep] = g[dep] if dep == lib { continue } for i := 0; ; i++ { if i == len(deps) { deps = append(deps, dep) d[dep] = true break } if dep == deps[i] { break } } } g[lib] = deps } return g, d, nil } func (g graph) orderFrom(start ...string) (order, cyclic []string) { L := make([]string, len(g)) i := len(L) temp := map[string]bool{} perm := map[string]bool{} var cycleFound bool var cycleStart string var visit func(string) visit = func(n string) { switch { case temp[n]: cycleFound = true cycleStart = n return case perm[n]: return } temp[n] = true for _, m := range g[n] { visit(m) if cycleFound { if cycleStart > "" { cyclic = append(cyclic, n) if n == cycleStart { cycleStart = "" } } return } } delete(temp, n) perm[n] = true i-- L[i] = n } for _, n := range start { if perm[n] { continue } visit(n) if cycleFound { return nil, cyclic } } return L[i:], nil }
try: from functools import reduce except: pass def topx(data, tops=None): 'Extract the set of top-level(s) in topological order' for k, v in data.items(): v.discard(k) if tops is None: tops = toplevels(data) return _topx(data, tops, [], set()) def _topx(data, tops, _sofar, _sofar_set): 'Recursive topological extractor' _sofar += [tops] _sofar_set.union(tops) depends = reduce(set.union, (data.get(top, set()) for top in tops)) if depends: _topx(data, depends, _sofar, _sofar_set) ordered, accum = [], set() for s in _sofar[::-1]: ordered += [sorted(s - accum)] accum |= s return ordered def printorder(order): 'Prettyprint topological ordering' if order: print("First: " + ', '.join(str(s) for s in order[0])) for o in order[1:]: print(" Then: " + ', '.join(str(s) for s in o)) def toplevels(data): for k, v in data.items(): v.discard(k) dependents = reduce(set.union, data.values()) return set(data.keys()) - dependents if __name__ == '__main__': data = dict( top1 = set('ip1 des1 ip2'.split()), top2 = set('ip2 des1 ip3'.split()), des1 = set('des1a des1b des1c'.split()), des1a = set('des1a1 des1a2'.split()), des1c = set('des1c1 extra1'.split()), ip2 = set('ip2a ip2b ip2c ipcommon'.split()), ip1 = set('ip1a ipcommon extra1'.split()), ) tops = toplevels(data) print("The top levels of the dependency graph are: " + ' '.join(tops)) for t in sorted(tops): print("\nThe compile order for top level: %s is..." % t) printorder(topx(data, set([t]))) if len(tops) > 1: print("\nThe compile order for top levels: %s is..." % ' and '.join(str(s) for s in sorted(tops)) ) printorder(topx(data, tops))
Translate the given Go code snippet into Python without altering its behavior.
package expand type Expander interface { Expand() []string } type Text string func (t Text) Expand() []string { return []string{string(t)} } type Alternation []Expander func (alt Alternation) Expand() []string { var out []string for _, e := range alt { out = append(out, e.Expand()...) } return out } type Sequence []Expander func (seq Sequence) Expand() []string { if len(seq) == 0 { return nil } out := seq[0].Expand() for _, e := range seq[1:] { out = combine(out, e.Expand()) } return out } func combine(al, bl []string) []string { out := make([]string, 0, len(al)*len(bl)) for _, a := range al { for _, b := range bl { out = append(out, a+b) } } return out } const ( escape = '\\' altStart = '{' altEnd = '}' altSep = ',' ) type piT struct{ pos, cnt, depth int } type Brace string func Expand(s string) []string { return Brace(s).Expand() } func (b Brace) Expand() []string { return b.Expander().Expand() } func (b Brace) Expander() Expander { s := string(b) var posInfo []piT var stack []int removePosInfo := func(i int) { end := len(posInfo) - 1 copy(posInfo[i:end], posInfo[i+1:]) posInfo = posInfo[:end] } inEscape := false for i, r := range s { if inEscape { inEscape = false continue } switch r { case escape: inEscape = true case altStart: stack = append(stack, len(posInfo)) posInfo = append(posInfo, piT{i, 0, len(stack)}) case altEnd: if len(stack) == 0 { continue } si := len(stack) - 1 pi := stack[si] if posInfo[pi].cnt == 0 { removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == len(stack) { removePosInfo(pi) } else { pi++ } } } else { posInfo = append(posInfo, piT{i, -2, len(stack)}) } stack = stack[:si] case altSep: if len(stack) == 0 { continue } posInfo = append(posInfo, piT{i, -1, len(stack)}) posInfo[stack[len(stack)-1]].cnt++ } } for len(stack) > 0 { si := len(stack) - 1 pi := stack[si] depth := posInfo[pi].depth removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == depth { removePosInfo(pi) } else { pi++ } } stack = stack[:si] } return buildExp(s, 0, posInfo) } func buildExp(s string, off int, info []piT) Expander { if len(info) == 0 { return Text(s) } var seq Sequence i := 0 var dj, j, depth int for dk, piK := range info { k := piK.pos - off switch s[k] { case altStart: if depth == 0 { dj = dk j = k depth = piK.depth } case altEnd: if piK.depth != depth { continue } if j > i { seq = append(seq, Text(s[i:j])) } alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk]) seq = append(seq, alt) i = k + 1 depth = 0 } } if j := len(s); j > i { seq = append(seq, Text(s[i:j])) } if len(seq) == 1 { return seq[0] } return seq } func buildAlt(s string, depth, off int, info []piT) Alternation { var alt Alternation i := 0 var di int for dk, piK := range info { if piK.depth != depth { continue } if k := piK.pos - off; s[k] == altSep { sub := buildExp(s[i:k], i+off, info[di:dk]) alt = append(alt, sub) i = k + 1 di = dk + 1 } } sub := buildExp(s[i:], i+off, info[di:]) alt = append(alt, sub) return alt }
def getitem(s, depth=0): out = [""] while s: c = s[0] if depth and (c == ',' or c == '}'): return out,s if c == '{': x = getgroup(s[1:], depth+1) if x: out,s = [a+b for a in out for b in x[0]], x[1] continue if c == '\\' and len(s) > 1: s, c = s[1:], c + s[1] out, s = [a+c for a in out], s[1:] return out,s def getgroup(s, depth): out, comma = [], False while s: g,s = getitem(s, depth) if not s: break out += g if s[0] == '}': if comma: return out, s[1:] return ['{' + a + '}' for a in out], s[1:] if s[0] == ',': comma,s = True, s[1:] return None for s in .split('\n'): print "\n\t".join([s] + getitem(s)[0]) + "\n"
Preserve the algorithm and functionality while converting the code from Go to Python.
import ( "image" "image/gif" "io/ioutil" "strings" "unicode" ) func f() (int, float64) { return 0, 0 } func g(int, float64) int { return 0 } func h(string, ...int) {}
def no_args(): pass no_args() def fixed_args(x, y): print('x=%r, y=%r' % (x, y)) fixed_args(1, 2) fixed_args(y=2, x=1) myargs=(1,2) fixed_args(*myargs) def opt_args(x=1): print(x) opt_args() opt_args(3.141) def var_args(*v): print(v) var_args(1, 2, 3) var_args(1, (2,3)) var_args() fixed_args(y=2, x=1) if 1: no_args() assert no_args() is None def return_something(): return 1 x = return_something() def is_builtin(x): print(x.__name__ in dir(__builtins__)) is_builtin(pow) is_builtin(is_builtin) def takes_anything(*args, **kwargs): for each in args: print(each) for key, value in sorted(kwargs.items()): print("%s:%s" % (key, value)) wrapped_fn(*args, **kwargs)
Preserve the algorithm and functionality while converting the code from Go to Python.
import ( "image" "image/gif" "io/ioutil" "strings" "unicode" ) func f() (int, float64) { return 0, 0 } func g(int, float64) int { return 0 } func h(string, ...int) {}
def no_args(): pass no_args() def fixed_args(x, y): print('x=%r, y=%r' % (x, y)) fixed_args(1, 2) fixed_args(y=2, x=1) myargs=(1,2) fixed_args(*myargs) def opt_args(x=1): print(x) opt_args() opt_args(3.141) def var_args(*v): print(v) var_args(1, 2, 3) var_args(1, (2,3)) var_args() fixed_args(y=2, x=1) if 1: no_args() assert no_args() is None def return_something(): return 1 x = return_something() def is_builtin(x): print(x.__name__ in dir(__builtins__)) is_builtin(pow) is_builtin(is_builtin) def takes_anything(*args, **kwargs): for each in args: print(each) for key, value in sorted(kwargs.items()): print("%s:%s" % (key, value)) wrapped_fn(*args, **kwargs)
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import "fmt" const max = 12 var ( super []byte pos int cnt [max]int ) func factSum(n int) int { s := 0 for x, f := 0, 1; x < n; { x++ f *= x s += f } return s } func r(n int) bool { if n == 0 { return false } c := super[pos-n] cnt[n]-- if cnt[n] == 0 { cnt[n] = n if !r(n - 1) { return false } } super[pos] = c pos++ return true } func superperm(n int) { pos = n le := factSum(n) super = make([]byte, le) for i := 0; i <= n; i++ { cnt[i] = i } for i := 1; i <= n; i++ { super[i-1] = byte(i) + '0' } for r(n) { } } func main() { for n := 0; n < max; n++ { fmt.Printf("superperm(%2d) ", n) superperm(n) fmt.Printf("len = %d\n", len(super)) } }
"Generate a short Superpermutation of n characters A... as a string using various algorithms." from __future__ import print_function, division from itertools import permutations from math import factorial import string import datetime import gc MAXN = 7 def s_perm0(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in permutations(allchars)] sp, tofind = allperms[0], set(allperms[1:]) while tofind: for skip in range(1, n): for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])): trial_perm = (sp + trial_add)[-n:] if trial_perm in tofind: sp += trial_add tofind.discard(trial_perm) trial_add = None break if trial_add is None: break assert all(perm in sp for perm in allperms) return sp def s_perm1(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: nxt = perms.pop() if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def s_perm2(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: nxt = perms.pop(0) if nxt not in sp: sp += nxt if perms: nxt = perms.pop(-1) if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def _s_perm3(n, cmp): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: lastn = sp[-n:] nxt = cmp(perms, key=lambda pm: sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn))) perms.remove(nxt) if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def s_perm3_max(n): return _s_perm3(n, max) def s_perm3_min(n): return _s_perm3(n, min) longest = [factorial(n) * n for n in range(MAXN + 1)] weight, runtime = {}, {} print(__doc__) for algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]: print('\n print(algo.__doc__) weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0) for n in range(1, MAXN + 1): gc.collect() gc.disable() t = datetime.datetime.now() sp = algo(n) t = datetime.datetime.now() - t gc.enable() runtime[algo.__name__] += t lensp = len(sp) wt = (lensp / longest[n]) ** 2 print(' For N=%i: SP length %5i Max: %5i Weight: %5.2f' % (n, lensp, longest[n], wt)) weight[algo.__name__] *= wt weight[algo.__name__] **= 1 / n weight[algo.__name__] = 1 / weight[algo.__name__] print('%*s Overall Weight: %5.2f in %.1f seconds.' % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds())) print('\n print('\n'.join('%12s (%.3f)' % kv for kv in sorted(weight.items(), key=lambda keyvalue: -keyvalue[1]))) print('\n print('\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))
Keep all operations the same but rewrite the snippet in Python.
package main import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" ) func validateInput(window *gtk.Window, str string) (int64, bool) { i, err := strconv.ParseInt(str, 10, 64) if err != nil { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Invalid value", ) dialog.Run() dialog.Destroy() return 0, false } return i, true } func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { rand.Seed(time.Now().UnixNano()) gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetTitle("Rosetta Code") window.SetPosition(gtk.WIN_POS_CENTER) window.Connect("destroy", func() { gtk.MainQuit() }) box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create box:") box.SetBorderWidth(1) label, err := gtk.LabelNew("Value:") check(err, "Unable to create label:") entry, err := gtk.EntryNew() check(err, "Unable to create entry:") entry.SetText("0") entry.Connect("activate", func() { str, _ := entry.GetText() validateInput(window, str) }) ib, err := gtk.ButtonNewWithLabel("Increment") check(err, "Unable to create increment button:") ib.Connect("clicked", func() { str, _ := entry.GetText() if i, ok := validateInput(window, str); ok { entry.SetText(strconv.FormatInt(i+1, 10)) } }) rb, err := gtk.ButtonNewWithLabel("Random") check(err, "Unable to create random button:") rb.Connect("clicked", func() { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, "Set random value", ) answer := dialog.Run() dialog.Destroy() if answer == gtk.RESPONSE_YES { entry.SetText(strconv.Itoa(rand.Intn(10000))) } }) box.PackStart(label, false, false, 2) box.PackStart(entry, false, false, 2) box.PackStart(ib, false, false, 2) box.PackStart(rb, false, false, 2) window.Add(box) window.ShowAll() gtk.Main() }
import random, tkMessageBox from Tkinter import * window = Tk() window.geometry("300x50+100+100") options = { "padx":5, "pady":5} s=StringVar() s.set(1) def increase(): s.set(int(s.get())+1) def rand(): if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"): s.set(random.randrange(0,5000)) def update(e): if not e.char.isdigit(): tkMessageBox.showerror('Error', 'Invalid input !') return "break" e = Entry(text=s) e.grid(column=0, row=0, **options) e.bind('<Key>', update) b1 = Button(text="Increase", command=increase, **options ) b1.grid(column=1, row=0, **options) b2 = Button(text="Random", command=rand, **options) b2.grid(column=2, row=0, **options) mainloop()
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "bufio" "fmt" "io" "math/rand" "time" ) func choseLineRandomly(r io.Reader) (s string, ln int, err error) { br := bufio.NewReader(r) s, err = br.ReadString('\n') if err != nil { return } ln = 1 lnLast := 1. var sLast string for { sLast, err = br.ReadString('\n') if err == io.EOF { return s, ln, nil } if err != nil { break } lnLast++ if rand.Float64() < 1/lnLast { s = sLast ln = int(lnLast) } } return } func oneOfN(n int, file io.Reader) int { _, ln, err := choseLineRandomly(file) if err != nil { panic(err) } return ln } type simReader int func (r *simReader) Read(b []byte) (int, error) { if *r <= 0 { return 0, io.EOF } b[0] = '\n' *r-- return 1, nil } func main() { n := 10 freq := make([]int, n) rand.Seed(time.Now().UnixNano()) for times := 0; times < 1e6; times++ { sr := simReader(n) freq[oneOfN(n, &sr)-1]++ } fmt.Println(freq) }
from random import randrange try: range = xrange except: pass def one_of_n(lines): choice = None for i, line in enumerate(lines): if randrange(i+1) == 0: choice = line return choice def one_of_n_test(n=10, trials=1000000): bins = [0] * n if n: for i in range(trials): bins[one_of_n(range(n))] += 1 return bins print(one_of_n_test())
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "strconv" ) func main() { var maxLen int var seqMaxLen [][]string for n := 1; n < 1e6; n++ { switch s := seq(n); { case len(s) == maxLen: seqMaxLen = append(seqMaxLen, s) case len(s) > maxLen: maxLen = len(s) seqMaxLen = [][]string{s} } } fmt.Println("Max sequence length:", maxLen) fmt.Println("Sequences:", len(seqMaxLen)) for _, seq := range seqMaxLen { fmt.Println("Sequence:") for _, t := range seq { fmt.Println(t) } } } func seq(n int) []string { s := strconv.Itoa(n) ss := []string{s} for { dSeq := sortD(s) d := dSeq[0] nd := 1 s = "" for i := 1; ; i++ { if i == len(dSeq) { s = fmt.Sprintf("%s%d%c", s, nd, d) break } if dSeq[i] == d { nd++ } else { s = fmt.Sprintf("%s%d%c", s, nd, d) d = dSeq[i] nd = 1 } } for _, s0 := range ss { if s == s0 { return ss } } ss = append(ss, s) } panic("unreachable") } func sortD(s string) []rune { r := make([]rune, len(s)) for i, d := range s { j := 0 for ; j < i; j++ { if d > r[j] { copy(r[j+1:], r[j:i]) break } } r[j] = d } return r }
from itertools import groupby, permutations def A036058(number): return ''.join( str(len(list(g))) + k for k,g in groupby(sorted(str(number), reverse=True)) ) def A036058_length(numberstring='0', printit=False): iterations, last_three, queue_index = 1, ([None] * 3), 0 def A036058(number): return ''.join( str(len(list(g))) + k for k,g in groupby(number) ) while True: if printit: print(" %2i %s" % (iterations, numberstring)) numberstring = ''.join(sorted(numberstring, reverse=True)) if numberstring in last_three: break assert iterations < 1000000 last_three[queue_index], numberstring = numberstring, A036058(numberstring) iterations += 1 queue_index +=1 queue_index %=3 return iterations def max_A036058_length( start_range=range(11) ): already_done = set() max_len = (-1, []) for n in start_range: sn = str(n) sns = tuple(sorted(sn, reverse=True)) if sns not in already_done: already_done.add(sns) size = A036058_length(sns) if size > max_len[0]: max_len = (size, [n]) elif size == max_len[0]: max_len[1].append(n) return max_len lenmax, starts = max_A036058_length( range(1000000) ) allstarts = [] for n in starts: allstarts += [int(''.join(x)) for x in set(k for k in permutations(str(n), 4) if k[0] != '0')] allstarts = [x for x in sorted(allstarts) if x < 1000000] print ( % (lenmax, allstarts) ) print ( ) for n in starts: print() A036058_length(str(n), printit=True)
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "strconv" ) func main() { var maxLen int var seqMaxLen [][]string for n := 1; n < 1e6; n++ { switch s := seq(n); { case len(s) == maxLen: seqMaxLen = append(seqMaxLen, s) case len(s) > maxLen: maxLen = len(s) seqMaxLen = [][]string{s} } } fmt.Println("Max sequence length:", maxLen) fmt.Println("Sequences:", len(seqMaxLen)) for _, seq := range seqMaxLen { fmt.Println("Sequence:") for _, t := range seq { fmt.Println(t) } } } func seq(n int) []string { s := strconv.Itoa(n) ss := []string{s} for { dSeq := sortD(s) d := dSeq[0] nd := 1 s = "" for i := 1; ; i++ { if i == len(dSeq) { s = fmt.Sprintf("%s%d%c", s, nd, d) break } if dSeq[i] == d { nd++ } else { s = fmt.Sprintf("%s%d%c", s, nd, d) d = dSeq[i] nd = 1 } } for _, s0 := range ss { if s == s0 { return ss } } ss = append(ss, s) } panic("unreachable") } func sortD(s string) []rune { r := make([]rune, len(s)) for i, d := range s { j := 0 for ; j < i; j++ { if d > r[j] { copy(r[j+1:], r[j:i]) break } } r[j] = d } return r }
from itertools import groupby, permutations def A036058(number): return ''.join( str(len(list(g))) + k for k,g in groupby(sorted(str(number), reverse=True)) ) def A036058_length(numberstring='0', printit=False): iterations, last_three, queue_index = 1, ([None] * 3), 0 def A036058(number): return ''.join( str(len(list(g))) + k for k,g in groupby(number) ) while True: if printit: print(" %2i %s" % (iterations, numberstring)) numberstring = ''.join(sorted(numberstring, reverse=True)) if numberstring in last_three: break assert iterations < 1000000 last_three[queue_index], numberstring = numberstring, A036058(numberstring) iterations += 1 queue_index +=1 queue_index %=3 return iterations def max_A036058_length( start_range=range(11) ): already_done = set() max_len = (-1, []) for n in start_range: sn = str(n) sns = tuple(sorted(sn, reverse=True)) if sns not in already_done: already_done.add(sns) size = A036058_length(sns) if size > max_len[0]: max_len = (size, [n]) elif size == max_len[0]: max_len[1].append(n) return max_len lenmax, starts = max_A036058_length( range(1000000) ) allstarts = [] for n in starts: allstarts += [int(''.join(x)) for x in set(k for k in permutations(str(n), 4) if k[0] != '0')] allstarts = [x for x in sorted(allstarts) if x < 1000000] print ( % (lenmax, allstarts) ) print ( ) for n in starts: print() A036058_length(str(n), printit=True)
Translate this program into Python but keep the logic exactly as in Go.
import ( "fmt" "strings" ) func main() { for _, n := range []int64{ 1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, } { fmt.Println(sayOrdinal(n)) } } var irregularOrdinals = map[string]string{ "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth", } func sayOrdinal(n int64) string { s := say(n) i := strings.LastIndexAny(s, " -") i++ if x, ok := irregularOrdinals[s[i:]]; ok { s = s[:i] + x } else if s[len(s)-1] == 'y' { s = s[:i] + s[i:len(s)-1] + "ieth" } else { s = s[:i] + s[i:] + "th" } return s } var small = [...]string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"} var tens = [...]string{"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"} var illions = [...]string{"", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion"} func say(n int64) string { var t string if n < 0 { t = "negative " n = -n } switch { case n < 20: t += small[n] case n < 100: t += tens[n/10] s := n % 10 if s > 0 { t += "-" + small[s] } case n < 1000: t += small[n/100] + " hundred" s := n % 100 if s > 0 { t += " " + say(s) } default: sx := "" for i := 0; n > 0; i++ { p := n % 1000 n /= 1000 if p > 0 { ix := say(p) + illions[i] if sx != "" { ix += " " + sx } sx = ix } } t += sx } return t }
irregularOrdinals = { "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth", } def num2ordinal(n): conversion = int(float(n)) num = spell_integer(conversion) hyphen = num.rsplit("-", 1) num = num.rsplit(" ", 1) delim = " " if len(num[-1]) > len(hyphen[-1]): num = hyphen delim = "-" if num[-1] in irregularOrdinals: num[-1] = delim + irregularOrdinals[num[-1]] elif num[-1].endswith("y"): num[-1] = delim + num[-1][:-1] + "ieth" else: num[-1] = delim + num[-1] + "th" return "".join(num) if __name__ == "__main__": tests = "1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2".split() for num in tests: print("{} => {}".format(num, num2ordinal(num))) TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")] def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num)
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "strconv" "strings" ) func sdn(n int64) bool { if n >= 1e10 { return false } s := strconv.FormatInt(n, 10) for d, p := range s { if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) { return false } } return true } func main() { for n := int64(0); n < 1e10; n++ { if sdn(n) { fmt.Println(n) } } }
>>> def isSelfDescribing(n): s = str(n) return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) >>> [x for x in range(4000000) if isSelfDescribing(x)] [1210, 2020, 21200, 3211000] >>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] [(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "strconv" "strings" ) func sdn(n int64) bool { if n >= 1e10 { return false } s := strconv.FormatInt(n, 10) for d, p := range s { if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) { return false } } return true } func main() { for n := int64(0); n < 1e10; n++ { if sdn(n) { fmt.Println(n) } } }
>>> def isSelfDescribing(n): s = str(n) return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) >>> [x for x in range(4000000) if isSelfDescribing(x)] [1210, 2020, 21200, 3211000] >>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] [(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
Maintain the same structure and functionality when rewriting this code in Python.
package main import "fmt" var example []int func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func checkSeq(pos, n, minLen int, seq []int) (int, int) { switch { case pos > minLen || seq[0] > n: return minLen, 0 case seq[0] == n: example = seq return pos, 1 case pos < minLen: return tryPerm(0, pos, n, minLen, seq) default: return minLen, 0 } } func tryPerm(i, pos, n, minLen int, seq []int) (int, int) { if i > pos { return minLen, 0 } seq2 := make([]int, len(seq)+1) copy(seq2[1:], seq) seq2[0] = seq[0] + seq[i] res11, res12 := checkSeq(pos+1, n, minLen, seq2) res21, res22 := tryPerm(i+1, pos, n, res11, seq) switch { case res21 < res11: return res21, res22 case res21 == res11: return res21, res12 + res22 default: fmt.Println("Error in tryPerm") return 0, 0 } } func initTryPerm(x, minLen int) (int, int) { return tryPerm(0, 0, x, minLen, []int{1}) } func findBrauer(num, minLen, nbLimit int) { actualMin, brauer := initTryPerm(num, minLen) fmt.Println("\nN =", num) fmt.Printf("Minimum length of chains : L(%d) = %d\n", num, actualMin) fmt.Println("Number of minimum length Brauer chains :", brauer) if brauer > 0 { reverse(example) fmt.Println("Brauer example :", example) } example = nil if num <= nbLimit { nonBrauer := findNonBrauer(num, actualMin+1, brauer) fmt.Println("Number of minimum length non-Brauer chains :", nonBrauer) if nonBrauer > 0 { fmt.Println("Non-Brauer example :", example) } example = nil } else { println("Non-Brauer analysis suppressed") } } func isAdditionChain(a []int) bool { for i := 2; i < len(a); i++ { if a[i] > a[i-1]*2 { return false } ok := false jloop: for j := i - 1; j >= 0; j-- { for k := j; k >= 0; k-- { if a[j]+a[k] == a[i] { ok = true break jloop } } } if !ok { return false } } if example == nil && !isBrauer(a) { example = make([]int, len(a)) copy(example, a) } return true } func isBrauer(a []int) bool { for i := 2; i < len(a); i++ { ok := false for j := i - 1; j >= 0; j-- { if a[i-1]+a[j] == a[i] { ok = true break } } if !ok { return false } } return true } func nextChains(index, le int, seq []int, pcount *int) { for { if index < le-1 { nextChains(index+1, le, seq, pcount) } if seq[index]+le-1-index >= seq[le-1] { return } seq[index]++ for i := index + 1; i < le-1; i++ { seq[i] = seq[i-1] + 1 } if isAdditionChain(seq) { (*pcount)++ } } } func findNonBrauer(num, le, brauer int) int { seq := make([]int, le) seq[0] = 1 seq[le-1] = num for i := 1; i < le-1; i++ { seq[i] = seq[i-1] + 1 } count := 0 if isAdditionChain(seq) { count = 1 } nextChains(2, le, seq, &count) return count - brauer } func main() { nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379} fmt.Println("Searching for Brauer chains up to a minimum length of 12:") for _, num := range nums { findBrauer(num, 12, 79) } }
def prepend(n, seq): return [n] + seq def check_seq(pos, seq, n, min_len): if pos > min_len or seq[0] > n: return min_len, 0 if seq[0] == n: return pos, 1 if pos < min_len: return try_perm(0, pos, seq, n, min_len) return min_len, 0 def try_perm(i, pos, seq, n, min_len): if i > pos: return min_len, 0 res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len) res2 = try_perm(i + 1, pos, seq, n, res1[0]) if res2[0] < res1[0]: return res2 if res2[0] == res1[0]: return res2[0], res1[1] + res2[1] raise Exception("try_perm exception") def init_try_perm(x): return try_perm(0, 0, [1], x, 12) def find_brauer(num): res = init_try_perm(num) print print "N = ", num print "Minimum length of chains: L(n) = ", res[0] print "Number of minimum length Brauer chains: ", res[1] nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379] for i in nums: find_brauer(i)
Change the following Go code into Python without altering its purpose.
package main import "fmt" func repeat(n int, f func()) { for i := 0; i < n; i++ { f() } } func fn() { fmt.Println("Example") } func main() { repeat(4, fn) }
def repeat(f,n): for i in range(n): f(); def procedure(): print("Example"); repeat(procedure,3);
Change the following Go code into Python without altering its purpose.
package main import ( "bufio" "errors" "fmt" "math" "os" "regexp" "strconv" "strings" ) func main() { fmt.Println("Numbers please separated by space/commas:") sc := bufio.NewScanner(os.Stdin) sc.Scan() s, n, min, max, err := spark(sc.Text()) if err != nil { fmt.Println(err) return } if n == 1 { fmt.Println("1 value =", min) } else { fmt.Println(n, "values. Min:", min, "Max:", max) } fmt.Println(s) } var sep = regexp.MustCompile(`[\s,]+`) func spark(s0 string) (sp string, n int, min, max float64, err error) { ss := sep.Split(s0, -1) n = len(ss) vs := make([]float64, n) var v float64 min = math.Inf(1) max = math.Inf(-1) for i, s := range ss { switch v, err = strconv.ParseFloat(s, 64); { case err != nil: case math.IsNaN(v): err = errors.New("NaN not supported.") case math.IsInf(v, 0): err = errors.New("Inf not supported.") default: if v < min { min = v } if v > max { max = v } vs[i] = v continue } return } if min == max { sp = strings.Repeat("▄", n) } else { rs := make([]rune, n) f := 8 / (max - min) for j, v := range vs { i := rune(f * (v - min)) if i > 7 { i = 7 } rs[j] = '▁' + i } sp = string(rs) } return }
bar = '▁▂▃▄▅▆▇█' barcount = len(bar) def sparkline(numbers): mn, mx = min(numbers), max(numbers) extent = mx - mn sparkline = ''.join(bar[min([barcount - 1, int((n - mn) / extent * barcount)])] for n in numbers) return mn, mx, sparkline if __name__ == '__main__': import re for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;" "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;" "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'): print("\nNumbers:", line) numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())] mn, mx, sp = sparkline(numbers) print(' min: %5f; max: %5f' % (mn, mx)) print(" " + sp)
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type Tree struct { nodeType NodeType left *Tree right *Tree value int } type atr struct { enumText string nodeType NodeType } var atrs = []atr{ {"Identifier", ndIdent}, {"String", ndString}, {"Integer", ndInteger}, {"Sequence", ndSequence}, {"If", ndIf}, {"Prtc", ndPrtc}, {"Prts", ndPrts}, {"Prti", ndPrti}, {"While", ndWhile}, {"Assign", ndAssign}, {"Negate", ndNegate}, {"Not", ndNot}, {"Multiply", ndMul}, {"Divide", ndDiv}, {"Mod", ndMod}, {"Add", ndAdd}, {"Subtract", ndSub}, {"Less", ndLss}, {"LessEqual", ndLeq}, {"Greater", ndGtr}, {"GreaterEqual", ndGeq}, {"Equal", ndEql}, {"NotEqual", ndNeq}, {"And", ndAnd}, {"Or", ndOr}, } var ( stringPool []string globalNames []string globalValues = make(map[int]int) ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func btoi(b bool) int { if b { return 1 } return 0 } func itob(i int) bool { if i == 0 { return false } return true } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, 0} } func makeLeaf(nodeType NodeType, value int) *Tree { return &Tree{nodeType, nil, nil, value} } func interp(x *Tree) int { if x == nil { return 0 } switch x.nodeType { case ndInteger: return x.value case ndIdent: return globalValues[x.value] case ndString: return x.value case ndAssign: n := interp(x.right) globalValues[x.left.value] = n return n case ndAdd: return interp(x.left) + interp(x.right) case ndSub: return interp(x.left) - interp(x.right) case ndMul: return interp(x.left) * interp(x.right) case ndDiv: return interp(x.left) / interp(x.right) case ndMod: return interp(x.left) % interp(x.right) case ndLss: return btoi(interp(x.left) < interp(x.right)) case ndGtr: return btoi(interp(x.left) > interp(x.right)) case ndLeq: return btoi(interp(x.left) <= interp(x.right)) case ndEql: return btoi(interp(x.left) == interp(x.right)) case ndNeq: return btoi(interp(x.left) != interp(x.right)) case ndAnd: return btoi(itob(interp(x.left)) && itob(interp(x.right))) case ndOr: return btoi(itob(interp(x.left)) || itob(interp(x.right))) case ndNegate: return -interp(x.left) case ndNot: if interp(x.left) == 0 { return 1 } return 0 case ndIf: if interp(x.left) != 0 { interp(x.right.left) } else { interp(x.right.right) } return 0 case ndWhile: for interp(x.left) != 0 { interp(x.right) } return 0 case ndPrtc: fmt.Printf("%c", interp(x.left)) return 0 case ndPrti: fmt.Printf("%d", interp(x.left)) return 0 case ndPrts: fmt.Print(stringPool[interp(x.left)]) return 0 case ndSequence: interp(x.left) interp(x.right) return 0 default: reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType)) } return 0 } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func fetchStringOffset(s string) int { var d strings.Builder s = s[1 : len(s)-1] for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } s = d.String() for i := 0; i < len(stringPool); i++ { if s == stringPool[i] { return i } } stringPool = append(stringPool, s) return len(stringPool) - 1 } func fetchVarOffset(name string) int { for i := 0; i < len(globalNames); i++ { if globalNames[i] == name { return i } } globalNames = append(globalNames, name) return len(globalNames) - 1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { var n int switch nodeType { case ndIdent: n = fetchVarOffset(s) case ndInteger: n, err = strconv.Atoi(s) check(err) case ndString: n = fetchStringOffset(s) default: reportError(fmt.Sprintf("Unknown node type: %s\n", s)) } return makeLeaf(nodeType, n) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) x := loadAst() interp(x) }
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return NULL node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type Tree struct { nodeType NodeType left *Tree right *Tree value int } type atr struct { enumText string nodeType NodeType } var atrs = []atr{ {"Identifier", ndIdent}, {"String", ndString}, {"Integer", ndInteger}, {"Sequence", ndSequence}, {"If", ndIf}, {"Prtc", ndPrtc}, {"Prts", ndPrts}, {"Prti", ndPrti}, {"While", ndWhile}, {"Assign", ndAssign}, {"Negate", ndNegate}, {"Not", ndNot}, {"Multiply", ndMul}, {"Divide", ndDiv}, {"Mod", ndMod}, {"Add", ndAdd}, {"Subtract", ndSub}, {"Less", ndLss}, {"LessEqual", ndLeq}, {"Greater", ndGtr}, {"GreaterEqual", ndGeq}, {"Equal", ndEql}, {"NotEqual", ndNeq}, {"And", ndAnd}, {"Or", ndOr}, } var ( stringPool []string globalNames []string globalValues = make(map[int]int) ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func btoi(b bool) int { if b { return 1 } return 0 } func itob(i int) bool { if i == 0 { return false } return true } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, 0} } func makeLeaf(nodeType NodeType, value int) *Tree { return &Tree{nodeType, nil, nil, value} } func interp(x *Tree) int { if x == nil { return 0 } switch x.nodeType { case ndInteger: return x.value case ndIdent: return globalValues[x.value] case ndString: return x.value case ndAssign: n := interp(x.right) globalValues[x.left.value] = n return n case ndAdd: return interp(x.left) + interp(x.right) case ndSub: return interp(x.left) - interp(x.right) case ndMul: return interp(x.left) * interp(x.right) case ndDiv: return interp(x.left) / interp(x.right) case ndMod: return interp(x.left) % interp(x.right) case ndLss: return btoi(interp(x.left) < interp(x.right)) case ndGtr: return btoi(interp(x.left) > interp(x.right)) case ndLeq: return btoi(interp(x.left) <= interp(x.right)) case ndEql: return btoi(interp(x.left) == interp(x.right)) case ndNeq: return btoi(interp(x.left) != interp(x.right)) case ndAnd: return btoi(itob(interp(x.left)) && itob(interp(x.right))) case ndOr: return btoi(itob(interp(x.left)) || itob(interp(x.right))) case ndNegate: return -interp(x.left) case ndNot: if interp(x.left) == 0 { return 1 } return 0 case ndIf: if interp(x.left) != 0 { interp(x.right.left) } else { interp(x.right.right) } return 0 case ndWhile: for interp(x.left) != 0 { interp(x.right) } return 0 case ndPrtc: fmt.Printf("%c", interp(x.left)) return 0 case ndPrti: fmt.Printf("%d", interp(x.left)) return 0 case ndPrts: fmt.Print(stringPool[interp(x.left)]) return 0 case ndSequence: interp(x.left) interp(x.right) return 0 default: reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType)) } return 0 } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func fetchStringOffset(s string) int { var d strings.Builder s = s[1 : len(s)-1] for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } s = d.String() for i := 0; i < len(stringPool); i++ { if s == stringPool[i] { return i } } stringPool = append(stringPool, s) return len(stringPool) - 1 } func fetchVarOffset(name string) int { for i := 0; i < len(globalNames); i++ { if globalNames[i] == name { return i } } globalNames = append(globalNames, name) return len(globalNames) - 1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { var n int switch nodeType { case ndIdent: n = fetchVarOffset(s) case ndInteger: n, err = strconv.Atoi(s) check(err) case ndString: n = fetchStringOffset(s) default: reportError(fmt.Sprintf("Unknown node type: %s\n", s)) } return makeLeaf(nodeType, n) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) x := loadAst() interp(x) }
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return NULL node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type Tree struct { nodeType NodeType left *Tree right *Tree value int } type atr struct { enumText string nodeType NodeType } var atrs = []atr{ {"Identifier", ndIdent}, {"String", ndString}, {"Integer", ndInteger}, {"Sequence", ndSequence}, {"If", ndIf}, {"Prtc", ndPrtc}, {"Prts", ndPrts}, {"Prti", ndPrti}, {"While", ndWhile}, {"Assign", ndAssign}, {"Negate", ndNegate}, {"Not", ndNot}, {"Multiply", ndMul}, {"Divide", ndDiv}, {"Mod", ndMod}, {"Add", ndAdd}, {"Subtract", ndSub}, {"Less", ndLss}, {"LessEqual", ndLeq}, {"Greater", ndGtr}, {"GreaterEqual", ndGeq}, {"Equal", ndEql}, {"NotEqual", ndNeq}, {"And", ndAnd}, {"Or", ndOr}, } var ( stringPool []string globalNames []string globalValues = make(map[int]int) ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func btoi(b bool) int { if b { return 1 } return 0 } func itob(i int) bool { if i == 0 { return false } return true } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, 0} } func makeLeaf(nodeType NodeType, value int) *Tree { return &Tree{nodeType, nil, nil, value} } func interp(x *Tree) int { if x == nil { return 0 } switch x.nodeType { case ndInteger: return x.value case ndIdent: return globalValues[x.value] case ndString: return x.value case ndAssign: n := interp(x.right) globalValues[x.left.value] = n return n case ndAdd: return interp(x.left) + interp(x.right) case ndSub: return interp(x.left) - interp(x.right) case ndMul: return interp(x.left) * interp(x.right) case ndDiv: return interp(x.left) / interp(x.right) case ndMod: return interp(x.left) % interp(x.right) case ndLss: return btoi(interp(x.left) < interp(x.right)) case ndGtr: return btoi(interp(x.left) > interp(x.right)) case ndLeq: return btoi(interp(x.left) <= interp(x.right)) case ndEql: return btoi(interp(x.left) == interp(x.right)) case ndNeq: return btoi(interp(x.left) != interp(x.right)) case ndAnd: return btoi(itob(interp(x.left)) && itob(interp(x.right))) case ndOr: return btoi(itob(interp(x.left)) || itob(interp(x.right))) case ndNegate: return -interp(x.left) case ndNot: if interp(x.left) == 0 { return 1 } return 0 case ndIf: if interp(x.left) != 0 { interp(x.right.left) } else { interp(x.right.right) } return 0 case ndWhile: for interp(x.left) != 0 { interp(x.right) } return 0 case ndPrtc: fmt.Printf("%c", interp(x.left)) return 0 case ndPrti: fmt.Printf("%d", interp(x.left)) return 0 case ndPrts: fmt.Print(stringPool[interp(x.left)]) return 0 case ndSequence: interp(x.left) interp(x.right) return 0 default: reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType)) } return 0 } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func fetchStringOffset(s string) int { var d strings.Builder s = s[1 : len(s)-1] for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } s = d.String() for i := 0; i < len(stringPool); i++ { if s == stringPool[i] { return i } } stringPool = append(stringPool, s) return len(stringPool) - 1 } func fetchVarOffset(name string) int { for i := 0; i < len(globalNames); i++ { if globalNames[i] == name { return i } } globalNames = append(globalNames, name) return len(globalNames) - 1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { var n int switch nodeType { case ndIdent: n = fetchVarOffset(s) case ndInteger: n, err = strconv.Atoi(s) check(err) case ndString: n = fetchStringOffset(s) default: reportError(fmt.Sprintf("Unknown node type: %s\n", s)) } return makeLeaf(nodeType, n) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) x := loadAst() interp(x) }
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return NULL node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type Tree struct { nodeType NodeType left *Tree right *Tree value int } type atr struct { enumText string nodeType NodeType } var atrs = []atr{ {"Identifier", ndIdent}, {"String", ndString}, {"Integer", ndInteger}, {"Sequence", ndSequence}, {"If", ndIf}, {"Prtc", ndPrtc}, {"Prts", ndPrts}, {"Prti", ndPrti}, {"While", ndWhile}, {"Assign", ndAssign}, {"Negate", ndNegate}, {"Not", ndNot}, {"Multiply", ndMul}, {"Divide", ndDiv}, {"Mod", ndMod}, {"Add", ndAdd}, {"Subtract", ndSub}, {"Less", ndLss}, {"LessEqual", ndLeq}, {"Greater", ndGtr}, {"GreaterEqual", ndGeq}, {"Equal", ndEql}, {"NotEqual", ndNeq}, {"And", ndAnd}, {"Or", ndOr}, } var ( stringPool []string globalNames []string globalValues = make(map[int]int) ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func btoi(b bool) int { if b { return 1 } return 0 } func itob(i int) bool { if i == 0 { return false } return true } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, 0} } func makeLeaf(nodeType NodeType, value int) *Tree { return &Tree{nodeType, nil, nil, value} } func interp(x *Tree) int { if x == nil { return 0 } switch x.nodeType { case ndInteger: return x.value case ndIdent: return globalValues[x.value] case ndString: return x.value case ndAssign: n := interp(x.right) globalValues[x.left.value] = n return n case ndAdd: return interp(x.left) + interp(x.right) case ndSub: return interp(x.left) - interp(x.right) case ndMul: return interp(x.left) * interp(x.right) case ndDiv: return interp(x.left) / interp(x.right) case ndMod: return interp(x.left) % interp(x.right) case ndLss: return btoi(interp(x.left) < interp(x.right)) case ndGtr: return btoi(interp(x.left) > interp(x.right)) case ndLeq: return btoi(interp(x.left) <= interp(x.right)) case ndEql: return btoi(interp(x.left) == interp(x.right)) case ndNeq: return btoi(interp(x.left) != interp(x.right)) case ndAnd: return btoi(itob(interp(x.left)) && itob(interp(x.right))) case ndOr: return btoi(itob(interp(x.left)) || itob(interp(x.right))) case ndNegate: return -interp(x.left) case ndNot: if interp(x.left) == 0 { return 1 } return 0 case ndIf: if interp(x.left) != 0 { interp(x.right.left) } else { interp(x.right.right) } return 0 case ndWhile: for interp(x.left) != 0 { interp(x.right) } return 0 case ndPrtc: fmt.Printf("%c", interp(x.left)) return 0 case ndPrti: fmt.Printf("%d", interp(x.left)) return 0 case ndPrts: fmt.Print(stringPool[interp(x.left)]) return 0 case ndSequence: interp(x.left) interp(x.right) return 0 default: reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType)) } return 0 } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func fetchStringOffset(s string) int { var d strings.Builder s = s[1 : len(s)-1] for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } s = d.String() for i := 0; i < len(stringPool); i++ { if s == stringPool[i] { return i } } stringPool = append(stringPool, s) return len(stringPool) - 1 } func fetchVarOffset(name string) int { for i := 0; i < len(globalNames); i++ { if globalNames[i] == name { return i } } globalNames = append(globalNames, name) return len(globalNames) - 1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { var n int switch nodeType { case ndIdent: n = fetchVarOffset(s) case ndInteger: n, err = strconv.Atoi(s) check(err) case ndString: n = fetchStringOffset(s) default: reportError(fmt.Sprintf("Unknown node type: %s\n", s)) } return makeLeaf(nodeType, n) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) x := loadAst() interp(x) }
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return NULL node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "math/big" ) func main() { a := big.NewInt(42) m := big.NewInt(2017) k := new(big.Int).ModInverse(a, m) fmt.Println(k) }
>>> def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) >>> def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m >>> modinv(42, 2017) 1969 >>>
Generate a Python translation of this Go snippet without changing its computational steps.
package main import "github.com/go-vgo/robotgo" func main() { robotgo.MouseClick("left", false) robotgo.MouseClick("right", true) }
import ctypes def click(): ctypes.windll.user32.mouse_event(0x2, 0,0,0,0) ctypes.windll.user32.mouse_event(0x4, 0,0,0,0) click()
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintln(w, "Goodbye, World!") }) log.Fatal(http.ListenAndServe(":8080", nil)) }
from wsgiref.simple_server import make_server def app(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) yield b"<h1>Goodbye, World!</h1>" server = make_server('127.0.0.1', 8080, app) server.serve_forever()
Write the same code in Python as shown below in Go.
package main import ( "github.com/fogleman/gg" "math" ) func main() { dc := gg.NewContext(400, 400) dc.SetRGB(1, 1, 1) dc.Clear() dc.SetRGB(0, 0, 1) c := (math.Sqrt(5) + 1) / 2 numberOfSeeds := 3000 for i := 0; i <= numberOfSeeds; i++ { fi := float64(i) fn := float64(numberOfSeeds) r := math.Pow(fi, c) / fn angle := 2 * math.Pi * c * fi x := r*math.Sin(angle) + 200 y := r*math.Cos(angle) + 200 fi /= fn / 5 dc.DrawCircle(x, y, fi) } dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("sunflower_fractal.png") }
from turtle import * from math import * iter = 3000 diskRatio = .5 factor = .5 + sqrt(1.25) screen = getscreen() (winWidth, winHeight) = screen.screensize() x = 0.0 y = 0.0 maxRad = pow(iter,factor)/iter; bgcolor("light blue") hideturtle() tracer(0, 0) for i in range(iter+1): r = pow(i,factor)/iter; if r/maxRad < diskRatio: pencolor("black") else: pencolor("yellow") theta = 2*pi*factor*i; up() setposition(x + r*sin(theta), y + r*cos(theta)) down() circle(10.0 * i/(1.0*iter)) update() done()
Port the following code from Go to Python with equivalent syntax and logic.
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 5 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 461, 277, 356, 488, 393 }; int demand[N_COLS] = { 278, 60, 461, 116, 1060 }; int costs[N_ROWS][N_COLS] = { { 46, 74, 9, 28, 99 }, { 12, 75, 6, 36, 48 }, { 35, 199, 4, 5, 71 }, { 61, 81, 44, 88, 9 }, { 85, 60, 14, 25, 79 } }; int main() { printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'V' + i); for (j = 0; j < N_COLS; ++j) printf(" %3d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }
from collections import defaultdict costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17}, 'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15}, 'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50}, 'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}} demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60} cols = sorted(demand.iterkeys()) supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50} res = dict((k, defaultdict(int)) for k in costs) g = {} for x in supply: g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g]) for x in demand: g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x]) while g: d = {} for x in demand: d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x] s = {} for x in supply: s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]] f = max(d, key=lambda n: d[n]) t = max(s, key=lambda n: s[n]) t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t) v = min(supply[f], demand[t]) res[f][t] += v demand[t] -= v if demand[t] == 0: for k, n in supply.iteritems(): if n != 0: g[k].remove(t) del g[t] del demand[t] supply[f] -= v if supply[f] == 0: for k, n in demand.iteritems(): if n != 0: g[k].remove(f) del g[f] del supply[f] for n in cols: print "\t", n, print cost = 0 for g in sorted(costs): print g, "\t", for n in cols: y = res[g][n] if y != 0: print y, cost += y * costs[g][n] print "\t", print print "\n\nTotal Cost = ", cost
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "math" ) const ( RE = 6371000 DD = 0.001 FIN = 1e7 ) func rho(a float64) float64 { return math.Exp(-a / 8500) } func radians(degrees float64) float64 { return degrees * math.Pi / 180 } func height(a, z, d float64) float64 { aa := RE + a hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z))) return hh - RE } func columnDensity(a, z float64) float64 { sum := 0.0 d := 0.0 for d < FIN { delta := math.Max(DD, DD*d) sum += rho(height(a, z, d+0.5*delta)) * delta d += delta } return sum } func airmass(a, z float64) float64 { return columnDensity(a, z) / columnDensity(a, 0) } func main() { fmt.Println("Angle 0 m 13700 m") fmt.Println("------------------------------------") for z := 0; z <= 90; z += 5 { fz := float64(z) fmt.Printf("%2d %11.8f %11.8f\n", z, airmass(0, fz), airmass(13700, fz)) } }
from math import sqrt, cos, exp DEG = 0.017453292519943295769236907684886127134 RE = 6371000 dd = 0.001 FIN = 10000000 def rho(a): return exp(-a / 8500.0) def height(a, z, d): return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE def column_density(a, z): dsum, d = 0.0, 0.0 while d < FIN: delta = max(dd, (dd)*d) dsum += rho(height(a, z, d + 0.5 * delta)) * delta d += delta return dsum def airmass(a, z): return column_density(a, z) / column_density(a, 0) print('Angle 0 m 13700 m\n', '-' * 36) for z in range(0, 91, 5): print(f"{z: 3d} {airmass(0, z): 12.7f} {airmass(13700, z): 12.7f}")
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math" ) type fps interface { extract(int) float64 } func one() fps { return &oneFps{} } func add(s1, s2 fps) fps { return &sum{s1: s1, s2: s2} } func sub(s1, s2 fps) fps { return &diff{s1: s1, s2: s2} } func mul(s1, s2 fps) fps { return &prod{s1: s1, s2: s2} } func div(s1, s2 fps) fps { return &quo{s1: s1, s2: s2} } func differentiate(s1 fps) fps { return &deriv{s1: s1} } func integrate(s1 fps) fps { return &integ{s1: s1} } func sinCos() (fps, fps) { sin := &integ{} cos := sub(one(), integrate(sin)) sin.s1 = cos return sin, cos } type oneFps struct{} func (*oneFps) extract(n int) float64 { if n == 0 { return 1 } return 0 } type sum struct { s []float64 s1, s2 fps } func (s *sum) extract(n int) float64 { for i := len(s.s); i <= n; i++ { s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i)) } return s.s[n] } type diff struct { s []float64 s1, s2 fps } func (s *diff) extract(n int) float64 { for i := len(s.s); i <= n; i++ { s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i)) } return s.s[n] } type prod struct { s []float64 s1, s2 fps } func (s *prod) extract(n int) float64 { for i := len(s.s); i <= n; i++ { c := 0. for k := 0; k <= i; k++ { c += s.s1.extract(k) * s.s1.extract(n-k) } s.s = append(s.s, c) } return s.s[n] } type quo struct { s1, s2 fps inv float64 c []float64 s []float64 } func (s *quo) extract(n int) float64 { switch { case len(s.s) > 0: case !math.IsInf(s.inv, 1): a0 := s.s2.extract(0) s.inv = 1 / a0 if a0 != 0 { break } fallthrough default: return math.NaN() } for i := len(s.s); i <= n; i++ { c := 0. for k := 1; k <= i; k++ { c += s.s2.extract(k) * s.c[n-k] } c = s.s1.extract(i) - c*s.inv s.c = append(s.c, c) s.s = append(s.s, c*s.inv) } return s.s[n] } type deriv struct { s []float64 s1 fps } func (s *deriv) extract(n int) float64 { for i := len(s.s); i <= n; { i++ s.s = append(s.s, float64(i)*s.s1.extract(i)) } return s.s[n] } type integ struct { s []float64 s1 fps } func (s *integ) extract(n int) float64 { if n == 0 { return 0 } for i := len(s.s) + 1; i <= n; i++ { s.s = append(s.s, s.s1.extract(i-1)/float64(i)) } return s.s[n-1] } func main() { partialSeries := func(f fps) (s string) { for i := 0; i < 6; i++ { s = fmt.Sprintf("%s %8.5f ", s, f.extract(i)) } return } sin, cos := sinCos() fmt.Println("sin:", partialSeries(sin)) fmt.Println("cos:", partialSeries(cos)) }
from itertools import islice from fractions import Fraction from functools import reduce try: from itertools import izip as zip except: pass def head(n): return lambda seq: islice(seq, n) def pipe(gen, *cmds): return reduce(lambda gen, cmd: cmd(gen), cmds, gen) def sinepower(): n = 0 fac = 1 sign = +1 zero = 0 yield zero while True: n +=1 fac *= n yield Fraction(1, fac*sign) sign = -sign n +=1 fac *= n yield zero def cosinepower(): n = 0 fac = 1 sign = +1 yield Fraction(1,fac) zero = 0 while True: n +=1 fac *= n yield zero sign = -sign n +=1 fac *= n yield Fraction(1, fac*sign) def pluspower(*powergenerators): for elements in zip(*powergenerators): yield sum(elements) def minuspower(*powergenerators): for elements in zip(*powergenerators): yield elements[0] - sum(elements[1:]) def mulpower(fgen,ggen): 'From: http://en.wikipedia.org/wiki/Power_series a,b = [],[] for f,g in zip(fgen, ggen): a.append(f) b.append(g) yield sum(f*g for f,g in zip(a, reversed(b))) def constpower(n): yield n while True: yield 0 def diffpower(gen): 'differentiatiate power series' next(gen) for n, an in enumerate(gen, start=1): yield an*n def intgpower(k=0): 'integrate power series with constant k' def _intgpower(gen): yield k for n, an in enumerate(gen, start=1): yield an * Fraction(1,n) return _intgpower print("cosine") c = list(pipe(cosinepower(), head(10))) print(c) print("sine") s = list(pipe(sinepower(), head(10))) print(s) integc = list(pipe(cosinepower(),intgpower(0), head(10))) integs1 = list(minuspower(pipe(constpower(1), head(10)), pipe(sinepower(),intgpower(0), head(10)))) assert s == integc, "The integral of cos should be sin" assert c == integs1, "1 minus the integral of sin should be cos"
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "math" ) type fps interface { extract(int) float64 } func one() fps { return &oneFps{} } func add(s1, s2 fps) fps { return &sum{s1: s1, s2: s2} } func sub(s1, s2 fps) fps { return &diff{s1: s1, s2: s2} } func mul(s1, s2 fps) fps { return &prod{s1: s1, s2: s2} } func div(s1, s2 fps) fps { return &quo{s1: s1, s2: s2} } func differentiate(s1 fps) fps { return &deriv{s1: s1} } func integrate(s1 fps) fps { return &integ{s1: s1} } func sinCos() (fps, fps) { sin := &integ{} cos := sub(one(), integrate(sin)) sin.s1 = cos return sin, cos } type oneFps struct{} func (*oneFps) extract(n int) float64 { if n == 0 { return 1 } return 0 } type sum struct { s []float64 s1, s2 fps } func (s *sum) extract(n int) float64 { for i := len(s.s); i <= n; i++ { s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i)) } return s.s[n] } type diff struct { s []float64 s1, s2 fps } func (s *diff) extract(n int) float64 { for i := len(s.s); i <= n; i++ { s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i)) } return s.s[n] } type prod struct { s []float64 s1, s2 fps } func (s *prod) extract(n int) float64 { for i := len(s.s); i <= n; i++ { c := 0. for k := 0; k <= i; k++ { c += s.s1.extract(k) * s.s1.extract(n-k) } s.s = append(s.s, c) } return s.s[n] } type quo struct { s1, s2 fps inv float64 c []float64 s []float64 } func (s *quo) extract(n int) float64 { switch { case len(s.s) > 0: case !math.IsInf(s.inv, 1): a0 := s.s2.extract(0) s.inv = 1 / a0 if a0 != 0 { break } fallthrough default: return math.NaN() } for i := len(s.s); i <= n; i++ { c := 0. for k := 1; k <= i; k++ { c += s.s2.extract(k) * s.c[n-k] } c = s.s1.extract(i) - c*s.inv s.c = append(s.c, c) s.s = append(s.s, c*s.inv) } return s.s[n] } type deriv struct { s []float64 s1 fps } func (s *deriv) extract(n int) float64 { for i := len(s.s); i <= n; { i++ s.s = append(s.s, float64(i)*s.s1.extract(i)) } return s.s[n] } type integ struct { s []float64 s1 fps } func (s *integ) extract(n int) float64 { if n == 0 { return 0 } for i := len(s.s) + 1; i <= n; i++ { s.s = append(s.s, s.s1.extract(i-1)/float64(i)) } return s.s[n-1] } func main() { partialSeries := func(f fps) (s string) { for i := 0; i < 6; i++ { s = fmt.Sprintf("%s %8.5f ", s, f.extract(i)) } return } sin, cos := sinCos() fmt.Println("sin:", partialSeries(sin)) fmt.Println("cos:", partialSeries(cos)) }
from itertools import islice from fractions import Fraction from functools import reduce try: from itertools import izip as zip except: pass def head(n): return lambda seq: islice(seq, n) def pipe(gen, *cmds): return reduce(lambda gen, cmd: cmd(gen), cmds, gen) def sinepower(): n = 0 fac = 1 sign = +1 zero = 0 yield zero while True: n +=1 fac *= n yield Fraction(1, fac*sign) sign = -sign n +=1 fac *= n yield zero def cosinepower(): n = 0 fac = 1 sign = +1 yield Fraction(1,fac) zero = 0 while True: n +=1 fac *= n yield zero sign = -sign n +=1 fac *= n yield Fraction(1, fac*sign) def pluspower(*powergenerators): for elements in zip(*powergenerators): yield sum(elements) def minuspower(*powergenerators): for elements in zip(*powergenerators): yield elements[0] - sum(elements[1:]) def mulpower(fgen,ggen): 'From: http://en.wikipedia.org/wiki/Power_series a,b = [],[] for f,g in zip(fgen, ggen): a.append(f) b.append(g) yield sum(f*g for f,g in zip(a, reversed(b))) def constpower(n): yield n while True: yield 0 def diffpower(gen): 'differentiatiate power series' next(gen) for n, an in enumerate(gen, start=1): yield an*n def intgpower(k=0): 'integrate power series with constant k' def _intgpower(gen): yield k for n, an in enumerate(gen, start=1): yield an * Fraction(1,n) return _intgpower print("cosine") c = list(pipe(cosinepower(), head(10))) print(c) print("sine") s = list(pipe(sinepower(), head(10))) print(s) integc = list(pipe(cosinepower(),intgpower(0), head(10))) integs1 = list(minuspower(pipe(constpower(1), head(10)), pipe(sinepower(),intgpower(0), head(10)))) assert s == integc, "The integral of cos should be sin" assert c == integs1, "1 minus the integral of sin should be cos"
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "math" "rcu" ) func main() { powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81} fmt.Println("Own digits power sums for N = 3 to 9 inclusive:") for n := 3; n < 10; n++ { for d := 2; d < 10; d++ { powers[d] *= d } i := int(math.Pow(10, float64(n-1))) max := i * 10 lastDigit := 0 sum := 0 var digits []int for i < max { if lastDigit == 0 { digits = rcu.Digits(i, 10) sum = 0 for _, d := range digits { sum += powers[d] } } else if lastDigit == 1 { sum++ } else { sum += powers[lastDigit] - powers[lastDigit-1] } if sum == i { fmt.Println(i) if lastDigit == 0 { fmt.Println(i + 1) } i += 10 - lastDigit lastDigit = 0 } else if sum > i { i += 10 - lastDigit lastDigit = 0 } else if lastDigit < 9 { i++ lastDigit++ } else { i++ lastDigit = 0 } } } }
def isowndigitspowersum(integer): digits = [int(c) for c in str(integer)] exponent = len(digits) return sum(x ** exponent for x in digits) == integer print("Own digits power sums for N = 3 to 9 inclusive:") for i in range(100, 1000000000): if isowndigitspowersum(i): print(i)
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "bufio" "encoding/binary" "fmt" "log" "math" "os" "strconv" "strings" ) type code = byte const ( fetch code = iota store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt ) var codeMap = map[string]code{ "fetch": fetch, "store": store, "push": push, "add": add, "sub": sub, "mul": mul, "div": div, "mod": mod, "lt": lt, "gt": gt, "le": le, "ge": ge, "eq": eq, "ne": ne, "and": and, "or": or, "neg": neg, "not": not, "jmp": jmp, "jz": jz, "prtc": prtc, "prts": prts, "prti": prti, "halt": halt, } var ( err error scanner *bufio.Scanner object []code stringPool []string ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func btoi(b bool) int32 { if b { return 1 } return 0 } func itob(i int32) bool { if i != 0 { return true } return false } func emitByte(c code) { object = append(object, c) } func emitWord(n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for _, b := range bs { emitByte(code(b)) } } func runVM(dataSize int) { stack := make([]int32, dataSize+1) pc := int32(0) for { op := object[pc] pc++ switch op { case fetch: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) stack = append(stack, stack[x]) pc += 4 case store: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) ln := len(stack) stack[x] = stack[ln-1] stack = stack[:ln-1] pc += 4 case push: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) stack = append(stack, x) pc += 4 case add: ln := len(stack) stack[ln-2] += stack[ln-1] stack = stack[:ln-1] case sub: ln := len(stack) stack[ln-2] -= stack[ln-1] stack = stack[:ln-1] case mul: ln := len(stack) stack[ln-2] *= stack[ln-1] stack = stack[:ln-1] case div: ln := len(stack) stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1])) stack = stack[:ln-1] case mod: ln := len(stack) stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1]))) stack = stack[:ln-1] case lt: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] < stack[ln-1]) stack = stack[:ln-1] case gt: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] > stack[ln-1]) stack = stack[:ln-1] case le: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1]) stack = stack[:ln-1] case ge: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1]) stack = stack[:ln-1] case eq: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] == stack[ln-1]) stack = stack[:ln-1] case ne: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] != stack[ln-1]) stack = stack[:ln-1] case and: ln := len(stack) stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1])) stack = stack[:ln-1] case or: ln := len(stack) stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1])) stack = stack[:ln-1] case neg: ln := len(stack) stack[ln-1] = -stack[ln-1] case not: ln := len(stack) stack[ln-1] = btoi(!itob(stack[ln-1])) case jmp: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) pc += x case jz: ln := len(stack) v := stack[ln-1] stack = stack[:ln-1] if v != 0 { pc += 4 } else { x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) pc += x } case prtc: ln := len(stack) fmt.Printf("%c", stack[ln-1]) stack = stack[:ln-1] case prts: ln := len(stack) fmt.Printf("%s", stringPool[stack[ln-1]]) stack = stack[:ln-1] case prti: ln := len(stack) fmt.Printf("%d", stack[ln-1]) stack = stack[:ln-1] case halt: return default: reportError(fmt.Sprintf("Unknown opcode %d\n", op)) } } } func translate(s string) string { var d strings.Builder for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } return d.String() } func loadCode() int { var dataSize int firstLine := true for scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") if len(line) == 0 { if firstLine { reportError("empty line") } else { break } } lineList := strings.Fields(line) if firstLine { dataSize, err = strconv.Atoi(lineList[1]) check(err) nStrings, err := strconv.Atoi(lineList[3]) check(err) for i := 0; i < nStrings; i++ { scanner.Scan() s := strings.Trim(scanner.Text(), "\"\n") stringPool = append(stringPool, translate(s)) } firstLine = false continue } offset, err := strconv.Atoi(lineList[0]) check(err) instr := lineList[1] opCode, ok := codeMap[instr] if !ok { reportError(fmt.Sprintf("Unknown instruction %s at %d", instr, opCode)) } emitByte(opCode) switch opCode { case jmp, jz: p, err := strconv.Atoi(lineList[3]) check(err) emitWord(p - offset - 1) case push: value, err := strconv.Atoi(lineList[2]) check(err) emitWord(value) case fetch, store: value, err := strconv.Atoi(strings.Trim(lineList[2], "[]")) check(err) emitWord(value) } } check(scanner.Err()) return dataSize } func main() { codeGen, err := os.Open("codegen.txt") check(err) defer codeGen.Close() scanner = bufio.NewScanner(codeGen) runVM(loadCode()) }
def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1 if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "bufio" "encoding/binary" "fmt" "log" "math" "os" "strconv" "strings" ) type code = byte const ( fetch code = iota store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt ) var codeMap = map[string]code{ "fetch": fetch, "store": store, "push": push, "add": add, "sub": sub, "mul": mul, "div": div, "mod": mod, "lt": lt, "gt": gt, "le": le, "ge": ge, "eq": eq, "ne": ne, "and": and, "or": or, "neg": neg, "not": not, "jmp": jmp, "jz": jz, "prtc": prtc, "prts": prts, "prti": prti, "halt": halt, } var ( err error scanner *bufio.Scanner object []code stringPool []string ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func btoi(b bool) int32 { if b { return 1 } return 0 } func itob(i int32) bool { if i != 0 { return true } return false } func emitByte(c code) { object = append(object, c) } func emitWord(n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for _, b := range bs { emitByte(code(b)) } } func runVM(dataSize int) { stack := make([]int32, dataSize+1) pc := int32(0) for { op := object[pc] pc++ switch op { case fetch: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) stack = append(stack, stack[x]) pc += 4 case store: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) ln := len(stack) stack[x] = stack[ln-1] stack = stack[:ln-1] pc += 4 case push: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) stack = append(stack, x) pc += 4 case add: ln := len(stack) stack[ln-2] += stack[ln-1] stack = stack[:ln-1] case sub: ln := len(stack) stack[ln-2] -= stack[ln-1] stack = stack[:ln-1] case mul: ln := len(stack) stack[ln-2] *= stack[ln-1] stack = stack[:ln-1] case div: ln := len(stack) stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1])) stack = stack[:ln-1] case mod: ln := len(stack) stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1]))) stack = stack[:ln-1] case lt: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] < stack[ln-1]) stack = stack[:ln-1] case gt: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] > stack[ln-1]) stack = stack[:ln-1] case le: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1]) stack = stack[:ln-1] case ge: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1]) stack = stack[:ln-1] case eq: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] == stack[ln-1]) stack = stack[:ln-1] case ne: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] != stack[ln-1]) stack = stack[:ln-1] case and: ln := len(stack) stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1])) stack = stack[:ln-1] case or: ln := len(stack) stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1])) stack = stack[:ln-1] case neg: ln := len(stack) stack[ln-1] = -stack[ln-1] case not: ln := len(stack) stack[ln-1] = btoi(!itob(stack[ln-1])) case jmp: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) pc += x case jz: ln := len(stack) v := stack[ln-1] stack = stack[:ln-1] if v != 0 { pc += 4 } else { x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) pc += x } case prtc: ln := len(stack) fmt.Printf("%c", stack[ln-1]) stack = stack[:ln-1] case prts: ln := len(stack) fmt.Printf("%s", stringPool[stack[ln-1]]) stack = stack[:ln-1] case prti: ln := len(stack) fmt.Printf("%d", stack[ln-1]) stack = stack[:ln-1] case halt: return default: reportError(fmt.Sprintf("Unknown opcode %d\n", op)) } } } func translate(s string) string { var d strings.Builder for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } return d.String() } func loadCode() int { var dataSize int firstLine := true for scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") if len(line) == 0 { if firstLine { reportError("empty line") } else { break } } lineList := strings.Fields(line) if firstLine { dataSize, err = strconv.Atoi(lineList[1]) check(err) nStrings, err := strconv.Atoi(lineList[3]) check(err) for i := 0; i < nStrings; i++ { scanner.Scan() s := strings.Trim(scanner.Text(), "\"\n") stringPool = append(stringPool, translate(s)) } firstLine = false continue } offset, err := strconv.Atoi(lineList[0]) check(err) instr := lineList[1] opCode, ok := codeMap[instr] if !ok { reportError(fmt.Sprintf("Unknown instruction %s at %d", instr, opCode)) } emitByte(opCode) switch opCode { case jmp, jz: p, err := strconv.Atoi(lineList[3]) check(err) emitWord(p - offset - 1) case push: value, err := strconv.Atoi(lineList[2]) check(err) emitWord(value) case fetch, store: value, err := strconv.Atoi(strings.Trim(lineList[2], "[]")) check(err) emitWord(value) } } check(scanner.Err()) return dataSize } func main() { codeGen, err := os.Open("codegen.txt") check(err) defer codeGen.Close() scanner = bufio.NewScanner(codeGen) runVM(loadCode()) }
def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1 if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break
Change the programming language of this snippet from Go to Python without modifying what it does.
package raster const b3Seg = 30 func (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) { var px, py [b3Seg + 1]int fx1, fy1 := float64(x1), float64(y1) fx2, fy2 := float64(x2), float64(y2) fx3, fy3 := float64(x3), float64(y3) fx4, fy4 := float64(x4), float64(y4) for i := range px { d := float64(i) / b3Seg a := 1 - d b, c := a * a, d * d a, b, c, d = a*b, 3*b*d, 3*a*c, c*d px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4) py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4) } x0, y0 := px[0], py[0] for i := 1; i <= b3Seg; i++ { x1, y1 := px[i], py[i] b.Line(x0, y0, x1, y1, p) x0, y0 = x1, y1 } } func (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) { b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel()) }
def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20): pts = [] for i in range(n+1): t = i / n a = (1. - t)**3 b = 3. * t * (1. - t)**2 c = 3.0 * t**2 * (1.0 - t) d = t**3 x = int(a * x0 + b * x1 + c * x2 + d * x3) y = int(a * y0 + b * y1 + c * y2 + d * y3) pts.append( (x, y) ) for i in range(n): self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1]) Bitmap.cubicbezier = cubicbezier bitmap = Bitmap(17,17) bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11) bitmap.chardisplay()
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import "fmt" func main() { list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list) list.sort() fmt.Println("sorted! ", list) } type pancake []int func (a pancake) sort() { for uns := len(a) - 1; uns > 0; uns-- { lx, lg := 0, a[0] for i := 1; i <= uns; i++ { if a[i] > lg { lx, lg = i, a[i] } } a.flip(lx) a.flip(uns) } } func (a pancake) flip(r int) { for l := 0; l < r; l, r = l+1, r-1 { a[l], a[r] = a[r], a[l] } }
tutor = False def pancakesort(data): if len(data) <= 1: return data if tutor: print() for size in range(len(data), 1, -1): maxindex = max(range(size), key=data.__getitem__) if maxindex+1 != size: if maxindex != 0: if tutor: print('With: %r doflip %i' % ( ' '.join(str(x) for x in data), maxindex+1 )) data[:maxindex+1] = reversed(data[:maxindex+1]) if tutor: print('With: %r doflip %i' % ( ' '.join(str(x) for x in data), size )) data[:size] = reversed(data[:size]) if tutor: print()
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "math/rand" "rcu" "strings" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var sb strings.Builder for i := 0; i < 1000; i++ { sb.WriteByte(byte(rand.Intn(10) + 48)) } number := sb.String() for i := 99999; i >= 0; i-- { quintet := fmt.Sprintf("%05d", i) if strings.Contains(number, quintet) { ci := rcu.Commatize(i) fmt.Printf("The largest number formed from 5 adjacent digits (%s) is: %6s\n", quintet, ci) break } } for i := 0; i <= 99999; i++ { quintet := fmt.Sprintf("%05d", i) if strings.Contains(number, quintet) { ci := rcu.Commatize(i) fmt.Printf("The smallest number formed from 5 adjacent digits (%s) is: %6s\n", quintet, ci) return } } }
from random import seed,randint from datetime import datetime seed(str(datetime.now())) largeNum = [randint(1,9)] for i in range(1,1000): largeNum.append(randint(0,9)) maxNum,minNum = 0,99999 for i in range(0,994): num = int("".join(map(str,largeNum[i:i+5]))) if num > maxNum: maxNum = num elif num < minNum: minNum = num print("Largest 5-adjacent number found ", maxNum) print("Smallest 5-adjacent number found ", minNum)
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "rcu" ) func main() { for i := 1; i < 100; i++ { if !rcu.IsPrime(rcu.DigitSum(i*i, 10)) { continue } if rcu.IsPrime(rcu.DigitSum(i*i*i, 10)) { fmt.Printf("%d ", i) } } fmt.Println() }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def digSum(n, b): s = 0 while n: s += (n % b) n = n // b return s if __name__ == '__main__': for n in range(11, 99): if isPrime(digSum(n**3, 10)) and isPrime(digSum(n**2, 10)): print(n, end = " ")
Generate an equivalent Python version of this Go code.
package main import ( "fmt" "math" "rcu" "time" ) func sos(n int) []int { if n < 3 { return []int{} } var primes []int k := (n-3)/2 + 1 marked := make([]bool, k) limit := (int(math.Sqrt(float64(n)))-3)/2 + 1 for i := 0; i < limit; i++ { p := 2*i + 3 s := (p*p - 3) / 2 for j := s; j < k; j += p { marked[j] = true } } for i := 0; i < k; i++ { if !marked[i] { primes = append(primes, 2*i+3) } } return primes } func soe(n int) []int { if n < 3 { return []int{} } var primes []int k := (n-3)/2 + 1 marked := make([]bool, k) limit := (int(math.Sqrt(float64(n)))-3)/2 + 1 for i := 0; i < limit; i++ { if !marked[i] { p := 2*i + 3 s := (p*p - 3) / 2 for j := s; j < k; j += p { marked[j] = true } } } for i := 0; i < k; i++ { if !marked[i] { primes = append(primes, 2*i+3) } } return primes } func main() { const limit = int(16e6) start := time.Now() primes := sos(limit) elapsed := int(time.Since(start).Milliseconds()) climit := rcu.Commatize(limit) celapsed := rcu.Commatize(elapsed) million := rcu.Commatize(1e6) millionth := rcu.Commatize(primes[1e6-1]) fmt.Printf("Using the Sieve of Sundaram generated primes up to %s in %s ms.\n\n", climit, celapsed) fmt.Println("First 100 odd primes generated by the Sieve of Sundaram:") for i, p := range primes[0:100] { fmt.Printf("%3d ", p) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\nThe %s Sundaram prime is %s\n", million, millionth) start = time.Now() primes = soe(limit) elapsed = int(time.Since(start).Milliseconds()) celapsed = rcu.Commatize(elapsed) millionth = rcu.Commatize(primes[1e6-1]) fmt.Printf("\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\n", celapsed) fmt.Printf("\nAs a check, the %s Sundaram prime would again have been %s\n", million, millionth) }
from numpy import log def sieve_of_Sundaram(nth, print_all=True): assert nth > 0, "nth must be a positive integer" k = int((2.4 * nth * log(nth)) // 2) integers_list = [True] * k for i in range(1, k): j = i while i + j + 2 * i * j < k: integers_list[i + j + 2 * i * j] = False j += 1 pcount = 0 for i in range(1, k + 1): if integers_list[i]: pcount += 1 if print_all: print(f"{2 * i + 1:4}", end=' ') if pcount % 10 == 0: print() if pcount == nth: print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n") break sieve_of_Sundaram(100, True) sieve_of_Sundaram(1000000, False)
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "strconv" "strings" ) var atomicMass = map[string]float64{ "H": 1.008, "He": 4.002602, "Li": 6.94, "Be": 9.0121831, "B": 10.81, "C": 12.011, "N": 14.007, "O": 15.999, "F": 18.998403163, "Ne": 20.1797, "Na": 22.98976928, "Mg": 24.305, "Al": 26.9815385, "Si": 28.085, "P": 30.973761998, "S": 32.06, "Cl": 35.45, "Ar": 39.948, "K": 39.0983, "Ca": 40.078, "Sc": 44.955908, "Ti": 47.867, "V": 50.9415, "Cr": 51.9961, "Mn": 54.938044, "Fe": 55.845, "Co": 58.933194, "Ni": 58.6934, "Cu": 63.546, "Zn": 65.38, "Ga": 69.723, "Ge": 72.630, "As": 74.921595, "Se": 78.971, "Br": 79.904, "Kr": 83.798, "Rb": 85.4678, "Sr": 87.62, "Y": 88.90584, "Zr": 91.224, "Nb": 92.90637, "Mo": 95.95, "Ru": 101.07, "Rh": 102.90550, "Pd": 106.42, "Ag": 107.8682, "Cd": 112.414, "In": 114.818, "Sn": 118.710, "Sb": 121.760, "Te": 127.60, "I": 126.90447, "Xe": 131.293, "Cs": 132.90545196, "Ba": 137.327, "La": 138.90547, "Ce": 140.116, "Pr": 140.90766, "Nd": 144.242, "Pm": 145, "Sm": 150.36, "Eu": 151.964, "Gd": 157.25, "Tb": 158.92535, "Dy": 162.500, "Ho": 164.93033, "Er": 167.259, "Tm": 168.93422, "Yb": 173.054, "Lu": 174.9668, "Hf": 178.49, "Ta": 180.94788, "W": 183.84, "Re": 186.207, "Os": 190.23, "Ir": 192.217, "Pt": 195.084, "Au": 196.966569, "Hg": 200.592, "Tl": 204.38, "Pb": 207.2, "Bi": 208.98040, "Po": 209, "At": 210, "Rn": 222, "Fr": 223, "Ra": 226, "Ac": 227, "Th": 232.0377, "Pa": 231.03588, "U": 238.02891, "Np": 237, "Pu": 244, "Am": 243, "Cm": 247, "Bk": 247, "Cf": 251, "Es": 252, "Fm": 257, "Uue": 315, "Ubn": 299, } func replaceParens(s string) string { var letter byte = 'a' for { start := strings.IndexByte(s, '(') if start == -1 { break } restart: for i := start + 1; i < len(s); i++ { if s[i] == ')' { expr := s[start+1 : i] symbol := fmt.Sprintf("@%c", letter) s = strings.Replace(s, s[start:i+1], symbol, 1) atomicMass[symbol] = evaluate(expr) letter++ break } if s[i] == '(' { start = i goto restart } } } return s } func evaluate(s string) float64 { s += string('[') var symbol, number string sum := 0.0 for i := 0; i < len(s); i++ { c := s[i] switch { case c >= '@' && c <= '[': n := 1 if number != "" { n, _ = strconv.Atoi(number) } if symbol != "" { sum += atomicMass[symbol] * float64(n) } if c == '[' { break } symbol = string(c) number = "" case c >= 'a' && c <= 'z': symbol += string(c) case c >= '0' && c <= '9': number += string(c) default: panic(fmt.Sprintf("Unexpected symbol %c in molecule", c)) } } return sum } func main() { molecules := []string{ "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue", } for _, molecule := range molecules { mass := evaluate(replaceParens(molecule)) fmt.Printf("%17s -> %7.3f\n", molecule, mass) } }
assert 1.008 == molar_mass('H') assert 2.016 == molar_mass('H2') assert 18.015 == molar_mass('H2O') assert 34.014 == molar_mass('H2O2') assert 34.014 == molar_mass('(HO)2') assert 142.036 == molar_mass('Na2SO4') assert 84.162 == molar_mass('C6H12') assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3') assert 176.124 == molar_mass('C6H4O2(OH)4') assert 386.664 == molar_mass('C27H46O') assert 315 == molar_mass('Uue')
Port the provided Go code into Python while preserving the original functionality.
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, UseSSL: false, BindDN: "uid=readonlyuser,ou=People,dc=example,dc=com", BindPassword: "readonlypassword", UserFilter: "(uid=%s)", GroupFilter: "(memberUid=%s)", Attributes: []string{"givenName", "sn", "mail", "uid"}, } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } }
import ldap l = ldap.initialize("ldap://ldap.example.com") try: l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_REFERRALS, 0) bind = l.simple_bind_s("me@example.com", "password") finally: l.unbind()
Change the following Go code into Python without altering its purpose.
package main import "fmt" func main() { lists := [][]int{ {9, 3, 3, 3, 2, 1, 7, 8, 5}, {5, 2, 9, 3, 3, 7, 8, 4, 1}, {1, 4, 3, 6, 7, 3, 8, 3, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {4, 6, 8, 7, 2, 3, 3, 3, 1}, {3, 3, 3, 1, 2, 4, 5, 1, 3}, {0, 3, 3, 3, 3, 7, 2, 2, 6}, {3, 3, 3, 3, 3, 4, 4, 4, 4}, } for d := 1; d <= 4; d++ { fmt.Printf("Exactly %d adjacent %d's:\n", d, d) for _, list := range lists { var indices []int for i, e := range list { if e == d { indices = append(indices, i) } } adjacent := false if len(indices) == d { adjacent = true for i := 1; i < len(indices); i++ { if indices[i]-indices[i-1] != 1 { adjacent = false break } } } fmt.Printf("%v -> %t\n", list, adjacent) } fmt.Println() } }
from itertools import dropwhile, takewhile def nnPeers(n): def p(x): return n == x def go(xs): fromFirstMatch = list(dropwhile( lambda v: not p(v), xs )) ns = list(takewhile(p, fromFirstMatch)) rest = fromFirstMatch[len(ns):] return p(len(ns)) and ( not any(p(x) for x in rest) ) return go def main(): print( '\n'.join([ f'{xs} -> {nnPeers(3)(xs)}' for xs in [ [9, 3, 3, 3, 2, 1, 7, 8, 5], [5, 2, 9, 3, 3, 7, 8, 4, 1], [1, 4, 3, 6, 7, 3, 8, 3, 2], [1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 6, 8, 7, 2, 3, 3, 3, 1] ] ]) ) if __name__ == '__main__': main()
Convert this Go snippet to Python and keep its semantics consistent.
package permute func Iter(p []int) func() int { f := pf(len(p)) return func() int { return f(p) } } func pf(n int) func([]int) int { sign := 1 switch n { case 0, 1: return func([]int) (s int) { s = sign sign = 0 return } default: p0 := pf(n - 1) i := n var d int return func(p []int) int { switch { case sign == 0: case i == n: i-- sign = p0(p[:i]) d = -1 case i == 0: i++ sign *= p0(p[1:]) d = 1 if sign == 0 { p[0], p[1] = p[1], p[0] } default: p[i], p[i-1] = p[i-1], p[i] sign = -sign i += d } return sign } } }
from operator import itemgetter DEBUG = False def spermutations(n): sign = 1 p = [[i, 0 if i == 0 else -1] for i in range(n)] if DEBUG: print ' yield tuple(pp[0] for pp in p), sign while any(pp[1] for pp in p): i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]), key=itemgetter(1)) sign *= -1 if d1 == -1: i2 = i1 - 1 p[i1], p[i2] = p[i2], p[i1] if i2 == 0 or p[i2 - 1][0] > n1: p[i2][1] = 0 elif d1 == 1: i2 = i1 + 1 p[i1], p[i2] = p[i2], p[i1] if i2 == n - 1 or p[i2 + 1][0] > n1: p[i2][1] = 0 if DEBUG: print ' yield tuple(pp[0] for pp in p), sign for i3, pp in enumerate(p): n3, d3 = pp if n3 > n1: pp[1] = 1 if i3 < i2 else -1 if DEBUG: print ' if __name__ == '__main__': from itertools import permutations for n in (3, 4): print '\nPermutations and sign of %i items' % n sp = set() for i in spermutations(n): sp.add(i[0]) print('Perm: %r Sign: %2i' % i) p = set(permutations(range(n))) assert sp == p, 'Two methods of generating permutations do not agree'
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import "rcu" func main() { var res []int for n := 1; n <= 70; n++ { m := 1 for rcu.DigitSum(m*n, 10) != n { m++ } res = append(res, m) } rcu.PrintTable(res, 7, 10, true) }
from itertools import count, islice def a131382(): return ( elemIndex(x)( productDigitSums(x) ) for x in count(1) ) def productDigitSums(n): return (digitSum(n * x) for x in count(0)) def main(): print( table(10)([ str(x) for x in islice( a131382(), 40 ) ]) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitSum(n): return sum(int(x) for x in list(str(n))) def elemIndex(x): def go(xs): try: return next( i for i, v in enumerate(xs) if x == v ) except StopIteration: return None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
Convert this Go block to Python, preserving its control flow and logic.
package main import "fmt" const ( N = 2200 N2 = N * N * 2 ) func main() { s := 3 var s1, s2 int var r [N + 1]bool var ab [N2 + 1]bool for a := 1; a <= N; a++ { a2 := a * a for b := a; b <= N; b++ { ab[a2 + b * b] = true } } for c := 1; c <= N; c++ { s1 = s s += 2 s2 = s for d := c + 1; d <= N; d++ { if ab[s1] { r[d] = true } s1 += s2 s2 += 2 } } for d := 1; d <= N; d++ { if !r[d] { fmt.Printf("%d ", d) } } fmt.Println() }
def quad(top=2200): r = [False] * top ab = [False] * (top * 2)**2 for a in range(1, top): for b in range(a, top): ab[a * a + b * b] = True s = 3 for c in range(1, top): s1, s, s2 = s, s + 2, s + 2 for d in range(c + 1, top): if ab[s1]: r[d] = True s1 += s2 s2 += 2 return [i for i, val in enumerate(r) if not val and i] if __name__ == '__main__': n = 2200 print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
Port the provided Go code into Python while preserving the original functionality.
package main import "fmt" var d = [][]int{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, } var inv = []int{0, 4, 3, 2, 1, 5, 6, 7, 8, 9} var p = [][]int{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, } func verhoeff(s string, validate, table bool) interface{} { if table { t := "Check digit" if validate { t = "Validation" } fmt.Printf("%s calculations for '%s':\n\n", t, s) fmt.Println(" i nᵢ p[i,nᵢ] c") fmt.Println("------------------") } if !validate { s = s + "0" } c := 0 le := len(s) - 1 for i := le; i >= 0; i-- { ni := int(s[i] - 48) pi := p[(le-i)%8][ni] c = d[c][pi] if table { fmt.Printf("%2d %d %d %d\n", le-i, ni, pi, c) } } if table && !validate { fmt.Printf("\ninv[%d] = %d\n", c, inv[c]) } if !validate { return inv[c] } return c == 0 } func main() { ss := []string{"236", "12345", "123456789012"} ts := []bool{true, true, false, true} for i, s := range ss { c := verhoeff(s, false, ts[i]).(int) fmt.Printf("\nThe check digit for '%s' is '%d'\n\n", s, c) for _, sc := range []string{s + string(c+48), s + "9"} { v := verhoeff(sc, true, ts[i]).(bool) ans := "correct" if !v { ans = "incorrect" } fmt.Printf("\nThe validation for '%s' is %s\n\n", sc, ans) } } }
MULTIPLICATION_TABLE = [ (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 2, 3, 4, 0, 6, 7, 8, 9, 5), (2, 3, 4, 0, 1, 7, 8, 9, 5, 6), (3, 4, 0, 1, 2, 8, 9, 5, 6, 7), (4, 0, 1, 2, 3, 9, 5, 6, 7, 8), (5, 9, 8, 7, 6, 0, 4, 3, 2, 1), (6, 5, 9, 8, 7, 1, 0, 4, 3, 2), (7, 6, 5, 9, 8, 2, 1, 0, 4, 3), (8, 7, 6, 5, 9, 3, 2, 1, 0, 4), (9, 8, 7, 6, 5, 4, 3, 2, 1, 0), ] INV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9) PERMUTATION_TABLE = [ (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 5, 7, 6, 2, 8, 3, 0, 9, 4), (5, 8, 0, 3, 7, 9, 6, 1, 4, 2), (8, 9, 1, 6, 0, 4, 3, 5, 2, 7), (9, 4, 5, 3, 1, 2, 6, 8, 7, 0), (4, 2, 8, 6, 5, 7, 3, 9, 0, 1), (2, 7, 9, 3, 8, 0, 6, 4, 1, 5), (7, 0, 4, 6, 9, 1, 3, 2, 5, 8), ] def verhoeffchecksum(n, validate=True, terse=True, verbose=False): if verbose: print(f"\n{'Validation' if validate else 'Check digit'}",\ f"calculations for {n}:\n\n i nᵢ p[i,nᵢ] c\n------------------") c, dig = 0, list(str(n if validate else 10 * n)) for i, ni in enumerate(dig[::-1]): p = PERMUTATION_TABLE[i % 8][int(ni)] c = MULTIPLICATION_TABLE[c][p] if verbose: print(f"{i:2} {ni} {p} {c}") if verbose and not validate: print(f"\ninv({c}) = {INV[c]}") if not terse: print(f"\nThe validation for '{n}' is {'correct' if c == 0 else 'incorrect'}."\ if validate else f"\nThe check digit for '{n}' is {INV[c]}.") return c == 0 if validate else INV[c] if __name__ == '__main__': for n, va, t, ve in [ (236, False, False, True), (2363, True, False, True), (2369, True, False, True), (12345, False, False, True), (123451, True, False, True), (123459, True, False, True), (123456789012, False, False, False), (1234567890120, True, False, False), (1234567890129, True, False, False)]: verhoeffchecksum(n, va, t, ve)
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "rcu" "strconv" "strings" ) func contains(list []int, s int) bool { for _, e := range list { if e == s { return true } } return false } func main() { fmt.Println("Steady squares under 10,000:") finalDigits := []int{1, 5, 6} for i := 1; i < 10000; i++ { if !contains(finalDigits, i%10) { continue } sq := i * i sqs := strconv.Itoa(sq) is := strconv.Itoa(i) if strings.HasSuffix(sqs, is) { fmt.Printf("%5s -> %10s\n", rcu.Commatize(i), rcu.Commatize(sq)) } } }
print("working...") print("Steady squares under 10.000 are:") limit = 10000 for n in range(1,limit): nstr = str(n) nlen = len(nstr) square = str(pow(n,2)) rn = square[-nlen:] if nstr == rn: print(str(n) + " " + str(square)) print("done...")
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "rcu" "strconv" ) func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } return string(chars) } func main() { fmt.Println("Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:") var numbers []int for i := int64(0); i < 25000; i++ { b2 := strconv.FormatInt(i, 2) if b2 == reverse(b2) { b4 := strconv.FormatInt(i, 4) if b4 == reverse(b4) { b16 := strconv.FormatInt(i, 16) if b16 == reverse(b16) { numbers = append(numbers, int(i)) } } } } for i, n := range numbers { fmt.Printf("%6s ", rcu.Commatize(n)) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\n\nFound", len(numbers), "such numbers.") }
def reverse(n, base): r = 0 while n > 0: r = r*base + n%base n = n//base return r def palindrome(n, base): return n == reverse(n, base) cnt = 0 for i in range(25000): if all(palindrome(i, base) for base in (2,4,16)): cnt += 1 print("{:5}".format(i), end=" \n"[cnt % 12 == 0]) print()
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) totalSecs := 0 totalSteps := 0 fmt.Println("Seconds steps behind steps ahead") fmt.Println("------- ------------ -----------") for trial := 1; trial < 10000; trial++ { sbeh := 0 slen := 100 secs := 0 for sbeh < slen { sbeh++ for wiz := 1; wiz < 6; wiz++ { if rand.Intn(slen) < sbeh { sbeh++ } slen++ } secs++ if trial == 1 && secs > 599 && secs < 610 { fmt.Printf("%d %d %d\n", secs, sbeh, slen-sbeh) } } totalSecs += secs totalSteps += slen } fmt.Println("\nAverage secs taken:", float64(totalSecs)/10000) fmt.Println("Average final length of staircase:", float64(totalSteps)/10000) }
from numpy import mean from random import sample def gen_long_stairs(start_step, start_length, climber_steps, add_steps): secs, behind, total = 0, start_step, start_length while True: behind += climber_steps behind += sum([behind > n for n in sample(range(total), add_steps)]) total += add_steps secs += 1 yield (secs, behind, total) ls = gen_long_stairs(1, 100, 1, 5) print("Seconds Behind Ahead\n----------------------") while True: secs, pos, len = next(ls) if 600 <= secs < 610: print(secs, " ", pos, " ", len - pos) elif secs == 610: break print("\nTen thousand trials to top:") times, heights = [], [] for trial in range(10_000): trialstairs = gen_long_stairs(1, 100, 1, 5) while True: sec, step, height = next(trialstairs) if step >= height: times.append(sec) heights.append(height) break print("Mean time:", mean(times), "secs. Mean height:", mean(heights))
Write a version of this Go function in Python with identical behavior.
package main import "C" import "fmt" func main() { for i := 0; i < 80*25; i++ { fmt.Print("A") } fmt.Println() conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE) info := C.CONSOLE_SCREEN_BUFFER_INFO{} pos := C.COORD{} C.GetConsoleScreenBufferInfo(conOut, &info) pos.X = info.srWindow.Left + 3 pos.Y = info.srWindow.Top + 6 var c C.wchar_t var le C.ulong ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le) if ret == 0 || le <= 0 { fmt.Println("Something went wrong!") return } fmt.Printf("The character at column 3, row 6 is '%c'\n", c) }
import curses from random import randint stdscr = curses.initscr() for rows in range(10): line = ''.join([chr(randint(41, 90)) for i in range(10)]) stdscr.addstr(line + '\n') icol = 3 - 1 irow = 6 - 1 ch = stdscr.instr(irow, icol, 1).decode(encoding="utf-8") stdscr.move(irow, icol + 10) stdscr.addstr('Character at column 3, row 6 = ' + ch + '\n') stdscr.getch() curses.endwin()
Please provide an equivalent version of this Go code in Python.
package main import "fmt" func random(seed int) int { return seed * seed / 1e3 % 1e6 } func main() { seed := 675248 for i := 1; i <= 5; i++ { seed = random(seed) fmt.Println(seed) } }
seed = 675248 def random(): global seed seed = int(str(seed ** 2).zfill(12)[3:9]) return seed for _ in range(5): print(random())
Change the following Go code into Python without altering its purpose.
package main import "fmt" func random(seed int) int { return seed * seed / 1e3 % 1e6 } func main() { seed := 675248 for i := 1; i <= 5; i++ { seed = random(seed) fmt.Println(seed) } }
seed = 675248 def random(): global seed seed = int(str(seed ** 2).zfill(12)[3:9]) return seed for _ in range(5): print(random())
Please provide an equivalent version of this Go code in Python.
package main import ( "bufio" "fmt" "io" "log" "os" "strings" "unicode" ) type line struct { kind lineKind option string value string disabled bool } type lineKind int const ( _ lineKind = iota ignore parseError comment blank value ) func (l line) String() string { switch l.kind { case ignore, parseError, comment, blank: return l.value case value: s := l.option if l.disabled { s = "; " + s } if l.value != "" { s += " " + l.value } return s } panic("unexpected line kind") } func removeDross(s string) string { return strings.Map(func(r rune) rune { if r < 32 || r > 0x7f || unicode.IsControl(r) { return -1 } return r }, s) } func parseLine(s string) line { if s == "" { return line{kind: blank} } if s[0] == '#' { return line{kind: comment, value: s} } s = removeDross(s) fields := strings.Fields(s) if len(fields) == 0 { return line{kind: blank} } semi := false for len(fields[0]) > 0 && fields[0][0] == ';' { semi = true fields[0] = fields[0][1:] } if fields[0] == "" { fields = fields[1:] } switch len(fields) { case 0: return line{kind: ignore} case 1: return line{ kind: value, option: strings.ToUpper(fields[0]), disabled: semi, } case 2: return line{ kind: value, option: strings.ToUpper(fields[0]), value: fields[1], disabled: semi, } } return line{kind: parseError, value: s} } type Config struct { options map[string]int lines []line } func (c *Config) index(option string) int { if i, ok := c.options[option]; ok { return i } return -1 } func (c *Config) addLine(l line) { switch l.kind { case ignore: return case value: if c.index(l.option) >= 0 { return } c.options[l.option] = len(c.lines) c.lines = append(c.lines, l) default: c.lines = append(c.lines, l) } } func ReadConfig(path string) (*Config, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() r := bufio.NewReader(f) c := &Config{options: make(map[string]int)} for { s, err := r.ReadString('\n') if s != "" { if err == nil { s = s[:len(s)-1] } c.addLine(parseLine(s)) } if err == io.EOF { break } if err != nil { return nil, err } } return c, nil } func (c *Config) Set(option string, val string) { if i := c.index(option); i >= 0 { line := &c.lines[i] line.disabled = false line.value = val return } c.addLine(line{ kind: value, option: option, value: val, }) } func (c *Config) Enable(option string, enabled bool) { if i := c.index(option); i >= 0 { c.lines[i].disabled = !enabled } } func (c *Config) Write(w io.Writer) { for _, line := range c.lines { fmt.Println(line) } } func main() { c, err := ReadConfig("/tmp/cfg") if err != nil { log.Fatalln(err) } c.Enable("NEEDSPEELING", false) c.Set("SEEDSREMOVED", "") c.Set("NUMBEROFBANANAS", "1024") c.Set("NUMBEROFSTRAWBERRIES", "62000") c.Write(os.Stdout) }
import re import string DISABLED_PREFIX = ';' class Option(object): def __init__(self, name, value=None, disabled=False, disabled_prefix=DISABLED_PREFIX): self.name = str(name) self.value = value self.disabled = bool(disabled) self.disabled_prefix = disabled_prefix def __str__(self): disabled = ('', '%s ' % self.disabled_prefix)[self.disabled] value = (' %s' % self.value, '')[self.value is None] return ''.join((disabled, self.name, value)) def get(self): enabled = not bool(self.disabled) if self.value is None: value = enabled else: value = enabled and self.value return value class Config(object): reOPTION = r'^\s*(?P<disabled>%s*)\s*(?P<name>\w+)(?:\s+(?P<value>.+?))?\s*$' def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX): self.disabled_prefix = disabled_prefix self.contents = [] self.options = {} self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix) if fname: self.parse_file(fname) def __str__(self): return '\n'.join(map(str, self.contents)) def parse_file(self, fname): with open(fname) as f: self.parse_lines(f) return self def parse_lines(self, lines): for line in lines: self.parse_line(line) return self def parse_line(self, line): s = ''.join(c for c in line.strip() if c in string.printable) moOPTION = self.creOPTION.match(s) if moOPTION: name = moOPTION.group('name').upper() if not name in self.options: self.add_option(name, moOPTION.group('value'), moOPTION.group('disabled')) else: if not s.startswith(self.disabled_prefix): self.contents.append(line.rstrip()) return self def add_option(self, name, value=None, disabled=False): name = name.upper() opt = Option(name, value, disabled) self.options[name] = opt self.contents.append(opt) return opt def set_option(self, name, value=None, disabled=False): name = name.upper() opt = self.options.get(name) if opt: opt.value = value opt.disabled = disabled else: opt = self.add_option(name, value, disabled) return opt def enable_option(self, name, value=None): return self.set_option(name, value, False) def disable_option(self, name, value=None): return self.set_option(name, value, True) def get_option(self, name): opt = self.options.get(name.upper()) value = opt.get() if opt else None return value if __name__ == '__main__': import sys cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None) cfg.disable_option('needspeeling') cfg.enable_option('seedsremoved') cfg.enable_option('numberofbananas', 1024) cfg.enable_option('numberofstrawberries', 62000) print cfg
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "image" "image/color" "image/jpeg" "math" "os" ) func kf3(k *[9]float64, src, dst *image.Gray) { for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ { for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ { var sum float64 var i int for yo := y - 1; yo <= y+1; yo++ { for xo := x - 1; xo <= x+1; xo++ { if (image.Point{xo, yo}).In(src.Rect) { sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y) } else { sum += k[i] * float64(src.At(x, y).(color.Gray).Y) } i++ } } dst.SetGray(x, y, color.Gray{uint8(math.Min(255, math.Max(0, sum)))}) } } } var blur = [9]float64{ 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9} func blurY(src *image.YCbCr) *image.YCbCr { dst := *src if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y { return &dst } srcGray := image.Gray{src.Y, src.YStride, src.Rect} dstGray := srcGray dstGray.Pix = make([]uint8, len(src.Y)) kf3(&blur, &srcGray, &dstGray) dst.Y = dstGray.Pix dst.Cb = append([]uint8{}, src.Cb...) dst.Cr = append([]uint8{}, src.Cr...) return &dst } func main() { f, err := os.Open("Lenna100.jpg") if err != nil { fmt.Println(err) return } img, err := jpeg.Decode(f) if err != nil { fmt.Println(err) return } f.Close() y, ok := img.(*image.YCbCr) if !ok { fmt.Println("expected color jpeg") return } f, err = os.Create("blur.jpg") if err != nil { fmt.Println(err) return } err = jpeg.Encode(f, blurY(y), &jpeg.Options{90}) if err != nil { fmt.Println(err) } }
from PIL import Image, ImageFilter if __name__=="__main__": im = Image.open("test.jpg") kernelValues = [-2,-1,0,-1,1,1,0,1,2] kernel = ImageFilter.Kernel((3,3), kernelValues) im2 = im.filter(kernel) im2.show()