Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func contains(a []string, s string) bool { for _, e := range a { if e == s { return true } } return false } func oneAway(a, b string) bool { sum := 0 for i := 0; i < len(a); i++ { if a[i] != b[i] { sum++ } } return sum == 1 } func wordLadder(words []string, a, b string) { l := len(a) var poss []string for _, word := range words { if len(word) == l { poss = append(poss, word) } } todo := [][]string{{a}} for len(todo) > 0 { curr := todo[0] todo = todo[1:] var next []string for _, word := range poss { if oneAway(word, curr[len(curr)-1]) { next = append(next, word) } } if contains(next, b) { curr = append(curr, b) fmt.Println(strings.Join(curr, " -> ")) return } for i := len(poss) - 1; i >= 0; i-- { if contains(next, poss[i]) { copy(poss[i:], poss[i+1:]) poss[len(poss)-1] = "" poss = poss[:len(poss)-1] } } for _, s := range next { temp := make([]string, len(curr)) copy(temp, curr) temp = append(temp, s) todo = append(todo, temp) } } fmt.Println(a, "into", b, "cannot be done.") } func main() { b, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords)) for i, bword := range bwords { words[i] = string(bword) } pairs := [][]string{ {"boy", "man"}, {"girl", "lady"}, {"john", "jane"}, {"child", "adult"}, } for _, pair := range pairs { wordLadder(words, pair[0], pair[1]) } }
import os,sys,zlib,urllib.request def h ( str,x=9 ): for c in str : x = ( x*33 + ord( c )) & 0xffffffffff return x def cache ( func,*param ): n = 'cache_%x.bin'%abs( h( repr( param ))) try : return eval( zlib.decompress( open( n,'rb' ).read())) except : pass s = func( *param ) open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' ))) return s dico_url = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt' read_url = lambda url : urllib.request.urlopen( url ).read() load_dico = lambda url : tuple( cache( read_url,url ).split( b'\n')) isnext = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1 def build_map ( words ): map = [(w.decode('ascii'),[]) for w in words] for i1,(w1,n1) in enumerate( map ): for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ): if isnext( w1,w2 ): n1.append( i2 ) n2.append( i1 ) return map def find_path ( words,w1,w2 ): i = [w[0] for w in words].index( w1 ) front,done,res = [i],{i:-1},[] while front : i = front.pop(0) word,next = words[i] for n in next : if n in done : continue done[n] = i if words[n][0] == w2 : while n >= 0 : res = [words[n][0]] + res n = done[n] return ' '.join( res ) front.append( n ) return '%s can not be turned into %s'%( w1,w2 ) for w in ('boy man','girl lady','john jane','alien drool','child adult'): print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "github.com/nsf/termbox-go" "github.com/simulatedsimian/joystick" "log" "os" "strconv" "time" ) func printAt(x, y int, s string) { for _, r := range s { termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault) x++ } } func readJoystick(js joystick.Joystick, hidden bool) { jinfo, err := js.Read() check(err) w, h := termbox.Size() tbcd := termbox.ColorDefault termbox.Clear(tbcd, tbcd) printAt(1, h-1, "q - quit") if hidden { printAt(11, h-1, "s - show buttons:") } else { bs := "" printAt(11, h-1, "h - hide buttons:") for button := 0; button < js.ButtonCount(); button++ { if jinfo.Buttons&(1<<uint32(button)) != 0 { bs += fmt.Sprintf(" %X", button+1) } } printAt(28, h-1, bs) } x := int(float64((jinfo.AxisData[0]+32767)*(w-1)) / 65535) y := int(float64((jinfo.AxisData[1]+32767)*(h-2)) / 65535) printAt(x, y, "+") termbox.Flush() } func check(err error) { if err != nil { log.Fatal(err) } } func main() { jsid := 0 if len(os.Args) > 1 { i, err := strconv.Atoi(os.Args[1]) check(err) jsid = i } js, jserr := joystick.Open(jsid) check(jserr) err := termbox.Init() check(err) defer termbox.Close() eventQueue := make(chan termbox.Event) go func() { for { eventQueue <- termbox.PollEvent() } }() ticker := time.NewTicker(time.Millisecond * 40) hidden := false for doQuit := false; !doQuit; { select { case ev := <-eventQueue: if ev.Type == termbox.EventKey { if ev.Ch == 'q' { doQuit = true } else if ev.Ch == 'h' { hidden = true } else if ev.Ch == 's' { hidden = false } } if ev.Type == termbox.EventResize { termbox.Flush() } case <-ticker.C: readJoystick(js, hidden) } } }
import sys import pygame pygame.init() clk = pygame.time.Clock() if pygame.joystick.get_count() == 0: raise IOError("No joystick detected") joy = pygame.joystick.Joystick(0) joy.init() size = width, height = 600, 600 screen = pygame.display.set_mode(size) pygame.display.set_caption("Joystick Tester") frameRect = pygame.Rect((45, 45), (510, 510)) crosshair = pygame.surface.Surface((10, 10)) crosshair.fill(pygame.Color("magenta")) pygame.draw.circle(crosshair, pygame.Color("blue"), (5,5), 5, 0) crosshair.set_colorkey(pygame.Color("magenta"), pygame.RLEACCEL) crosshair = crosshair.convert() writer = pygame.font.Font(pygame.font.get_default_font(), 15) buttons = {} for b in range(joy.get_numbuttons()): buttons[b] = [ writer.render( hex(b)[2:].upper(), 1, pygame.Color("red"), pygame.Color("black") ).convert(), ((15*b)+45, 560) ] while True: pygame.event.pump() for events in pygame.event.get(): if events.type == pygame.QUIT: pygame.quit() sys.exit() screen.fill(pygame.Color("black")) x = joy.get_axis(0) y = joy.get_axis(1) screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5)) pygame.draw.rect(screen, pygame.Color("red"), frameRect, 1) for b in range(joy.get_numbuttons()): if joy.get_button(b): screen.blit(buttons[b][0], buttons[b][1]) pygame.display.flip() clk.tick(40)
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "rcu" ) func main() { limit := int(1e9) gapStarts := make(map[int]int) primes := rcu.Primes(limit * 5) for i := 1; i < len(primes); i++ { gap := primes[i] - primes[i-1] if _, ok := gapStarts[gap]; !ok { gapStarts[gap] = primes[i-1] } } pm := 10 gap1 := 2 for { for _, ok := gapStarts[gap1]; !ok; { gap1 += 2 } start1 := gapStarts[gap1] gap2 := gap1 + 2 if _, ok := gapStarts[gap2]; !ok { gap1 = gap2 + 2 continue } start2 := gapStarts[gap2] diff := start2 - start1 if diff < 0 { diff = -diff } if diff > pm { cpm := rcu.Commatize(pm) cst1 := rcu.Commatize(start1) cst2 := rcu.Commatize(start2) cd := rcu.Commatize(diff) fmt.Printf("Earliest difference > %s between adjacent prime gap starting primes:\n", cpm) fmt.Printf("Gap %d starts at %s, gap %d starts at %s, difference is %s.\n\n", gap1, cst1, gap2, cst2, cd) if pm == limit { break } pm *= 10 } else { gap1 = gap2 } } }
from primesieve import primes LIMIT = 10**9 pri = primes(LIMIT * 5) gapstarts = {} for i in range(1, len(pri)): if pri[i] - pri[i - 1] not in gapstarts: gapstarts[pri[i] - pri[i - 1]] = pri[i - 1] PM, GAP1, = 10, 2 while True: while GAP1 not in gapstarts: GAP1 += 2 start1 = gapstarts[GAP1] GAP2 = GAP1 + 2 if GAP2 not in gapstarts: GAP1 = GAP2 + 2 continue start2 = gapstarts[GAP2] diff = abs(start2 - start1) if diff > PM: print(f"Earliest difference >{PM: ,} between adjacent prime gap starting primes:") print(f"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\n") if PM == LIMIT: break PM *= 10 else: GAP1 = GAP2
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "sort" ) type matrix [][]int func dList(n, start int) (r matrix) { start-- a := make([]int, n) for i := range a { a[i] = i } a[0], a[start] = start, a[0] sort.Ints(a[1:]) first := a[1] var recurse func(last int) recurse = func(last int) { if last == first { for j, v := range a[1:] { if j+1 == v { return } } b := make([]int, n) copy(b, a) for i := range b { b[i]++ } r = append(r, b) return } for i := last; i >= 1; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func reducedLatinSquare(n int, echo bool) uint64 { if n <= 0 { if echo { fmt.Println("[]\n") } return 0 } else if n == 1 { if echo { fmt.Println("[1]\n") } return 1 } rlatin := make(matrix, n) for i := 0; i < n; i++ { rlatin[i] = make([]int, n) } for j := 0; j < n; j++ { rlatin[0][j] = j + 1 } count := uint64(0) var recurse func(i int) recurse = func(i int) { rows := dList(n, i) outer: for r := 0; r < len(rows); r++ { copy(rlatin[i-1], rows[r]) for k := 0; k < i-1; k++ { for j := 1; j < n; j++ { if rlatin[k][j] == rlatin[i-1][j] { if r < len(rows)-1 { continue outer } else if i > 2 { return } } } } if i < n { recurse(i + 1) } else { count++ if echo { printSquare(rlatin, n) } } } return } recurse(2) return count } func printSquare(latin matrix, n int) { for i := 0; i < n; i++ { fmt.Println(latin[i]) } fmt.Println() } func factorial(n uint64) uint64 { if n == 0 { return 1 } prod := uint64(1) for i := uint64(2); i <= n; i++ { prod *= i } return prod } func main() { fmt.Println("The four reduced latin squares of order 4 are:\n") reducedLatinSquare(4, true) fmt.Println("The size of the set of reduced latin squares for the following orders") fmt.Println("and hence the total number of latin squares of these orders are:\n") for n := uint64(1); n <= 6; n++ { size := reducedLatinSquare(int(n), false) f := factorial(n - 1) f *= f * n * size fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f) } }
def dList(n, start): start -= 1 a = range(n) a[start] = a[0] a[0] = start a[1:] = sorted(a[1:]) first = a[1] r = [] def recurse(last): if (last == first): for j,v in enumerate(a[1:]): if j + 1 == v: return b = [x + 1 for x in a] r.append(b) return for i in xrange(last, 0, -1): a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] recurse(n - 1) return r def printSquare(latin,n): for row in latin: print row print def reducedLatinSquares(n,echo): if n <= 0: if echo: print [] return 0 elif n == 1: if echo: print [1] return 1 rlatin = [None] * n for i in xrange(n): rlatin[i] = [None] * n for j in xrange(0, n): rlatin[0][j] = j + 1 class OuterScope: count = 0 def recurse(i): rows = dList(n, i) for r in xrange(len(rows)): rlatin[i - 1] = rows[r] justContinue = False k = 0 while not justContinue and k < i - 1: for j in xrange(1, n): if rlatin[k][j] == rlatin[i - 1][j]: if r < len(rows) - 1: justContinue = True break if i > 2: return k += 1 if not justContinue: if i < n: recurse(i + 1) else: OuterScope.count += 1 if echo: printSquare(rlatin, n) recurse(2) return OuterScope.count def factorial(n): if n == 0: return 1 prod = 1 for i in xrange(2, n + 1): prod *= i return prod print "The four reduced latin squares of order 4 are:\n" reducedLatinSquares(4,True) print "The size of the set of reduced latin squares for the following orders" print "and hence the total number of latin squares of these orders are:\n" for n in xrange(1, 7): size = reducedLatinSquares(n, False) f = factorial(n - 1) f *= f * n * size print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f)
Write the same code in Python as shown below in Go.
package main import ( "fmt" "rcu" ) func main() { const limit = 1e9 primes := rcu.Primes(limit) var orm30 [][2]int j := int(1e5) count := 0 var counts []int for i := 0; i < len(primes)-1; i++ { p1 := primes[i] p2 := primes[i+1] if (p2-p1)%18 != 0 { continue } key1 := 1 for _, dig := range rcu.Digits(p1, 10) { key1 *= primes[dig] } key2 := 1 for _, dig := range rcu.Digits(p2, 10) { key2 *= primes[dig] } if key1 == key2 { if count < 30 { orm30 = append(orm30, [2]int{p1, p2}) } if p1 >= j { counts = append(counts, count) j *= 10 } count++ } } counts = append(counts, count) fmt.Println("First 30 Ormiston pairs:") for i := 0; i < 30; i++ { fmt.Printf("%5v ", orm30[i]) if (i+1)%3 == 0 { fmt.Println() } } fmt.Println() j = int(1e5) for i := 0; i < len(counts); i++ { fmt.Printf("%s Ormiston pairs before %s\n", rcu.Commatize(counts[i]), rcu.Commatize(j)) j *= 10 } }
from sympy import primerange PRIMES1M = list(primerange(1, 1_000_000)) ASBASE10SORT = [str(sorted(list(str(i)))) for i in PRIMES1M] ORMISTONS = [(PRIMES1M[i - 1], PRIMES1M[i]) for i in range(1, len(PRIMES1M)) if ASBASE10SORT[i - 1] == ASBASE10SORT[i]] print('First 30 Ormiston pairs:') for (i, o) in enumerate(ORMISTONS): if i < 30: print(f'({o[0] : 6} {o[1] : 6} )', end='\n' if (i + 1) % 5 == 0 else ' ') else: break print(len(ORMISTONS), 'is the count of Ormiston pairs up to one million.')
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "regexp" ) var bits = []string{ "0 0 0 1 1 0 1 ", "0 0 1 1 0 0 1 ", "0 0 1 0 0 1 1 ", "0 1 1 1 1 0 1 ", "0 1 0 0 0 1 1 ", "0 1 1 0 0 0 1 ", "0 1 0 1 1 1 1 ", "0 1 1 1 0 1 1 ", "0 1 1 0 1 1 1 ", "0 0 0 1 0 1 1 ", } var ( lhs = make(map[string]int) rhs = make(map[string]int) ) var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1} const ( s = "# #" m = " # # " e = "# #" d = "(?:#| ){7}" ) func init() { for i := 0; i <= 9; i++ { lt := make([]byte, 7) rt := make([]byte, 7) for j := 0; j < 14; j += 2 { if bits[i][j] == '1' { lt[j/2] = '#' rt[j/2] = ' ' } else { lt[j/2] = ' ' rt[j/2] = '#' } } lhs[string(lt)] = i rhs[string(rt)] = i } } func reverse(s string) string { b := []byte(s) for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } return string(b) } func main() { barcodes := []string{ " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", } expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`, s, d, d, d, d, d, d, m, d, d, d, d, d, d, e) rx := regexp.MustCompile(expr) fmt.Println("UPC-A barcodes:") for i, bc := range barcodes { for j := 0; j <= 1; j++ { if !rx.MatchString(bc) { fmt.Printf("%2d: Invalid format\n", i+1) break } codes := rx.FindStringSubmatch(bc) digits := make([]int, 12) var invalid, ok bool for i := 1; i <= 6; i++ { digits[i-1], ok = lhs[codes[i]] if !ok { invalid = true } digits[i+5], ok = rhs[codes[i+6]] if !ok { invalid = true } } if invalid { if j == 0 { bc = reverse(bc) continue } else { fmt.Printf("%2d: Invalid digit(s)\n", i+1) break } } sum := 0 for i, d := range digits { sum += weights[i] * d } if sum%10 != 0 { fmt.Printf("%2d: Checksum error\n", i+1) break } else { ud := "" if j == 1 { ud = "(upside down)" } fmt.Printf("%2d: %v %s\n", i+1, digits, ud) break } } } }
import itertools import re RE_BARCODE = re.compile( r"^(?P<s_quiet> +)" r"(?P<s_guard> r"(?P<left>[ r"(?P<m_guard> r"(?P<right>[ r"(?P<e_guard> r"(?P<e_quiet> +)$" ) LEFT_DIGITS = { (0, 0, 0, 1, 1, 0, 1): 0, (0, 0, 1, 1, 0, 0, 1): 1, (0, 0, 1, 0, 0, 1, 1): 2, (0, 1, 1, 1, 1, 0, 1): 3, (0, 1, 0, 0, 0, 1, 1): 4, (0, 1, 1, 0, 0, 0, 1): 5, (0, 1, 0, 1, 1, 1, 1): 6, (0, 1, 1, 1, 0, 1, 1): 7, (0, 1, 1, 0, 1, 1, 1): 8, (0, 0, 0, 1, 0, 1, 1): 9, } RIGHT_DIGITS = { (1, 1, 1, 0, 0, 1, 0): 0, (1, 1, 0, 0, 1, 1, 0): 1, (1, 1, 0, 1, 1, 0, 0): 2, (1, 0, 0, 0, 0, 1, 0): 3, (1, 0, 1, 1, 1, 0, 0): 4, (1, 0, 0, 1, 1, 1, 0): 5, (1, 0, 1, 0, 0, 0, 0): 6, (1, 0, 0, 0, 1, 0, 0): 7, (1, 0, 0, 1, 0, 0, 0): 8, (1, 1, 1, 0, 1, 0, 0): 9, } MODULES = { " ": 0, " } DIGITS_PER_SIDE = 6 MODULES_PER_DIGIT = 7 class ParityError(Exception): class ChecksumError(Exception): def group(iterable, n): args = [iter(iterable)] * n return tuple(itertools.zip_longest(*args)) def parse(barcode): match = RE_BARCODE.match(barcode) left = group((MODULES[c] for c in match.group("left")), MODULES_PER_DIGIT) right = group((MODULES[c] for c in match.group("right")), MODULES_PER_DIGIT) left, right = check_parity(left, right) return tuple( itertools.chain( (LEFT_DIGITS[d] for d in left), (RIGHT_DIGITS[d] for d in right), ) ) def check_parity(left, right): left_parity = sum(sum(d) % 2 for d in left) right_parity = sum(sum(d) % 2 for d in right) if left_parity == 0 and right_parity == DIGITS_PER_SIDE: _left = tuple(tuple(reversed(d)) for d in reversed(right)) right = tuple(tuple(reversed(d)) for d in reversed(left)) left = _left elif left_parity != DIGITS_PER_SIDE or right_parity != 0: error = tuple( itertools.chain( (LEFT_DIGITS.get(d, "_") for d in left), (RIGHT_DIGITS.get(d, "_") for d in right), ) ) raise ParityError(" ".join(str(d) for d in error)) return left, right def checksum(digits): odds = (digits[i] for i in range(0, 11, 2)) evens = (digits[i] for i in range(1, 10, 2)) check_digit = (sum(odds) * 3 + sum(evens)) % 10 if check_digit != 0: check_digit = 10 - check_digit if digits[-1] != check_digit: raise ChecksumError(str(check_digit)) return check_digit def main(): barcodes = [ " " " " " " " " " " " ] for barcode in barcodes: try: digits = parse(barcode) except ParityError as err: print(f"{err} parity error!") continue try: check_digit = checksum(digits) except ChecksumError as err: print(f"{' '.join(str(d) for d in digits)} checksum error! ({err})") continue print(f"{' '.join(str(d) for d in digits)}") if __name__ == "__main__": main()
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ { used[16] = true } else { used[9] = true } alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i, j, k := 0, 0, 0; k < len(alphabet); k++ { c := alphabet[k] if c < 'A' || c > 'Z' { continue } d := int(c - 65) if !used[d] { p.table[i][j] = c used[d] = true j++ if j == 5 { i++ if i == 5 { break } j = 0 } } } } func (p *playfair) getCleanText(plainText string) string { plainText = strings.ToUpper(plainText) var cleanText strings.Builder prevByte := byte('\000') for i := 0; i < len(plainText); i++ { nextByte := plainText[i] if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) { continue } if nextByte == 'J' && p.pfo == iEqualsJ { nextByte = 'I' } if nextByte != prevByte { cleanText.WriteByte(nextByte) } else { cleanText.WriteByte('X') cleanText.WriteByte(nextByte) } prevByte = nextByte } l := cleanText.Len() if l%2 == 1 { if cleanText.String()[l-1] != 'X' { cleanText.WriteByte('X') } else { cleanText.WriteByte('Z') } } return cleanText.String() } func (p *playfair) findByte(c byte) (int, int) { for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { if p.table[i][j] == c { return i, j } } } return -1, -1 } func (p *playfair) encode(plainText string) string { cleanText := p.getCleanText(plainText) var cipherText strings.Builder l := len(cleanText) for i := 0; i < l; i += 2 { row1, col1 := p.findByte(cleanText[i]) row2, col2 := p.findByte(cleanText[i+1]) switch { case row1 == row2: cipherText.WriteByte(p.table[row1][(col1+1)%5]) cipherText.WriteByte(p.table[row2][(col2+1)%5]) case col1 == col2: cipherText.WriteByte(p.table[(row1+1)%5][col1]) cipherText.WriteByte(p.table[(row2+1)%5][col2]) default: cipherText.WriteByte(p.table[row1][col2]) cipherText.WriteByte(p.table[row2][col1]) } if i < l-1 { cipherText.WriteByte(' ') } } return cipherText.String() } func (p *playfair) decode(cipherText string) string { var decodedText strings.Builder l := len(cipherText) for i := 0; i < l; i += 3 { row1, col1 := p.findByte(cipherText[i]) row2, col2 := p.findByte(cipherText[i+1]) switch { case row1 == row2: temp := 4 if col1 > 0 { temp = col1 - 1 } decodedText.WriteByte(p.table[row1][temp]) temp = 4 if col2 > 0 { temp = col2 - 1 } decodedText.WriteByte(p.table[row2][temp]) case col1 == col2: temp := 4 if row1 > 0 { temp = row1 - 1 } decodedText.WriteByte(p.table[temp][col1]) temp = 4 if row2 > 0 { temp = row2 - 1 } decodedText.WriteByte(p.table[temp][col2]) default: decodedText.WriteByte(p.table[row1][col2]) decodedText.WriteByte(p.table[row2][col1]) } if i < l-1 { decodedText.WriteByte(' ') } } return decodedText.String() } func (p *playfair) printTable() { fmt.Println("The table to be used is :\n") for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { fmt.Printf("%c ", p.table[i][j]) } fmt.Println() } } func main() { scanner := bufio.NewScanner(os.Stdin) fmt.Print("Enter Playfair keyword : ") scanner.Scan() keyword := scanner.Text() var ignoreQ string for ignoreQ != "y" && ignoreQ != "n" { fmt.Print("Ignore Q when building table y/n : ") scanner.Scan() ignoreQ = strings.ToLower(scanner.Text()) } pfo := noQ if ignoreQ == "n" { pfo = iEqualsJ } var table [5][5]byte pf := &playfair{keyword, pfo, table} pf.init() pf.printTable() fmt.Print("\nEnter plain text : ") scanner.Scan() plainText := scanner.Text() if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) return } encodedText := pf.encode(plainText) fmt.Println("\nEncoded text is :", encodedText) decodedText := pf.decode(encodedText) fmt.Println("Deccoded text is :", decodedText) }
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if to is None: to = 'I' if from_ == 'J' else '' def canonicalize(s): return filter(str.isupper, s.upper()).replace(from_, to) m = partition(uniq(canonicalize(key + ascii_uppercase)), 5) enc = {} for row in m: for i, j in product(xrange(5), repeat=2): if i != j: enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5] for c in zip(*m): for i, j in product(xrange(5), repeat=2): if i != j: enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5] for i1, j1, i2, j2 in product(xrange(5), repeat=4): if i1 != i2 and j1 != j2: enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1] dec = dict((v, k) for k, v in enc.iteritems()) def sub_enc(txt): lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt)) return " ".join(enc[a + (b if b else 'X')] for a, b in lst) def sub_dec(encoded): return " ".join(dec[p] for p in partition(canonicalize(encoded), 2)) return sub_enc, sub_dec (encode, decode) = playfair("Playfair example") orig = "Hide the gold in...the TREESTUMP!!!" print "Original:", orig enc = encode(orig) print "Encoded:", enc print "Decoded:", decode(enc)
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ { used[16] = true } else { used[9] = true } alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i, j, k := 0, 0, 0; k < len(alphabet); k++ { c := alphabet[k] if c < 'A' || c > 'Z' { continue } d := int(c - 65) if !used[d] { p.table[i][j] = c used[d] = true j++ if j == 5 { i++ if i == 5 { break } j = 0 } } } } func (p *playfair) getCleanText(plainText string) string { plainText = strings.ToUpper(plainText) var cleanText strings.Builder prevByte := byte('\000') for i := 0; i < len(plainText); i++ { nextByte := plainText[i] if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) { continue } if nextByte == 'J' && p.pfo == iEqualsJ { nextByte = 'I' } if nextByte != prevByte { cleanText.WriteByte(nextByte) } else { cleanText.WriteByte('X') cleanText.WriteByte(nextByte) } prevByte = nextByte } l := cleanText.Len() if l%2 == 1 { if cleanText.String()[l-1] != 'X' { cleanText.WriteByte('X') } else { cleanText.WriteByte('Z') } } return cleanText.String() } func (p *playfair) findByte(c byte) (int, int) { for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { if p.table[i][j] == c { return i, j } } } return -1, -1 } func (p *playfair) encode(plainText string) string { cleanText := p.getCleanText(plainText) var cipherText strings.Builder l := len(cleanText) for i := 0; i < l; i += 2 { row1, col1 := p.findByte(cleanText[i]) row2, col2 := p.findByte(cleanText[i+1]) switch { case row1 == row2: cipherText.WriteByte(p.table[row1][(col1+1)%5]) cipherText.WriteByte(p.table[row2][(col2+1)%5]) case col1 == col2: cipherText.WriteByte(p.table[(row1+1)%5][col1]) cipherText.WriteByte(p.table[(row2+1)%5][col2]) default: cipherText.WriteByte(p.table[row1][col2]) cipherText.WriteByte(p.table[row2][col1]) } if i < l-1 { cipherText.WriteByte(' ') } } return cipherText.String() } func (p *playfair) decode(cipherText string) string { var decodedText strings.Builder l := len(cipherText) for i := 0; i < l; i += 3 { row1, col1 := p.findByte(cipherText[i]) row2, col2 := p.findByte(cipherText[i+1]) switch { case row1 == row2: temp := 4 if col1 > 0 { temp = col1 - 1 } decodedText.WriteByte(p.table[row1][temp]) temp = 4 if col2 > 0 { temp = col2 - 1 } decodedText.WriteByte(p.table[row2][temp]) case col1 == col2: temp := 4 if row1 > 0 { temp = row1 - 1 } decodedText.WriteByte(p.table[temp][col1]) temp = 4 if row2 > 0 { temp = row2 - 1 } decodedText.WriteByte(p.table[temp][col2]) default: decodedText.WriteByte(p.table[row1][col2]) decodedText.WriteByte(p.table[row2][col1]) } if i < l-1 { decodedText.WriteByte(' ') } } return decodedText.String() } func (p *playfair) printTable() { fmt.Println("The table to be used is :\n") for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { fmt.Printf("%c ", p.table[i][j]) } fmt.Println() } } func main() { scanner := bufio.NewScanner(os.Stdin) fmt.Print("Enter Playfair keyword : ") scanner.Scan() keyword := scanner.Text() var ignoreQ string for ignoreQ != "y" && ignoreQ != "n" { fmt.Print("Ignore Q when building table y/n : ") scanner.Scan() ignoreQ = strings.ToLower(scanner.Text()) } pfo := noQ if ignoreQ == "n" { pfo = iEqualsJ } var table [5][5]byte pf := &playfair{keyword, pfo, table} pf.init() pf.printTable() fmt.Print("\nEnter plain text : ") scanner.Scan() plainText := scanner.Text() if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) return } encodedText := pf.encode(plainText) fmt.Println("\nEncoded text is :", encodedText) decodedText := pf.decode(encodedText) fmt.Println("Deccoded text is :", decodedText) }
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if to is None: to = 'I' if from_ == 'J' else '' def canonicalize(s): return filter(str.isupper, s.upper()).replace(from_, to) m = partition(uniq(canonicalize(key + ascii_uppercase)), 5) enc = {} for row in m: for i, j in product(xrange(5), repeat=2): if i != j: enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5] for c in zip(*m): for i, j in product(xrange(5), repeat=2): if i != j: enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5] for i1, j1, i2, j2 in product(xrange(5), repeat=4): if i1 != i2 and j1 != j2: enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1] dec = dict((v, k) for k, v in enc.iteritems()) def sub_enc(txt): lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt)) return " ".join(enc[a + (b if b else 'X')] for a, b in lst) def sub_dec(encoded): return " ".join(dec[p] for p in partition(canonicalize(encoded), 2)) return sub_enc, sub_dec (encode, decode) = playfair("Playfair example") orig = "Hide the gold in...the TREESTUMP!!!" print "Original:", orig enc = encode(orig) print "Encoded:", enc print "Decoded:", decode(enc)
Write the same code in Python as shown below in Go.
package main import ( "fmt" "math/big" ) func harmonic(n int) *big.Rat { sum := new(big.Rat) for i := int64(1); i <= int64(n); i++ { r := big.NewRat(1, i) sum.Add(sum, r) } return sum } func main() { fmt.Println("The first 20 harmonic numbers and the 100th, expressed in rational form, are:") numbers := make([]int, 21) for i := 1; i <= 20; i++ { numbers[i-1] = i } numbers[20] = 100 for _, i := range numbers { fmt.Printf("%3d : %s\n", i, harmonic(i)) } fmt.Println("\nThe first harmonic number to exceed the following integers is:") const limit = 10 for i, n, h := 1, 1, 0.0; i <= limit; n++ { h += 1.0 / float64(n) if h > float64(i) { fmt.Printf("integer = %2d -> n = %6d -> harmonic number = %9.6f (to 6dp)\n", i, n, h) i++ } } }
from fractions import Fraction def harmonic_series(): n, h = Fraction(1), Fraction(1) while True: yield h h += 1 / (n + 1) n += 1 if __name__ == '__main__': from itertools import islice for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)): print(n, '/', d)
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "io" "log" "math" "math/rand" "os" "time" ) type MinHeapNode struct{ element, index int } type MinHeap struct{ nodes []MinHeapNode } func left(i int) int { return (2*i + 1) } func right(i int) int { return (2*i + 2) } func newMinHeap(nodes []MinHeapNode) *MinHeap { mh := new(MinHeap) mh.nodes = nodes for i := (len(nodes) - 1) / 2; i >= 0; i-- { mh.minHeapify(i) } return mh } func (mh *MinHeap) getMin() MinHeapNode { return mh.nodes[0] } func (mh *MinHeap) replaceMin(x MinHeapNode) { mh.nodes[0] = x mh.minHeapify(0) } func (mh *MinHeap) minHeapify(i int) { l, r := left(i), right(i) smallest := i heapSize := len(mh.nodes) if l < heapSize && mh.nodes[l].element < mh.nodes[i].element { smallest = l } if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element { smallest = r } if smallest != i { mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i] mh.minHeapify(smallest) } } func merge(arr []int, l, m, r int) { n1, n2 := m-l+1, r-m tl := make([]int, n1) tr := make([]int, n2) copy(tl, arr[l:]) copy(tr, arr[m+1:]) i, j, k := 0, 0, l for i < n1 && j < n2 { if tl[i] <= tr[j] { arr[k] = tl[i] k++ i++ } else { arr[k] = tr[j] k++ j++ } } for i < n1 { arr[k] = tl[i] k++ i++ } for j < n2 { arr[k] = tr[j] k++ j++ } } func mergeSort(arr []int, l, r int) { if l < r { m := l + (r-l)/2 mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r) } } func mergeFiles(outputFile string, n, k int) { in := make([]*os.File, k) var err error for i := 0; i < k; i++ { fileName := fmt.Sprintf("es%d", i) in[i], err = os.Open(fileName) check(err) } out, err := os.Create(outputFile) check(err) nodes := make([]MinHeapNode, k) i := 0 for ; i < k; i++ { _, err = fmt.Fscanf(in[i], "%d", &nodes[i].element) if err == io.EOF { break } check(err) nodes[i].index = i } hp := newMinHeap(nodes[:i]) count := 0 for count != i { root := hp.getMin() fmt.Fprintf(out, "%d ", root.element) _, err = fmt.Fscanf(in[root.index], "%d", &root.element) if err == io.EOF { root.element = math.MaxInt32 count++ } else { check(err) } hp.replaceMin(root) } for j := 0; j < k; j++ { in[j].Close() } out.Close() } func check(err error) { if err != nil { log.Fatal(err) } } func createInitialRuns(inputFile string, runSize, numWays int) { in, err := os.Open(inputFile) out := make([]*os.File, numWays) for i := 0; i < numWays; i++ { fileName := fmt.Sprintf("es%d", i) out[i], err = os.Create(fileName) check(err) } arr := make([]int, runSize) moreInput := true nextOutputFile := 0 var i int for moreInput { for i = 0; i < runSize; i++ { _, err := fmt.Fscanf(in, "%d", &arr[i]) if err == io.EOF { moreInput = false break } check(err) } mergeSort(arr, 0, i-1) for j := 0; j < i; j++ { fmt.Fprintf(out[nextOutputFile], "%d ", arr[j]) } nextOutputFile++ } for j := 0; j < numWays; j++ { out[j].Close() } in.Close() } func externalSort(inputFile, outputFile string, numWays, runSize int) { createInitialRuns(inputFile, runSize, numWays) mergeFiles(outputFile, runSize, numWays) } func main() { numWays := 4 runSize := 10 inputFile := "input.txt" outputFile := "output.txt" in, err := os.Create(inputFile) check(err) rand.Seed(time.Now().UnixNano()) for i := 0; i < numWays*runSize; i++ { fmt.Fprintf(in, "%d ", rand.Intn(math.MaxInt32)) } in.Close() externalSort(inputFile, outputFile, numWays, runSize) for i := 0; i < numWays; i++ { fileName := fmt.Sprintf("es%d", i) err = os.Remove(fileName) check(err) } }
import io def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None: mergers = [] while True: text = list(source.read(n)) if not len(text): break; text.sort() merge_me = file_opener() merge_me.write(''.join(text)) mergers.append(merge_me) merge_me.seek(0) stack_tops = [f.read(1) for f in mergers] while stack_tops: c = min(stack_tops) sink.write(c) i = stack_tops.index(c) t = mergers[i].read(1) if t: stack_tops[i] = t else: del stack_tops[i] mergers[i].close() del mergers[i] def main(): input_file_too_large_for_memory = io.StringIO('678925341') t = list(input_file_too_large_for_memory.read()) t.sort() expect = ''.join(t) print('expect', expect) for memory_size in range(1,12): input_file_too_large_for_memory.seek(0) output_file_too_large_for_memory = io.StringIO() sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO) output_file_too_large_for_memory.seek(0) assert(output_file_too_large_for_memory.read() == expect) print('memory size {} passed'.format(memory_size)) if __name__ == '__main__': example = main example()
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "io" "log" "math" "math/rand" "os" "time" ) type MinHeapNode struct{ element, index int } type MinHeap struct{ nodes []MinHeapNode } func left(i int) int { return (2*i + 1) } func right(i int) int { return (2*i + 2) } func newMinHeap(nodes []MinHeapNode) *MinHeap { mh := new(MinHeap) mh.nodes = nodes for i := (len(nodes) - 1) / 2; i >= 0; i-- { mh.minHeapify(i) } return mh } func (mh *MinHeap) getMin() MinHeapNode { return mh.nodes[0] } func (mh *MinHeap) replaceMin(x MinHeapNode) { mh.nodes[0] = x mh.minHeapify(0) } func (mh *MinHeap) minHeapify(i int) { l, r := left(i), right(i) smallest := i heapSize := len(mh.nodes) if l < heapSize && mh.nodes[l].element < mh.nodes[i].element { smallest = l } if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element { smallest = r } if smallest != i { mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i] mh.minHeapify(smallest) } } func merge(arr []int, l, m, r int) { n1, n2 := m-l+1, r-m tl := make([]int, n1) tr := make([]int, n2) copy(tl, arr[l:]) copy(tr, arr[m+1:]) i, j, k := 0, 0, l for i < n1 && j < n2 { if tl[i] <= tr[j] { arr[k] = tl[i] k++ i++ } else { arr[k] = tr[j] k++ j++ } } for i < n1 { arr[k] = tl[i] k++ i++ } for j < n2 { arr[k] = tr[j] k++ j++ } } func mergeSort(arr []int, l, r int) { if l < r { m := l + (r-l)/2 mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r) } } func mergeFiles(outputFile string, n, k int) { in := make([]*os.File, k) var err error for i := 0; i < k; i++ { fileName := fmt.Sprintf("es%d", i) in[i], err = os.Open(fileName) check(err) } out, err := os.Create(outputFile) check(err) nodes := make([]MinHeapNode, k) i := 0 for ; i < k; i++ { _, err = fmt.Fscanf(in[i], "%d", &nodes[i].element) if err == io.EOF { break } check(err) nodes[i].index = i } hp := newMinHeap(nodes[:i]) count := 0 for count != i { root := hp.getMin() fmt.Fprintf(out, "%d ", root.element) _, err = fmt.Fscanf(in[root.index], "%d", &root.element) if err == io.EOF { root.element = math.MaxInt32 count++ } else { check(err) } hp.replaceMin(root) } for j := 0; j < k; j++ { in[j].Close() } out.Close() } func check(err error) { if err != nil { log.Fatal(err) } } func createInitialRuns(inputFile string, runSize, numWays int) { in, err := os.Open(inputFile) out := make([]*os.File, numWays) for i := 0; i < numWays; i++ { fileName := fmt.Sprintf("es%d", i) out[i], err = os.Create(fileName) check(err) } arr := make([]int, runSize) moreInput := true nextOutputFile := 0 var i int for moreInput { for i = 0; i < runSize; i++ { _, err := fmt.Fscanf(in, "%d", &arr[i]) if err == io.EOF { moreInput = false break } check(err) } mergeSort(arr, 0, i-1) for j := 0; j < i; j++ { fmt.Fprintf(out[nextOutputFile], "%d ", arr[j]) } nextOutputFile++ } for j := 0; j < numWays; j++ { out[j].Close() } in.Close() } func externalSort(inputFile, outputFile string, numWays, runSize int) { createInitialRuns(inputFile, runSize, numWays) mergeFiles(outputFile, runSize, numWays) } func main() { numWays := 4 runSize := 10 inputFile := "input.txt" outputFile := "output.txt" in, err := os.Create(inputFile) check(err) rand.Seed(time.Now().UnixNano()) for i := 0; i < numWays*runSize; i++ { fmt.Fprintf(in, "%d ", rand.Intn(math.MaxInt32)) } in.Close() externalSort(inputFile, outputFile, numWays, runSize) for i := 0; i < numWays; i++ { fileName := fmt.Sprintf("es%d", i) err = os.Remove(fileName) check(err) } }
import io def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None: mergers = [] while True: text = list(source.read(n)) if not len(text): break; text.sort() merge_me = file_opener() merge_me.write(''.join(text)) mergers.append(merge_me) merge_me.seek(0) stack_tops = [f.read(1) for f in mergers] while stack_tops: c = min(stack_tops) sink.write(c) i = stack_tops.index(c) t = mergers[i].read(1) if t: stack_tops[i] = t else: del stack_tops[i] mergers[i].close() del mergers[i] def main(): input_file_too_large_for_memory = io.StringIO('678925341') t = list(input_file_too_large_for_memory.read()) t.sort() expect = ''.join(t) print('expect', expect) for memory_size in range(1,12): input_file_too_large_for_memory.seek(0) output_file_too_large_for_memory = io.StringIO() sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO) output_file_too_large_for_memory.seek(0) assert(output_file_too_large_for_memory.read() == expect) print('memory size {} passed'.format(memory_size)) if __name__ == '__main__': example = main example()
Preserve the algorithm and functionality while converting the code from Go to Python.
package cf type NG4 struct { A1, A int64 B1, B int64 } func (ng NG4) needsIngest() bool { if ng.isDone() { panic("b₁==b==0") } return ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B } func (ng NG4) isDone() bool { return ng.B1 == 0 && ng.B == 0 } func (ng *NG4) ingest(t int64) { ng.A1, ng.A, ng.B1, ng.B = ng.A+ng.A1*t, ng.A1, ng.B+ng.B1*t, ng.B1 } func (ng *NG4) ingestInfinite() { ng.A, ng.B = ng.A1, ng.B1 } func (ng *NG4) egest(t int64) { ng.A1, ng.A, ng.B1, ng.B = ng.B1, ng.B, ng.A1-ng.B1*t, ng.A-ng.B*t } func (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction { return func() NextFn { next := cf() done := false return func() (int64, bool) { if done { return 0, false } for ng.needsIngest() { if t, ok := next(); ok { ng.ingest(t) } else { ng.ingestInfinite() } } t := ng.A1 / ng.B1 ng.egest(t) done = ng.isDone() return t, true } } }
class NG: def __init__(self, a1, a, b1, b): self.a1, self.a, self.b1, self.b = a1, a, b1, b def ingress(self, n): self.a, self.a1 = self.a1, self.a + self.a1 * n self.b, self.b1 = self.b1, self.b + self.b1 * n @property def needterm(self): return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1 @property def egress(self): n = self.a // self.b self.a, self.b = self.b, self.a - self.b * n self.a1, self.b1 = self.b1, self.a1 - self.b1 * n return n @property def egress_done(self): if self.needterm: self.a, self.b = self.a1, self.b1 return self.egress @property def done(self): return self.b == 0 and self.b1 == 0
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) func calkinWilf(n int) []*big.Rat { cw := make([]*big.Rat, n+1) cw[0] = big.NewRat(1, 1) one := big.NewRat(1, 1) two := big.NewRat(2, 1) for i := 1; i < n; i++ { t := new(big.Rat).Set(cw[i-1]) f, _ := t.Float64() f = math.Floor(f) t.SetFloat64(f) t.Mul(t, two) t.Sub(t, cw[i-1]) t.Add(t, one) t.Inv(t) cw[i] = new(big.Rat).Set(t) } return cw } func toContinued(r *big.Rat) []int { a := r.Num().Int64() b := r.Denom().Int64() var res []int for { res = append(res, int(a/b)) t := a % b a, b = b, t if a == 1 { break } } le := len(res) if le%2 == 0 { res[le-1]-- res = append(res, 1) } return res } func getTermNumber(cf []int) int { b := "" d := "1" for _, n := range cf { b = strings.Repeat(d, n) + b if d == "1" { d = "0" } else { d = "1" } } i, _ := strconv.ParseInt(b, 2, 64) return int(i) } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { cw := calkinWilf(20) fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:") for i := 1; i <= 20; i++ { fmt.Printf("%2d: %s\n", i, cw[i-1].RatString()) } fmt.Println() r := big.NewRat(83116, 51639) cf := toContinued(r) tn := getTermNumber(cf) fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn)) }
from fractions import Fraction from math import floor from itertools import islice, groupby def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a) def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = den, divmod(num, den) yield digit def get_term_num(rational): ans, dig, pwr = 0, 1, 0 for n in r2cf(rational): for _ in range(n): ans |= dig << pwr pwr += 1 dig ^= 1 return ans if __name__ == '__main__': print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20))) x = Fraction(83116, 51639) print(f"\n{x} is the {get_term_num(x):_}'th term.")
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) func calkinWilf(n int) []*big.Rat { cw := make([]*big.Rat, n+1) cw[0] = big.NewRat(1, 1) one := big.NewRat(1, 1) two := big.NewRat(2, 1) for i := 1; i < n; i++ { t := new(big.Rat).Set(cw[i-1]) f, _ := t.Float64() f = math.Floor(f) t.SetFloat64(f) t.Mul(t, two) t.Sub(t, cw[i-1]) t.Add(t, one) t.Inv(t) cw[i] = new(big.Rat).Set(t) } return cw } func toContinued(r *big.Rat) []int { a := r.Num().Int64() b := r.Denom().Int64() var res []int for { res = append(res, int(a/b)) t := a % b a, b = b, t if a == 1 { break } } le := len(res) if le%2 == 0 { res[le-1]-- res = append(res, 1) } return res } func getTermNumber(cf []int) int { b := "" d := "1" for _, n := range cf { b = strings.Repeat(d, n) + b if d == "1" { d = "0" } else { d = "1" } } i, _ := strconv.ParseInt(b, 2, 64) return int(i) } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { cw := calkinWilf(20) fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:") for i := 1; i <= 20; i++ { fmt.Printf("%2d: %s\n", i, cw[i-1].RatString()) } fmt.Println() r := big.NewRat(83116, 51639) cf := toContinued(r) tn := getTermNumber(cf) fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn)) }
from fractions import Fraction from math import floor from itertools import islice, groupby def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a) def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = den, divmod(num, den) yield digit def get_term_num(rational): ans, dig, pwr = 0, 1, 0 for n in r2cf(rational): for _ in range(n): ans |= dig << pwr pwr += 1 dig ^= 1 return ans if __name__ == '__main__': print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20))) x = Fraction(83116, 51639) print(f"\n{x} is the {get_term_num(x):_}'th term.")
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" ) func main() { fact := big.NewInt(1) sum := 0.0 first := int64(0) firstRatio := 0.0 fmt.Println("The mean proportion of zero digits in factorials up to the following are:") for n := int64(1); n <= 50000; n++ { fact.Mul(fact, big.NewInt(n)) bytes := []byte(fact.String()) digits := len(bytes) zeros := 0 for _, b := range bytes { if b == '0' { zeros++ } } sum += float64(zeros)/float64(digits) ratio := sum / float64(n) if n == 100 || n == 1000 || n == 10000 { fmt.Printf("%6s = %12.10f\n", rcu.Commatize(int(n)), ratio) } if first > 0 && ratio >= 0.16 { first = 0 firstRatio = 0.0 } else if first == 0 && ratio < 0.16 { first = n firstRatio = ratio } } fmt.Printf("%6s = %12.10f", rcu.Commatize(int(first)), firstRatio) fmt.Println(" (stays below 0.16 after this)") fmt.Printf("%6s = %12.10f\n", "50,000", sum / 50000) }
def facpropzeros(N, verbose = True): proportions = [0.0] * N fac, psum = 1, 0.0 for i in range(N): fac *= i + 1 d = list(str(fac)) psum += sum(map(lambda x: x == '0', d)) / len(d) proportions[i] = psum / (i + 1) if verbose: print("The mean proportion of 0 in factorials from 1 to {} is {}.".format(N, psum / N)) return proportions for n in [100, 1000, 10000]: facpropzeros(n) props = facpropzeros(47500, False) n = (next(i for i in reversed(range(len(props))) if props[i] > 0.16)) print("The mean proportion dips permanently below 0.16 at {}.".format(n + 2))
Write the same code in Python as shown below in Go.
package main import ( "fmt" "math" "math/rand" "time" ) type xy struct { x, y float64 } const n = 1000 const scale = 100. func d(p1, p2 xy) float64 { return math.Hypot(p2.x-p1.x, p2.y-p1.y) } func main() { rand.Seed(time.Now().Unix()) points := make([]xy, n) for i := range points { points[i] = xy{rand.Float64() * scale, rand.Float64() * scale} } p1, p2 := closestPair(points) fmt.Println(p1, p2) fmt.Println("distance:", d(p1, p2)) } func closestPair(points []xy) (p1, p2 xy) { if len(points) < 2 { panic("at least two points expected") } min := 2 * scale for i, q1 := range points[:len(points)-1] { for _, q2 := range points[i+1:] { if dq := d(q1, q2); dq < min { p1, p2 = q1, q2 min = dq } } } return }
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for i in range(numPoints-1) for j in range(i+1,numPoints)), key=itemgetter(0)) def closestPair(point): xP = sorted(point, key= attrgetter('real')) yP = sorted(point, key= attrgetter('imag')) return _closestPair(xP, yP) def _closestPair(xP, yP): numPoints = len(xP) if numPoints <= 3: return bruteForceClosestPair(xP) Pl = xP[:numPoints/2] Pr = xP[numPoints/2:] Yl, Yr = [], [] xDivider = Pl[-1].real for p in yP: if p.real <= xDivider: Yl.append(p) else: Yr.append(p) dl, pairl = _closestPair(Pl, Yl) dr, pairr = _closestPair(Pr, Yr) dm, pairm = (dl, pairl) if dl < dr else (dr, pairr) closeY = [p for p in yP if abs(p.real - xDivider) < dm] numCloseY = len(closeY) if numCloseY > 1: closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j])) for i in range(numCloseY-1) for j in range(i+1,min(i+8, numCloseY))), key=itemgetter(0)) return (dm, pairm) if dm <= closestY[0] else closestY else: return dm, pairm def times(): import timeit functions = [bruteForceClosestPair, closestPair] for f in functions: print 'Time for', f.__name__, timeit.Timer( '%s(pointList)' % f.__name__, 'from closestpair import %s, pointList' % f.__name__).timeit(number=1) pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)] if __name__ == '__main__': pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)] print pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) for i in range(10): pointList = [randrange(11)+1j*randrange(11) for i in range(10)] print '\n', pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) print '\n' times() times() times()
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "unsafe" ) func main() { myVar := 3.14 myPointer := &myVar fmt.Println("Address:", myPointer, &myVar) fmt.Printf("Address: %p %p\n", myPointer, &myVar) var addr64 int64 var addr32 int32 ptr := unsafe.Pointer(myPointer) if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) { addr64 = int64(uintptr(ptr)) fmt.Printf("Pointer stored in int64: %#016x\n", addr64) } if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) { addr32 = int32(uintptr(ptr)) fmt.Printf("Pointer stored in int32: %#08x\n", addr32) } addr := uintptr(ptr) fmt.Printf("Pointer stored in uintptr: %#08x\n", addr) fmt.Println("value as float:", myVar) i := (*int32)(unsafe.Pointer(&myVar)) fmt.Printf("value as int32: %#08x\n", *i) }
var num = 12 var pointer = ptr(num) print pointer @unsafe pointer.addr = 0xFFFE
Please provide an equivalent version of this Go code in Python.
package main type animal struct { alive bool } type dog struct { animal obedienceTrained bool } type cat struct { animal litterBoxTrained bool } type lab struct { dog color string } type collie struct { dog catchesFrisbee bool } func main() { var pet lab pet.alive = true pet.obedienceTrained = false pet.color = "yellow" }
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass class Lab(Dog): pass class Collie(Dog): pass
Port the following code from Go to Python with equivalent syntax and logic.
var x map[string]int x = make(map[string]int) x = make(map[string]int, 42) x["foo"] = 3 y1 := x["bar"] y2, ok := x["bar"] delete(x, "foo") x = map[string]int{ "foo": 2, "bar": 42, "baz": -1, }
hash = dict() hash = dict(red="FF0000", green="00FF00", blue="0000FF") hash = { 'key1':1, 'key2':2, } value = hash[key]
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "github.com/fogleman/gg" "math" ) const tau = 2 * math.Pi func hsb2rgb(hue, sat, bri float64) (r, g, b int) { u := int(bri*255 + 0.5) if sat == 0 { r, g, b = u, u, u } else { h := (hue - math.Floor(hue)) * 6 f := h - math.Floor(h) p := int(bri*(1-sat)*255 + 0.5) q := int(bri*(1-sat*f)*255 + 0.5) t := int(bri*(1-sat*(1-f))*255 + 0.5) switch int(h) { case 0: r, g, b = u, t, p case 1: r, g, b = q, u, p case 2: r, g, b = p, u, t case 3: r, g, b = p, q, u case 4: r, g, b = t, p, u case 5: r, g, b = u, p, q } } return } func colorWheel(dc *gg.Context) { width, height := dc.Width(), dc.Height() centerX, centerY := width/2, height/2 radius := centerX if centerY < radius { radius = centerY } for y := 0; y < height; y++ { dy := float64(y - centerY) for x := 0; x < width; x++ { dx := float64(x - centerX) dist := math.Sqrt(dx*dx + dy*dy) if dist <= float64(radius) { theta := math.Atan2(dy, dx) hue := (theta + math.Pi) / tau r, g, b := hsb2rgb(hue, 1, 1) dc.SetRGB255(r, g, b) dc.SetPixel(x, y) } } } } func main() { const width, height = 480, 480 dc := gg.NewContext(width, height) dc.SetRGB(1, 1, 1) dc.Clear() colorWheel(dc) dc.SavePNG("color_wheel.png") }
size(300, 300) background(0) radius = min(width, height) / 2.0 cx, cy = width / 2, width / 2 for x in range(width): for y in range(height): rx = x - cx ry = y - cy s = sqrt(rx ** 2 + ry ** 2) / radius if s <= 1.0: h = ((atan2(ry, rx) / PI) + 1.0) / 2.0 colorMode(HSB) c = color(int(h * 255), int(s * 255), 255) set(x, y, c)
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "image" "image/color" "image/gif" "log" "math" "os" ) func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) { for x := 0; x < w; x++ { for y := 0; y < h; y++ { img.SetColorIndex(x, y, ci) } } } func hsb2rgb(hue, sat, bri float64) (r, g, b int) { u := int(bri*255 + 0.5) if sat == 0 { r, g, b = u, u, u } else { h := (hue - math.Floor(hue)) * 6 f := h - math.Floor(h) p := int(bri*(1-sat)*255 + 0.5) q := int(bri*(1-sat*f)*255 + 0.5) t := int(bri*(1-sat*(1-f))*255 + 0.5) switch int(h) { case 0: r, g, b = u, t, p case 1: r, g, b = q, u, p case 2: r, g, b = p, u, t case 3: r, g, b = p, q, u case 4: r, g, b = t, p, u case 5: r, g, b = u, p, q } } return } func main() { const degToRad = math.Pi / 180 const nframes = 100 const delay = 4 w, h := 640, 640 anim := gif.GIF{LoopCount: nframes} rect := image.Rect(0, 0, w, h) palette := make([]color.Color, nframes+1) palette[0] = color.White for i := 1; i <= nframes; i++ { r, g, b := hsb2rgb(float64(i)/nframes, 1, 1) palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255} } for f := 1; f <= nframes; f++ { img := image.NewPaletted(rect, palette) setBackgroundColor(img, w, h, 0) for y := 0; y < h; y++ { for x := 0; x < w; x++ { fx, fy := float64(x), float64(y) value := math.Sin(fx / 16) value += math.Sin(fy / 8) value += math.Sin((fx + fy) / 16) value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8) value += 4 value /= 8 _, rem := math.Modf(value + float64(f)/float64(nframes)) ci := uint8(nframes*rem) + 1 img.SetColorIndex(x, y, ci) } } anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } file, err := os.Create("plasma.gif") if err != nil { log.Fatal(err) } defer file.Close() if err2 := gif.EncodeAll(file, &anim); err != nil { log.Fatal(err2) } }
pal = [0] * 128 r = 42 g = 84 b = 126 rd = gd = bd = False def setup(): global buffer size(600, 600) frameRate(25) buffer = [None] * width * height for x in range(width): for y in range(width): value = int(((128 + (128 * sin(x / 32.0))) + (128 + (128 * cos(y / 32.0))) + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4) buffer[x + y * width] = value def draw(): global r, g, b, rd, gd, bd if r > 128: rd = True if not rd: r += 1 else: r-=1 if r < 0: rd = False if g > 128: gd = True if not gd: g += 1 else: g- = 1 if r < 0: gd = False if b > 128: bd = True if not bd: b += 1 else: b- = 1 if b < 0: bd = False for i in range(128): s_1 = sin(i * PI / 25) s_2 = sin(i * PI / 50 + PI / 4) pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128) loadPixels() for i, b in enumerate(buffer): pixels[i] = pal[(b + frameCount) % 127] updatePixels()
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "strconv" "strings" ) type sandpile struct{ a [9]int } var neighbors = [][]int{ {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7}, } func newSandpile(a [9]int) *sandpile { return &sandpile{a} } func (s *sandpile) plus(other *sandpile) *sandpile { b := [9]int{} for i := 0; i < 9; i++ { b[i] = s.a[i] + other.a[i] } return &sandpile{b} } func (s *sandpile) isStable() bool { for _, e := range s.a { if e > 3 { return false } } return true } func (s *sandpile) topple() { for i := 0; i < 9; i++ { if s.a[i] > 3 { s.a[i] -= 4 for _, j := range neighbors[i] { s.a[j]++ } return } } } func (s *sandpile) String() string { var sb strings.Builder for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { sb.WriteString(strconv.Itoa(s.a[3*i+j]) + " ") } sb.WriteString("\n") } return sb.String() } func main() { fmt.Println("Avalanche of topplings:\n") s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3}) fmt.Println(s4) for !s4.isStable() { s4.topple() fmt.Println(s4) } fmt.Println("Commutative additions:\n") s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3}) s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0}) s3_a := s1.plus(s2) for !s3_a.isStable() { s3_a.topple() } s3_b := s2.plus(s1) for !s3_b.isStable() { s3_b.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s1, s2, s3_a) fmt.Printf("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s\n", s2, s1, s3_b) fmt.Println("Addition of identity sandpile:\n") s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3}) s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2}) s4 = s3.plus(s3_id) for !s4.isStable() { s4.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s3, s3_id, s4) fmt.Println("Addition of identities:\n") s5 := s3_id.plus(s3_id) for !s5.isStable() { s5.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s", s3_id, s3_id, s5) }
from itertools import product from collections import defaultdict class Sandpile(): def __init__(self, gridtext): array = [int(x) for x in gridtext.strip().split()] self.grid = defaultdict(int, {(i //3, i % 3): x for i, x in enumerate(array)}) _border = set((r, c) for r, c in product(range(-1, 4), repeat=2) if not 0 <= r <= 2 or not 0 <= c <= 2 ) _cell_coords = list(product(range(3), repeat=2)) def topple(self): g = self.grid for r, c in self._cell_coords: if g[(r, c)] >= 4: g[(r - 1, c)] += 1 g[(r + 1, c)] += 1 g[(r, c - 1)] += 1 g[(r, c + 1)] += 1 g[(r, c)] -= 4 return True return False def stabilise(self): while self.topple(): pass g = self.grid for row_col in self._border.intersection(g.keys()): del g[row_col] return self __pos__ = stabilise def __eq__(self, other): g = self.grid return all(g[row_col] == other.grid[row_col] for row_col in self._cell_coords) def __add__(self, other): g = self.grid ans = Sandpile("") for row_col in self._cell_coords: ans.grid[row_col] = g[row_col] + other.grid[row_col] return ans.stabilise() def __str__(self): g, txt = self.grid, [] for row in range(3): txt.append(' '.join(str(g[(row, col)]) for col in range(3))) return '\n'.join(txt) def __repr__(self): return f'{self.__class__.__name__}()' unstable = Sandpile() s1 = Sandpile() s2 = Sandpile() s3 = Sandpile("3 3 3 3 3 3 3 3 3") s3_id = Sandpile("2 1 2 1 0 1 2 1 2")
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "strconv" "strings" ) type sandpile struct{ a [9]int } var neighbors = [][]int{ {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7}, } func newSandpile(a [9]int) *sandpile { return &sandpile{a} } func (s *sandpile) plus(other *sandpile) *sandpile { b := [9]int{} for i := 0; i < 9; i++ { b[i] = s.a[i] + other.a[i] } return &sandpile{b} } func (s *sandpile) isStable() bool { for _, e := range s.a { if e > 3 { return false } } return true } func (s *sandpile) topple() { for i := 0; i < 9; i++ { if s.a[i] > 3 { s.a[i] -= 4 for _, j := range neighbors[i] { s.a[j]++ } return } } } func (s *sandpile) String() string { var sb strings.Builder for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { sb.WriteString(strconv.Itoa(s.a[3*i+j]) + " ") } sb.WriteString("\n") } return sb.String() } func main() { fmt.Println("Avalanche of topplings:\n") s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3}) fmt.Println(s4) for !s4.isStable() { s4.topple() fmt.Println(s4) } fmt.Println("Commutative additions:\n") s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3}) s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0}) s3_a := s1.plus(s2) for !s3_a.isStable() { s3_a.topple() } s3_b := s2.plus(s1) for !s3_b.isStable() { s3_b.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s1, s2, s3_a) fmt.Printf("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s\n", s2, s1, s3_b) fmt.Println("Addition of identity sandpile:\n") s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3}) s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2}) s4 = s3.plus(s3_id) for !s4.isStable() { s4.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s3, s3_id, s4) fmt.Println("Addition of identities:\n") s5 := s3_id.plus(s3_id) for !s5.isStable() { s5.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s", s3_id, s3_id, s5) }
from itertools import product from collections import defaultdict class Sandpile(): def __init__(self, gridtext): array = [int(x) for x in gridtext.strip().split()] self.grid = defaultdict(int, {(i //3, i % 3): x for i, x in enumerate(array)}) _border = set((r, c) for r, c in product(range(-1, 4), repeat=2) if not 0 <= r <= 2 or not 0 <= c <= 2 ) _cell_coords = list(product(range(3), repeat=2)) def topple(self): g = self.grid for r, c in self._cell_coords: if g[(r, c)] >= 4: g[(r - 1, c)] += 1 g[(r + 1, c)] += 1 g[(r, c - 1)] += 1 g[(r, c + 1)] += 1 g[(r, c)] -= 4 return True return False def stabilise(self): while self.topple(): pass g = self.grid for row_col in self._border.intersection(g.keys()): del g[row_col] return self __pos__ = stabilise def __eq__(self, other): g = self.grid return all(g[row_col] == other.grid[row_col] for row_col in self._cell_coords) def __add__(self, other): g = self.grid ans = Sandpile("") for row_col in self._cell_coords: ans.grid[row_col] = g[row_col] + other.grid[row_col] return ans.stabilise() def __str__(self): g, txt = self.grid, [] for row in range(3): txt.append(' '.join(str(g[(row, col)]) for col in range(3))) return '\n'.join(txt) def __repr__(self): return f'{self.__class__.__name__}()' unstable = Sandpile() s1 = Sandpile() s2 = Sandpile() s3 = Sandpile("3 3 3 3 3 3 3 3 3") s3_id = Sandpile("2 1 2 1 0 1 2 1 2")
Produce a functionally identical Python code for the snippet given in Go.
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = newPoint(3, 4) i.print() i = newCircle(5, 12, 13) i.print() } func (p *point) getX() float64 { return p.x } func (p *point) getY() float64 { return p.y } func (p *point) setX(v float64) { p.x = v } func (p *point) setY(v float64) { p.y = v } func (c *circle) getX() float64 { return c.x } func (c *circle) getY() float64 { return c.y } func (c *circle) getR() float64 { return c.r } func (c *circle) setX(v float64) { c.x = v } func (c *circle) setY(v float64) { c.y = v } func (c *circle) setR(v float64) { c.r = v } func (p *point) clone() *point { r := *p; return &r } func (c *circle) clone() *circle { r := *c; return &r } func (p *point) set(q *point) { *p = *q } func (c *circle) set(d *circle) { *c = *d } func newPoint(x, y float64) *point { return &point{x, y} } func newCircle(x, y, r float64) *circle { return &circle{x, y, r} }
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y) class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.radius = radius def __repr__(self): return '<Circle 0x%x x: %f y: %f radius: %f>' % ( id(self), self.center.x, self.center.y, self.radius)
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = newPoint(3, 4) i.print() i = newCircle(5, 12, 13) i.print() } func (p *point) getX() float64 { return p.x } func (p *point) getY() float64 { return p.y } func (p *point) setX(v float64) { p.x = v } func (p *point) setY(v float64) { p.y = v } func (c *circle) getX() float64 { return c.x } func (c *circle) getY() float64 { return c.y } func (c *circle) getR() float64 { return c.r } func (c *circle) setX(v float64) { c.x = v } func (c *circle) setY(v float64) { c.y = v } func (c *circle) setR(v float64) { c.r = v } func (p *point) clone() *point { r := *p; return &r } func (c *circle) clone() *circle { r := *c; return &r } func (p *point) set(q *point) { *p = *q } func (c *circle) set(d *circle) { *c = *d } func newPoint(x, y float64) *point { return &point{x, y} } func newCircle(x, y, r float64) *circle { return &circle{x, y, r} }
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y) class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.radius = radius def __repr__(self): return '<Circle 0x%x x: %f y: %f radius: %f>' % ( id(self), self.center.x, self.center.y, self.radius)
Write the same code in Python as shown below in Go.
package romap type Romap struct{ imap map[byte]int } func New(m map[byte]int) *Romap { if m == nil { return nil } return &Romap{m} } func (rom *Romap) Get(key byte) (int, bool) { i, ok := rom.imap[key] return i, ok } func (rom *Romap) Reset(key byte) { _, ok := rom.imap[key] if ok { rom.imap[key] = 0 } }
from collections import UserDict import copy class Dict(UserDict): def __init__(self, dict=None, **kwargs): self.__init = True super().__init__(dict, **kwargs) self.default = copy.deepcopy(self.data) self.__init = False def __delitem__(self, key): if key in self.default: self.data[key] = self.default[key] else: raise NotImplementedError def __setitem__(self, key, item): if self.__init: super().__setitem__(key, item) elif key in self.data: self.data[key] = item else: raise KeyError def __repr__(self): return "%s(%s)" % (type(self).__name__, super().__repr__()) def fromkeys(cls, iterable, value=None): if self.__init: super().fromkeys(cls, iterable, value) else: for key in iterable: if key in self.data: self.data[key] = value else: raise KeyError def clear(self): self.data.update(copy.deepcopy(self.default)) def pop(self, key, default=None): raise NotImplementedError def popitem(self): raise NotImplementedError def update(self, E, **F): if self.__init: super().update(E, **F) else: haskeys = False try: keys = E.keys() haskeys = Ture except AttributeError: pass if haskeys: for key in keys: self[key] = E[key] else: for key, val in E: self[key] = val for key in F: self[key] = F[key] def setdefault(self, key, default=None): if key not in self.data: raise KeyError else: return super().setdefault(key, default)
Write the same code in Python as shown below in Go.
package main import ( "fmt" "math" "sort" "time" ) type term struct { coeff uint64 ix1, ix2 int8 } const maxDigits = 19 func toUint64(digits []int8, reverse bool) uint64 { sum := uint64(0) if !reverse { for i := 0; i < len(digits); i++ { sum = sum*10 + uint64(digits[i]) } } else { for i := len(digits) - 1; i >= 0; i-- { sum = sum*10 + uint64(digits[i]) } } return sum } func isSquare(n uint64) bool { if 0x202021202030213&(1<<(n&63)) != 0 { root := uint64(math.Sqrt(float64(n))) return root*root == n } return false } func seq(from, to, step int8) []int8 { var res []int8 for i := from; i <= to; i += step { res = append(res, i) } return res } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { start := time.Now() pow := uint64(1) fmt.Println("Aggregate timings to process all numbers up to:") allTerms := make([][]term, maxDigits-1) for r := 2; r <= maxDigits; r++ { var terms []term pow *= 10 pow1, pow2 := pow, uint64(1) for i1, i2 := int8(0), int8(r-1); i1 < i2; i1, i2 = i1+1, i2-1 { terms = append(terms, term{pow1 - pow2, i1, i2}) pow1 /= 10 pow2 *= 10 } allTerms[r-2] = terms } fml := map[int8][][]int8{ 0: {{2, 2}, {8, 8}}, 1: {{6, 5}, {8, 7}}, 4: {{4, 0}}, 6: {{6, 0}, {8, 2}}, } dmd := make(map[int8][][]int8) for i := int8(0); i < 100; i++ { a := []int8{i / 10, i % 10} d := a[0] - a[1] dmd[d] = append(dmd[d], a) } fl := []int8{0, 1, 4, 6} dl := seq(-9, 9, 1) zl := []int8{0} el := seq(-8, 8, 2) ol := seq(-9, 9, 2) il := seq(0, 9, 1) var rares []uint64 lists := make([][][]int8, 4) for i, f := range fl { lists[i] = [][]int8{{f}} } var digits []int8 count := 0 var fnpr func(cand, di []int8, dis [][]int8, indices [][2]int8, nmr uint64, nd, level int) fnpr = func(cand, di []int8, dis [][]int8, indices [][2]int8, nmr uint64, nd, level int) { if level == len(dis) { digits[indices[0][0]] = fml[cand[0]][di[0]][0] digits[indices[0][1]] = fml[cand[0]][di[0]][1] le := len(di) if nd%2 == 1 { le-- digits[nd/2] = di[le] } for i, d := range di[1:le] { digits[indices[i+1][0]] = dmd[cand[i+1]][d][0] digits[indices[i+1][1]] = dmd[cand[i+1]][d][1] } r := toUint64(digits, true) npr := nmr + 2*r if !isSquare(npr) { return } count++ fmt.Printf(" R/N %2d:", count) ms := uint64(time.Since(start).Milliseconds()) fmt.Printf(" %9s ms", commatize(ms)) n := toUint64(digits, false) fmt.Printf(" (%s)\n", commatize(n)) rares = append(rares, n) } else { for _, num := range dis[level] { di[level] = num fnpr(cand, di, dis, indices, nmr, nd, level+1) } } } var fnmr func(cand []int8, list [][]int8, indices [][2]int8, nd, level int) fnmr = func(cand []int8, list [][]int8, indices [][2]int8, nd, level int) { if level == len(list) { var nmr, nmr2 uint64 for i, t := range allTerms[nd-2] { if cand[i] >= 0 { nmr += t.coeff * uint64(cand[i]) } else { nmr2 += t.coeff * uint64(-cand[i]) if nmr >= nmr2 { nmr -= nmr2 nmr2 = 0 } else { nmr2 -= nmr nmr = 0 } } } if nmr2 >= nmr { return } nmr -= nmr2 if !isSquare(nmr) { return } var dis [][]int8 dis = append(dis, seq(0, int8(len(fml[cand[0]]))-1, 1)) for i := 1; i < len(cand); i++ { dis = append(dis, seq(0, int8(len(dmd[cand[i]]))-1, 1)) } if nd%2 == 1 { dis = append(dis, il) } di := make([]int8, len(dis)) fnpr(cand, di, dis, indices, nmr, nd, 0) } else { for _, num := range list[level] { cand[level] = num fnmr(cand, list, indices, nd, level+1) } } } for nd := 2; nd <= maxDigits; nd++ { digits = make([]int8, nd) if nd == 4 { lists[0] = append(lists[0], zl) lists[1] = append(lists[1], ol) lists[2] = append(lists[2], el) lists[3] = append(lists[3], ol) } else if len(allTerms[nd-2]) > len(lists[0]) { for i := 0; i < 4; i++ { lists[i] = append(lists[i], dl) } } var indices [][2]int8 for _, t := range allTerms[nd-2] { indices = append(indices, [2]int8{t.ix1, t.ix2}) } for _, list := range lists { cand := make([]int8, len(list)) fnmr(cand, list, indices, nd, 0) } ms := uint64(time.Since(start).Milliseconds()) fmt.Printf(" %2d digits: %9s ms\n", nd, commatize(ms)) } sort.Slice(rares, func(i, j int) bool { return rares[i] < rares[j] }) fmt.Printf("\nThe rare numbers with up to %d digits are:\n", maxDigits) for i, rare := range rares { fmt.Printf(" %2d: %25s\n", i+1, commatize(rare)) } }
from math import floor, sqrt from datetime import datetime def main(): start = datetime.now() for i in xrange(1, 10 ** 11): if rare(i): print "found a rare:", i end = datetime.now() print "time elapsed:", end - start def is_square(n): s = floor(sqrt(n + 0.5)) return s * s == n def reverse(n): return int(str(n)[::-1]) def is_palindrome(n): return n == reverse(n) def rare(n): r = reverse(n) return ( not is_palindrome(n) and n > r and is_square(n+r) and is_square(n-r) ) if __name__ == '__main__': main()
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func contains(list []int, value int) bool { for _, v := range list { if v == value { return true } } return false } func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) > 10 { words = append(words, s) } } vowelIndices := []int{0, 4, 8, 14, 20} wordGroups := make([][]string, 12) for _, word := range words { letters := make([]int, 26) for _, c := range word { index := c - 97 if index >= 0 && index < 26 { letters[index]++ } } eligible := true uc := 0 for i := 0; i < 26; i++ { if !contains(vowelIndices, i) { if letters[i] > 1 { eligible = false break } else if letters[i] == 1 { uc++ } } } if eligible { wordGroups[uc] = append(wordGroups[uc], word) } } for i := 11; i >= 0; i-- { count := len(wordGroups[i]) if count > 0 { s := "s" if count == 1 { s = "" } fmt.Printf("%d word%s found with %d unique consonants:\n", count, s, i) for j := 0; j < count; j++ { fmt.Printf("%-15s", wordGroups[i][j]) if j > 0 && (j+1)%5 == 0 { fmt.Println() } } fmt.Println() if count%5 != 0 { fmt.Println() } } } }
print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w) for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)] if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func contains(list []int, value int) bool { for _, v := range list { if v == value { return true } } return false } func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) > 10 { words = append(words, s) } } vowelIndices := []int{0, 4, 8, 14, 20} wordGroups := make([][]string, 12) for _, word := range words { letters := make([]int, 26) for _, c := range word { index := c - 97 if index >= 0 && index < 26 { letters[index]++ } } eligible := true uc := 0 for i := 0; i < 26; i++ { if !contains(vowelIndices, i) { if letters[i] > 1 { eligible = false break } else if letters[i] == 1 { uc++ } } } if eligible { wordGroups[uc] = append(wordGroups[uc], word) } } for i := 11; i >= 0; i-- { count := len(wordGroups[i]) if count > 0 { s := "s" if count == 1 { s = "" } fmt.Printf("%d word%s found with %d unique consonants:\n", count, s, i) for j := 0; j < count; j++ { fmt.Printf("%-15s", wordGroups[i][j]) if j > 0 && (j+1)%5 == 0 { fmt.Println() } } fmt.Println() if count%5 != 0 { fmt.Println() } } } }
print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w) for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)] if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func isPrime(n int) bool { if n < 2 { return false } if n%2 == 0 { return n == 2 } if n%3 == 0 { return n == 3 } d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } func main() { var primeRunes []rune for i := 33; i < 256; i += 2 { if isPrime(i) { primeRunes = append(primeRunes, rune(i)) } } primeString := string(primeRunes) wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) fmt.Println("Prime words in", wordList, "are:") for _, bword := range bwords { word := string(bword) ok := true for _, c := range word { if !strings.ContainsRune(primeString, c) { ok = false break } } if ok { fmt.Println(word) } } }
for i in range(65,123): check = 1 for j in range(2,i): if i%j == 0: check = 0 if check==1: print(chr(i),end='')
Write the same code in Python as shown below in Go.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func isPrime(n int) bool { if n < 2 { return false } if n%2 == 0 { return n == 2 } if n%3 == 0 { return n == 3 } d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } func main() { var primeRunes []rune for i := 33; i < 256; i += 2 { if isPrime(i) { primeRunes = append(primeRunes, rune(i)) } } primeString := string(primeRunes) wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) fmt.Println("Prime words in", wordList, "are:") for _, bword := range bwords { word := string(bword) ok := true for _, c := range word { if !strings.ContainsRune(primeString, c) { ok = false break } } if ok { fmt.Println(word) } } }
for i in range(65,123): check = 1 for j in range(2,i): if i%j == 0: check = 0 if check==1: print(chr(i),end='')
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "math" "rcu" ) func divisorCount(n int) int { k := 1 if n%2 == 1 { k = 2 } count := 0 sqrt := int(math.Sqrt(float64(n))) for i := 1; i <= sqrt; i += k { if n%i == 0 { count++ j := n / i if j != i { count++ } } } return count } func main() { var numbers50 []int count := 0 for n := 1; count < 50000; n++ { dc := divisorCount(n) if n == 1 || dc == 8 { count++ if count <= 50 { numbers50 = append(numbers50, n) if count == 50 { rcu.PrintTable(numbers50, 10, 3, false) } } else if count == 500 { fmt.Printf("\n500th  : %s", rcu.Commatize(n)) } else if count == 5000 { fmt.Printf("\n5,000th : %s", rcu.Commatize(n)) } else if count == 50000 { fmt.Printf("\n50,000th: %s\n", rcu.Commatize(n)) } } } }
from functools import reduce from sympy import divisors FOUND = 0 for num in range(1, 1_000_000): divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1 if num * num * num == divprod: FOUND += 1 if FOUND <= 50: print(f'{num:5}', end='\n' if FOUND % 10 == 0 else '') if FOUND == 500: print(f'\nFive hundreth: {num:,}') if FOUND == 5000: print(f'\nFive thousandth: {num:,}') if FOUND == 50000: print(f'\nFifty thousandth: {num:,}') break
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "math" "rcu" ) func divisorCount(n int) int { k := 1 if n%2 == 1 { k = 2 } count := 0 sqrt := int(math.Sqrt(float64(n))) for i := 1; i <= sqrt; i += k { if n%i == 0 { count++ j := n / i if j != i { count++ } } } return count } func main() { var numbers50 []int count := 0 for n := 1; count < 50000; n++ { dc := divisorCount(n) if n == 1 || dc == 8 { count++ if count <= 50 { numbers50 = append(numbers50, n) if count == 50 { rcu.PrintTable(numbers50, 10, 3, false) } } else if count == 500 { fmt.Printf("\n500th  : %s", rcu.Commatize(n)) } else if count == 5000 { fmt.Printf("\n5,000th : %s", rcu.Commatize(n)) } else if count == 50000 { fmt.Printf("\n50,000th: %s\n", rcu.Commatize(n)) } } } }
from functools import reduce from sympy import divisors FOUND = 0 for num in range(1, 1_000_000): divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1 if num * num * num == divprod: FOUND += 1 if FOUND <= 50: print(f'{num:5}', end='\n' if FOUND % 10 == 0 else '') if FOUND == 500: print(f'\nFive hundreth: {num:,}') if FOUND == 5000: print(f'\nFive thousandth: {num:,}') if FOUND == 50000: print(f'\nFifty thousandth: {num:,}') break
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "rcu" ) func main() { const limit = 1e10 primes := rcu.Primes(limit) var orm25 []int j := int(1e9) count := 0 var counts []int for i := 0; i < len(primes)-2; i++ { p1 := primes[i] p2 := primes[i+1] p3 := primes[i+2] if (p2-p1)%18 != 0 || (p3-p2)%18 != 0 { continue } key1 := 1 for _, dig := range rcu.Digits(p1, 10) { key1 *= primes[dig] } key2 := 1 for _, dig := range rcu.Digits(p2, 10) { key2 *= primes[dig] } if key1 != key2 { continue } key3 := 1 for _, dig := range rcu.Digits(p3, 10) { key3 *= primes[dig] } if key2 == key3 { if count < 25 { orm25 = append(orm25, p1) } if p1 >= j { counts = append(counts, count) j *= 10 } count++ } } counts = append(counts, count) fmt.Println("Smallest members of first 25 Ormiston triples:") for i := 0; i < 25; i++ { fmt.Printf("%8v ", orm25[i]) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println() j = int(1e9) for i := 0; i < len(counts); i++ { fmt.Printf("%s Ormiston triples before %s\n", rcu.Commatize(counts[i]), rcu.Commatize(j)) j *= 10 fmt.Println() } }
import textwrap from itertools import pairwise from typing import Iterator from typing import List import primesieve def primes() -> Iterator[int]: it = primesieve.Iterator() while True: yield it.next_prime() def triplewise(iterable): for (a, _), (b, c) in pairwise(pairwise(iterable)): yield a, b, c def is_anagram(a: int, b: int, c: int) -> bool: return sorted(str(a)) == sorted(str(b)) == sorted(str(c)) def up_to_one_billion() -> int: count = 0 for triple in triplewise(primes()): if is_anagram(*triple): count += 1 if triple[2] >= 1_000_000_000: break return count def up_to_ten_billion() -> int: count = 0 for triple in triplewise(primes()): if is_anagram(*triple): count += 1 if triple[2] >= 10_000_000_000: break return count def first_25() -> List[int]: rv: List[int] = [] for triple in triplewise(primes()): if is_anagram(*triple): rv.append(triple[0]) if len(rv) >= 25: break return rv if __name__ == "__main__": print("Smallest members of first 25 Ormiston triples:") print(textwrap.fill(" ".join(str(i) for i in first_25())), "\n") print(up_to_one_billion(), "Ormiston triples before 1,000,000,000") print(up_to_ten_billion(), "Ormiston triples before 10,000,000,000")
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "bufio" "fmt" "math" "math/rand" "os" "strconv" "strings" "time" ) type cell struct { isMine bool display byte } const lMargin = 4 var ( grid [][]cell mineCount int minesMarked int isGameOver bool ) var scanner = bufio.NewScanner(os.Stdin) func makeGrid(n, m int) { if n <= 0 || m <= 0 { panic("Grid dimensions must be positive.") } grid = make([][]cell, n) for i := 0; i < n; i++ { grid[i] = make([]cell, m) for j := 0; j < m; j++ { grid[i][j].display = '.' } } min := int(math.Round(float64(n*m) * 0.1)) max := int(math.Round(float64(n*m) * 0.2)) mineCount = min + rand.Intn(max-min+1) rm := mineCount for rm > 0 { x, y := rand.Intn(n), rand.Intn(m) if !grid[x][y].isMine { rm-- grid[x][y].isMine = true } } minesMarked = 0 isGameOver = false } func displayGrid(isEndOfGame bool) { if !isEndOfGame { fmt.Println("Grid has", mineCount, "mine(s),", minesMarked, "mine(s) marked.") } margin := strings.Repeat(" ", lMargin) fmt.Print(margin, " ") for i := 1; i <= len(grid); i++ { fmt.Print(i) } fmt.Println() fmt.Println(margin, strings.Repeat("-", len(grid))) for y := 0; y < len(grid[0]); y++ { fmt.Printf("%*d:", lMargin, y+1) for x := 0; x < len(grid); x++ { fmt.Printf("%c", grid[x][y].display) } fmt.Println() } } func endGame(msg string) { isGameOver = true fmt.Println(msg) ans := "" for ans != "y" && ans != "n" { fmt.Print("Another game (y/n)? : ") scanner.Scan() ans = strings.ToLower(scanner.Text()) } if scanner.Err() != nil || ans == "n" { return } makeGrid(6, 4) displayGrid(false) } func resign() { found := 0 for y := 0; y < len(grid[0]); y++ { for x := 0; x < len(grid); x++ { if grid[x][y].isMine { if grid[x][y].display == '?' { grid[x][y].display = 'Y' found++ } else if grid[x][y].display != 'x' { grid[x][y].display = 'N' } } } } displayGrid(true) msg := fmt.Sprint("You found ", found, " out of ", mineCount, " mine(s).") endGame(msg) } func usage() { fmt.Println("h or ? - this help,") fmt.Println("c x y - clear cell (x,y),") fmt.Println("m x y - marks (toggles) cell (x,y),") fmt.Println("n - start a new game,") fmt.Println("q - quit/resign the game,") fmt.Println("where x is the (horizontal) column number and y is the (vertical) row number.\n") } func markCell(x, y int) { if grid[x][y].display == '?' { minesMarked-- grid[x][y].display = '.' } else if grid[x][y].display == '.' { minesMarked++ grid[x][y].display = '?' } } func countAdjMines(x, y int) int { count := 0 for j := y - 1; j <= y+1; j++ { if j >= 0 && j < len(grid[0]) { for i := x - 1; i <= x+1; i++ { if i >= 0 && i < len(grid) { if grid[i][j].isMine { count++ } } } } } return count } func clearCell(x, y int) bool { if x >= 0 && x < len(grid) && y >= 0 && y < len(grid[0]) { if grid[x][y].display == '.' { if !grid[x][y].isMine { count := countAdjMines(x, y) if count > 0 { grid[x][y].display = string(48 + count)[0] } else { grid[x][y].display = ' ' clearCell(x+1, y) clearCell(x+1, y+1) clearCell(x, y+1) clearCell(x-1, y+1) clearCell(x-1, y) clearCell(x-1, y-1) clearCell(x, y-1) clearCell(x+1, y-1) } } else { grid[x][y].display = 'x' fmt.Println("Kaboom! You lost!") return false } } } return true } func testForWin() bool { isCleared := false if minesMarked == mineCount { isCleared = true for x := 0; x < len(grid); x++ { for y := 0; y < len(grid[0]); y++ { if grid[x][y].display == '.' { isCleared = false } } } } if isCleared { fmt.Println("You won!") } return isCleared } func splitAction(action string) (int, int, bool) { fields := strings.Fields(action) if len(fields) != 3 { return 0, 0, false } x, err := strconv.Atoi(fields[1]) if err != nil || x < 1 || x > len(grid) { return 0, 0, false } y, err := strconv.Atoi(fields[2]) if err != nil || y < 1 || y > len(grid[0]) { return 0, 0, false } return x, y, true } func main() { rand.Seed(time.Now().UnixNano()) usage() makeGrid(6, 4) displayGrid(false) for !isGameOver { fmt.Print("\n>") scanner.Scan() action := strings.ToLower(scanner.Text()) if scanner.Err() != nil || len(action) == 0 { continue } switch action[0] { case 'h', '?': usage() case 'n': makeGrid(6, 4) displayGrid(false) case 'c': x, y, ok := splitAction(action) if !ok { continue } if clearCell(x-1, y-1) { displayGrid(false) if testForWin() { resign() } } else { resign() } case 'm': x, y, ok := splitAction(action) if !ok { continue } markCell(x-1, y-1) displayGrid(false) if testForWin() { resign() } case 'q': resign() } } }
gridsize = (6, 4) minerange = (0.2, 0.6) try: raw_input except: raw_input = input import random from itertools import product from pprint import pprint as pp def gridandmines(gridsize=gridsize, minerange=minerange): xgrid, ygrid = gridsize minmines, maxmines = minerange minecount = xgrid * ygrid minecount = random.randint(int(minecount*minmines), int(minecount*maxmines)) grid = set(product(range(xgrid), range(ygrid))) mines = set(random.sample(grid, minecount)) show = {xy:'.' for xy in grid} return grid, mines, show def printgrid(show, gridsize=gridsize): xgrid, ygrid = gridsize grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid)) for y in range(ygrid)) print( grid ) def resign(showgrid, mines, markedmines): for m in mines: showgrid[m] = 'Y' if m in markedmines else 'N' def clear(x,y, showgrid, grid, mines, markedmines): if showgrid[(x, y)] == '.': xychar = str(sum(1 for xx in (x-1, x, x+1) for yy in (y-1, y, y+1) if (xx, yy) in mines )) if xychar == '0': xychar = '.' showgrid[(x,y)] = xychar for xx in (x-1, x, x+1): for yy in (y-1, y, y+1): xxyy = (xx, yy) if ( xxyy != (x, y) and xxyy in grid and xxyy not in mines | markedmines ): clear(xx, yy, showgrid, grid, mines, markedmines) if __name__ == '__main__': grid, mines, showgrid = gridandmines() markedmines = set([]) print( __doc__ ) print( '\nThere are %i true mines of fixed position in the grid\n' % len(mines) ) printgrid(showgrid) while markedmines != mines: inp = raw_input('m x y/c x y/p/r: ').strip().split() if inp: if inp[0] == 'm': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in markedmines: markedmines.remove((x,y)) showgrid[(x,y)] = '.' else: markedmines.add((x,y)) showgrid[(x,y)] = '?' elif inp[0] == 'p': printgrid(showgrid) elif inp[0] == 'c': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in mines | markedmines: print( '\nKLABOOM!! You hit a mine.\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break clear(x,y, showgrid, grid, mines, markedmines) printgrid(showgrid) elif inp[0] == 'r': print( '\nResigning!\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break print( '\nYou got %i and missed %i of the %i mines' % (len(mines.intersection(markedmines)), len(markedmines.difference(mines)), len(mines)) )
Write the same code in Python as shown below in Go.
package main import ( "fmt" "strings" ) func btoi(b bool) int { if b { return 1 } return 0 } func evolve(l, rule int) { fmt.Printf(" Rule #%d:\n", rule) cells := "O" for x := 0; x < l; x++ { cells = addNoCells(cells) width := 40 + (len(cells) >> 1) fmt.Printf("%*s\n", width, cells) cells = step(cells, rule) } } func step(cells string, rule int) string { newCells := new(strings.Builder) for i := 0; i < len(cells)-2; i++ { bin := 0 b := uint(2) for n := i; n < i+3; n++ { bin += btoi(cells[n] == 'O') << b b >>= 1 } a := '.' if rule&(1<<uint(bin)) != 0 { a = 'O' } newCells.WriteRune(a) } return newCells.String() } func addNoCells(cells string) string { l, r := "O", "O" if cells[0] == 'O' { l = "." } if cells[len(cells)-1] == 'O' { r = "." } cells = l + cells + r cells = l + cells + r return cells } func main() { for _, r := range []int{90, 30} { evolve(25, r) fmt.Println() } }
def _notcell(c): return '0' if c == '1' else '1' def eca_infinite(cells, rule): lencells = len(cells) rulebits = '{0:08b}'.format(rule) neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)} c = cells while True: yield c c = _notcell(c[0])*2 + c + _notcell(c[-1])*2 c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1)) if __name__ == '__main__': lines = 25 for rule in (90, 30): print('\nRule: %i' % rule) for i, c in zip(range(lines), eca_infinite('1', rule)): print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "fmt" "github.com/atotto/clipboard" "io/ioutil" "log" "os" "runtime" "strconv" "strings" ) func check(err error) { if err != nil { clipboard.WriteAll("") log.Fatal(err) } } func interpret(source string) { source2 := source if runtime.GOOS == "windows" { source2 = strings.ReplaceAll(source, "\r\n", "\n") } lines := strings.Split(source2, "\n") le := len(lines) for i := 0; i < le; i++ { lines[i] = strings.TrimSpace(lines[i]) switch lines[i] { case "Copy": if i == le-1 { log.Fatal("There are no lines after the Copy command.") } i++ err := clipboard.WriteAll(lines[i]) check(err) case "CopyFile": if i == le-1 { log.Fatal("There are no lines after the CopyFile command.") } i++ if lines[i] == "TheF*ckingCode" { err := clipboard.WriteAll(source) check(err) } else { bytes, err := ioutil.ReadFile(lines[i]) check(err) err = clipboard.WriteAll(string(bytes)) check(err) } case "Duplicate": if i == le-1 { log.Fatal("There are no lines after the Duplicate command.") } i++ times, err := strconv.Atoi(lines[i]) check(err) if times < 0 { log.Fatal("Can't duplicate text a negative number of times.") } text, err := clipboard.ReadAll() check(err) err = clipboard.WriteAll(strings.Repeat(text, times+1)) check(err) case "Pasta!": text, err := clipboard.ReadAll() check(err) fmt.Println(text) return default: if lines[i] == "" { continue } log.Fatal("Unknown command, " + lines[i]) } } } func main() { if len(os.Args) != 2 { log.Fatal("There should be exactly one command line argument, the CopyPasta file path.") } bytes, err := ioutil.ReadFile(os.Args[1]) check(err) interpret(string(bytes)) err = clipboard.WriteAll("") check(err) }
import sys def fatal_error(errtext): print("%" + errtext) print("usage: " + sys.argv[0] + " [filename.cp]") sys.exit(1) fname = None source = None try: fname = sys.argv[1] source = open(fname).read() except: fatal_error("error while trying to read from specified file") lines = source.split("\n") clipboard = "" loc = 0 while(loc < len(lines)): command = lines[loc].strip() try: if(command == "Copy"): clipboard += lines[loc + 1] elif(command == "CopyFile"): if(lines[loc + 1] == "TheF*ckingCode"): clipboard += source else: filetext = open(lines[loc+1]).read() clipboard += filetext elif(command == "Duplicate"): clipboard += clipboard * ((int(lines[loc + 1])) - 1) elif(command == "Pasta!"): print(clipboard) sys.exit(0) else: fatal_error("unknown command '" + command + "' encountered on line " + str(loc + 1)) except Exception as e: fatal_error("error while executing command '" + command + "' on line " + str(loc + 1) + ": " + e) loc += 2
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "github.com/atotto/clipboard" "io/ioutil" "log" "os" "runtime" "strconv" "strings" ) func check(err error) { if err != nil { clipboard.WriteAll("") log.Fatal(err) } } func interpret(source string) { source2 := source if runtime.GOOS == "windows" { source2 = strings.ReplaceAll(source, "\r\n", "\n") } lines := strings.Split(source2, "\n") le := len(lines) for i := 0; i < le; i++ { lines[i] = strings.TrimSpace(lines[i]) switch lines[i] { case "Copy": if i == le-1 { log.Fatal("There are no lines after the Copy command.") } i++ err := clipboard.WriteAll(lines[i]) check(err) case "CopyFile": if i == le-1 { log.Fatal("There are no lines after the CopyFile command.") } i++ if lines[i] == "TheF*ckingCode" { err := clipboard.WriteAll(source) check(err) } else { bytes, err := ioutil.ReadFile(lines[i]) check(err) err = clipboard.WriteAll(string(bytes)) check(err) } case "Duplicate": if i == le-1 { log.Fatal("There are no lines after the Duplicate command.") } i++ times, err := strconv.Atoi(lines[i]) check(err) if times < 0 { log.Fatal("Can't duplicate text a negative number of times.") } text, err := clipboard.ReadAll() check(err) err = clipboard.WriteAll(strings.Repeat(text, times+1)) check(err) case "Pasta!": text, err := clipboard.ReadAll() check(err) fmt.Println(text) return default: if lines[i] == "" { continue } log.Fatal("Unknown command, " + lines[i]) } } } func main() { if len(os.Args) != 2 { log.Fatal("There should be exactly one command line argument, the CopyPasta file path.") } bytes, err := ioutil.ReadFile(os.Args[1]) check(err) interpret(string(bytes)) err = clipboard.WriteAll("") check(err) }
import sys def fatal_error(errtext): print("%" + errtext) print("usage: " + sys.argv[0] + " [filename.cp]") sys.exit(1) fname = None source = None try: fname = sys.argv[1] source = open(fname).read() except: fatal_error("error while trying to read from specified file") lines = source.split("\n") clipboard = "" loc = 0 while(loc < len(lines)): command = lines[loc].strip() try: if(command == "Copy"): clipboard += lines[loc + 1] elif(command == "CopyFile"): if(lines[loc + 1] == "TheF*ckingCode"): clipboard += source else: filetext = open(lines[loc+1]).read() clipboard += filetext elif(command == "Duplicate"): clipboard += clipboard * ((int(lines[loc + 1])) - 1) elif(command == "Pasta!"): print(clipboard) sys.exit(0) else: fatal_error("unknown command '" + command + "' encountered on line " + str(loc + 1)) except Exception as e: fatal_error("error while executing command '" + command + "' on line " + str(loc + 1) + ": " + e) loc += 2
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "rcu" ) const limit = 100000 func nonTwinSums(twins []int) []int { sieve := make([]bool, limit+1) for i := 0; i < len(twins); i++ { for j := i; j < len(twins); j++ { sum := twins[i] + twins[j] if sum > limit { break } sieve[sum] = true } } var res []int for i := 2; i < limit; i += 2 { if !sieve[i] { res = append(res, i) } } return res } func main() { primes := rcu.Primes(limit)[2:] twins := []int{3} for i := 0; i < len(primes)-1; i++ { if primes[i+1]-primes[i] == 2 { if twins[len(twins)-1] != primes[i] { twins = append(twins, primes[i]) } twins = append(twins, primes[i+1]) } } fmt.Println("Non twin prime sums:") ntps := nonTwinSums(twins) rcu.PrintTable(ntps, 10, 4, false) fmt.Println("Found", len(ntps)) fmt.Println("\nNon twin prime sums (including 1):") twins = append([]int{1}, twins...) ntps = nonTwinSums(twins) rcu.PrintTable(ntps, 10, 4, false) fmt.Println("Found", len(ntps)) }
from sympy import sieve def nonpairsums(include1=False, limit=20_000): tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve) for i in range(limit+2)] if include1: tpri[1] = True twinsums = [False] * (limit * 2) for i in range(limit): for j in range(limit-i+1): if tpri[i] and tpri[j]: twinsums[i + j] = True return [i for i in range(2, limit+1, 2) if not twinsums[i]] print('Non twin prime sums:') for k, p in enumerate(nonpairsums()): print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '') print('\n\nNon twin prime sums (including 1):') for k, p in enumerate(nonpairsums(include1=True)): print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "rcu" ) func nonDescending(p int) bool { var digits []int for p > 0 { digits = append(digits, p%10) p = p / 10 } for i := 0; i < len(digits)-1; i++ { if digits[i+1] > digits[i] { return false } } return true } func main() { primes := rcu.Primes(999) var nonDesc []int for _, p := range primes { if nonDescending(p) { nonDesc = append(nonDesc, p) } } fmt.Println("Primes below 1,000 with digits in non-decreasing order:") for i, n := range nonDesc { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n%d such primes found.\n", len(nonDesc)) }
from operator import le from itertools import takewhile def monotonicDigits(base): def go(n): return monotonic(le)( showIntAtBase(base)(digitFromInt)(n)('') ) return go def monotonic(op): def go(xs): return all(map(op, xs, xs[1:])) return go def main(): xs = [ str(n) for n in takewhile( lambda n: 1000 > n, filter(monotonicDigits(10), primes()) ) ] w = len(xs[-1]) print(f'{len(xs)} matches for base 10:\n') print('\n'.join( ' '.join(row) for row in chunksOf(10)([ x.rjust(w, ' ') for x in xs ]) )) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitFromInt(n): return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if ( 0 <= n < 36 ) else '?' def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n def showIntAtBase(base): def wrap(toChr, n, rs): def go(nd, r): n, d = nd r_ = toChr(d) + r return go(divmod(n, base), r_) if 0 != n else r_ return 'unsupported base' if 1 >= base else ( 'negative number' if 0 > n else ( go(divmod(n, base), rs)) ) return lambda toChr: lambda n: lambda rs: ( wrap(toChr, n, rs) ) if __name__ == '__main__': main()
Write the same code in Python as shown below in Go.
package main import ( "fmt" "rcu" ) func nonDescending(p int) bool { var digits []int for p > 0 { digits = append(digits, p%10) p = p / 10 } for i := 0; i < len(digits)-1; i++ { if digits[i+1] > digits[i] { return false } } return true } func main() { primes := rcu.Primes(999) var nonDesc []int for _, p := range primes { if nonDescending(p) { nonDesc = append(nonDesc, p) } } fmt.Println("Primes below 1,000 with digits in non-decreasing order:") for i, n := range nonDesc { fmt.Printf("%3d ", n) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n%d such primes found.\n", len(nonDesc)) }
from operator import le from itertools import takewhile def monotonicDigits(base): def go(n): return monotonic(le)( showIntAtBase(base)(digitFromInt)(n)('') ) return go def monotonic(op): def go(xs): return all(map(op, xs, xs[1:])) return go def main(): xs = [ str(n) for n in takewhile( lambda n: 1000 > n, filter(monotonicDigits(10), primes()) ) ] w = len(xs[-1]) print(f'{len(xs)} matches for base 10:\n') print('\n'.join( ' '.join(row) for row in chunksOf(10)([ x.rjust(w, ' ') for x in xs ]) )) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitFromInt(n): return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if ( 0 <= n < 36 ) else '?' def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n def showIntAtBase(base): def wrap(toChr, n, rs): def go(nd, r): n, d = nd r_ = toChr(d) + r return go(divmod(n, base), r_) if 0 != n else r_ return 'unsupported base' if 1 >= base else ( 'negative number' if 0 > n else ( go(divmod(n, base), rs)) ) return lambda toChr: lambda n: lambda rs: ( wrap(toChr, n, rs) ) if __name__ == '__main__': main()
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "image" "reflect" ) type t struct { X int next *t } func main() { report(t{}) report(image.Point{}) } func report(x interface{}) { t := reflect.TypeOf(x) n := t.NumField() fmt.Printf("Type %v has %d fields:\n", t, n) fmt.Println("Name Type Exported") for i := 0; i < n; i++ { f := t.Field(i) fmt.Printf("%-8s %-8v %-8t\n", f.Name, f.Type, f.PkgPath == "", ) } fmt.Println() }
class Parent(object): __priv = 'private' def __init__(self, name): self.name = name def __repr__(self): return '%s(%s)' % (type(self).__name__, self.name) def doNothing(self): pass import re class Child(Parent): __rePrivate = re.compile('^_(Child|Parent)__') __reBleh = re.compile('\Wbleh$') @property def reBleh(self): return self.__reBleh def __init__(self, name, *args): super(Child, self).__init__(name) self.args = args def __dir__(self): myDir = filter( lambda p: not self.__rePrivate.match(p), list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ ))) return myDir + map( lambda p: p + '_bleh', filter( lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)), myDir)) def __getattr__(self, name): if name[-5:] == '_bleh': return str(getattr(self, name[:-5])) + ' bleh' if hasattr(super(Child, chld), '__getattr__'): return super(Child, self).__getattr__(name) raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) def __setattr__(self, name, value): if name[-5:] == '_bleh': if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))): setattr(self, name[:-5], self.reBleh.sub('', value)) elif hasattr(super(Child, self), '__setattr__'): super(Child, self).__setattr__(name, value) elif hasattr(self, '__dict__'): self.__dict__[name] = value def __repr__(self): return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()')) def doStuff(self): return (1+1.0/1e6) ** 1e6 par = Parent('par') par.parent = True dir(par) inspect.getmembers(par) chld = Child('chld', 0, 'I', 'two') chld.own = "chld's own" dir(chld) inspect.getmembers(chld)
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "strings" ) const limit = 50000 var ( divs, subs []int mins [][]string ) func minsteps(n int) { if n == 1 { mins[1] = []string{} return } min := limit var p, q int var op byte for _, div := range divs { if n%div == 0 { d := n / div steps := len(mins[d]) + 1 if steps < min { min = steps p, q, op = d, div, '/' } } } for _, sub := range subs { if d := n - sub; d >= 1 { steps := len(mins[d]) + 1 if steps < min { min = steps p, q, op = d, sub, '-' } } } mins[n] = append(mins[n], fmt.Sprintf("%c%d -> %d", op, q, p)) mins[n] = append(mins[n], mins[p]...) } func main() { for r := 0; r < 2; r++ { divs = []int{2, 3} if r == 0 { subs = []int{1} } else { subs = []int{2} } mins = make([][]string, limit+1) fmt.Printf("With: Divisors: %v, Subtractors: %v =>\n", divs, subs) fmt.Println(" Minimum number of steps to diminish the following numbers down to 1 is:") for i := 1; i <= limit; i++ { minsteps(i) if i <= 10 { steps := len(mins[i]) plural := "s" if steps == 1 { plural = " " } fmt.Printf(" %2d: %d step%s: %s\n", i, steps, plural, strings.Join(mins[i], ", ")) } } for _, lim := range []int{2000, 20000, 50000} { max := 0 for _, min := range mins[0 : lim+1] { m := len(min) if m > max { max = m } } var maxs []int for i, min := range mins[0 : lim+1] { if len(min) == max { maxs = append(maxs, i) } } nums := len(maxs) verb, verb2, plural := "are", "have", "s" if nums == 1 { verb, verb2, plural = "is", "has", "" } fmt.Printf(" There %s %d number%s in the range 1-%d ", verb, nums, plural, lim) fmt.Printf("that %s maximum 'minimal steps' of %d:\n", verb2, max) fmt.Println(" ", maxs) } fmt.Println() } }
from functools import lru_cache DIVS = {2, 3} SUBS = {1} class Minrec(): "Recursive, memoised minimised steps to 1" def __init__(self, divs=DIVS, subs=SUBS): self.divs, self.subs = divs, subs @lru_cache(maxsize=None) def _minrec(self, n): "Recursive, memoised" if n == 1: return 0, ['=1'] possibles = {} for d in self.divs: if n % d == 0: possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d) for s in self.subs: if n > s: possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s) thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1]) ret = 1 + count, [thiskind] + otherkinds return ret def __call__(self, n): "Recursive, memoised" ans = self._minrec(n)[1][:-1] return len(ans), ans if __name__ == '__main__': for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]: minrec = Minrec(DIVS, SUBS) print('\nMINIMUM STEPS TO 1: Recursive algorithm') print(' Possible divisors: ', DIVS) print(' Possible decrements:', SUBS) for n in range(1, 11): steps, how = minrec(n) print(f' minrec({n:2}) in {steps:2} by: ', ', '.join(how)) upto = 2000 print(f'\n Those numbers up to {upto} that take the maximum, "minimal steps down to 1":') stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1)) mx = stepn[-1][0] ans = [x[1] for x in stepn if x[0] == mx] print(' Taking', mx, f'steps is/are the {len(ans)} numbers:', ', '.join(str(n) for n in sorted(ans))) print()
Write a version of this Go function in Python with identical behavior.
package main import ( "fmt" "strings" ) const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.` type formatter struct { text [][]string width []int } func newFormatter(text string) *formatter { var f formatter for _, line := range strings.Split(text, "\n") { words := strings.Split(line, "$") for words[len(words)-1] == "" { words = words[:len(words)-1] } f.text = append(f.text, words) for i, word := range words { if i == len(f.width) { f.width = append(f.width, len(word)) } else if len(word) > f.width[i] { f.width[i] = len(word) } } } return &f } const ( left = iota middle right ) func (f formatter) print(j int) { for _, line := range f.text { for i, word := range line { fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s", len(word)+(f.width[i]-len(word))*j/2, word)) } fmt.Println("") } fmt.Println("") } func main() { f := newFormatter(text) f.print(left) f.print(middle) f.print(right) }
from itertools import zip_longest txt = parts = [line.rstrip("$").split("$") for line in txt.splitlines()] widths = [max(len(word) for word in col) for col in zip_longest(*parts, fillvalue='')] for justify in "<_Left ^_Center >_Right".split(): j, jtext = justify.split('_') print(f"{jtext} column-aligned output:\n") for line in parts: print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line))) print("- " * 52)
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Write the same code in Python as shown below in Go.
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Maintain the same structure and functionality when rewriting this code in Python.
package main import "rcu" func isIdoneal(n int) bool { for a := 1; a < n; a++ { for b := a + 1; b < n; b++ { if a*b+a+b > n { break } for c := b + 1; c < n; c++ { sum := a*b + b*c + a*c if sum == n { return false } if sum > n { break } } } } return true } func main() { var idoneals []int for n := 1; n <= 1850; n++ { if isIdoneal(n) { idoneals = append(idoneals, n) } } rcu.PrintTable(idoneals, 13, 4, false) }
def is_idoneal(num): for a in range(1, num): for b in range(a + 1, num): if a * b + a + b > num: break for c in range(b + 1, num): sum3 = a * b + b * c + a * c if sum3 == num: return False if sum3 > num: break return True row = 0 for n in range(1, 2000): if is_idoneal(n): row += 1 print(f'{n:5}', end='\n' if row % 13 == 0 else '')
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "fmt" "log" "math/big" "strings" ) const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" var big0 = new(big.Int) var big58 = big.NewInt(58) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func convertToBase58(hash string, base int) (string, error) { var x, ok = new(big.Int).SetString(hash, base) if !ok { return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base) } var sb strings.Builder var rem = new(big.Int) for x.Cmp(big0) == 1 { x.QuoRem(x, big58, rem) r := rem.Int64() sb.WriteByte(alphabet[r]) } return reverse(sb.String()), nil } func main() { s := "25420294593250030202636073700053352635053786165627414518" b, err := convertToBase58(s, 10) if err != nil { log.Fatal(err) } fmt.Println(s, "->", b) hashes := [...]string{ "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", } for _, hash := range hashes { b58, err := convertToBase58(hash, 0) if err != nil { log.Fatal(err) } fmt.Printf("%-56s -> %s\n", hash, b58) } }
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def convertToBase58(num): sb = '' while (num > 0): r = num % 58 sb = sb + ALPHABET[r] num = num // 58; return sb[::-1] s = 25420294593250030202636073700053352635053786165627414518 b = convertToBase58(s) print("%-56d -> %s" % (s, b)) hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e] for num in hash_arr: b = convertToBase58(num) print("0x%-54x -> %s" % (num, b))
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "log" "math/big" "strings" ) const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" var big0 = new(big.Int) var big58 = big.NewInt(58) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func convertToBase58(hash string, base int) (string, error) { var x, ok = new(big.Int).SetString(hash, base) if !ok { return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base) } var sb strings.Builder var rem = new(big.Int) for x.Cmp(big0) == 1 { x.QuoRem(x, big58, rem) r := rem.Int64() sb.WriteByte(alphabet[r]) } return reverse(sb.String()), nil } func main() { s := "25420294593250030202636073700053352635053786165627414518" b, err := convertToBase58(s, 10) if err != nil { log.Fatal(err) } fmt.Println(s, "->", b) hashes := [...]string{ "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", } for _, hash := range hashes { b58, err := convertToBase58(hash, 0) if err != nil { log.Fatal(err) } fmt.Printf("%-56s -> %s\n", hash, b58) } }
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def convertToBase58(num): sb = '' while (num > 0): r = num % 58 sb = sb + ALPHABET[r] num = num // 58; return sb[::-1] s = 25420294593250030202636073700053352635053786165627414518 b = convertToBase58(s) print("%-56d -> %s" % (s, b)) hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e] for num in hash_arr: b = convertToBase58(num) print("0x%-54x -> %s" % (num, b))
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) n := 0 for n < 1 || n > 5 { fmt.Print("How many integer variables do you want to create (max 5) : ") scanner.Scan() n, _ = strconv.Atoi(scanner.Text()) check(scanner.Err()) } vars := make(map[string]int) fmt.Println("OK, enter the variable names and their values, below") for i := 1; i <= n; { fmt.Println("\n Variable", i) fmt.Print(" Name  : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if _, ok := vars[name]; ok { fmt.Println(" Sorry, you've already created a variable of that name, try again") continue } var value int var err error for { fmt.Print(" Value : ") scanner.Scan() value, err = strconv.Atoi(scanner.Text()) check(scanner.Err()) if err != nil { fmt.Println(" Not a valid integer, try again") } else { break } } vars[name] = value i++ } fmt.Println("\nEnter q to quit") for { fmt.Print("\nWhich variable do you want to inspect : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if s := strings.ToLower(name); s == "q" { return } v, ok := vars[name] if !ok { fmt.Println("Sorry there's no variable of that name, try again") } else { fmt.Println("It's value is", v) } } }
>>> name = raw_input("Enter a variable name: ") Enter a variable name: X >>> globals()[name] = 42 >>> X 42
Please provide an equivalent version of this Go code in Python.
package main import ( "crypto/des" "encoding/hex" "fmt" "log" ) func main() { key, err := hex.DecodeString("0e329232ea6d0d73") if err != nil { log.Fatal(err) } c, err := des.NewCipher(key) if err != nil { log.Fatal(err) } src, err := hex.DecodeString("8787878787878787") if err != nil { log.Fatal(err) } dst := make([]byte, des.BlockSize) c.Encrypt(dst, src) fmt.Printf("%x\n", dst) }
IP = ( 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 ) IP_INV = ( 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 ) PC1 = ( 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ) PC2 = ( 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ) E = ( 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 ) Sboxes = { 0: ( 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 ), 1: ( 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 ), 2: ( 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 ), 3: ( 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 ), 4: ( 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 ), 5: ( 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 ), 6: ( 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 ), 7: ( 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 ) } P = ( 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 ) def encrypt(msg, key, decrypt=False): assert isinstance(msg, int) and isinstance(key, int) assert not msg.bit_length() > 64 assert not key.bit_length() > 64 key = permutation_by_table(key, 64, PC1) C0 = key >> 28 D0 = key & (2**28-1) round_keys = generate_round_keys(C0, D0) msg_block = permutation_by_table(msg, 64, IP) L0 = msg_block >> 32 R0 = msg_block & (2**32-1) L_last = L0 R_last = R0 for i in range(1,17): if decrypt: i = 17-i L_round = R_last R_round = L_last ^ round_function(R_last, round_keys[i]) L_last = L_round R_last = R_round cipher_block = (R_round<<32) + L_round cipher_block = permutation_by_table(cipher_block, 64, IP_INV) return cipher_block def round_function(Ri, Ki): Ri = permutation_by_table(Ri, 32, E) Ri ^= Ki Ri_blocks = [((Ri & (0b111111 << shift_val)) >> shift_val) for shift_val in (42,36,30,24,18,12,6,0)] for i, block in enumerate(Ri_blocks): row = ((0b100000 & block) >> 4) + (0b1 & block) col = (0b011110 & block) >> 1 Ri_blocks[i] = Sboxes[i][16*row+col] Ri_blocks = zip(Ri_blocks, (28,24,20,16,12,8,4,0)) Ri = 0 for block, lshift_val in Ri_blocks: Ri += (block << lshift_val) Ri = permutation_by_table(Ri, 32, P) return Ri def permutation_by_table(block, block_len, table): block_str = bin(block)[2:].zfill(block_len) perm = [] for pos in range(len(table)): perm.append(block_str[table[pos]-1]) return int(''.join(perm), 2) def generate_round_keys(C0, D0): round_keys = dict.fromkeys(range(0,17)) lrot_values = (1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1) lrot = lambda val, r_bits, max_bits: \ (val << r_bits%max_bits) & (2**max_bits-1) | \ ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits))) C0 = lrot(C0, 0, 28) D0 = lrot(D0, 0, 28) round_keys[0] = (C0, D0) for i, rot_val in enumerate(lrot_values): i+=1 Ci = lrot(round_keys[i-1][0], rot_val, 28) Di = lrot(round_keys[i-1][1], rot_val, 28) round_keys[i] = (Ci, Di) del round_keys[0] for i, (Ci, Di) in round_keys.items(): Ki = (Ci << 28) + Di round_keys[i] = permutation_by_table(Ki, 56, PC2) return round_keys k = 0x0e329232ea6d0d73 k2 = 0x133457799BBCDFF1 m = 0x8787878787878787 m2 = 0x0123456789ABCDEF def prove(key, msg): print('key: {:x}'.format(key)) print('message: {:x}'.format(msg)) cipher_text = encrypt(msg, key) print('encrypted: {:x}'.format(cipher_text)) plain_text = encrypt(cipher_text, key, decrypt=True) print('decrypted: {:x}'.format(plain_text)) prove(k, m) print('----------') prove(k2, m2)
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) type vector = []*big.Int type matrix []vector var ( zero = new(big.Int) one = big.NewInt(1) ) func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) temp := new(big.Int) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { result[i][j] = new(big.Int) for k := 0; k < rows2; k++ { temp.Mul(m1[i][k], m2[k][j]) result[i][j].Add(result[i][j], temp) } } } return result } func identityMatrix(n uint64) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := uint64(0); i < n; i++ { ident[i] = make(vector, n) for j := uint64(0); j < n; j++ { ident[i][j] = new(big.Int) if i == j { ident[i][j].Set(one) } } } return ident } func (m matrix) pow(n *big.Int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n.Cmp(zero) == -1: panic("Negative exponents not supported") case n.Cmp(zero) == 0: return identityMatrix(uint64(le)) case n.Cmp(one) == 0: return m } pow := identityMatrix(uint64(le)) base := m e := new(big.Int).Set(n) temp := new(big.Int) for e.Cmp(zero) > 0 { temp.And(e, one) if temp.Cmp(one) == 0 { pow = pow.mul(base) } e.Rsh(e, 1) base = base.mul(base) } return pow } func fibonacci(n *big.Int) *big.Int { if n.Cmp(zero) == 0 { return zero } m := matrix{{one, one}, {one, zero}} m = m.pow(n.Sub(n, one)) return m[0][0] } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { start := time.Now() n := new(big.Int) for i := uint64(10); i <= 1e7; i *= 10 { n.SetUint64(i) s := fibonacci(n).String() fmt.Printf("The digits of the %sth Fibonacci number (%s) are:\n", commatize(i), commatize(uint64(len(s)))) if len(s) > 20 { fmt.Printf(" First 20 : %s\n", s[0:20]) if len(s) < 40 { fmt.Printf(" Final %-2d : %s\n", len(s)-20, s[20:]) } else { fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) } } else { fmt.Printf(" All %-2d  : %s\n", len(s), s) } fmt.Println() } sfxs := []string{"nd", "th"} for i, e := range []uint{16, 32} { n.Lsh(one, e) s := fibonacci(n).String() fmt.Printf("The digits of the 2^%d%s Fibonacci number (%s) are:\n", e, sfxs[i], commatize(uint64(len(s)))) fmt.Printf(" First 20 : %s\n", s[0:20]) fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) fmt.Println() } fmt.Printf("Took %s\n\n", time.Since(start)) }
class Head(): def __init__(self, lo, hi=None, shift=0): if hi is None: hi = lo d = hi - lo ds, ls, hs = str(d), str(lo), str(hi) if d and len(ls) > len(ds): assert(len(ls) - len(ds) + 1 > 21) lo = int(str(lo)[:len(ls) - len(ds) + 1]) hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1 shift += len(ds) - 1 elif len(ls) > 100: lo = int(str(ls)[:100]) hi = lo + 1 shift = len(ls) - 100 self.lo, self.hi, self.shift = lo, hi, shift def __mul__(self, other): lo = self.lo*other.lo hi = self.hi*other.hi shift = self.shift + other.shift return Head(lo, hi, shift) def __add__(self, other): if self.shift < other.shift: return other + self sh = self.shift - other.shift if sh >= len(str(other.hi)): return Head(self.lo, self.hi, self.shift) ls = str(other.lo) hs = str(other.hi) lo = self.lo + int(ls[:len(ls)-sh]) hi = self.hi + int(hs[:len(hs)-sh]) return Head(lo, hi, self.shift) def __repr__(self): return str(self.hi)[:20] class Tail(): def __init__(self, v): self.v = int(f'{v:020d}'[-20:]) def __add__(self, other): return Tail(self.v + other.v) def __mul__(self, other): return Tail(self.v*other.v) def __repr__(self): return f'{self.v:020d}'[-20:] def mul(a, b): return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2] def fibo(n, cls): n -= 1 zero, one = cls(0), cls(1) m = (one, one, zero) e = (one, zero, one) while n: if n&1: e = mul(m, e) m = mul(m, m) n >>= 1 return f'{e[0]}' for i in range(2, 10): n = 10**i print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail)) for i in range(3, 8): n = 2**i s = f'2^{n}' print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) type vector = []*big.Int type matrix []vector var ( zero = new(big.Int) one = big.NewInt(1) ) func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) temp := new(big.Int) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { result[i][j] = new(big.Int) for k := 0; k < rows2; k++ { temp.Mul(m1[i][k], m2[k][j]) result[i][j].Add(result[i][j], temp) } } } return result } func identityMatrix(n uint64) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := uint64(0); i < n; i++ { ident[i] = make(vector, n) for j := uint64(0); j < n; j++ { ident[i][j] = new(big.Int) if i == j { ident[i][j].Set(one) } } } return ident } func (m matrix) pow(n *big.Int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n.Cmp(zero) == -1: panic("Negative exponents not supported") case n.Cmp(zero) == 0: return identityMatrix(uint64(le)) case n.Cmp(one) == 0: return m } pow := identityMatrix(uint64(le)) base := m e := new(big.Int).Set(n) temp := new(big.Int) for e.Cmp(zero) > 0 { temp.And(e, one) if temp.Cmp(one) == 0 { pow = pow.mul(base) } e.Rsh(e, 1) base = base.mul(base) } return pow } func fibonacci(n *big.Int) *big.Int { if n.Cmp(zero) == 0 { return zero } m := matrix{{one, one}, {one, zero}} m = m.pow(n.Sub(n, one)) return m[0][0] } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { start := time.Now() n := new(big.Int) for i := uint64(10); i <= 1e7; i *= 10 { n.SetUint64(i) s := fibonacci(n).String() fmt.Printf("The digits of the %sth Fibonacci number (%s) are:\n", commatize(i), commatize(uint64(len(s)))) if len(s) > 20 { fmt.Printf(" First 20 : %s\n", s[0:20]) if len(s) < 40 { fmt.Printf(" Final %-2d : %s\n", len(s)-20, s[20:]) } else { fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) } } else { fmt.Printf(" All %-2d  : %s\n", len(s), s) } fmt.Println() } sfxs := []string{"nd", "th"} for i, e := range []uint{16, 32} { n.Lsh(one, e) s := fibonacci(n).String() fmt.Printf("The digits of the 2^%d%s Fibonacci number (%s) are:\n", e, sfxs[i], commatize(uint64(len(s)))) fmt.Printf(" First 20 : %s\n", s[0:20]) fmt.Printf(" Final 20 : %s\n", s[len(s)-20:]) fmt.Println() } fmt.Printf("Took %s\n\n", time.Since(start)) }
class Head(): def __init__(self, lo, hi=None, shift=0): if hi is None: hi = lo d = hi - lo ds, ls, hs = str(d), str(lo), str(hi) if d and len(ls) > len(ds): assert(len(ls) - len(ds) + 1 > 21) lo = int(str(lo)[:len(ls) - len(ds) + 1]) hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1 shift += len(ds) - 1 elif len(ls) > 100: lo = int(str(ls)[:100]) hi = lo + 1 shift = len(ls) - 100 self.lo, self.hi, self.shift = lo, hi, shift def __mul__(self, other): lo = self.lo*other.lo hi = self.hi*other.hi shift = self.shift + other.shift return Head(lo, hi, shift) def __add__(self, other): if self.shift < other.shift: return other + self sh = self.shift - other.shift if sh >= len(str(other.hi)): return Head(self.lo, self.hi, self.shift) ls = str(other.lo) hs = str(other.hi) lo = self.lo + int(ls[:len(ls)-sh]) hi = self.hi + int(hs[:len(hs)-sh]) return Head(lo, hi, self.shift) def __repr__(self): return str(self.hi)[:20] class Tail(): def __init__(self, v): self.v = int(f'{v:020d}'[-20:]) def __add__(self, other): return Tail(self.v + other.v) def __mul__(self, other): return Tail(self.v*other.v) def __repr__(self): return f'{self.v:020d}'[-20:] def mul(a, b): return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2] def fibo(n, cls): n -= 1 zero, one = cls(0), cls(1) m = (one, one, zero) e = (one, zero, one) while n: if n&1: e = mul(m, e) m = mul(m, m) n >>= 1 return f'{e[0]}' for i in range(2, 10): n = 10**i print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail)) for i in range(3, 8): n = 2**i s = f'2^{n}' print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))
Produce a functionally identical Python code for the snippet given in Go.
package main import "fmt" func reverse(n uint64) uint64 { r := uint64(0) for n > 0 { r = n%10 + r*10 n /= 10 } return r } func main() { pow := uint64(10) nextN: for n := 2; n < 10; n++ { low := pow * 9 pow *= 10 high := pow - 1 fmt.Printf("Largest palindromic product of two %d-digit integers: ", n) for i := high; i >= low; i-- { j := reverse(i) p := i*pow + j for k := high; k > low; k -= 2 { if k % 10 == 5 { continue } l := p / k if l > high { break } if p%k == 0 { fmt.Printf("%d x %d = %d\n", k, l, p) continue nextN } } } } }
T=[set([(0, 0)])] def double(it): for a, b in it: yield a, b yield b, a def tails(n): if len(T)<=n: l = set() for i in range(10): for j in range(i, 10): I = i*10**(n-1) J = j*10**(n-1) it = tails(n-1) if I!=J: it = double(it) for t1, t2 in it: if ((I+t1)*(J+t2)+1)%10**n == 0: l.add((I+t1, J+t2)) T.append(l) return T[n] def largestPalindrome(n): m, tail = 0, n // 2 head = n - tail up = 10**head for L in range(1, 9*10**(head-1)+1): m = 0 sol = None for i in range(1, L + 1): lo = max(i, int(up - (up - L + 1)**2 / (up - i)) + 1) hi = int(up - (up - L)**2 / (up - i)) for j in range(lo, hi + 1): I = (up-i) * 10**tail J = (up-j) * 10**tail it = tails(tail) if I!=J: it = double(it) for t1, t2 in it: val = (I + t1)*(J + t2) s = str(val) if s == s[::-1] and val>m: sol = (I + t1, J + t2) m = val if m: print("{:2d}\t{:4d}".format(n, m % 1337), sol, sol[0] * sol[1]) return m % 1337 return 0 if __name__ == "__main__": for k in range(1, 14): largestPalindrome(k)
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "regexp" "strings" ) var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func commatize(s string, startIndex, period int, sep string) string { if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == "" { return s } m := reg.FindString(s[startIndex:]) if m == "" { return s } splits := strings.Split(m, ".") ip := splits[0] if len(ip) > period { pi := reverse(ip) for i := (len(ip) - 1) / period * period; i >= period; i -= period { pi = pi[:i] + sep + pi[i:] } ip = reverse(pi) } if strings.Contains(m, ".") { dp := splits[1] if len(dp) > period { for i := (len(dp) - 1) / period * period; i >= period; i -= period { dp = dp[:i] + sep + dp[i:] } } ip += "." + dp } return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1) } func main() { tests := [...]string{ "123456789.123456789", ".123456789", "57256.1D-4", "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "-in Aus$+1411.8millions", "===US$0017440 millions=== (in 2000 dollars)", "123.e8000 is pretty big.", "The land area of the earth is 57268900(29% of the surface) square miles.", "Ain't no numbers in this here words, nohow, no way, Jose.", "James was never known as 0000000007", "Arthur Eddington wrote: I believe there are " + "15747724136275002577605653961181555468044717914527116709366231425076185631031296" + " protons in the universe.", " $-140000±100 millions.", "6/9/1946 was a good year for some.", } fmt.Println(commatize(tests[0], 0, 2, "*")) fmt.Println(commatize(tests[1], 0, 3, "-")) fmt.Println(commatize(tests[2], 0, 4, "__")) fmt.Println(commatize(tests[3], 0, 5, " ")) fmt.Println(commatize(tests[4], 0, 3, ".")) for _, test := range tests[5:] { fmt.Println(commatize(test, 0, 3, ",")) } }
import re as RegEx def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ): outString = "" strPos = 0 matches = RegEx.findall( "[0-9]*", _string ) for match in matches[:-1]: if not match: outString += _string[ strPos ] strPos += 1 else: if len(match) > _periodLen: leadIn = match[:_startPos] periods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ] outString += leadIn + _separator.join( periods ) else: outString += match strPos += len( match ) return outString print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) ) print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." )) print ( Commatize( "\"-in Aus$+1411.8millions\"" )) print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" )) print ( Commatize( "123.e8000 is pretty big." )) print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." )) print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." )) print ( Commatize( "James was never known as 0000000007" )) print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." )) print ( Commatize( "␢␢␢$-140000±100 millions." )) print ( Commatize( "6/9/1946 was a good year for some." ))
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "regexp" "strings" ) var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func commatize(s string, startIndex, period int, sep string) string { if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == "" { return s } m := reg.FindString(s[startIndex:]) if m == "" { return s } splits := strings.Split(m, ".") ip := splits[0] if len(ip) > period { pi := reverse(ip) for i := (len(ip) - 1) / period * period; i >= period; i -= period { pi = pi[:i] + sep + pi[i:] } ip = reverse(pi) } if strings.Contains(m, ".") { dp := splits[1] if len(dp) > period { for i := (len(dp) - 1) / period * period; i >= period; i -= period { dp = dp[:i] + sep + dp[i:] } } ip += "." + dp } return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1) } func main() { tests := [...]string{ "123456789.123456789", ".123456789", "57256.1D-4", "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "-in Aus$+1411.8millions", "===US$0017440 millions=== (in 2000 dollars)", "123.e8000 is pretty big.", "The land area of the earth is 57268900(29% of the surface) square miles.", "Ain't no numbers in this here words, nohow, no way, Jose.", "James was never known as 0000000007", "Arthur Eddington wrote: I believe there are " + "15747724136275002577605653961181555468044717914527116709366231425076185631031296" + " protons in the universe.", " $-140000±100 millions.", "6/9/1946 was a good year for some.", } fmt.Println(commatize(tests[0], 0, 2, "*")) fmt.Println(commatize(tests[1], 0, 3, "-")) fmt.Println(commatize(tests[2], 0, 4, "__")) fmt.Println(commatize(tests[3], 0, 5, " ")) fmt.Println(commatize(tests[4], 0, 3, ".")) for _, test := range tests[5:] { fmt.Println(commatize(test, 0, 3, ",")) } }
import re as RegEx def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ): outString = "" strPos = 0 matches = RegEx.findall( "[0-9]*", _string ) for match in matches[:-1]: if not match: outString += _string[ strPos ] strPos += 1 else: if len(match) > _periodLen: leadIn = match[:_startPos] periods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ] outString += leadIn + _separator.join( periods ) else: outString += match strPos += len( match ) return outString print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) ) print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." )) print ( Commatize( "\"-in Aus$+1411.8millions\"" )) print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" )) print ( Commatize( "123.e8000 is pretty big." )) print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." )) print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." )) print ( Commatize( "James was never known as 0000000007" )) print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." )) print ( Commatize( "␢␢␢$-140000±100 millions." )) print ( Commatize( "6/9/1946 was a good year for some." ))
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "math/big" ) func cumulative_freq(freq map[byte]int64) map[byte]int64 { total := int64(0) cf := make(map[byte]int64) for i := 0; i < 256; i++ { b := byte(i) if v, ok := freq[b]; ok { cf[b] = total total += v } } return cf } func arithmethic_coding(str string, radix int64) (*big.Int, *big.Int, map[byte]int64) { chars := []byte(str) freq := make(map[byte]int64) for _, c := range chars { freq[c] += 1 } cf := cumulative_freq(freq) base := len(chars) L := big.NewInt(0) pf := big.NewInt(1) bigBase := big.NewInt(int64(base)) for _, c := range chars { x := big.NewInt(cf[c]) L.Mul(L, bigBase) L.Add(L, x.Mul(x, pf)) pf.Mul(pf, big.NewInt(freq[c])) } U := big.NewInt(0) U.Set(L) U.Add(U, pf) bigOne := big.NewInt(1) bigZero := big.NewInt(0) bigRadix := big.NewInt(radix) tmp := big.NewInt(0).Set(pf) powr := big.NewInt(0) for { tmp.Div(tmp, bigRadix) if tmp.Cmp(bigZero) == 0 { break } powr.Add(powr, bigOne) } diff := big.NewInt(0) diff.Sub(U, bigOne) diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil)) return diff, powr, freq } func arithmethic_decoding(num *big.Int, radix int64, pow *big.Int, freq map[byte]int64) string { powr := big.NewInt(radix) enc := big.NewInt(0).Set(num) enc.Mul(enc, powr.Exp(powr, pow, nil)) base := int64(0) for _, v := range freq { base += v } cf := cumulative_freq(freq) dict := make(map[int64]byte) for k, v := range cf { dict[v] = k } lchar := -1 for i := int64(0); i < base; i++ { if v, ok := dict[i]; ok { lchar = int(v) } else if lchar != -1 { dict[i] = byte(lchar) } } decoded := make([]byte, base) bigBase := big.NewInt(base) for i := base - 1; i >= 0; i-- { pow := big.NewInt(0) pow.Exp(bigBase, big.NewInt(i), nil) div := big.NewInt(0) div.Div(enc, pow) c := dict[div.Int64()] fv := freq[c] cv := cf[c] prod := big.NewInt(0).Mul(pow, big.NewInt(cv)) diff := big.NewInt(0).Sub(enc, prod) enc.Div(diff, big.NewInt(fv)) decoded[base-i-1] = c } return string(decoded) } func main() { var radix = int64(10) strSlice := []string{ `DABDDB`, `DABDDBBDDBA`, `ABRACADABRA`, `TOBEORNOTTOBEORTOBEORNOT`, } for _, str := range strSlice { enc, pow, freq := arithmethic_coding(str, radix) dec := arithmethic_decoding(enc, radix, pow, freq) fmt.Printf("%-25s=> %19s * %d^%s\n", str, enc, radix, pow) if str != dec { panic("\tHowever that is incorrect!") } } }
from collections import Counter def cumulative_freq(freq): cf = {} total = 0 for b in range(256): if b in freq: cf[b] = total total += freq[b] return cf def arithmethic_coding(bytes, radix): freq = Counter(bytes) cf = cumulative_freq(freq) base = len(bytes) lower = 0 pf = 1 for b in bytes: lower = lower*base + cf[b]*pf pf *= freq[b] upper = lower+pf pow = 0 while True: pf //= radix if pf==0: break pow += 1 enc = (upper-1) // radix**pow return enc, pow, freq def arithmethic_decoding(enc, radix, pow, freq): enc *= radix**pow; base = sum(freq.values()) cf = cumulative_freq(freq) dict = {} for k,v in cf.items(): dict[v] = k lchar = None for i in range(base): if i in dict: lchar = dict[i] elif lchar is not None: dict[i] = lchar decoded = bytearray() for i in range(base-1, -1, -1): pow = base**i div = enc//pow c = dict[div] fv = freq[c] cv = cf[c] rem = (enc - pow*cv) // fv enc = rem decoded.append(c) return bytes(decoded) radix = 10 for str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split(): enc, pow, freq = arithmethic_coding(str, radix) dec = arithmethic_decoding(enc, radix, pow, freq) print("%-25s=> %19s * %d^%s" % (str, enc, radix, pow)) if str != dec: raise Exception("\tHowever that is incorrect!")
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/big" ) func cumulative_freq(freq map[byte]int64) map[byte]int64 { total := int64(0) cf := make(map[byte]int64) for i := 0; i < 256; i++ { b := byte(i) if v, ok := freq[b]; ok { cf[b] = total total += v } } return cf } func arithmethic_coding(str string, radix int64) (*big.Int, *big.Int, map[byte]int64) { chars := []byte(str) freq := make(map[byte]int64) for _, c := range chars { freq[c] += 1 } cf := cumulative_freq(freq) base := len(chars) L := big.NewInt(0) pf := big.NewInt(1) bigBase := big.NewInt(int64(base)) for _, c := range chars { x := big.NewInt(cf[c]) L.Mul(L, bigBase) L.Add(L, x.Mul(x, pf)) pf.Mul(pf, big.NewInt(freq[c])) } U := big.NewInt(0) U.Set(L) U.Add(U, pf) bigOne := big.NewInt(1) bigZero := big.NewInt(0) bigRadix := big.NewInt(radix) tmp := big.NewInt(0).Set(pf) powr := big.NewInt(0) for { tmp.Div(tmp, bigRadix) if tmp.Cmp(bigZero) == 0 { break } powr.Add(powr, bigOne) } diff := big.NewInt(0) diff.Sub(U, bigOne) diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil)) return diff, powr, freq } func arithmethic_decoding(num *big.Int, radix int64, pow *big.Int, freq map[byte]int64) string { powr := big.NewInt(radix) enc := big.NewInt(0).Set(num) enc.Mul(enc, powr.Exp(powr, pow, nil)) base := int64(0) for _, v := range freq { base += v } cf := cumulative_freq(freq) dict := make(map[int64]byte) for k, v := range cf { dict[v] = k } lchar := -1 for i := int64(0); i < base; i++ { if v, ok := dict[i]; ok { lchar = int(v) } else if lchar != -1 { dict[i] = byte(lchar) } } decoded := make([]byte, base) bigBase := big.NewInt(base) for i := base - 1; i >= 0; i-- { pow := big.NewInt(0) pow.Exp(bigBase, big.NewInt(i), nil) div := big.NewInt(0) div.Div(enc, pow) c := dict[div.Int64()] fv := freq[c] cv := cf[c] prod := big.NewInt(0).Mul(pow, big.NewInt(cv)) diff := big.NewInt(0).Sub(enc, prod) enc.Div(diff, big.NewInt(fv)) decoded[base-i-1] = c } return string(decoded) } func main() { var radix = int64(10) strSlice := []string{ `DABDDB`, `DABDDBBDDBA`, `ABRACADABRA`, `TOBEORNOTTOBEORTOBEORNOT`, } for _, str := range strSlice { enc, pow, freq := arithmethic_coding(str, radix) dec := arithmethic_decoding(enc, radix, pow, freq) fmt.Printf("%-25s=> %19s * %d^%s\n", str, enc, radix, pow) if str != dec { panic("\tHowever that is incorrect!") } } }
from collections import Counter def cumulative_freq(freq): cf = {} total = 0 for b in range(256): if b in freq: cf[b] = total total += freq[b] return cf def arithmethic_coding(bytes, radix): freq = Counter(bytes) cf = cumulative_freq(freq) base = len(bytes) lower = 0 pf = 1 for b in bytes: lower = lower*base + cf[b]*pf pf *= freq[b] upper = lower+pf pow = 0 while True: pf //= radix if pf==0: break pow += 1 enc = (upper-1) // radix**pow return enc, pow, freq def arithmethic_decoding(enc, radix, pow, freq): enc *= radix**pow; base = sum(freq.values()) cf = cumulative_freq(freq) dict = {} for k,v in cf.items(): dict[v] = k lchar = None for i in range(base): if i in dict: lchar = dict[i] elif lchar is not None: dict[i] = lchar decoded = bytearray() for i in range(base-1, -1, -1): pow = base**i div = enc//pow c = dict[div] fv = freq[c] cv = cf[c] rem = (enc - pow*cv) // fv enc = rem decoded.append(c) return bytes(decoded) radix = 10 for str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split(): enc, pow, freq = arithmethic_coding(str, radix) dec = arithmethic_decoding(enc, radix, pow, freq) print("%-25s=> %19s * %d^%s" % (str, enc, radix, pow)) if str != dec: raise Exception("\tHowever that is incorrect!")
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import "fmt" var g = [][]int{ 0: {1}, 1: {2}, 2: {0}, 3: {1, 2, 4}, 4: {3, 5}, 5: {2, 6}, 6: {5}, 7: {4, 6, 7}, } func main() { fmt.Println(kosaraju(g)) } func kosaraju(g [][]int) []int { vis := make([]bool, len(g)) L := make([]int, len(g)) x := len(L) t := make([][]int, len(g)) var Visit func(int) Visit = func(u int) { if !vis[u] { vis[u] = true for _, v := range g[u] { Visit(v) t[v] = append(t[v], u) } x-- L[x] = u } } for u := range g { Visit(u) } c := make([]int, len(g)) var Assign func(int, int) Assign = func(u, root int) { if vis[u] { vis[u] = false c[u] = root for _, v := range t[u] { Assign(v, root) } } } for _, u := range L { Assign(u, u) } return c }
def kosaraju(g): class nonlocal: pass size = len(g) vis = [False]*size l = [0]*size nonlocal.x = size t = [[]]*size def visit(u): if not vis[u]: vis[u] = True for v in g[u]: visit(v) t[v] = t[v] + [u] nonlocal.x = nonlocal.x - 1 l[nonlocal.x] = u for u in range(len(g)): visit(u) c = [0]*size def assign(u, root): if vis[u]: vis[u] = False c[u] = root for v in t[u]: assign(v, root) for u in l: assign(u, u) return c g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]] print kosaraju(g)
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "image" "reflect" ) type t int func (r t) Twice() t { return r * 2 } func (r t) Half() t { return r / 2 } func (r t) Less(r2 t) bool { return r < r2 } func (r t) privateMethod() {} func main() { report(t(0)) report(image.Point{}) } func report(x interface{}) { v := reflect.ValueOf(x) t := reflect.TypeOf(x) n := t.NumMethod() fmt.Printf("Type %v has %d exported methods:\n", t, n) const format = "%-6s %-46s %s\n" fmt.Printf(format, "Name", "Method expression", "Method value") for i := 0; i < n; i++ { fmt.Printf(format, t.Method(i).Name, t.Method(i).Func.Type(), v.Method(i).Type(), ) } fmt.Println() }
import inspect class Super(object): def __init__(self, name): self.name = name def __str__(self): return "Super(%s)" % (self.name,) def doSup(self): return 'did super stuff' @classmethod def cls(cls): return 'cls method (in sup)' @classmethod def supCls(cls): return 'Super method' @staticmethod def supStatic(): return 'static method' class Other(object): def otherMethod(self): return 'other method' class Sub(Other, Super): def __init__(self, name, *args): super(Sub, self).__init__(name); self.rest = args; self.methods = {} def __dir__(self): return list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ + self.methods.keys() \ )) def __getattr__(self, name): if name in self.methods: if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0: if self.methods[name].__code__.co_varnames[0] == 'self': return self.methods[name].__get__(self, type(self)) if self.methods[name].__code__.co_varnames[0] == 'cls': return self.methods[name].__get__(type(self), type) return self.methods[name] raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) def __str__(self): return "Sub(%s)" % self.name def doSub(): return 'did sub stuff' @classmethod def cls(cls): return 'cls method (in Sub)' @classmethod def subCls(cls): return 'Sub method' @staticmethod def subStatic(): return 'Sub method' sup = Super('sup') sub = Sub('sub', 0, 'I', 'two') sub.methods['incr'] = lambda x: x+1 sub.methods['strs'] = lambda self, x: str(self) * x [method for method in dir(sub) if callable(getattr(sub, method))] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)] [method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)] inspect.getmembers(sub, predicate=inspect.ismethod) map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
Write the same code in Python as shown below in Go.
package main import ( "fmt" "math/rand" "time" ) var F = [][]int{ {1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}, } var I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}} var L = [][]int{ {1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}, } var N = [][]int{ {0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3}, {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}, } var P = [][]int{ {0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1}, {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2}, {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}, } var T = [][]int{ {0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0}, {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}, } var U = [][]int{ {0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1}, {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}, } var V = [][]int{ {1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0}, {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}, } var W = [][]int{ {1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}, } var X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}} var Y = [][]int{ {1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2}, {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}, } var Z = [][]int{ {0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2}, {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}, } var shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z} var symbols = []byte("FILNPTUVWXYZ-") const ( nRows = 8 nCols = 8 blank = 12 ) var grid [nRows][nCols]int var placed [12]bool func tryPlaceOrientation(o []int, r, c, shapeIndex int) bool { for i := 0; i < len(o); i += 2 { x := c + o[i+1] y := r + o[i] if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 { return false } } grid[r][c] = shapeIndex for i := 0; i < len(o); i += 2 { grid[r+o[i]][c+o[i+1]] = shapeIndex } return true } func removeOrientation(o []int, r, c int) { grid[r][c] = -1 for i := 0; i < len(o); i += 2 { grid[r+o[i]][c+o[i+1]] = -1 } } func solve(pos, numPlaced int) bool { if numPlaced == len(shapes) { return true } row := pos / nCols col := pos % nCols if grid[row][col] != -1 { return solve(pos+1, numPlaced) } for i := range shapes { if !placed[i] { for _, orientation := range shapes[i] { if !tryPlaceOrientation(orientation, row, col, i) { continue } placed[i] = true if solve(pos+1, numPlaced+1) { return true } removeOrientation(orientation, row, col) placed[i] = false } } } return false } func shuffleShapes() { rand.Shuffle(len(shapes), func(i, j int) { shapes[i], shapes[j] = shapes[j], shapes[i] symbols[i], symbols[j] = symbols[j], symbols[i] }) } func printResult() { for _, r := range grid { for _, i := range r { fmt.Printf("%c ", symbols[i]) } fmt.Println() } } func main() { rand.Seed(time.Now().UnixNano()) shuffleShapes() for r := 0; r < nRows; r++ { for i := range grid[r] { grid[r][i] = -1 } } for i := 0; i < 4; i++ { var randRow, randCol int for { randRow = rand.Intn(nRows) randCol = rand.Intn(nCols) if grid[randRow][randCol] != blank { break } } grid[randRow][randCol] = blank } if solve(0, 0) { printResult() } else { fmt.Println("No solution") } }
from itertools import product minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)), ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)), ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)), ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)), ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)), ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)), ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)), ((4311810305, 8, 4), (31, 4, 8)), ((132866, 6, 6),)) boxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋' boxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)] patterns = boxchar_single_width tiles = [] for row in reversed(minos): tiles.append([]) for n, x, y in row: for shift in (b*8 + a for a, b in product(range(x), range(y))): tiles[-1].append(n << shift) def img(seq): b = [[0]*10 for _ in range(10)] for i, s in enumerate(seq): for j, k in product(range(8), range(8)): if s & (1<<(j*8 + k)): b[j + 1][k + 1] = i + 1 idices = [[0]*9 for _ in range(9)] for i, j in product(range(9), range(9)): n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1]) idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:]))) return '\n'.join(''.join(patterns[i] for i in row) for row in idices) def tile(board=0, seq=tuple(), tiles=tiles): if not tiles: yield img(seq) return for c in tiles[0]: b = board | c tnext = [] for t in tiles[1:]: tnext.append(tuple(n for n in t if not n&b)) if not tnext[-1]: break else: yield from tile(b, seq + (c,), tnext) for x in tile(): print(x)
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func main() { var e example m := reflect.ValueOf(e).MethodByName("Foo") r := m.Call(nil) fmt.Println(r[0].Int()) }
class Example(object): def foo(self, x): return 42 + x name = "foo" getattr(Example(), name)(5)
Convert the following code from Go to Python, ensuring the logic remains intact.
x := 3
example1 = 3 example2 = 3.0 example3 = True example4 = "hello" example1 = "goodbye"
Write the same code in Python as shown below in Go.
package main import ( "fmt" "math" "math/rand" "time" ) type ff = func([]float64) float64 type parameters struct{ omega, phip, phig float64 } type state struct { iter int gbpos []float64 gbval float64 min []float64 max []float64 params parameters pos [][]float64 vel [][]float64 bpos [][]float64 bval []float64 nParticles int nDims int } func (s state) report(testfunc string) { fmt.Println("Test Function  :", testfunc) fmt.Println("Iterations  :", s.iter) fmt.Println("Global Best Position :", s.gbpos) fmt.Println("Global Best Value  :", s.gbval) } func psoInit(min, max []float64, params parameters, nParticles int) *state { nDims := len(min) pos := make([][]float64, nParticles) vel := make([][]float64, nParticles) bpos := make([][]float64, nParticles) bval := make([]float64, nParticles) for i := 0; i < nParticles; i++ { pos[i] = min vel[i] = make([]float64, nDims) bpos[i] = min bval[i] = math.Inf(1) } iter := 0 gbpos := make([]float64, nDims) for i := 0; i < nDims; i++ { gbpos[i] = math.Inf(1) } gbval := math.Inf(1) return &state{iter, gbpos, gbval, min, max, params, pos, vel, bpos, bval, nParticles, nDims} } func pso(fn ff, y *state) *state { p := y.params v := make([]float64, y.nParticles) bpos := make([][]float64, y.nParticles) bval := make([]float64, y.nParticles) gbpos := make([]float64, y.nDims) gbval := math.Inf(1) for j := 0; j < y.nParticles; j++ { v[j] = fn(y.pos[j]) if v[j] < y.bval[j] { bpos[j] = y.pos[j] bval[j] = v[j] } else { bpos[j] = y.bpos[j] bval[j] = y.bval[j] } if bval[j] < gbval { gbval = bval[j] gbpos = bpos[j] } } rg := rand.Float64() pos := make([][]float64, y.nParticles) vel := make([][]float64, y.nParticles) for j := 0; j < y.nParticles; j++ { pos[j] = make([]float64, y.nDims) vel[j] = make([]float64, y.nDims) rp := rand.Float64() ok := true for z := 0; z < y.nDims; z++ { pos[j][z] = 0 vel[j][z] = 0 } for k := 0; k < y.nDims; k++ { vel[j][k] = p.omega*y.vel[j][k] + p.phip*rp*(bpos[j][k]-y.pos[j][k]) + p.phig*rg*(gbpos[k]-y.pos[j][k]) pos[j][k] = y.pos[j][k] + vel[j][k] ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k] } if !ok { for k := 0; k < y.nDims; k++ { pos[j][k] = y.min[k] + (y.max[k]-y.min[k])*rand.Float64() } } } iter := 1 + y.iter return &state{iter, gbpos, gbval, y.min, y.max, y.params, pos, vel, bpos, bval, y.nParticles, y.nDims} } func iterate(fn ff, n int, y *state) *state { r := y for i := 0; i < n; i++ { r = pso(fn, r) } return r } func mccormick(x []float64) float64 { a, b := x[0], x[1] return math.Sin(a+b) + (a-b)*(a-b) + 1.0 + 2.5*b - 1.5*a } func michalewicz(x []float64) float64 { m := 10.0 sum := 0.0 for i := 1; i <= len(x); i++ { j := x[i-1] k := math.Sin(float64(i) * j * j / math.Pi) sum += math.Sin(j) * math.Pow(k, 2*m) } return -sum } func main() { rand.Seed(time.Now().UnixNano()) st := psoInit( []float64{-1.5, -3.0}, []float64{4.0, 4.0}, parameters{0.0, 0.6, 0.3}, 100, ) st = iterate(mccormick, 40, st) st.report("McCormick") fmt.Println("f(-.54719, -1.54719) :", mccormick([]float64{-.54719, -1.54719})) fmt.Println() st = psoInit( []float64{0.0, 0.0}, []float64{math.Pi, math.Pi}, parameters{0.3, 0.3, 0.3}, 1000, ) st = iterate(michalewicz, 30, st) st.report("Michalewicz (2D)") fmt.Println("f(2.20, 1.57)  :", michalewicz([]float64{2.2, 1.57}))
import math import random INFINITY = 1 << 127 MAX_INT = 1 << 31 class Parameters: def __init__(self, omega, phip, phig): self.omega = omega self.phip = phip self.phig = phig class State: def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims): self.iter = iter self.gbpos = gbpos self.gbval = gbval self.min = min self.max = max self.parameters = parameters self.pos = pos self.vel = vel self.bpos = bpos self.bval = bval self.nParticles = nParticles self.nDims = nDims def report(self, testfunc): print "Test Function :", testfunc print "Iterations  :", self.iter print "Global Best Position :", self.gbpos print "Global Best Value  : %.16f" % self.gbval def uniform01(): v = random.random() assert 0.0 <= v and v < 1.0 return v def psoInit(min, max, parameters, nParticles): nDims = len(min) pos = [min[:]] * nParticles vel = [[0.0] * nDims] * nParticles bpos = [min[:]] * nParticles bval = [INFINITY] * nParticles iter = 0 gbpos = [INFINITY] * nDims gbval = INFINITY return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims); def pso(fn, y): p = y.parameters v = [0.0] * (y.nParticles) bpos = [y.min[:]] * (y.nParticles) bval = [0.0] * (y.nParticles) gbpos = [0.0] * (y.nDims) gbval = INFINITY for j in xrange(0, y.nParticles): v[j] = fn(y.pos[j]) if v[j] < y.bval[j]: bpos[j] = y.pos[j][:] bval[j] = v[j] else: bpos[j] = y.bpos[j][:] bval[j] = y.bval[j] if bval[j] < gbval: gbval = bval[j] gbpos = bpos[j][:] rg = uniform01() pos = [[None] * (y.nDims)] * (y.nParticles) vel = [[None] * (y.nDims)] * (y.nParticles) for j in xrange(0, y.nParticles): rp = uniform01() ok = True vel[j] = [0.0] * (len(vel[j])) pos[j] = [0.0] * (len(pos[j])) for k in xrange(0, y.nDims): vel[j][k] = p.omega * y.vel[j][k] \ + p.phip * rp * (bpos[j][k] - y.pos[j][k]) \ + p.phig * rg * (gbpos[k] - y.pos[j][k]) pos[j][k] = y.pos[j][k] + vel[j][k] ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k] if not ok: for k in xrange(0, y.nDims): pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01() iter = 1 + y.iter return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims); def iterate(fn, n, y): r = y old = y if n == MAX_INT: while True: r = pso(fn, r) if r == old: break old = r else: for _ in xrange(0, n): r = pso(fn, r) return r def mccormick(x): (a, b) = x return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a def michalewicz(x): m = 10 d = len(x) sum = 0.0 for i in xrange(1, d): j = x[i - 1] k = math.sin(i * j * j / math.pi) sum += math.sin(j) * k ** (2.0 * m) return -sum def main(): state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100) state = iterate(mccormick, 40, state) state.report("McCormick") print "f(-.54719, -1.54719) : %.16f" % (mccormick([-.54719, -1.54719])) print state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000) state = iterate(michalewicz, 30, state) state.report("Michalewicz (2D)") print "f(2.20, 1.57)  : %.16f" % (michalewicz([2.2, 1.57])) main()
Generate an equivalent Python version of this Go code.
package main import "fmt" func f(s1, s2, sep string) string { return s1 + sep + sep + s2 } func main() { fmt.Println(f("Rosetta", "Code", ":")) }
python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(string1, string2, separator): return separator.join([string1, '', string2]) >>> f('Rosetta', 'Code', ':') 'Rosetta::Code' >>>
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import "fmt" func f(s1, s2, sep string) string { return s1 + sep + sep + s2 } func main() { fmt.Println(f("Rosetta", "Code", ":")) }
python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(string1, string2, separator): return separator.join([string1, '', string2]) >>> f('Rosetta', 'Code', ':') 'Rosetta::Code' >>>
Generate an equivalent Python version of this Go code.
package main import ( "fmt" "math/big" ) func rank(l []uint) (r big.Int) { for _, n := range l { r.Lsh(&r, n+1) r.SetBit(&r, int(n), 1) } return } func unrank(n big.Int) (l []uint) { m := new(big.Int).Set(&n) for a := m.BitLen(); a > 0; { m.SetBit(m, a-1, 0) b := m.BitLen() l = append(l, uint(a-b-1)) a = b } return } func main() { var b big.Int for i := 0; i <= 10; i++ { b.SetInt64(int64(i)) u := unrank(b) r := rank(u) fmt.Println(i, u, &r) } b.SetString("12345678901234567890", 10) u := unrank(b) r := rank(u) fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r) }
def rank(x): return int('a'.join(map(str, [1] + x)), 11) def unrank(n): s = '' while n: s,n = "0123456789a"[n%11] + s, n//11 return map(int, s.split('a'))[1:] l = [1, 2, 3, 10, 100, 987654321] print l n = rank(l) print n l = unrank(n) print l
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "io/ioutil" "os" ) func main() { fn := "myth" bx := ".backup" var err error if tf, err := os.Readlink(fn); err == nil { fn = tf } var fi os.FileInfo if fi, err = os.Stat(fn); err != nil { fmt.Println(err) return } if err = os.Rename(fn, fn+bx); err != nil { fmt.Println(err) return } err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm()) if err != nil { fmt.Println(err) } }
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "fmt" "io/ioutil" "os" ) func main() { fn := "myth" bx := ".backup" var err error if tf, err := os.Readlink(fn); err == nil { fn = tf } var fi os.FileInfo if fi, err = os.Stat(fn); err != nil { fmt.Println(err) return } if err = os.Rename(fn, fn+bx); err != nil { fmt.Println(err) return } err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm()) if err != nil { fmt.Println(err) } }
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "io/ioutil" "os" ) func main() { fn := "myth" bx := ".backup" var err error if tf, err := os.Readlink(fn); err == nil { fn = tf } var fi os.FileInfo if fi, err = os.Stat(fn); err != nil { fmt.Println(err) return } if err = os.Rename(fn, fn+bx); err != nil { fmt.Println(err) return } err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm()) if err != nil { fmt.Println(err) } }
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
Write the same code in Python as shown below in Go.
package main import ( "fmt" "strings" ) func reverseGender(s string) string { if strings.Contains(s, "She") { return strings.Replace(s, "She", "He", -1) } else if strings.Contains(s, "He") { return strings.Replace(s, "He", "She", -1) } return s } func main() { s := "She was a soul stripper. She took my heart!" t := reverseGender(s) fmt.Println(t) fmt.Println(reverseGender(t)) }
import re male2female=u re_nl=re.compile(r",[ \n]*") m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ] switch={} words=[] re_plural=re.compile("E*S$") re_ES=re.compile("ES$") def gen_pluralize(m,f): yield re_plural.sub("",m),re_plural.sub("",f) yield re_ES.sub("es",m),re_ES.sub("es",f) yield re_plural.sub("s",m),re_plural.sub("s",f) def gen_capitalize_pluralize(m,f): for m,f in gen_pluralize(m,f): yield m.capitalize(), f.capitalize() yield m,f def gen_switch_role_capitalize_pluralize(m,f): for m,f in gen_capitalize_pluralize(m,f): yield m,f yield f,m for m,f in m2f: for xy,xx in gen_switch_role_capitalize_pluralize(m,f): if xy not in switch: switch[xy]=xx words.append(xy) words="|".join(words) re_word=re.compile(ur"\b("+words+ur")\b") text=u def rev_gender(text): text=re_word.split(text) return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1] print rev_gender(text)
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "strings" ) func reverseGender(s string) string { if strings.Contains(s, "She") { return strings.Replace(s, "She", "He", -1) } else if strings.Contains(s, "He") { return strings.Replace(s, "He", "She", -1) } return s } func main() { s := "She was a soul stripper. She took my heart!" t := reverseGender(s) fmt.Println(t) fmt.Println(reverseGender(t)) }
import re male2female=u re_nl=re.compile(r",[ \n]*") m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ] switch={} words=[] re_plural=re.compile("E*S$") re_ES=re.compile("ES$") def gen_pluralize(m,f): yield re_plural.sub("",m),re_plural.sub("",f) yield re_ES.sub("es",m),re_ES.sub("es",f) yield re_plural.sub("s",m),re_plural.sub("s",f) def gen_capitalize_pluralize(m,f): for m,f in gen_pluralize(m,f): yield m.capitalize(), f.capitalize() yield m,f def gen_switch_role_capitalize_pluralize(m,f): for m,f in gen_capitalize_pluralize(m,f): yield m,f yield f,m for m,f in m2f: for xy,xx in gen_switch_role_capitalize_pluralize(m,f): if xy not in switch: switch[xy]=xx words.append(xy) words="|".join(words) re_word=re.compile(ur"\b("+words+ur")\b") text=u def rev_gender(text): text=re_word.split(text) return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1] print rev_gender(text)
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" "time" ) func main() { scanner := bufio.NewScanner(os.Stdin) number := 0 for number < 1 { fmt.Print("Enter number of seconds delay > 0 : ") scanner.Scan() input := scanner.Text() if err := scanner.Err(); err != nil { log.Fatal(err) } number, _ = strconv.Atoi(input) } filename := "" for filename == "" { fmt.Print("Enter name of .mp3 file to play (without extension) : ") scanner.Scan() filename = scanner.Text() if err := scanner.Err(); err != nil { log.Fatal(err) } } cls := "\033[2J\033[0;0H" fmt.Printf("%sAlarm will sound in %d seconds...", cls, number) time.Sleep(time.Duration(number) * time.Second) fmt.Printf(cls) cmd := exec.Command("play", filename+".mp3") if err := cmd.Run(); err != nil { log.Fatal(err) } }
import time import os seconds = input("Enter a number of seconds: ") sound = input("Enter an mp3 filename: ") time.sleep(float(seconds)) os.startfile(sound + ".mp3")
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" dd = r - 1.0 } else { binary += "0" dd = r } } return binary } func binToDec(s string) float64 { ss := strings.Replace(s, ".", "", 1) num, _ := strconv.ParseInt(ss, 2, 64) ss = strings.Split(s, ".")[1] ss = strings.Replace(ss, "1", "0", -1) den, _ := strconv.ParseInt("1" + ss, 2, 64) return float64(num) / float64(den) } func main() { f := 23.34375 fmt.Printf("%v\t => %s\n", f, decToBin(f)) s := "1011.11101" fmt.Printf("%s\t => %v\n", s, binToDec(s)) }
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char in hx[2:p]) return (('-' if neg else '') + bn.strip('0') + hx[p:p+2] + bin(int(hx[p+2:]))[2:]) def float_bin2dec(bn): neg = False if bn[0] == '-': bn = bn[1:] neg = True dp = bn.index('.') extra0 = '0' * (4 - (dp % 4)) bn2 = extra0 + bn dp = bn2.index('.') p = bn2.index('p') hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i]) for i in range(0, dp+1, 4)) bn3 = bn2[dp+1:p] extra0 = '0' * (4 - (len(bn3) % 4)) bn4 = bn3 + extra0 hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0')) for i in range(0, len(bn4), 4)) hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2] + str(int('0b' + bn2[p+2:], 2))) return float.fromhex(hx)
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" dd = r - 1.0 } else { binary += "0" dd = r } } return binary } func binToDec(s string) float64 { ss := strings.Replace(s, ".", "", 1) num, _ := strconv.ParseInt(ss, 2, 64) ss = strings.Split(s, ".")[1] ss = strings.Replace(ss, "1", "0", -1) den, _ := strconv.ParseInt("1" + ss, 2, 64) return float64(num) / float64(den) } func main() { f := 23.34375 fmt.Printf("%v\t => %s\n", f, decToBin(f)) s := "1011.11101" fmt.Printf("%s\t => %v\n", s, binToDec(s)) }
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char in hx[2:p]) return (('-' if neg else '') + bn.strip('0') + hx[p:p+2] + bin(int(hx[p+2:]))[2:]) def float_bin2dec(bn): neg = False if bn[0] == '-': bn = bn[1:] neg = True dp = bn.index('.') extra0 = '0' * (4 - (dp % 4)) bn2 = extra0 + bn dp = bn2.index('.') p = bn2.index('p') hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i]) for i in range(0, dp+1, 4)) bn3 = bn2[dp+1:p] extra0 = '0' * (4 - (len(bn3) % 4)) bn4 = bn3 + extra0 hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0')) for i in range(0, len(bn4), 4)) hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2] + str(int('0b' + bn2[p+2:], 2))) return float.fromhex(hx)
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" dd = r - 1.0 } else { binary += "0" dd = r } } return binary } func binToDec(s string) float64 { ss := strings.Replace(s, ".", "", 1) num, _ := strconv.ParseInt(ss, 2, 64) ss = strings.Split(s, ".")[1] ss = strings.Replace(ss, "1", "0", -1) den, _ := strconv.ParseInt("1" + ss, 2, 64) return float64(num) / float64(den) } func main() { f := 23.34375 fmt.Printf("%v\t => %s\n", f, decToBin(f)) s := "1011.11101" fmt.Printf("%s\t => %v\n", s, binToDec(s)) }
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char in hx[2:p]) return (('-' if neg else '') + bn.strip('0') + hx[p:p+2] + bin(int(hx[p+2:]))[2:]) def float_bin2dec(bn): neg = False if bn[0] == '-': bn = bn[1:] neg = True dp = bn.index('.') extra0 = '0' * (4 - (dp % 4)) bn2 = extra0 + bn dp = bn2.index('.') p = bn2.index('p') hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i]) for i in range(0, dp+1, 4)) bn3 = bn2[dp+1:p] extra0 = '0' * (4 - (len(bn3) % 4)) bn4 = bn3 + extra0 hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0')) for i in range(0, len(bn4), 4)) hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2] + str(int('0b' + bn2[p+2:], 2))) return float.fromhex(hx)
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
>>> def eval_with_x(code, a, b): return eval(code, {'x':b}) - eval(code, {'x':a}) >>> eval_with_x('2 ** x', 3, 5) 24
Write a version of this Go function in Python with identical behavior.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
>>> def eval_with_x(code, a, b): return eval(code, {'x':b}) - eval(code, {'x':a}) >>> eval_with_x('2 ** x', 3, 5) 24
Generate an equivalent Python version of this Go code.
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}}, {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}}, {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}}, {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}}, {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}}, {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}}, {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}}, {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}}, } func main() { for _, m := range testCases { fmt.Printf("tan %v = %v\n", m, tans(m)) } } var one = big.NewRat(1, 1) func tans(m []mTerm) *big.Rat { if len(m) == 1 { return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d)) } half := len(m) / 2 a := tans(m[:half]) b := tans(m[half:]) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) } func tanEval(coef int64, f *big.Rat) *big.Rat { if coef == 1 { return f } if coef < 0 { r := tanEval(-coef, f) return r.Neg(r) } ca := coef / 2 cb := coef - ca a := tanEval(ca, f) b := tanEval(cb, f) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) }
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and part: machins.append(part) part = [] part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1), Fraction(int(numer), (int(denom) if denom else 1)) ) ) machins.append(part) return machins def tans(xs): xslen = len(xs) if xslen == 1: return tanEval(*xs[0]) aa, bb = xs[:xslen//2], xs[xslen//2:] a, b = tans(aa), tans(bb) return (a + b) / (1 - a * b) def tanEval(coef, f): if coef == 1: return f if coef < 0: return -tanEval(-coef, f) ca = coef // 2 cb = coef - ca a, b = tanEval(ca, f), tanEval(cb, f) return (a + b) / (1 - a * b) if __name__ == '__main__': machins = parse_eqn() for machin, eqn in zip(machins, equationtext.split('\n')): ans = tans(machin) print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}}, {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}}, {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}}, {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}}, {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}}, {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}}, {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}}, {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}}, } func main() { for _, m := range testCases { fmt.Printf("tan %v = %v\n", m, tans(m)) } } var one = big.NewRat(1, 1) func tans(m []mTerm) *big.Rat { if len(m) == 1 { return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d)) } half := len(m) / 2 a := tans(m[:half]) b := tans(m[half:]) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) } func tanEval(coef int64, f *big.Rat) *big.Rat { if coef == 1 { return f } if coef < 0 { r := tanEval(-coef, f) return r.Neg(r) } ca := coef / 2 cb := coef - ca a := tanEval(ca, f) b := tanEval(cb, f) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) }
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and part: machins.append(part) part = [] part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1), Fraction(int(numer), (int(denom) if denom else 1)) ) ) machins.append(part) return machins def tans(xs): xslen = len(xs) if xslen == 1: return tanEval(*xs[0]) aa, bb = xs[:xslen//2], xs[xslen//2:] a, b = tans(aa), tans(bb) return (a + b) / (1 - a * b) def tanEval(coef, f): if coef == 1: return f if coef < 0: return -tanEval(-coef, f) ca = coef // 2 cb = coef - ca a, b = tanEval(ca, f), tanEval(cb, f) return (a + b) / (1 - a * b) if __name__ == '__main__': machins = parse_eqn() for machin, eqn in zip(machins, equationtext.split('\n')): ans = tans(machin) print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "fmt" "math" "bytes" "encoding/binary" ) type testCase struct { hashCode string string } var testCases = []testCase{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"}, {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"}, {"d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"}, {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" + "123456789012345678901234567890123456789012345678901234567890"}, } func main() { for _, tc := range testCases { fmt.Printf("%s\n%x\n\n", tc.hashCode, md5(tc.string)) } } var shift = [...]uint{7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21} var table [64]uint32 func init() { for i := range table { table[i] = uint32((1 << 32) * math.Abs(math.Sin(float64(i + 1)))) } } func md5(s string) (r [16]byte) { padded := bytes.NewBuffer([]byte(s)) padded.WriteByte(0x80) for padded.Len() % 64 != 56 { padded.WriteByte(0) } messageLenBits := uint64(len(s)) * 8 binary.Write(padded, binary.LittleEndian, messageLenBits) var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476 var buffer [16]uint32 for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil { a1, b1, c1, d1 := a, b, c, d for j := 0; j < 64; j++ { var f uint32 bufferIndex := j round := j >> 4 switch round { case 0: f = (b1 & c1) | (^b1 & d1) case 1: f = (b1 & d1) | (c1 & ^d1) bufferIndex = (bufferIndex*5 + 1) & 0x0F case 2: f = b1 ^ c1 ^ d1 bufferIndex = (bufferIndex*3 + 5) & 0x0F case 3: f = c1 ^ (b1 | ^d1) bufferIndex = (bufferIndex * 7) & 0x0F } sa := shift[(round<<2)|(j&3)] a1 += f + buffer[bufferIndex] + table[j] a1, d1, c1, b1 = d1, c1, b1, a1<<sa|a1>>(32-sa)+b1 } a, b, c, d = a+a1, b+b1, c+c1, d+d1 } binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d}) return }
import math rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] constants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)] init_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] functions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \ 16*[lambda b, c, d: (d & b) | (~d & c)] + \ 16*[lambda b, c, d: b ^ c ^ d] + \ 16*[lambda b, c, d: c ^ (b | ~d)] index_functions = 16*[lambda i: i] + \ 16*[lambda i: (5*i + 1)%16] + \ 16*[lambda i: (3*i + 5)%16] + \ 16*[lambda i: (7*i)%16] def left_rotate(x, amount): x &= 0xFFFFFFFF return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF def md5(message): message = bytearray(message) orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff message.append(0x80) while len(message)%64 != 56: message.append(0) message += orig_len_in_bits.to_bytes(8, byteorder='little') hash_pieces = init_values[:] for chunk_ofst in range(0, len(message), 64): a, b, c, d = hash_pieces chunk = message[chunk_ofst:chunk_ofst+64] for i in range(64): f = functions[i](b, c, d) g = index_functions[i](i) to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little') new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF a, b, c, d = d, new_b, b, c for i, val in enumerate([a, b, c, d]): hash_pieces[i] += val hash_pieces[i] &= 0xFFFFFFFF return sum(x<<(32*i) for i, x in enumerate(hash_pieces)) def md5_to_hex(digest): raw = digest.to_bytes(16, byteorder='little') return '{:032x}'.format(int.from_bytes(raw, byteorder='big')) if __name__=='__main__': demo = [b"", b"a", b"abc", b"message digest", b"abcdefghijklmnopqrstuvwxyz", b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"] for message in demo: print(md5_to_hex(md5(message)),' <= "',message.decode('ascii'),'"', sep='')
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "math/rand" "os" "time" ) type r2 struct { x, y float64 } type r2c struct { r2 c int } func kmpp(k int, data []r2c) { kMeans(data, kmppSeeds(k, data)) } func kmppSeeds(k int, data []r2c) []r2 { s := make([]r2, k) s[0] = data[rand.Intn(len(data))].r2 d2 := make([]float64, len(data)) for i := 1; i < k; i++ { var sum float64 for j, p := range data { _, dMin := nearest(p, s[:i]) d2[j] = dMin * dMin sum += d2[j] } target := rand.Float64() * sum j := 0 for sum = d2[0]; sum < target; sum += d2[j] { j++ } s[i] = data[j].r2 } return s } func nearest(p r2c, mean []r2) (int, float64) { iMin := 0 dMin := math.Hypot(p.x-mean[0].x, p.y-mean[0].y) for i := 1; i < len(mean); i++ { d := math.Hypot(p.x-mean[i].x, p.y-mean[i].y) if d < dMin { dMin = d iMin = i } } return iMin, dMin } func kMeans(data []r2c, mean []r2) { for i, p := range data { cMin, _ := nearest(p, mean) data[i].c = cMin } mLen := make([]int, len(mean)) for { for i := range mean { mean[i] = r2{} mLen[i] = 0 } for _, p := range data { mean[p.c].x += p.x mean[p.c].y += p.y mLen[p.c]++ } for i := range mean { inv := 1 / float64(mLen[i]) mean[i].x *= inv mean[i].y *= inv } var changes int for i, p := range data { if cMin, _ := nearest(p, mean); cMin != p.c { changes++ data[i].c = cMin } } if changes == 0 { return } } } type ecParam struct { k int nPoints int xBox, yBox int stdv int } func main() { ec := &ecParam{6, 30000, 300, 200, 30} origin, data := genECData(ec) vis(ec, data, "origin") fmt.Println("Data set origins:") fmt.Println(" x y") for _, o := range origin { fmt.Printf("%5.1f %5.1f\n", o.x, o.y) } kmpp(ec.k, data) fmt.Println( "\nCluster centroids, mean distance from centroid, number of points:") fmt.Println(" x y distance points") cent := make([]r2, ec.k) cLen := make([]int, ec.k) inv := make([]float64, ec.k) for _, p := range data { cent[p.c].x += p.x cent[p.c].y += p.y cLen[p.c]++ } for i, iLen := range cLen { inv[i] = 1 / float64(iLen) cent[i].x *= inv[i] cent[i].y *= inv[i] } dist := make([]float64, ec.k) for _, p := range data { dist[p.c] += math.Hypot(p.x-cent[p.c].x, p.y-cent[p.c].y) } for i, iLen := range cLen { fmt.Printf("%5.1f %5.1f %8.1f %6d\n", cent[i].x, cent[i].y, dist[i]*inv[i], iLen) } vis(ec, data, "clusters") } func genECData(ec *ecParam) (orig []r2, data []r2c) { rand.Seed(time.Now().UnixNano()) orig = make([]r2, ec.k) data = make([]r2c, ec.nPoints) for i, n := 0, 0; i < ec.k; i++ { x := rand.Float64() * float64(ec.xBox) y := rand.Float64() * float64(ec.yBox) orig[i] = r2{x, y} for j := ec.nPoints / ec.k; j > 0; j-- { data[n].x = rand.NormFloat64()*float64(ec.stdv) + x data[n].y = rand.NormFloat64()*float64(ec.stdv) + y data[n].c = i n++ } } return } func vis(ec *ecParam, data []r2c, fn string) { colors := make([]color.NRGBA, ec.k) for i := range colors { i3 := i * 3 third := i3 / ec.k frac := uint8((i3 % ec.k) * 255 / ec.k) switch third { case 0: colors[i] = color.NRGBA{frac, 255 - frac, 0, 255} case 1: colors[i] = color.NRGBA{0, frac, 255 - frac, 255} case 2: colors[i] = color.NRGBA{255 - frac, 0, frac, 255} } } bounds := image.Rect(-ec.stdv, -ec.stdv, ec.xBox+ec.stdv, ec.yBox+ec.stdv) im := image.NewNRGBA(bounds) draw.Draw(im, bounds, image.NewUniform(color.White), image.ZP, draw.Src) fMinX := float64(bounds.Min.X) fMaxX := float64(bounds.Max.X) fMinY := float64(bounds.Min.Y) fMaxY := float64(bounds.Max.Y) for _, p := range data { imx := math.Floor(p.x) imy := math.Floor(float64(ec.yBox) - p.y) if imx >= fMinX && imx < fMaxX && imy >= fMinY && imy < fMaxY { im.SetNRGBA(int(imx), int(imy), colors[p.c]) } } f, err := os.Create(fn + ".png") if err != nil { fmt.Println(err) return } err = png.Encode(f, im) if err != nil { fmt.Println(err) } err = f.Close() if err != nil { fmt.Println(err) } }
from math import pi, sin, cos from collections import namedtuple from random import random, choice from copy import copy try: import psyco psyco.full() except ImportError: pass FLOAT_MAX = 1e100 class Point: __slots__ = ["x", "y", "group"] def __init__(self, x=0.0, y=0.0, group=0): self.x, self.y, self.group = x, y, group def generate_points(npoints, radius): points = [Point() for _ in xrange(npoints)] for p in points: r = random() * radius ang = random() * 2 * pi p.x = r * cos(ang) p.y = r * sin(ang) return points def nearest_cluster_center(point, cluster_centers): def sqr_distance_2D(a, b): return (a.x - b.x) ** 2 + (a.y - b.y) ** 2 min_index = point.group min_dist = FLOAT_MAX for i, cc in enumerate(cluster_centers): d = sqr_distance_2D(cc, point) if min_dist > d: min_dist = d min_index = i return (min_index, min_dist) def kpp(points, cluster_centers): cluster_centers[0] = copy(choice(points)) d = [0.0 for _ in xrange(len(points))] for i in xrange(1, len(cluster_centers)): sum = 0 for j, p in enumerate(points): d[j] = nearest_cluster_center(p, cluster_centers[:i])[1] sum += d[j] sum *= random() for j, di in enumerate(d): sum -= di if sum > 0: continue cluster_centers[i] = copy(points[j]) break for p in points: p.group = nearest_cluster_center(p, cluster_centers)[0] def lloyd(points, nclusters): cluster_centers = [Point() for _ in xrange(nclusters)] kpp(points, cluster_centers) lenpts10 = len(points) >> 10 changed = 0 while True: for cc in cluster_centers: cc.x = 0 cc.y = 0 cc.group = 0 for p in points: cluster_centers[p.group].group += 1 cluster_centers[p.group].x += p.x cluster_centers[p.group].y += p.y for cc in cluster_centers: cc.x /= cc.group cc.y /= cc.group changed = 0 for p in points: min_i = nearest_cluster_center(p, cluster_centers)[0] if min_i != p.group: changed += 1 p.group = min_i if changed <= lenpts10: break for i, cc in enumerate(cluster_centers): cc.group = i return cluster_centers def print_eps(points, cluster_centers, W=400, H=400): Color = namedtuple("Color", "r g b"); colors = [] for i in xrange(len(cluster_centers)): colors.append(Color((3 * (i + 1) % 11) / 11.0, (7 * i % 11) / 11.0, (9 * i % 11) / 11.0)) max_x = max_y = -FLOAT_MAX min_x = min_y = FLOAT_MAX for p in points: if max_x < p.x: max_x = p.x if min_x > p.x: min_x = p.x if max_y < p.y: max_y = p.y if min_y > p.y: min_y = p.y scale = min(W / (max_x - min_x), H / (max_y - min_y)) cx = (max_x + min_x) / 2 cy = (max_y + min_y) / 2 print "%%!PS-Adobe-3.0\n%%%%BoundingBox: -5 -5 %d %d" % (W + 10, H + 10) print ("/l {rlineto} def /m {rmoveto} def\n" + "/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\n" + "/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath " + " gsave 1 setgray fill grestore gsave 3 setlinewidth" + " 1 setgray stroke grestore 0 setgray stroke }def") for i, cc in enumerate(cluster_centers): print ("%g %g %g setrgbcolor" % (colors[i].r, colors[i].g, colors[i].b)) for p in points: if p.group != i: continue print ("%.3f %.3f c" % ((p.x - cx) * scale + W / 2, (p.y - cy) * scale + H / 2)) print ("\n0 setgray %g %g s" % ((cc.x - cx) * scale + W / 2, (cc.y - cy) * scale + H / 2)) print "\n%%%%EOF" def main(): npoints = 30000 k = 7 points = generate_points(npoints, 10) cluster_centers = lloyd(points, k) print_eps(points, cluster_centers) main()
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "bytes" "fmt" "math/rand" "time" ) type maze struct { c2 [][]byte h2 [][]byte v2 [][]byte } func newMaze(rows, cols int) *maze { c := make([]byte, rows*cols) h := bytes.Repeat([]byte{'-'}, rows*cols) v := bytes.Repeat([]byte{'|'}, rows*cols) c2 := make([][]byte, rows) h2 := make([][]byte, rows) v2 := make([][]byte, rows) for i := range h2 { c2[i] = c[i*cols : (i+1)*cols] h2[i] = h[i*cols : (i+1)*cols] v2[i] = v[i*cols : (i+1)*cols] } return &maze{c2, h2, v2} } func (m *maze) String() string { hWall := []byte("+---") hOpen := []byte("+ ") vWall := []byte("| ") vOpen := []byte(" ") rightCorner := []byte("+\n") rightWall := []byte("|\n") var b []byte for r, hw := range m.h2 { for _, h := range hw { if h == '-' || r == 0 { b = append(b, hWall...) } else { b = append(b, hOpen...) if h != '-' && h != 0 { b[len(b)-2] = h } } } b = append(b, rightCorner...) for c, vw := range m.v2[r] { if vw == '|' || c == 0 { b = append(b, vWall...) } else { b = append(b, vOpen...) if vw != '|' && vw != 0 { b[len(b)-4] = vw } } if m.c2[r][c] != 0 { b[len(b)-2] = m.c2[r][c] } } b = append(b, rightWall...) } for _ = range m.h2[0] { b = append(b, hWall...) } b = append(b, rightCorner...) return string(b) } func (m *maze) gen() { m.g2(rand.Intn(len(m.c2)), rand.Intn(len(m.c2[0]))) } const ( up = iota dn rt lf ) func (m *maze) g2(r, c int) { m.c2[r][c] = ' ' for _, dir := range rand.Perm(4) { switch dir { case up: if r > 0 && m.c2[r-1][c] == 0 { m.h2[r][c] = 0 m.g2(r-1, c) } case lf: if c > 0 && m.c2[r][c-1] == 0 { m.v2[r][c] = 0 m.g2(r, c-1) } case dn: if r < len(m.c2)-1 && m.c2[r+1][c] == 0 { m.h2[r+1][c] = 0 m.g2(r+1, c) } case rt: if c < len(m.c2[0])-1 && m.c2[r][c+1] == 0 { m.v2[r][c+1] = 0 m.g2(r, c+1) } } } } func main() { rand.Seed(time.Now().UnixNano()) const height = 4 const width = 7 m := newMaze(height, width) m.gen() m.solve( rand.Intn(height), rand.Intn(width), rand.Intn(height), rand.Intn(width)) fmt.Print(m) } func (m *maze) solve(ra, ca, rz, cz int) { var rSolve func(ra, ca, dir int) bool rSolve = func(r, c, dir int) bool { if r == rz && c == cz { m.c2[r][c] = 'F' return true } if dir != dn && m.h2[r][c] == 0 { if rSolve(r-1, c, up) { m.c2[r][c] = '^' m.h2[r][c] = '^' return true } } if dir != up && r+1 < len(m.h2) && m.h2[r+1][c] == 0 { if rSolve(r+1, c, dn) { m.c2[r][c] = 'v' m.h2[r+1][c] = 'v' return true } } if dir != lf && c+1 < len(m.v2[0]) && m.v2[r][c+1] == 0 { if rSolve(r, c+1, rt) { m.c2[r][c] = '>' m.v2[r][c+1] = '>' return true } } if dir != rt && m.v2[r][c] == 0 { if rSolve(r, c-1, lf) { m.c2[r][c] = '<' m.v2[r][c] = '<' return true } } return false } rSolve(ra, ca, -1) m.c2[ra][ca] = 'S' }
def Dijkstra(Graph, source): infinity = float('infinity') n = len(graph) dist = [infinity]*n previous = [infinity]*n dist[source] = 0 Q = list(range(n)) while Q: u = min(Q, key=lambda n:dist[n]) Q.remove(u) if dist[u] == infinity: break for v in range(n): if Graph[u][v] and (v in Q): alt = dist[u] + Graph[u][v] if alt < dist[v]: dist[v] = alt previous[v] = u return dist,previous def display_solution(predecessor): cell = len(predecessor)-1 while cell: print(cell,end='<') cell = predecessor[cell] print(0)
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "log" "math/rand" "time" ) func generate(from, to int64) { if to < from || from < 0 { log.Fatal("Invalid range.") } span := to - from + 1 generated := make([]bool, span) count := span for count > 0 { n := from + rand.Int63n(span) if !generated[n-from] { generated[n-from] = true fmt.Printf("%2d ", n) count-- } } fmt.Println() } func main() { rand.Seed(time.Now().UnixNano()) for i := 1; i <= 5; i++ { generate(1, 20) } }
import random print(random.sample(range(1, 21), 20))
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import "fmt" type solution struct{ peg, over, land int } type move struct{ from, to int } var emptyStart = 1 var board [16]bool var jumpMoves = [16][]move{ {}, {{2, 4}, {3, 6}}, {{4, 7}, {5, 9}}, {{5, 8}, {6, 10}}, {{2, 1}, {5, 6}, {7, 11}, {8, 13}}, {{8, 12}, {9, 14}}, {{3, 1}, {5, 4}, {9, 13}, {10, 15}}, {{4, 2}, {8, 9}}, {{5, 3}, {9, 10}}, {{5, 2}, {8, 7}}, {{9, 8}}, {{12, 13}}, {{8, 5}, {13, 14}}, {{8, 4}, {9, 6}, {12, 11}, {14, 15}}, {{9, 5}, {13, 12}}, {{10, 6}, {14, 13}}, } var solutions []solution func initBoard() { for i := 1; i < 16; i++ { board[i] = true } board[emptyStart] = false } func (sol solution) split() (int, int, int) { return sol.peg, sol.over, sol.land } func (mv move) split() (int, int) { return mv.from, mv.to } func drawBoard() { var pegs [16]byte for i := 1; i < 16; i++ { if board[i] { pegs[i] = fmt.Sprintf("%X", i)[0] } else { pegs[i] = '-' } } fmt.Printf(" %c\n", pegs[1]) fmt.Printf(" %c %c\n", pegs[2], pegs[3]) fmt.Printf(" %c %c %c\n", pegs[4], pegs[5], pegs[6]) fmt.Printf(" %c %c %c %c\n", pegs[7], pegs[8], pegs[9], pegs[10]) fmt.Printf(" %c %c %c %c %c\n", pegs[11], pegs[12], pegs[13], pegs[14], pegs[15]) } func solved() bool { count := 0 for _, b := range board { if b { count++ } } return count == 1 } func solve() { if solved() { return } for peg := 1; peg < 16; peg++ { if board[peg] { for _, mv := range jumpMoves[peg] { over, land := mv.split() if board[over] && !board[land] { saveBoard := board board[peg] = false board[over] = false board[land] = true solutions = append(solutions, solution{peg, over, land}) solve() if solved() { return } board = saveBoard solutions = solutions[:len(solutions)-1] } } } } } func main() { initBoard() solve() initBoard() drawBoard() fmt.Printf("Starting with peg %X removed\n\n", emptyStart) for _, solution := range solutions { peg, over, land := solution.split() board[peg] = false board[over] = false board[land] = true drawBoard() fmt.Printf("Peg %X jumped over %X to land on %X\n\n", peg, over, land) } }
def DrawBoard(board): peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for n in xrange(1,16): peg[n] = '.' if n in board: peg[n] = "%X" % n print " %s" % peg[1] print " %s %s" % (peg[2],peg[3]) print " %s %s %s" % (peg[4],peg[5],peg[6]) print " %s %s %s %s" % (peg[7],peg[8],peg[9],peg[10]) print " %s %s %s %s %s" % (peg[11],peg[12],peg[13],peg[14],peg[15]) def RemovePeg(board,n): board.remove(n) def AddPeg(board,n): board.append(n) def IsPeg(board,n): return n in board JumpMoves = { 1: [ (2,4),(3,6) ], 2: [ (4,7),(5,9) ], 3: [ (5,8),(6,10) ], 4: [ (2,1),(5,6),(7,11),(8,13) ], 5: [ (8,12),(9,14) ], 6: [ (3,1),(5,4),(9,13),(10,15) ], 7: [ (4,2),(8,9) ], 8: [ (5,3),(9,10) ], 9: [ (5,2),(8,7) ], 10: [ (9,8) ], 11: [ (12,13) ], 12: [ (8,5),(13,14) ], 13: [ (8,4),(9,6),(12,11),(14,15) ], 14: [ (9,5),(13,12) ], 15: [ (10,6),(14,13) ] } Solution = [] def Solve(board): if len(board) == 1: return board for peg in xrange(1,16): if IsPeg(board,peg): movelist = JumpMoves[peg] for over,land in movelist: if IsPeg(board,over) and not IsPeg(board,land): saveboard = board[:] RemovePeg(board,peg) RemovePeg(board,over) AddPeg(board,land) Solution.append((peg,over,land)) board = Solve(board) if len(board) == 1: return board board = saveboard[:] del Solution[-1] return board def InitSolve(empty): board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] RemovePeg(board,empty_start) Solve(board) empty_start = 1 InitSolve(empty_start) board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] RemovePeg(board,empty_start) for peg,over,land in Solution: RemovePeg(board,peg) RemovePeg(board,over) AddPeg(board,land) DrawBoard(board) print "Peg %X jumped over %X to land on %X\n" % (peg,over,land)
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "sort" ) func fourFaceCombs() (res [][4]int) { found := make([]bool, 256) for i := 1; i <= 4; i++ { for j := 1; j <= 4; j++ { for k := 1; k <= 4; k++ { for l := 1; l <= 4; l++ { c := [4]int{i, j, k, l} sort.Ints(c[:]) key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1) if !found[key] { found[key] = true res = append(res, c) } } } } } return } func cmp(x, y [4]int) int { xw := 0 yw := 0 for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { if x[i] > y[j] { xw++ } else if y[j] > x[i] { yw++ } } } if xw < yw { return -1 } else if xw > yw { return 1 } return 0 } func findIntransitive3(cs [][4]int) (res [][3][4]int) { var c = len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[i], cs[k]) if third == 1 { res = append(res, [3][4]int{cs[i], cs[j], cs[k]}) } } } } } } return } func findIntransitive4(cs [][4]int) (res [][4][4]int) { c := len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { for l := 0; l < c; l++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[k], cs[l]) if third == -1 { fourth := cmp(cs[i], cs[l]) if fourth == 1 { res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]}) } } } } } } } } return } func main() { combs := fourFaceCombs() fmt.Println("Number of eligible 4-faced dice", len(combs)) it3 := findIntransitive3(combs) fmt.Printf("\n%d ordered lists of 3 non-transitive dice found, namely:\n", len(it3)) for _, a := range it3 { fmt.Println(a) } it4 := findIntransitive4(combs) fmt.Printf("\n%d ordered lists of 4 non-transitive dice found, namely:\n", len(it4)) for _, a := range it4 { fmt.Println(a) } }
from itertools import combinations_with_replacement as cmbr from time import time def dice_gen(n, faces, m): dice = list(cmbr(faces, n)) succ = [set(j for j, b in enumerate(dice) if sum((x>y) - (x<y) for x in a for y in b) > 0) for a in dice] def loops(seq): s = succ[seq[-1]] if len(seq) == m: if seq[0] in s: yield seq return for d in (x for x in s if x > seq[0] and not x in seq): yield from loops(seq + (d,)) yield from (tuple(''.join(dice[s]) for s in x) for i, v in enumerate(succ) for x in loops((i,))) t = time() for n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]: for i, x in enumerate(dice_gen(n, faces, loop_len)): pass print(f'{n}-sided, markings {faces}, loop length {loop_len}:') print(f'\t{i + 1}*{loop_len} solutions, e.g. {" > ".join(x)} > [loop]') t, t0 = time(), t print(f'\ttime: {t - t0:.4f} seconds\n')
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "sort" ) func fourFaceCombs() (res [][4]int) { found := make([]bool, 256) for i := 1; i <= 4; i++ { for j := 1; j <= 4; j++ { for k := 1; k <= 4; k++ { for l := 1; l <= 4; l++ { c := [4]int{i, j, k, l} sort.Ints(c[:]) key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1) if !found[key] { found[key] = true res = append(res, c) } } } } } return } func cmp(x, y [4]int) int { xw := 0 yw := 0 for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { if x[i] > y[j] { xw++ } else if y[j] > x[i] { yw++ } } } if xw < yw { return -1 } else if xw > yw { return 1 } return 0 } func findIntransitive3(cs [][4]int) (res [][3][4]int) { var c = len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[i], cs[k]) if third == 1 { res = append(res, [3][4]int{cs[i], cs[j], cs[k]}) } } } } } } return } func findIntransitive4(cs [][4]int) (res [][4][4]int) { c := len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { for l := 0; l < c; l++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[k], cs[l]) if third == -1 { fourth := cmp(cs[i], cs[l]) if fourth == 1 { res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]}) } } } } } } } } return } func main() { combs := fourFaceCombs() fmt.Println("Number of eligible 4-faced dice", len(combs)) it3 := findIntransitive3(combs) fmt.Printf("\n%d ordered lists of 3 non-transitive dice found, namely:\n", len(it3)) for _, a := range it3 { fmt.Println(a) } it4 := findIntransitive4(combs) fmt.Printf("\n%d ordered lists of 4 non-transitive dice found, namely:\n", len(it4)) for _, a := range it4 { fmt.Println(a) } }
from itertools import combinations_with_replacement as cmbr from time import time def dice_gen(n, faces, m): dice = list(cmbr(faces, n)) succ = [set(j for j, b in enumerate(dice) if sum((x>y) - (x<y) for x in a for y in b) > 0) for a in dice] def loops(seq): s = succ[seq[-1]] if len(seq) == m: if seq[0] in s: yield seq return for d in (x for x in s if x > seq[0] and not x in seq): yield from loops(seq + (d,)) yield from (tuple(''.join(dice[s]) for s in x) for i, v in enumerate(succ) for x in loops((i,))) t = time() for n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]: for i, x in enumerate(dice_gen(n, faces, loop_len)): pass print(f'{n}-sided, markings {faces}, loop length {loop_len}:') print(f'\t{i + 1}*{loop_len} solutions, e.g. {" > ".join(x)} > [loop]') t, t0 = time(), t print(f'\ttime: {t - t0:.4f} seconds\n')
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "sort" "sync" "time" ) type history struct { timestamp tsFunc hs []hset } type tsFunc func() time.Time type hset struct { int t time.Time } func newHistory(ts tsFunc) history { return history{ts, []hset{{t: ts()}}} } func (h history) int() int { return h.hs[len(h.hs)-1].int } func (h *history) set(x int) time.Time { t := h.timestamp() h.hs = append(h.hs, hset{x, t}) return t } func (h history) dump() { for _, hs := range h.hs { fmt.Println(hs.t.Format(time.StampNano), hs.int) } } func (h history) recall(t time.Time) (int, bool) { i := sort.Search(len(h.hs), func(i int) bool { return h.hs[i].t.After(t) }) if i > 0 { return h.hs[i-1].int, true } return 0, false } func newTimestamper() tsFunc { var last time.Time return func() time.Time { if t := time.Now(); t.After(last) { last = t } else { last.Add(1) } return last } } func newProtectedTimestamper() tsFunc { var last time.Time var m sync.Mutex return func() (t time.Time) { t = time.Now() m.Lock() if t.After(last) { last = t } else { last.Add(1) t = last } m.Unlock() return } } func main() { ts := newTimestamper() h := newHistory(ts) ref := []time.Time{h.set(3), h.set(1), h.set(4)} fmt.Println("History of variable h:") h.dump() fmt.Println("Recalling values:") for _, t := range ref { rv, _ := h.recall(t) fmt.Println(rv) } }
import sys HIST = {} def trace(frame, event, arg): for name,val in frame.f_locals.items(): if name not in HIST: HIST[name] = [] else: if HIST[name][-1] is val: continue HIST[name].append(val) return trace def undo(name): HIST[name].pop(-1) return HIST[name][-1] def main(): a = 10 a = 20 for i in range(5): c = i print "c:", c, "-> undo x3 ->", c = undo('c') c = undo('c') c = undo('c') print c print 'HIST:', HIST sys.settrace(trace) main()
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "github.com/fogleman/gg" "math/rand" "time" ) const c = 0.00001 func linear(x float64) float64 { return x*0.7 + 40 } type trainer struct { inputs []float64 answer int } func newTrainer(x, y float64, a int) *trainer { return &trainer{[]float64{x, y, 1}, a} } type perceptron struct { weights []float64 training []*trainer } func newPerceptron(n, w, h int) *perceptron { weights := make([]float64, n) for i := 0; i < n; i++ { weights[i] = rand.Float64()*2 - 1 } training := make([]*trainer, 2000) for i := 0; i < 2000; i++ { x := rand.Float64() * float64(w) y := rand.Float64() * float64(h) answer := 1 if y < linear(x) { answer = -1 } training[i] = newTrainer(x, y, answer) } return &perceptron{weights, training} } func (p *perceptron) feedForward(inputs []float64) int { if len(inputs) != len(p.weights) { panic("weights and input length mismatch, program terminated") } sum := 0.0 for i, w := range p.weights { sum += inputs[i] * w } if sum > 0 { return 1 } return -1 } func (p *perceptron) train(inputs []float64, desired int) { guess := p.feedForward(inputs) err := float64(desired - guess) for i := range p.weights { p.weights[i] += c * err * inputs[i] } } func (p *perceptron) draw(dc *gg.Context, iterations int) { le := len(p.training) for i, count := 0, 0; i < iterations; i, count = i+1, (count+1)%le { p.train(p.training[count].inputs, p.training[count].answer) } x := float64(dc.Width()) y := linear(x) dc.SetLineWidth(2) dc.SetRGB255(0, 0, 0) dc.DrawLine(0, linear(0), x, y) dc.Stroke() dc.SetLineWidth(1) for i := 0; i < le; i++ { guess := p.feedForward(p.training[i].inputs) x := p.training[i].inputs[0] - 4 y := p.training[i].inputs[1] - 4 if guess > 0 { dc.SetRGB(0, 0, 1) } else { dc.SetRGB(1, 0, 0) } dc.DrawCircle(x, y, 8) dc.Stroke() } } func main() { rand.Seed(time.Now().UnixNano()) w, h := 640, 360 perc := newPerceptron(3, w, h) dc := gg.NewContext(w, h) dc.SetRGB(1, 1, 1) dc.Clear() perc.draw(dc, 2000) dc.SavePNG("perceptron.png") }
import random TRAINING_LENGTH = 2000 class Perceptron: def __init__(self,n): self.c = .01 self.weights = [random.uniform(-1.0, 1.0) for _ in range(n)] def feed_forward(self, inputs): vars = [] for i in range(len(inputs)): vars.append(inputs[i] * self.weights[i]) return self.activate(sum(vars)) def activate(self, value): return 1 if value > 0 else -1 def train(self, inputs, desired): guess = self.feed_forward(inputs) error = desired - guess for i in range(len(inputs)): self.weights[i] += self.c * error * inputs[i] class Trainer(): def __init__(self, x, y, a): self.inputs = [x, y, 1] self.answer = a def F(x): return 2 * x + 1 if __name__ == "__main__": ptron = Perceptron(3) training = [] for i in range(TRAINING_LENGTH): x = random.uniform(-10,10) y = random.uniform(-10,10) answer = 1 if y < F(x): answer = -1 training.append(Trainer(x,y,answer)) result = [] for y in range(-10,10): temp = [] for x in range(-10,10): if ptron.feed_forward([x,y,1]) == 1: temp.append('^') else: temp.append('.') result.append(temp) print('Untrained') for row in result: print(''.join(v for v in row)) for t in training: ptron.train(t.inputs, t.answer) result = [] for y in range(-10,10): temp = [] for x in range(-10,10): if ptron.feed_forward([x,y,1]) == 1: temp.append('^') else: temp.append('.') result.append(temp) print('Trained') for row in result: print(''.join(v for v in row))
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time error"); return; } fmt.Println("Return value:", val) }
>>> exec 10
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time error"); return; } fmt.Println("Return value:", val) }
>>> exec 10
Convert this Go block to Python, preserving its control flow and logic.
package main import "fmt" func gcd(a, b uint) uint { if b == 0 { return a } return gcd(b, a%b) } func lcm(a, b uint) uint { return a / gcd(a, b) * b } func ipow(x, p uint) uint { prod := uint(1) for p > 0 { if p&1 != 0 { prod *= x } p >>= 1 x *= x } return prod } func getPrimes(n uint) []uint { var primes []uint for i := uint(2); i <= n; i++ { div := n / i mod := n % i for mod == 0 { primes = append(primes, i) n = div div = n / i mod = n % i } } return primes } func isPrime(n uint) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := uint(5) for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func pisanoPeriod(m uint) uint { var p, c uint = 0, 1 for i := uint(0); i < m*m; i++ { p, c = c, (p+c)%m if p == 0 && c == 1 { return i + 1 } } return 1 } func pisanoPrime(p uint, k uint) uint { if !isPrime(p) || k == 0 { return 0 } return ipow(p, k-1) * pisanoPeriod(p) } func pisano(m uint) uint { primes := getPrimes(m) primePowers := make(map[uint]uint) for _, p := range primes { primePowers[p]++ } var pps []uint for k, v := range primePowers { pps = append(pps, pisanoPrime(k, v)) } if len(pps) == 0 { return 1 } if len(pps) == 1 { return pps[0] } f := pps[0] for i := 1; i < len(pps); i++ { f = lcm(f, pps[i]) } return f } func main() { for p := uint(2); p < 15; p++ { pp := pisanoPrime(p, 2) if pp > 0 { fmt.Printf("pisanoPrime(%2d: 2) = %d\n", p, pp) } } fmt.Println() for p := uint(2); p < 180; p++ { pp := pisanoPrime(p, 1) if pp > 0 { fmt.Printf("pisanoPrime(%3d: 1) = %d\n", p, pp) } } fmt.Println() fmt.Println("pisano(n) for integers 'n' from 1 to 180 are:") for n := uint(1); n <= 180; n++ { fmt.Printf("%3d ", pisano(n)) if n != 1 && n%15 == 0 { fmt.Println() } } fmt.Println() }
from sympy import isprime, lcm, factorint, primerange from functools import reduce def pisano1(m): "Simple definition" if m < 2: return 1 lastn, n = 0, 1 for i in range(m ** 2): lastn, n = n, (lastn + n) % m if lastn == 0 and n == 1: return i + 1 return 1 def pisanoprime(p, k): "Use conjecture π(p ** k) == p ** (k − 1) * π(p) for prime p and int k > 1" assert isprime(p) and k > 0 return p ** (k - 1) * pisano1(p) def pisano_mult(m, n): "pisano(m*n) where m and n assumed coprime integers" return lcm(pisano1(m), pisano1(n)) def pisano2(m): "Uses prime factorization of m" return reduce(lcm, (pisanoprime(prime, mult) for prime, mult in factorint(m).items()), 1) if __name__ == '__main__': for n in range(1, 181): assert pisano1(n) == pisano2(n), "Wall-Sun-Sun prime exists??!!" print("\nPisano period (p, 2) for primes less than 50\n ", [pisanoprime(prime, 2) for prime in primerange(1, 50)]) print("\nPisano period (p, 1) for primes less than 180\n ", [pisanoprime(prime, 1) for prime in primerange(1, 180)]) print("\nPisano period (p) for integers 1 to 180") for i in range(1, 181): print(" %3d" % pisano2(i), end="" if i % 10 else "\n")
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import "fmt" const ( right = 1 left = -1 straight = 0 ) func normalize(tracks []int) string { size := len(tracks) a := make([]byte, size) for i := 0; i < size; i++ { a[i] = "abc"[tracks[i]+1] } norm := string(a) for i := 0; i < size; i++ { s := string(a) if s < norm { norm = s } tmp := a[0] copy(a, a[1:]) a[size-1] = tmp } return norm } func fullCircleStraight(tracks []int, nStraight int) bool { if nStraight == 0 { return true } count := 0 for _, track := range tracks { if track == straight { count++ } } if count != nStraight { return false } var straightTracks [12]int for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ { if tracks[i] == straight { straightTracks[idx%12]++ } idx += tracks[i] } any1, any2 := false, false for i := 0; i <= 5; i++ { if straightTracks[i] != straightTracks[i+6] { any1 = true break } } for i := 0; i <= 7; i++ { if straightTracks[i] != straightTracks[i+4] { any2 = true break } } return !any1 || !any2 } func fullCircleRight(tracks []int) bool { sum := 0 for _, track := range tracks { sum += track * 30 } if sum%360 != 0 { return false } var rTurns [12]int for i, idx := 0, 0; i < len(tracks) && idx >= 0; i++ { if tracks[i] == right { rTurns[idx%12]++ } idx += tracks[i] } any1, any2 := false, false for i := 0; i <= 5; i++ { if rTurns[i] != rTurns[i+6] { any1 = true break } } for i := 0; i <= 7; i++ { if rTurns[i] != rTurns[i+4] { any2 = true break } } return !any1 || !any2 } func circuits(nCurved, nStraight int) { solutions := make(map[string][]int) gen := getPermutationsGen(nCurved, nStraight) for gen.hasNext() { tracks := gen.next() if !fullCircleStraight(tracks, nStraight) { continue } if !fullCircleRight(tracks) { continue } tracks2 := make([]int, len(tracks)) copy(tracks2, tracks) solutions[normalize(tracks)] = tracks2 } report(solutions, nCurved, nStraight) } func getPermutationsGen(nCurved, nStraight int) PermutationsGen { if (nCurved+nStraight-12)%4 != 0 { panic("input must be 12 + k * 4") } var trackTypes []int switch nStraight { case 0: trackTypes = []int{right, left} case 12: trackTypes = []int{right, straight} default: trackTypes = []int{right, left, straight} } return NewPermutationsGen(nCurved+nStraight, trackTypes) } func report(sol map[string][]int, numC, numS int) { size := len(sol) fmt.Printf("\n%d solution(s) for C%d,%d \n", size, numC, numS) if numC <= 20 { for _, tracks := range sol { for _, track := range tracks { fmt.Printf("%2d ", track) } fmt.Println() } } } type PermutationsGen struct { NumPositions int choices []int indices []int sequence []int carry int } func NewPermutationsGen(numPositions int, choices []int) PermutationsGen { indices := make([]int, numPositions) sequence := make([]int, numPositions) carry := 0 return PermutationsGen{numPositions, choices, indices, sequence, carry} } func (p *PermutationsGen) next() []int { p.carry = 1 for i := 1; i < len(p.indices) && p.carry > 0; i++ { p.indices[i] += p.carry p.carry = 0 if p.indices[i] == len(p.choices) { p.carry = 1 p.indices[i] = 0 } } for j := 0; j < len(p.indices); j++ { p.sequence[j] = p.choices[p.indices[j]] } return p.sequence } func (p *PermutationsGen) hasNext() bool { return p.carry != 1 } func main() { for n := 12; n <= 28; n += 4 { circuits(n, 0) } circuits(12, 4) }
from itertools import count, islice import numpy as np from numpy import sin, cos, pi ANGDIV = 12 ANG = 2*pi/ANGDIV def draw_all(sols): import matplotlib.pyplot as plt def draw_track(ax, s): turn, xend, yend = 0, [0], [0] for d in s: x0, y0 = xend[-1], yend[-1] a = turn*ANG cs, sn = cos(a), sin(a) ang = a + d*pi/2 cx, cy = x0 + cos(ang), y0 + sin(ang) da = np.linspace(ang, ang + d*ANG, 10) xs = cx - cos(da) ys = cy - sin(da) ax.plot(xs, ys, 'green' if d == -1 else 'orange') xend.append(xs[-1]) yend.append(ys[-1]) turn += d ax.plot(xend, yend, 'k.', markersize=1) ax.set_aspect(1) ls = len(sols) if ls == 0: return w, h = min((abs(w*2 - h*3) + w*h - ls, w, h) for w, h in ((w, (ls + w - 1)//w) for w in range(1, ls + 1)))[1:] fig, ax = plt.subplots(h, w, squeeze=False) for a in ax.ravel(): a.set_axis_off() for i, s in enumerate(sols): draw_track(ax[i//w, i%w], s) plt.show() def match_up(this, that, equal_lr, seen): if not this or not that: return n = len(this[0][-1]) n2 = n*2 l_lo, l_hi, r_lo, r_hi = 0, 0, 0, 0 def record(m): for _ in range(n2): seen[m] = True m = (m&1) << (n2 - 1) | (m >> 1) if equal_lr: m ^= (1<<n2) - 1 for _ in range(n2): seen[m] = True m = (m&1) << (n2 - 1) | (m >> 1) l_n, r_n = len(this), len(that) tol = 1e-3 while l_lo < l_n: while l_hi < l_n and this[l_hi][0] - this[l_lo][0] <= tol: l_hi += 1 while r_lo < r_n and that[r_lo][0] < this[l_lo][0] - tol: r_lo += 1 r_hi = r_lo while r_hi < r_n and that[r_hi][0] < this[l_lo][0] + tol: r_hi += 1 for a in this[l_lo:l_hi]: m_left = a[-2]<<n for b in that[r_lo:r_hi]: if (m := m_left | b[-2]) not in seen: if np.abs(a[1] + b[2]) < tol: record(m) record(int(f'{m:b}'[::-1], base=2)) yield(a[-1] + b[-1]) l_lo, r_lo = l_hi, r_hi def track_combo(left, right): n = (left + right)//2 n1 = left + right - n alphas = np.exp(1j*ANG*np.arange(ANGDIV)) def half_track(m, n): turns = tuple(1 - 2*(m>>i & 1) for i in range(n)) rcnt = np.cumsum(turns)%ANGDIV asum = np.sum(alphas[rcnt]) want = asum/alphas[rcnt[-1]] return np.abs(asum), asum, want, m, turns res = [[] for _ in range(right + 1)] for i in range(1<<n): b = i.bit_count() if b <= right: res[b].append(half_track(i, n)) for v in res: v.sort() if n1 == n: return res, res res1 = [[] for _ in range(right + 1)] for i in range(1<<n1): b = i.bit_count() if b <= right: res1[b].append(half_track(i, n1)) for v in res: v.sort() return res, res1 def railway(n): seen = {} for l in range(n//2, n + 1): r = n - l if not l >= r: continue if (l - r)%ANGDIV == 0: res_l, res_r = track_combo(l, r) for i, this in enumerate(res_l): if 2*i < r: continue that = res_r[r - i] for s in match_up(this, that, l == r, seen): yield s sols = [] for i, s in enumerate(railway(30)): print(i + 1, s) sols.append(s) draw_all(sols[:40])
Write a version of this Go function in Python with identical behavior.
package main import ( "fmt" "sort" ) type point struct{ x, y int } type polyomino []point type pointset map[point]bool func (p point) rotate90() point { return point{p.y, -p.x} } func (p point) rotate180() point { return point{-p.x, -p.y} } func (p point) rotate270() point { return point{-p.y, p.x} } func (p point) reflect() point { return point{-p.x, p.y} } func (p point) String() string { return fmt.Sprintf("(%d, %d)", p.x, p.y) } func (p point) contiguous() polyomino { return polyomino{point{p.x - 1, p.y}, point{p.x + 1, p.y}, point{p.x, p.y - 1}, point{p.x, p.y + 1}} } func (po polyomino) minima() (int, int) { minx := po[0].x miny := po[0].y for i := 1; i < len(po); i++ { if po[i].x < minx { minx = po[i].x } if po[i].y < miny { miny = po[i].y } } return minx, miny } func (po polyomino) translateToOrigin() polyomino { minx, miny := po.minima() res := make(polyomino, len(po)) for i, p := range po { res[i] = point{p.x - minx, p.y - miny} } sort.Slice(res, func(i, j int) bool { return res[i].x < res[j].x || (res[i].x == res[j].x && res[i].y < res[j].y) }) return res } func (po polyomino) rotationsAndReflections() []polyomino { rr := make([]polyomino, 8) for i := 0; i < 8; i++ { rr[i] = make(polyomino, len(po)) } copy(rr[0], po) for j := 0; j < len(po); j++ { rr[1][j] = po[j].rotate90() rr[2][j] = po[j].rotate180() rr[3][j] = po[j].rotate270() rr[4][j] = po[j].reflect() rr[5][j] = po[j].rotate90().reflect() rr[6][j] = po[j].rotate180().reflect() rr[7][j] = po[j].rotate270().reflect() } return rr } func (po polyomino) canonical() polyomino { rr := po.rotationsAndReflections() minr := rr[0].translateToOrigin() mins := minr.String() for i := 1; i < 8; i++ { r := rr[i].translateToOrigin() s := r.String() if s < mins { minr = r mins = s } } return minr } func (po polyomino) String() string { return fmt.Sprintf("%v", []point(po)) } func (po polyomino) toPointset() pointset { pset := make(pointset, len(po)) for _, p := range po { pset[p] = true } return pset } func (po polyomino) newPoints() polyomino { pset := po.toPointset() m := make(pointset) for _, p := range po { pts := p.contiguous() for _, pt := range pts { if !pset[pt] { m[pt] = true } } } poly := make(polyomino, 0, len(m)) for k := range m { poly = append(poly, k) } return poly } func (po polyomino) newPolys() []polyomino { pts := po.newPoints() res := make([]polyomino, len(pts)) for i, pt := range pts { poly := make(polyomino, len(po)) copy(poly, po) poly = append(poly, pt) res[i] = poly.canonical() } return res } var monomino = polyomino{point{0, 0}} var monominoes = []polyomino{monomino} func rank(n int) []polyomino { switch { case n < 0: panic("n cannot be negative. Program terminated.") case n == 0: return []polyomino{} case n == 1: return monominoes default: r := rank(n - 1) m := make(map[string]bool) var polys []polyomino for _, po := range r { for _, po2 := range po.newPolys() { if s := po2.String(); !m[s] { polys = append(polys, po2) m[s] = true } } } sort.Slice(polys, func(i, j int) bool { return polys[i].String() < polys[j].String() }) return polys } } func main() { const n = 5 fmt.Printf("All free polyominoes of rank %d:\n\n", n) for _, poly := range rank(n) { for _, pt := range poly { fmt.Printf("%s ", pt) } fmt.Println() } const k = 10 fmt.Printf("\nNumber of free polyominoes of ranks 1 to %d:\n", k) for i := 1; i <= k; i++ { fmt.Printf("%d ", len(rank(i))) } fmt.Println() }
from itertools import imap, imap, groupby, chain, imap from operator import itemgetter from sys import argv from array import array def concat_map(func, it): return list(chain.from_iterable(imap(func, it))) def minima(poly): return (min(pt[0] for pt in poly), min(pt[1] for pt in poly)) def translate_to_origin(poly): (minx, miny) = minima(poly) return [(x - minx, y - miny) for (x, y) in poly] rotate90 = lambda (x, y): ( y, -x) rotate180 = lambda (x, y): (-x, -y) rotate270 = lambda (x, y): (-y, x) reflect = lambda (x, y): (-x, y) def rotations_and_reflections(poly): return (poly, map(rotate90, poly), map(rotate180, poly), map(rotate270, poly), map(reflect, poly), [reflect(rotate90(pt)) for pt in poly], [reflect(rotate180(pt)) for pt in poly], [reflect(rotate270(pt)) for pt in poly]) def canonical(poly): return min(sorted(translate_to_origin(pl)) for pl in rotations_and_reflections(poly)) def unique(lst): lst.sort() return map(next, imap(itemgetter(1), groupby(lst))) contiguous = lambda (x, y): [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)] def new_points(poly): return unique([pt for pt in concat_map(contiguous, poly) if pt not in poly]) def new_polys(poly): return unique([canonical(poly + [pt]) for pt in new_points(poly)]) monomino = [(0, 0)] monominoes = [monomino] def rank(n): assert n >= 0 if n == 0: return [] if n == 1: return monominoes return unique(concat_map(new_polys, rank(n - 1))) def text_representation(poly): min_pt = minima(poly) max_pt = (max(p[0] for p in poly), max(p[1] for p in poly)) table = [array('c', ' ') * (max_pt[1] - min_pt[1] + 1) for _ in xrange(max_pt[0] - min_pt[0] + 1)] for pt in poly: table[pt[0] - min_pt[0]][pt[1] - min_pt[1]] = ' return "\n".join(row.tostring() for row in table) def main(): print [len(rank(n)) for n in xrange(1, 11)] n = int(argv[1]) if (len(argv) == 2) else 5 print "\nAll free polyominoes of rank %d:" % n for poly in rank(n): print text_representation(poly), "\n" main()
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "net/url" "os" "strings" "time" ) var key string func init() { const keyFile = "api_key.txt" f, err := os.Open(keyFile) if err != nil { log.Fatal(err) } keydata, err := ioutil.ReadAll(f) if err != nil { log.Fatal(err) } key = strings.TrimSpace(string(keydata)) } type EventResponse struct { Results []Result } type Result struct { ID string Status string Name string EventURL string `json:"event_url"` Description string Time EventTime } type EventTime struct{ time.Time } func (et *EventTime) UnmarshalJSON(data []byte) error { var msec int64 if err := json.Unmarshal(data, &msec); err != nil { return err } et.Time = time.Unix(0, msec*int64(time.Millisecond)) return nil } func (et EventTime) MarshalJSON() ([]byte, error) { msec := et.UnixNano() / int64(time.Millisecond) return json.Marshal(msec) } func (r *Result) String() string { var b bytes.Buffer fmt.Fprintln(&b, "ID:", r.ID) fmt.Fprintln(&b, "URL:", r.EventURL) fmt.Fprintln(&b, "Time:", r.Time.Format(time.UnixDate)) d := r.Description const limit = 65 if len(d) > limit { d = d[:limit-1] + "…" } fmt.Fprintln(&b, "Description:", d) return b.String() } func main() { v := url.Values{ "topic": []string{"photo"}, "time": []string{",1w"}, "key": []string{key}, } u := url.URL{ Scheme: "http", Host: "api.meetup.com", Path: "2/open_events.json", RawQuery: v.Encode(), } resp, err := http.Get(u.String()) if err != nil { log.Fatal(err) } defer resp.Body.Close() log.Println("HTTP Status:", resp.Status) body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } var buf bytes.Buffer if err = json.Indent(&buf, body, "", " "); err != nil { log.Fatal(err) } var evresp EventResponse json.Unmarshal(body, &evresp) fmt.Println("Got", len(evresp.Results), "events") if len(evresp.Results) > 0 { fmt.Println("First event:\n", &evresp.Results[0]) } }
import requests import json city = None topic = None def getEvent(url_path, key) : responseString = "" params = {'city':city, 'key':key,'topic':topic} r = requests.get(url_path, params = params) print(r.url) responseString = r.text return responseString def getApiKey(key_path): key = "" f = open(key_path, 'r') key = f.read() return key def submitEvent(url_path,params): r = requests.post(url_path, data=json.dumps(params)) print(r.text+" : Event Submitted")
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import "fmt" var solution = make(chan int) var nearMiss = make(chan int) var done = make(chan bool) func main() { for i := 0; i < 4096; i++ { go checkPerm(i) } var ms []int for i := 0; i < 4096; { select { case <-done: i++ case s := <-solution: print12("solution", s) case m := <-nearMiss: ms = append(ms, m) } } for _, m := range ms { print12("near miss", m) } } func print12(label string, bits int) { fmt.Print(label, ":") for i := 1; i <= 12; i++ { if bits&1 == 1 { fmt.Print(" ", i) } bits >>= 1 } fmt.Println() } func checkPerm(tz int) { ts := func(n uint) bool { return tz>>(n-1)&1 == 1 } ntrue := func(xs ...uint) int { nt := 0 for _, x := range xs { if ts(x) { nt++ } } return nt } var con bool test := func(statement uint, b bool) { switch { case ts(statement) == b: case con: panic("bail") default: con = true } } defer func() { if x := recover(); x != nil { if msg, ok := x.(string); !ok && msg != "bail" { panic(x) } } done <- true }() test(1, true) test(2, ntrue(7, 8, 9, 10, 11, 12) == 3) test(3, ntrue(2, 4, 6, 8, 10, 12) == 2) test(4, !ts(5) || ts(6) && ts(7)) test(5, !ts(4) && !ts(3) && !ts(2)) test(6, ntrue(1, 3, 5, 7, 9, 11) == 4) test(7, ts(2) != ts(3)) test(8, !ts(7) || ts(5) && ts(6)) test(9, ntrue(1, 2, 3, 4, 5, 6) == 3) test(10, ts(11) && ts(12)) test(11, ntrue(7, 8, 9) == 1) test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4) if con { nearMiss <- tz } else { solution <- tz } }
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), ) def printer(st, matches): if False in matches: print('Missed by one statement: %i, %s' % docs[matches.index(False)]) else: print('Full match:') print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) funcs, docs = zip(*constraintinfo) full, partial = [], [] for st in product( *([(False, True)] * 12) ): truths = [bool(func(st)) for func in funcs] matches = [s == t for s,t in zip(st, truths)] mcount = sum(matches) if mcount == 12: full.append((st, matches)) elif mcount == 11: partial.append((st, matches)) for stm in full + partial: printer(*stm)
Translate this program into Python but keep the logic exactly as in Go.
package main import "fmt" var solution = make(chan int) var nearMiss = make(chan int) var done = make(chan bool) func main() { for i := 0; i < 4096; i++ { go checkPerm(i) } var ms []int for i := 0; i < 4096; { select { case <-done: i++ case s := <-solution: print12("solution", s) case m := <-nearMiss: ms = append(ms, m) } } for _, m := range ms { print12("near miss", m) } } func print12(label string, bits int) { fmt.Print(label, ":") for i := 1; i <= 12; i++ { if bits&1 == 1 { fmt.Print(" ", i) } bits >>= 1 } fmt.Println() } func checkPerm(tz int) { ts := func(n uint) bool { return tz>>(n-1)&1 == 1 } ntrue := func(xs ...uint) int { nt := 0 for _, x := range xs { if ts(x) { nt++ } } return nt } var con bool test := func(statement uint, b bool) { switch { case ts(statement) == b: case con: panic("bail") default: con = true } } defer func() { if x := recover(); x != nil { if msg, ok := x.(string); !ok && msg != "bail" { panic(x) } } done <- true }() test(1, true) test(2, ntrue(7, 8, 9, 10, 11, 12) == 3) test(3, ntrue(2, 4, 6, 8, 10, 12) == 2) test(4, !ts(5) || ts(6) && ts(7)) test(5, !ts(4) && !ts(3) && !ts(2)) test(6, ntrue(1, 3, 5, 7, 9, 11) == 4) test(7, ts(2) != ts(3)) test(8, !ts(7) || ts(5) && ts(6)) test(9, ntrue(1, 2, 3, 4, 5, 6) == 3) test(10, ts(11) && ts(12)) test(11, ntrue(7, 8, 9) == 1) test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4) if con { nearMiss <- tz } else { solution <- tz } }
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), ) def printer(st, matches): if False in matches: print('Missed by one statement: %i, %s' % docs[matches.index(False)]) else: print('Full match:') print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) funcs, docs = zip(*constraintinfo) full, partial = [], [] for st in product( *([(False, True)] * 12) ): truths = [bool(func(st)) for func in funcs] matches = [s == t for s,t in zip(st, truths)] mcount = sum(matches) if mcount == 12: full.append((st, matches)) elif mcount == 11: partial.append((st, matches)) for stm in full + partial: printer(*stm)
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "math" ) type rule func(float64, float64) float64 var dxs = []float64{ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087, } var dys = []float64{ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032, } func funnel(fa []float64, r rule) []float64 { x := 0.0 result := make([]float64, len(fa)) for i, f := range fa { result[i] = x + f x = r(x, f) } return result } func mean(fa []float64) float64 { sum := 0.0 for _, f := range fa { sum += f } return sum / float64(len(fa)) } func stdDev(fa []float64) float64 { m := mean(fa) sum := 0.0 for _, f := range fa { sum += (f - m) * (f - m) } return math.Sqrt(sum / float64(len(fa))) } func experiment(label string, r rule) { rxs := funnel(dxs, r) rys := funnel(dys, r) fmt.Println(label, " : x y") fmt.Printf("Mean  : %7.4f, %7.4f\n", mean(rxs), mean(rys)) fmt.Printf("Std Dev : %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys)) fmt.Println() } func main() { experiment("Rule 1", func(_, _ float64) float64 { return 0.0 }) experiment("Rule 2", func(_, dz float64) float64 { return -dz }) experiment("Rule 3", func(z, dz float64) float64 { return -(z + dz) }) experiment("Rule 4", func(z, dz float64) float64 { return z + dz }) }
import math dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087] dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032] def funnel(dxs, rule): x, rxs = 0, [] for dx in dxs: rxs.append(x + dx) x = rule(x, dx) return rxs def mean(xs): return sum(xs) / len(xs) def stddev(xs): m = mean(xs) return math.sqrt(sum((x-m)**2 for x in xs) / len(xs)) def experiment(label, rule): rxs, rys = funnel(dxs, rule), funnel(dys, rule) print label print 'Mean x, y  : %.4f, %.4f' % (mean(rxs), mean(rys)) print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys)) print experiment('Rule 1:', lambda z, dz: 0) experiment('Rule 2:', lambda z, dz: -dz) experiment('Rule 3:', lambda z, dz: -(z+dz)) experiment('Rule 4:', lambda z, dz: z+dz)
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "math" ) type rule func(float64, float64) float64 var dxs = []float64{ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087, } var dys = []float64{ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032, } func funnel(fa []float64, r rule) []float64 { x := 0.0 result := make([]float64, len(fa)) for i, f := range fa { result[i] = x + f x = r(x, f) } return result } func mean(fa []float64) float64 { sum := 0.0 for _, f := range fa { sum += f } return sum / float64(len(fa)) } func stdDev(fa []float64) float64 { m := mean(fa) sum := 0.0 for _, f := range fa { sum += (f - m) * (f - m) } return math.Sqrt(sum / float64(len(fa))) } func experiment(label string, r rule) { rxs := funnel(dxs, r) rys := funnel(dys, r) fmt.Println(label, " : x y") fmt.Printf("Mean  : %7.4f, %7.4f\n", mean(rxs), mean(rys)) fmt.Printf("Std Dev : %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys)) fmt.Println() } func main() { experiment("Rule 1", func(_, _ float64) float64 { return 0.0 }) experiment("Rule 2", func(_, dz float64) float64 { return -dz }) experiment("Rule 3", func(z, dz float64) float64 { return -(z + dz) }) experiment("Rule 4", func(z, dz float64) float64 { return z + dz }) }
import math dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087] dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032] def funnel(dxs, rule): x, rxs = 0, [] for dx in dxs: rxs.append(x + dx) x = rule(x, dx) return rxs def mean(xs): return sum(xs) / len(xs) def stddev(xs): m = mean(xs) return math.sqrt(sum((x-m)**2 for x in xs) / len(xs)) def experiment(label, rule): rxs, rys = funnel(dxs, rule), funnel(dys, rule) print label print 'Mean x, y  : %.4f, %.4f' % (mean(rxs), mean(rys)) print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys)) print experiment('Rule 1:', lambda z, dz: 0) experiment('Rule 2:', lambda z, dz: -dz) experiment('Rule 3:', lambda z, dz: -(z+dz)) experiment('Rule 4:', lambda z, dz: z+dz)