Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same code in Python as shown below in Go.
package main import "fmt" import "io/ioutil" import "log" import "os" import "regexp" import "strings" func main() { err := fix() if err != nil { log.Fatalln(err) } } func fix() (err error) { buf, err := ioutil.ReadAll(os.Stdin) if err != nil { return err } out, err := Lang(string(buf)) if err != nil { return err } fmt.Println(out) return nil } func Lang(in string) (out string, err error) { reg := regexp.MustCompile("<[^>]+>") out = reg.ReplaceAllStringFunc(in, repl) return out, nil } func repl(in string) (out string) { if in == "</code>" { return "</"+"lang>" } mid := in[1 : len(in)-1] var langs = []string{ "abap", "actionscript", "actionscript3", "ada", "apache", "applescript", "apt_sources", "asm", "asp", "autoit", "avisynth", "bash", "basic4gl", "bf", "blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg", "cfm", "cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css", "d", "delphi", "diff", "_div", "dos", "dot", "eiffel", "email", "fortran", "freebasic", "genero", "gettext", "glsl", "gml", "gnuplot", "go", "groovy", "haskell", "hq9plus", "html4strict", "idl", "ini", "inno", "intercal", "io", "java", "java5", "javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp", "lolcode", "lotusformulas", "lotusscript", "lscript", "lua", "m68k", "make", "matlab", "mirc", "modula3", "mpasm", "mxml", "mysql", "nsis", "objc", "ocaml", "ocaml-brief", "oobas", "oracle11", "oracle8", "pascal", "per", "perl", "php", "php-brief", "pic16", "pixelbender", "plsql", "povray", "powershell", "progress", "prolog", "providex", "python", "qbasic", "rails", "reg", "robots", "ruby", "sas", "scala", "scheme", "scilab", "sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm", "text", "thinbasic", "tsql", "typoscript", "vb", "vbnet", "verilog", "vhdl", "vim", "visualfoxpro", "visualprolog", "whitespace", "winbatch", "xml", "xorg_conf", "xpp", "z80", } for _, lang := range langs { if mid == lang { return fmt.Sprintf("<lang %s>", lang) } if strings.HasPrefix(mid, "/") { if mid[len("/"):] == lang { return "</"+"lang>" } } if strings.HasPrefix(mid, "code ") { if mid[len("code "):] == lang { return fmt.Sprintf("<lang %s>", lang) } } } return in }
from re import sub testtexts = [ , , ] for txt in testtexts: text2 = sub(r'<lang\s+\"?([\w\d\s]+)\"?\s?>', r'<syntaxhighlight lang=\1>', txt) text2 = sub(r'<lang\s*>', r'<syntaxhighlight lang=text>', text2) text2 = sub(r'</lang\s*>', r'
Write the same code in Python as shown below in Go.
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { p[i] = values[x] } fmt.Println(p) if decide(p) { return } for i := 0; ; { pn[i]++ if pn[i] < k { break } pn[i] = 0 i++ if i == n { return } } } }
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ + ':\n')(repr)(showList)( replicateM(2) )([[1, 2, 3], 'abc']) ) def liftA2List(f): return lambda xs: lambda ys: [ f(*xy) for xy in product(xs, ys) ] def fTable(s): def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) def showList(xs): return '[' + ','.join( showList(x) if isinstance(x, list) else repr(x) for x in xs ) + ']' if __name__ == '__main__': main()
Produce a functionally identical Python code for the snippet given in Go.
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { p[i] = values[x] } fmt.Println(p) if decide(p) { return } for i := 0; ; { pn[i]++ if pn[i] < k { break } pn[i] = 0 i++ if i == n { return } } } }
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ + ':\n')(repr)(showList)( replicateM(2) )([[1, 2, 3], 'abc']) ) def liftA2List(f): return lambda xs: lambda ys: [ f(*xy) for xy in product(xs, ys) ] def fTable(s): def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) def showList(xs): return '[' + ','.join( showList(x) if isinstance(x, list) else repr(x) for x in xs ) + ']' if __name__ == '__main__': main()
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "strconv" ) func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd } start = false } switch c { case '1': num1 = (num2 & 0xFFFFFF80) >> 7 num2 = num2 << 25 case '2': num1 = (num2 & 0xFFFFFFF0) >> 4 num2 = num2 << 28 case '3': num1 = (num2 & 0xFFFFFFF8) >> 3 num2 = num2 << 29 case '4': num1 = num2 << 1 num2 = num2 >> 31 case '5': num1 = num2 << 5 num2 = num2 >> 27 case '6': num1 = num2 << 12 num2 = num2 >> 20 case '7': num3 := num2 & 0x0000FF00 num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16) num1 = num3 | num4 num2 = (num2 & 0xFF000000) >> 8 case '8': num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24) num2 = (num2 & 0x00FF0000) >> 8 case '9': num1 = ^num2 default: num1 = num2 } num1 &= 0xFFFFFFFF num2 &= 0xFFFFFFFF if c != '0' && c != '9' { num1 |= num2 } num2 = num1 } return num1 } func testPasswordCalc(password, nonce string, expected uint32) { res := ownCalcPass(password, nonce) m := fmt.Sprintf("%s %s  %-10d  %-10d", password, nonce, res, expected) if res == expected { fmt.Println("PASS", m) } else { fmt.Println("FAIL", m) } } func main() { testPasswordCalc("12345", "603356072", 25280520) testPasswordCalc("12345", "410501656", 119537670) testPasswordCalc("12345", "630292165", 4269684735) }
def ownCalcPass (password, nonce, test=False) : start = True num1 = 0 num2 = 0 password = int(password) if test: print("password: %08x" % (password)) for c in nonce : if c != "0": if start: num2 = password start = False if test: print("c: %s num1: %08x num2: %08x" % (c, num1, num2)) if c == '1': num1 = (num2 & 0xFFFFFF80) >> 7 num2 = num2 << 25 elif c == '2': num1 = (num2 & 0xFFFFFFF0) >> 4 num2 = num2 << 28 elif c == '3': num1 = (num2 & 0xFFFFFFF8) >> 3 num2 = num2 << 29 elif c == '4': num1 = num2 << 1 num2 = num2 >> 31 elif c == '5': num1 = num2 << 5 num2 = num2 >> 27 elif c == '6': num1 = num2 << 12 num2 = num2 >> 20 elif c == '7': num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 ) num2 = ( num2 & 0xFF000000 ) >> 8 elif c == '8': num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 ) num2 = (num2 & 0x00FF0000) >> 8 elif c == '9': num1 = ~num2 else : num1 = num2 num1 &= 0xFFFFFFFF num2 &= 0xFFFFFFFF if (c not in "09"): num1 |= num2 if test: print(" num1: %08x num2: %08x" % (num1, num2)) num2 = num1 return num1 def test_passwd_calc(passwd, nonce, expected): res = ownCalcPass(passwd, nonce, False) m = passwd+' '+nonce+' '+str(res)+' '+str(expected) if res == int(expected) : print('PASS '+m) else : print('FAIL '+m) if __name__ == '__main__': test_passwd_calc('12345','603356072','25280520') test_passwd_calc('12345','410501656','119537670') test_passwd_calc('12345','630292165','4269684735')
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "bytes" "fmt" "io/ioutil" "log" "math/rand" "sort" "strings" "time" ) var adfgvx = "ADFGVX" var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func distinct(bs []byte) []byte { var u []byte for _, b := range bs { if !bytes.Contains(u, []byte{b}) { u = append(u, b) } } return u } func allAsciiAlphaNum(word []byte) bool { for _, b := range word { if !((b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122)) { return false } } return true } func orderKey(key string) []int { temp := make([][2]byte, len(key)) for i := 0; i < len(key); i++ { temp[i] = [2]byte{key[i], byte(i)} } sort.Slice(temp, func(i, j int) bool { return temp[i][0] < temp[j][0] }) res := make([]int, len(key)) for i := 0; i < len(key); i++ { res[i] = int(temp[i][1]) } return res } func createPolybius() []string { temp := []byte(alphabet) rand.Shuffle(36, func(i, j int) { temp[i], temp[j] = temp[j], temp[i] }) alphabet = string(temp) fmt.Println("6 x 6 Polybius square:\n") fmt.Println(" | A D F G V X") fmt.Println("---------------") p := make([]string, 6) for i := 0; i < 6; i++ { fmt.Printf("%c | ", adfgvx[i]) p[i] = alphabet[6*i : 6*(i+1)] for _, c := range p[i] { fmt.Printf("%c ", c) } fmt.Println() } return p } func createKey(n int) string { if n < 7 || n > 12 { log.Fatal("Key should be within 7 and 12 letters long.") } bs, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } words := bytes.Split(bs, []byte{'\n'}) var candidates [][]byte for _, word := range words { if len(word) == n && len(distinct(word)) == n && allAsciiAlphaNum(word) { candidates = append(candidates, word) } } k := string(bytes.ToUpper(candidates[rand.Intn(len(candidates))])) fmt.Println("\nThe key is", k) return k } func encrypt(polybius []string, key, plainText string) string { temp := "" outer: for _, ch := range []byte(plainText) { for r := 0; r <= 5; r++ { for c := 0; c <= 5; c++ { if polybius[r][c] == ch { temp += fmt.Sprintf("%c%c", adfgvx[r], adfgvx[c]) continue outer } } } } colLen := len(temp) / len(key) if len(temp)%len(key) > 0 { colLen++ } table := make([][]string, colLen) for i := 0; i < colLen; i++ { table[i] = make([]string, len(key)) } for i := 0; i < len(temp); i++ { table[i/len(key)][i%len(key)] = string(temp[i]) } order := orderKey(key) cols := make([][]string, len(key)) for i := 0; i < len(key); i++ { cols[i] = make([]string, colLen) for j := 0; j < colLen; j++ { cols[i][j] = table[j][order[i]] } } res := make([]string, len(cols)) for i := 0; i < len(cols); i++ { res[i] = strings.Join(cols[i], "") } return strings.Join(res, " ") } func decrypt(polybius []string, key, cipherText string) string { colStrs := strings.Split(cipherText, " ") maxColLen := 0 for _, s := range colStrs { if len(s) > maxColLen { maxColLen = len(s) } } cols := make([][]string, len(colStrs)) for i, s := range colStrs { var ls []string for _, c := range s { ls = append(ls, string(c)) } if len(s) < maxColLen { cols[i] = make([]string, maxColLen) copy(cols[i], ls) } else { cols[i] = ls } } table := make([][]string, maxColLen) order := orderKey(key) for i := 0; i < maxColLen; i++ { table[i] = make([]string, len(key)) for j := 0; j < len(key); j++ { table[i][order[j]] = cols[j][i] } } temp := "" for i := 0; i < len(table); i++ { temp += strings.Join(table[i], "") } plainText := "" for i := 0; i < len(temp); i += 2 { r := strings.IndexByte(adfgvx, temp[i]) c := strings.IndexByte(adfgvx, temp[i+1]) plainText = plainText + string(polybius[r][c]) } return plainText } func main() { rand.Seed(time.Now().UnixNano()) plainText := "ATTACKAT1200AM" polybius := createPolybius() key := createKey(9) fmt.Println("\nPlaintext :", plainText) cipherText := encrypt(polybius, key, plainText) fmt.Println("\nEncrypted :", cipherText) plainText2 := decrypt(polybius, key, cipherText) fmt.Println("\nDecrypted :", plainText2) }
from random import shuffle, choice from itertools import product, accumulate from numpy import floor, sqrt class ADFGVX: def __init__(self, spoly, k, alph='ADFGVX'): self.polybius = list(spoly.upper()) self.pdim = int(floor(sqrt(len(self.polybius)))) self.key = list(k.upper()) self.keylen = len(self.key) self.alphabet = list(alph) pairs = [p[0] + p[1] for p in product(self.alphabet, self.alphabet)] self.encode = dict(zip(self.polybius, pairs)) self.decode = dict((v, k) for (k, v) in self.encode.items()) def encrypt(self, msg): chars = list(''.join([self.encode[c] for c in msg.upper() if c in self.polybius])) colvecs = [(lett, chars[i:len(chars):self.keylen]) \ for (i, lett) in enumerate(self.key)] colvecs.sort(key=lambda x: x[0]) return ''.join([''.join(a[1]) for a in colvecs]) def decrypt(self, cod): chars = [c for c in cod if c in self.alphabet] sortedkey = sorted(self.key) order = [self.key.index(ch) for ch in sortedkey] originalorder = [sortedkey.index(ch) for ch in self.key] base, extra = divmod(len(chars), self.keylen) strides = [base + (1 if extra > i else 0) for i in order] starts = list(accumulate(strides[:-1], lambda x, y: x + y)) starts = [0] + starts ends = [starts[i] + strides[i] for i in range(self.keylen)] cols = [chars[starts[i]:ends[i]] for i in originalorder] pairs = [] for i in range((len(chars) - 1) // self.keylen + 1): for j in range(self.keylen): if i * self.keylen + j < len(chars): pairs.append(cols[j][i]) return ''.join([self.decode[pairs[i] + pairs[i + 1]] for i in range(0, len(pairs), 2)]) if __name__ == '__main__': PCHARS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') shuffle(PCHARS) POLYBIUS = ''.join(PCHARS) with open('unixdict.txt') as fh: WORDS = [w for w in (fh.read()).split() \ if len(w) == 9 and len(w) == len(set(list(w)))] KEY = choice(WORDS) SECRET, MESSAGE = ADFGVX(POLYBIUS, KEY), 'ATTACKAT1200AM' print(f'Polybius: {POLYBIUS}, key: {KEY}') print('Message: ', MESSAGE) ENCODED = SECRET.encrypt(MESSAGE) DECODED = SECRET.decrypt(ENCODED) print('Encoded: ', ENCODED) print('Decoded: ', DECODED)
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "bytes" "fmt" "io/ioutil" "log" "math/rand" "sort" "strings" "time" ) var adfgvx = "ADFGVX" var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func distinct(bs []byte) []byte { var u []byte for _, b := range bs { if !bytes.Contains(u, []byte{b}) { u = append(u, b) } } return u } func allAsciiAlphaNum(word []byte) bool { for _, b := range word { if !((b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122)) { return false } } return true } func orderKey(key string) []int { temp := make([][2]byte, len(key)) for i := 0; i < len(key); i++ { temp[i] = [2]byte{key[i], byte(i)} } sort.Slice(temp, func(i, j int) bool { return temp[i][0] < temp[j][0] }) res := make([]int, len(key)) for i := 0; i < len(key); i++ { res[i] = int(temp[i][1]) } return res } func createPolybius() []string { temp := []byte(alphabet) rand.Shuffle(36, func(i, j int) { temp[i], temp[j] = temp[j], temp[i] }) alphabet = string(temp) fmt.Println("6 x 6 Polybius square:\n") fmt.Println(" | A D F G V X") fmt.Println("---------------") p := make([]string, 6) for i := 0; i < 6; i++ { fmt.Printf("%c | ", adfgvx[i]) p[i] = alphabet[6*i : 6*(i+1)] for _, c := range p[i] { fmt.Printf("%c ", c) } fmt.Println() } return p } func createKey(n int) string { if n < 7 || n > 12 { log.Fatal("Key should be within 7 and 12 letters long.") } bs, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } words := bytes.Split(bs, []byte{'\n'}) var candidates [][]byte for _, word := range words { if len(word) == n && len(distinct(word)) == n && allAsciiAlphaNum(word) { candidates = append(candidates, word) } } k := string(bytes.ToUpper(candidates[rand.Intn(len(candidates))])) fmt.Println("\nThe key is", k) return k } func encrypt(polybius []string, key, plainText string) string { temp := "" outer: for _, ch := range []byte(plainText) { for r := 0; r <= 5; r++ { for c := 0; c <= 5; c++ { if polybius[r][c] == ch { temp += fmt.Sprintf("%c%c", adfgvx[r], adfgvx[c]) continue outer } } } } colLen := len(temp) / len(key) if len(temp)%len(key) > 0 { colLen++ } table := make([][]string, colLen) for i := 0; i < colLen; i++ { table[i] = make([]string, len(key)) } for i := 0; i < len(temp); i++ { table[i/len(key)][i%len(key)] = string(temp[i]) } order := orderKey(key) cols := make([][]string, len(key)) for i := 0; i < len(key); i++ { cols[i] = make([]string, colLen) for j := 0; j < colLen; j++ { cols[i][j] = table[j][order[i]] } } res := make([]string, len(cols)) for i := 0; i < len(cols); i++ { res[i] = strings.Join(cols[i], "") } return strings.Join(res, " ") } func decrypt(polybius []string, key, cipherText string) string { colStrs := strings.Split(cipherText, " ") maxColLen := 0 for _, s := range colStrs { if len(s) > maxColLen { maxColLen = len(s) } } cols := make([][]string, len(colStrs)) for i, s := range colStrs { var ls []string for _, c := range s { ls = append(ls, string(c)) } if len(s) < maxColLen { cols[i] = make([]string, maxColLen) copy(cols[i], ls) } else { cols[i] = ls } } table := make([][]string, maxColLen) order := orderKey(key) for i := 0; i < maxColLen; i++ { table[i] = make([]string, len(key)) for j := 0; j < len(key); j++ { table[i][order[j]] = cols[j][i] } } temp := "" for i := 0; i < len(table); i++ { temp += strings.Join(table[i], "") } plainText := "" for i := 0; i < len(temp); i += 2 { r := strings.IndexByte(adfgvx, temp[i]) c := strings.IndexByte(adfgvx, temp[i+1]) plainText = plainText + string(polybius[r][c]) } return plainText } func main() { rand.Seed(time.Now().UnixNano()) plainText := "ATTACKAT1200AM" polybius := createPolybius() key := createKey(9) fmt.Println("\nPlaintext :", plainText) cipherText := encrypt(polybius, key, plainText) fmt.Println("\nEncrypted :", cipherText) plainText2 := decrypt(polybius, key, cipherText) fmt.Println("\nDecrypted :", plainText2) }
from random import shuffle, choice from itertools import product, accumulate from numpy import floor, sqrt class ADFGVX: def __init__(self, spoly, k, alph='ADFGVX'): self.polybius = list(spoly.upper()) self.pdim = int(floor(sqrt(len(self.polybius)))) self.key = list(k.upper()) self.keylen = len(self.key) self.alphabet = list(alph) pairs = [p[0] + p[1] for p in product(self.alphabet, self.alphabet)] self.encode = dict(zip(self.polybius, pairs)) self.decode = dict((v, k) for (k, v) in self.encode.items()) def encrypt(self, msg): chars = list(''.join([self.encode[c] for c in msg.upper() if c in self.polybius])) colvecs = [(lett, chars[i:len(chars):self.keylen]) \ for (i, lett) in enumerate(self.key)] colvecs.sort(key=lambda x: x[0]) return ''.join([''.join(a[1]) for a in colvecs]) def decrypt(self, cod): chars = [c for c in cod if c in self.alphabet] sortedkey = sorted(self.key) order = [self.key.index(ch) for ch in sortedkey] originalorder = [sortedkey.index(ch) for ch in self.key] base, extra = divmod(len(chars), self.keylen) strides = [base + (1 if extra > i else 0) for i in order] starts = list(accumulate(strides[:-1], lambda x, y: x + y)) starts = [0] + starts ends = [starts[i] + strides[i] for i in range(self.keylen)] cols = [chars[starts[i]:ends[i]] for i in originalorder] pairs = [] for i in range((len(chars) - 1) // self.keylen + 1): for j in range(self.keylen): if i * self.keylen + j < len(chars): pairs.append(cols[j][i]) return ''.join([self.decode[pairs[i] + pairs[i + 1]] for i in range(0, len(pairs), 2)]) if __name__ == '__main__': PCHARS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') shuffle(PCHARS) POLYBIUS = ''.join(PCHARS) with open('unixdict.txt') as fh: WORDS = [w for w in (fh.read()).split() \ if len(w) == 9 and len(w) == len(set(list(w)))] KEY = choice(WORDS) SECRET, MESSAGE = ADFGVX(POLYBIUS, KEY), 'ATTACKAT1200AM' print(f'Polybius: {POLYBIUS}, key: {KEY}') print('Message: ', MESSAGE) ENCODED = SECRET.encrypt(MESSAGE) DECODED = SECRET.decrypt(ENCODED) print('Encoded: ', ENCODED) print('Decoded: ', DECODED)
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "math" ) type float float64 func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) } func main() { ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"} for _, x := range []float{float(-5), float(5)} { for _, e := range []float{float(2), float(3)} { fmt.Printf("x = %2.0f e = %0.0f | ", x, e) fmt.Printf("%s = %4.0f | ", ops[0], -x.p(e)) fmt.Printf("%s = %4.0f | ", ops[1], -(x).p(e)) fmt.Printf("%s = %4.0f | ", ops[2], (-x).p(e)) fmt.Printf("%s = %4.0f\n", ops[3], -(x.p(e))) } } }
from itertools import product xx = '-5 +5'.split() pp = '2 3'.split() texts = '-x**p -(x)**p (-x)**p -(x**p)'.split() print('Integer variable exponentiation') for x, p in product(xx, pp): print(f' x,p = {x:2},{p}; ', end=' ') x, p = int(x), int(p) print('; '.join(f"{t} =={eval(t):4}" for t in texts)) print('\nBonus integer literal exponentiation') X, P = 'xp' xx.insert(0, ' 5') texts.insert(0, 'x**p') for x, p in product(xx, pp): texts2 = [t.replace(X, x).replace(P, p) for t in texts] print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "math" ) type float float64 func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) } func main() { ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"} for _, x := range []float{float(-5), float(5)} { for _, e := range []float{float(2), float(3)} { fmt.Printf("x = %2.0f e = %0.0f | ", x, e) fmt.Printf("%s = %4.0f | ", ops[0], -x.p(e)) fmt.Printf("%s = %4.0f | ", ops[1], -(x).p(e)) fmt.Printf("%s = %4.0f | ", ops[2], (-x).p(e)) fmt.Printf("%s = %4.0f\n", ops[3], -(x.p(e))) } } }
from itertools import product xx = '-5 +5'.split() pp = '2 3'.split() texts = '-x**p -(x)**p (-x)**p -(x**p)'.split() print('Integer variable exponentiation') for x, p in product(xx, pp): print(f' x,p = {x:2},{p}; ', end=' ') x, p = int(x), int(p) print('; '.join(f"{t} =={eval(t):4}" for t in texts)) print('\nBonus integer literal exponentiation') X, P = 'xp' xx.insert(0, ' 5') texts.insert(0, 'x**p') for x, p in product(xx, pp): texts2 = [t.replace(X, x).replace(P, p) for t in texts] print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "strings" ) func isDigit(b byte) bool { return '0' <= b && b <= '9' } func separateHouseNumber(address string) (street string, house string) { length := len(address) fields := strings.Fields(address) size := len(fields) last := fields[size-1] penult := fields[size-2] if isDigit(last[0]) { isdig := isDigit(penult[0]) if size > 2 && isdig && !strings.HasPrefix(penult, "194") { house = fmt.Sprintf("%s %s", penult, last) } else { house = last } } else if size > 2 { house = fmt.Sprintf("%s %s", penult, last) } street = strings.TrimRight(address[:length-len(house)], " ") return } func main() { addresses := [...]string{ "Plataanstraat 5", "Straat 12", "Straat 12 II", "Dr. J. Straat 12", "Dr. J. Straat 12 a", "Dr. J. Straat 12-14", "Laan 1940 - 1945 37", "Plein 1940 2", "1213-laan 11", "16 april 1944 Pad 1", "1e Kruisweg 36", "Laan 1940-'45 66", "Laan '40-'45", "Langeloërduinen 3 46", "Marienwaerdt 2e Dreef 2", "Provincialeweg N205 1", "Rivium 2e Straat 59.", "Nieuwe gracht 20rd", "Nieuwe gracht 20rd 2", "Nieuwe gracht 20zw /2", "Nieuwe gracht 20zw/3", "Nieuwe gracht 20 zw/4", "Bahnhofstr. 4", "Wertstr. 10", "Lindenhof 1", "Nordesch 20", "Weilstr. 6", "Harthauer Weg 2", "Mainaustr. 49", "August-Horch-Str. 3", "Marktplatz 31", "Schmidener Weg 3", "Karl-Weysser-Str. 6", } fmt.Println("Street House Number") fmt.Println("--------------------- ------------") for _, address := range addresses { street, house := separateHouseNumber(address) if house == "" { house = "(none)" } fmt.Printf("%-22s %s\n", street, house) } }
Plataanstraat 5 split as (Plataanstraat, 5) Straat 12 split as (Straat, 12) Straat 12 II split as (Straat, 12 II) Dr. J. Straat 12 split as (Dr. J. Straat , 12) Dr. J. Straat 12 a split as (Dr. J. Straat, 12 a) Dr. J. Straat 12-14 split as (Dr. J. Straat, 12-14) Laan 1940 – 1945 37 split as (Laan 1940 – 1945, 37) Plein 1940 2 split as (Plein 1940, 2) 1213-laan 11 split as (1213-laan, 11) 16 april 1944 Pad 1 split as (16 april 1944 Pad, 1) 1e Kruisweg 36 split as (1e Kruisweg, 36) Laan 1940-’45 66 split as (Laan 1940-’45, 66) Laan ’40-’45 split as (Laan ’40-’45,) Langeloërduinen 3 46 split as (Langeloërduinen, 3 46) Marienwaerdt 2e Dreef 2 split as (Marienwaerdt 2e Dreef, 2) Provincialeweg N205 1 split as (Provincialeweg N205, 1) Rivium 2e Straat 59. split as (Rivium 2e Straat, 59.) Nieuwe gracht 20rd split as (Nieuwe gracht, 20rd) Nieuwe gracht 20rd 2 split as (Nieuwe gracht, 20rd 2) Nieuwe gracht 20zw /2 split as (Nieuwe gracht, 20zw /2) Nieuwe gracht 20zw/3 split as (Nieuwe gracht, 20zw/3) Nieuwe gracht 20 zw/4 split as (Nieuwe gracht, 20 zw/4) Bahnhofstr. 4 split as (Bahnhofstr., 4) Wertstr. 10 split as (Wertstr., 10) Lindenhof 1 split as (Lindenhof, 1) Nordesch 20 split as (Nordesch, 20) Weilstr. 6 split as (Weilstr., 6) Harthauer Weg 2 split as (Harthauer Weg, 2) Mainaustr. 49 split as (Mainaustr., 49) August-Horch-Str. 3 split as (August-Horch-Str., 3) Marktplatz 31 split as (Marktplatz, 31) Schmidener Weg 3 split as (Schmidener Weg, 3) Karl-Weysser-Str. 6 split as (Karl-Weysser-Str., 6)''')
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "strings" ) type nNode struct { name string children []nNode } type iNode struct { level int name string } func toNest(iNodes []iNode, start, level int, n *nNode) { if level == 0 { n.name = iNodes[0].name } for i := start + 1; i < len(iNodes); i++ { if iNodes[i].level == level+1 { c := nNode{iNodes[i].name, nil} toNest(iNodes, i, level+1, &c) n.children = append(n.children, c) } else if iNodes[i].level <= level { return } } } func makeIndent(outline string, tab int) []iNode { lines := strings.Split(outline, "\n") iNodes := make([]iNode, len(lines)) for i, line := range lines { line2 := strings.TrimLeft(line, " ") le, le2 := len(line), len(line2) level := (le - le2) / tab iNodes[i] = iNode{level, line2} } return iNodes } func toMarkup(n nNode, cols []string, depth int) string { var span int var colSpan func(nn nNode) colSpan = func(nn nNode) { for i, c := range nn.children { if i > 0 { span++ } colSpan(c) } } for _, c := range n.children { span = 1 colSpan(c) } var lines []string lines = append(lines, `{| class="wikitable" style="text-align: center;"`) const l1, l2 = "|-", "| |" lines = append(lines, l1) span = 1 colSpan(n) s := fmt.Sprintf(`| style="background: %s " colSpan=%d | %s`, cols[0], span, n.name) lines = append(lines, s, l1) var nestedFor func(nn nNode, level, maxLevel, col int) nestedFor = func(nn nNode, level, maxLevel, col int) { if level == 1 && maxLevel > level { for i, c := range nn.children { nestedFor(c, 2, maxLevel, i) } } else if level < maxLevel { for _, c := range nn.children { nestedFor(c, level+1, maxLevel, col) } } else { if len(nn.children) > 0 { for i, c := range nn.children { span = 1 colSpan(c) cn := col + 1 if maxLevel == 1 { cn = i + 1 } s := fmt.Sprintf(`| style="background: %s " colspan=%d | %s`, cols[cn], span, c.name) lines = append(lines, s) } } else { lines = append(lines, l2) } } } for maxLevel := 1; maxLevel < depth; maxLevel++ { nestedFor(n, 1, maxLevel, 0) if maxLevel < depth-1 { lines = append(lines, l1) } } lines = append(lines, "|}") return strings.Join(lines, "\n") } func main() { const outline = `Display an outline as a nested table. Parse the outline to a tree, measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. count the leaves descending from each node, defining the width of a leaf as 1, and the width of a parent node as a sum. (The sum of the widths of its children) and write out a table with 'colspan' values either as a wiki table, or as HTML.` const ( yellow = "#ffffe6;" orange = "#ffebd2;" green = "#f0fff0;" blue = "#e6ffff;" pink = "#ffeeff;" ) cols := []string{yellow, orange, green, blue, pink} iNodes := makeIndent(outline, 4) var n nNode toNest(iNodes, 0, 0, &n) fmt.Println(toMarkup(n, cols, 4)) fmt.Println("\n") const outline2 = `Display an outline as a nested table. Parse the outline to a tree, measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. count the leaves descending from each node, defining the width of a leaf as 1, and the width of a parent node as a sum. (The sum of the widths of its children) Propagating the sums upward as necessary. and write out a table with 'colspan' values either as a wiki table, or as HTML. Optionally add color to the nodes.` cols2 := []string{blue, yellow, orange, green, pink} var n2 nNode iNodes2 := makeIndent(outline2, 4) toNest(iNodes2, 0, 0, &n2) fmt.Println(toMarkup(n2, cols2, 4)) }
import itertools import re import sys from collections import deque from typing import NamedTuple RE_OUTLINE = re.compile(r"^((?: |\t)*)(.+)$", re.M) COLORS = itertools.cycle( [ " " " " " ] ) class Node: def __init__(self, indent, value, parent, children=None): self.indent = indent self.value = value self.parent = parent self.children = children or [] self.color = None def depth(self): if self.parent: return self.parent.depth() + 1 return -1 def height(self): if not self.children: return 0 return max(child.height() for child in self.children) + 1 def colspan(self): if self.leaf: return 1 return sum(child.colspan() for child in self.children) @property def leaf(self): return not bool(self.children) def __iter__(self): q = deque() q.append(self) while q: node = q.popleft() yield node q.extend(node.children) class Token(NamedTuple): indent: int value: str def tokenize(outline): for match in RE_OUTLINE.finditer(outline): indent, value = match.groups() yield Token(len(indent), value) def parse(outline): tokens = list(tokenize(outline)) temp_root = Node(-1, "", None) _parse(tokens, 0, temp_root) root = temp_root.children[0] pad_tree(root, root.height()) return root def _parse(tokens, index, node): if index >= len(tokens): return token = tokens[index] if token.indent == node.indent: current = Node(token.indent, token.value, node.parent) node.parent.children.append(current) _parse(tokens, index + 1, current) elif token.indent > node.indent: current = Node(token.indent, token.value, node) node.children.append(current) _parse(tokens, index + 1, current) elif token.indent < node.indent: _parse(tokens, index, node.parent) def pad_tree(node, height): if node.leaf and node.depth() < height: pad_node = Node(node.indent + 1, "", node) node.children.append(pad_node) for child in node.children: pad_tree(child, height) def color_tree(node): if not node.value: node.color = " elif node.depth() <= 1: node.color = next(COLORS) else: node.color = node.parent.color for child in node.children: color_tree(child) def table_data(node): indent = " " if node.colspan() > 1: colspan = f'colspan="{node.colspan()}"' else: colspan = "" if node.color: style = f'style="background-color: {node.color};"' else: style = "" attrs = " ".join([colspan, style]) return f"{indent}<td{attrs}>{node.value}</td>" def html_table(tree): table_cols = tree.colspan() row_cols = 0 buf = ["<table style='text-align: center;'>"] for node in tree: if row_cols == 0: buf.append(" <tr>") buf.append(table_data(node)) row_cols += node.colspan() if row_cols == table_cols: buf.append(" </tr>") row_cols = 0 buf.append("</table>") return "\n".join(buf) def wiki_table_data(node): if not node.value: return "| |" if node.colspan() > 1: colspan = f"colspan={node.colspan()}" else: colspan = "" if node.color: style = f'style="background: {node.color};"' else: style = "" attrs = " ".join([colspan, style]) return f"| {attrs} | {node.value}" def wiki_table(tree): table_cols = tree.colspan() row_cols = 0 buf = ['{| class="wikitable" style="text-align: center;"'] for node in tree: if row_cols == 0: buf.append("|-") buf.append(wiki_table_data(node)) row_cols += node.colspan() if row_cols == table_cols: row_cols = 0 buf.append("|}") return "\n".join(buf) def example(table_format="wiki"): outline = ( "Display an outline as a nested table.\n" " Parse the outline to a tree,\n" " measuring the indent of each line,\n" " translating the indentation to a nested structure,\n" " and padding the tree to even depth.\n" " count the leaves descending from each node,\n" " defining the width of a leaf as 1,\n" " and the width of a parent node as a sum.\n" " (The sum of the widths of its children)\n" " and write out a table with 'colspan' values\n" " either as a wiki table,\n" " or as HTML." ) tree = parse(outline) color_tree(tree) if table_format == "wiki": print(wiki_table(tree)) else: print(html_table(tree)) if __name__ == "__main__": args = sys.argv[1:] if len(args) == 1: table_format = args[0] else: table_format = "wiki" example(table_format)
Generate a Python translation of this Go snippet without changing its computational steps.
package main import "fmt" func indexOf(l []int, n int) int { for i := 0; i < len(l); i++ { if l[i] == n { return i } } return -1 } func common2(l1, l2 []int) []int { c1, c2 := len(l1), len(l2) shortest, longest := l1, l2 if c1 > c2 { shortest, longest = l2, l1 } longest2 := make([]int, len(longest)) copy(longest2, longest) var res []int for _, e := range shortest { ix := indexOf(longest2, e) if ix >= 0 { res = append(res, e) longest2 = append(longest2[:ix], longest2[ix+1:]...) } } return res } func commonN(ll [][]int) []int { n := len(ll) if n == 0 { return []int{} } if n == 1 { return ll[0] } res := common2(ll[0], ll[1]) if n == 2 { return res } for _, l := range ll[2:] { res = common2(res, l) } return res } func main() { lls := [][][]int{ {{2, 5, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 9, 8, 4}, {1, 3, 7, 6, 9}}, {{2, 2, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 2, 2, 4}, {2, 3, 7, 6, 2}}, } for _, ll := range lls { fmt.Println("Intersection of", ll, "is:") fmt.Println(commonN(ll)) fmt.Println() } }
def common_list_elements(*lists): return list(set.intersection(*(set(list_) for list_ in lists))) if __name__ == "__main__": test_cases = [ ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]), ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]), ] for case in test_cases: result = common_list_elements(*case) print(f"Intersection of {case} is {result}")
Port the provided Go code into Python while preserving the original functionality.
package main import "fmt" func indexOf(l []int, n int) int { for i := 0; i < len(l); i++ { if l[i] == n { return i } } return -1 } func common2(l1, l2 []int) []int { c1, c2 := len(l1), len(l2) shortest, longest := l1, l2 if c1 > c2 { shortest, longest = l2, l1 } longest2 := make([]int, len(longest)) copy(longest2, longest) var res []int for _, e := range shortest { ix := indexOf(longest2, e) if ix >= 0 { res = append(res, e) longest2 = append(longest2[:ix], longest2[ix+1:]...) } } return res } func commonN(ll [][]int) []int { n := len(ll) if n == 0 { return []int{} } if n == 1 { return ll[0] } res := common2(ll[0], ll[1]) if n == 2 { return res } for _, l := range ll[2:] { res = common2(res, l) } return res } func main() { lls := [][][]int{ {{2, 5, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 9, 8, 4}, {1, 3, 7, 6, 9}}, {{2, 2, 1, 3, 8, 9, 4, 6}, {3, 5, 6, 2, 2, 2, 4}, {2, 3, 7, 6, 2}}, } for _, ll := range lls { fmt.Println("Intersection of", ll, "is:") fmt.Println(commonN(ll)) fmt.Println() } }
def common_list_elements(*lists): return list(set.intersection(*(set(list_) for list_ in lists))) if __name__ == "__main__": test_cases = [ ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]), ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]), ] for case in test_cases: result = common_list_elements(*case) print(f"Intersection of {case} is {result}")
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "math" ) type mwriter struct { value float64 log string } func (m mwriter) bind(f func(v float64) mwriter) mwriter { n := f(m.value) n.log = m.log + n.log return n } func unit(v float64, s string) mwriter { return mwriter{v, fmt.Sprintf("  %-17s: %g\n", s, v)} } func root(v float64) mwriter { return unit(math.Sqrt(v), "Took square root") } func addOne(v float64) mwriter { return unit(v+1, "Added one") } func half(v float64) mwriter { return unit(v/2, "Divided by two") } func main() { mw1 := unit(5, "Initial value") mw2 := mw1.bind(root).bind(addOne).bind(half) fmt.Println("The Golden Ratio is", mw2.value) fmt.Println("\nThis was derived as follows:-") fmt.Println(mw2.log) }
from __future__ import annotations import functools import math import os from typing import Any from typing import Callable from typing import Generic from typing import List from typing import TypeVar from typing import Union T = TypeVar("T") class Writer(Generic[T]): def __init__(self, value: Union[T, Writer[T]], *msgs: str): if isinstance(value, Writer): self.value: T = value.value self.msgs: List[str] = value.msgs + list(msgs) else: self.value = value self.msgs = list(f"{msg}: {self.value}" for msg in msgs) def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]: writer = func(self.value) return Writer(writer, *self.msgs) def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]: return self.bind(func) def __str__(self): return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}" def __repr__(self): return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")" def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]: @functools.wraps(func) def wrapped(value): return Writer(func(value), msg) return wrapped if __name__ == "__main__": square_root = lift(math.sqrt, "square root") add_one = lift(lambda x: x + 1, "add one") half = lift(lambda x: x / 2, "div two") print(Writer(5, "initial") >> square_root >> add_one >> half)
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "math" "strings" "time" ) var board [][]bool var diag1, diag2 [][]int var diag1Lookup, diag2Lookup []bool var n, minCount int var layout string func isAttacked(piece string, row, col int) bool { if piece == "Q" { for i := 0; i < n; i++ { if board[i][col] || board[row][i] { return true } } if diag1Lookup[diag1[row][col]] || diag2Lookup[diag2[row][col]] { return true } } else if piece == "B" { if diag1Lookup[diag1[row][col]] || diag2Lookup[diag2[row][col]] { return true } } else { if board[row][col] { return true } if row+2 < n && col-1 >= 0 && board[row+2][col-1] { return true } if row-2 >= 0 && col-1 >= 0 && board[row-2][col-1] { return true } if row+2 < n && col+1 < n && board[row+2][col+1] { return true } if row-2 >= 0 && col+1 < n && board[row-2][col+1] { return true } if row+1 < n && col+2 < n && board[row+1][col+2] { return true } if row-1 >= 0 && col+2 < n && board[row-1][col+2] { return true } if row+1 < n && col-2 >= 0 && board[row+1][col-2] { return true } if row-1 >= 0 && col-2 >= 0 && board[row-1][col-2] { return true } } return false } func abs(i int) int { if i < 0 { i = -i } return i } func attacks(piece string, row, col, trow, tcol int) bool { if piece == "Q" { return row == trow || col == tcol || abs(row-trow) == abs(col-tcol) } else if piece == "B" { return abs(row-trow) == abs(col-tcol) } else { rd := abs(trow - row) cd := abs(tcol - col) return (rd == 1 && cd == 2) || (rd == 2 && cd == 1) } } func storeLayout(piece string) { var sb strings.Builder for _, row := range board { for _, cell := range row { if cell { sb.WriteString(piece + " ") } else { sb.WriteString(". ") } } sb.WriteString("\n") } layout = sb.String() } func placePiece(piece string, countSoFar, maxCount int) { if countSoFar >= minCount { return } allAttacked := true ti := 0 tj := 0 for i := 0; i < n; i++ { for j := 0; j < n; j++ { if !isAttacked(piece, i, j) { allAttacked = false ti = i tj = j break } } if !allAttacked { break } } if allAttacked { minCount = countSoFar storeLayout(piece) return } if countSoFar <= maxCount { si := ti sj := tj if piece == "K" { si = si - 2 sj = sj - 2 if si < 0 { si = 0 } if sj < 0 { sj = 0 } } for i := si; i < n; i++ { for j := sj; j < n; j++ { if !isAttacked(piece, i, j) { if (i == ti && j == tj) || attacks(piece, i, j, ti, tj) { board[i][j] = true if piece != "K" { diag1Lookup[diag1[i][j]] = true diag2Lookup[diag2[i][j]] = true } placePiece(piece, countSoFar+1, maxCount) board[i][j] = false if piece != "K" { diag1Lookup[diag1[i][j]] = false diag2Lookup[diag2[i][j]] = false } } } } } } } func main() { start := time.Now() pieces := []string{"Q", "B", "K"} limits := map[string]int{"Q": 10, "B": 10, "K": 10} names := map[string]string{"Q": "Queens", "B": "Bishops", "K": "Knights"} for _, piece := range pieces { fmt.Println(names[piece]) fmt.Println("=======\n") for n = 1; ; n++ { board = make([][]bool, n) for i := 0; i < n; i++ { board[i] = make([]bool, n) } if piece != "K" { diag1 = make([][]int, n) for i := 0; i < n; i++ { diag1[i] = make([]int, n) for j := 0; j < n; j++ { diag1[i][j] = i + j } } diag2 = make([][]int, n) for i := 0; i < n; i++ { diag2[i] = make([]int, n) for j := 0; j < n; j++ { diag2[i][j] = i - j + n - 1 } } diag1Lookup = make([]bool, 2*n-1) diag2Lookup = make([]bool, 2*n-1) } minCount = math.MaxInt32 layout = "" for maxCount := 1; maxCount <= n*n; maxCount++ { placePiece(piece, 0, maxCount) if minCount <= n*n { break } } fmt.Printf("%2d x %-2d : %d\n", n, n, minCount) if n == limits[piece] { fmt.Printf("\n%s on a %d x %d board:\n", names[piece], n, n) fmt.Println("\n" + layout) break } } } elapsed := time.Now().Sub(start) fmt.Printf("Took %s\n", elapsed) }
from mip import Model, BINARY, xsum, minimize def n_queens_min(N): if N < 4: brd = [[0 for i in range(N)] for j in range(N)] brd[0 if N < 2 else 1][0 if N < 2 else 1] = 1 return 1, brd model = Model() board = [[model.add_var(var_type=BINARY) for j in range(N)] for i in range(N)] for k in range(N): model += xsum(board[k][j] for j in range(N)) <= 1 model += xsum(board[i][k] for i in range(N)) <= 1 for k in range(1, 2 * N - 2): model += xsum(board[k - j][j] for j in range(max(0, k - N + 1), min(k + 1, N))) <= 1 for k in range(2 - N, N - 1): model += xsum(board[k + j][j] for j in range(max(0, -k), min(N - k, N))) <= 1 for i in range(N): for j in range(N): model += xsum([xsum(board[i][k] for k in range(N)), xsum(board[k][j] for k in range(N)), xsum(board[i + k][j + k] for k in range(-N, N) if 0 <= i + k < N and 0 <= j + k < N), xsum(board[i - k][j + k] for k in range(-N, N) if 0 <= i - k < N and 0 <= j + k < N)]) >= 1 model.objective = minimize(xsum(board[i][j] for i in range(N) for j in range(N))) model.optimize() return model.objective_value, [[board[i][j].x for i in range(N)] for j in range(N)] def n_bishops_min(N): model = Model() board = [[model.add_var(var_type=BINARY) for j in range(N)] for i in range(N)] for i in range(N): for j in range(N): model += xsum([ xsum(board[i + k][j + k] for k in range(-N, N) if 0 <= i + k < N and 0 <= j + k < N), xsum(board[i - k][j + k] for k in range(-N, N) if 0 <= i - k < N and 0 <= j + k < N)]) >= 1 model.objective = minimize(xsum(board[i][j] for i in range(N) for j in range(N))) model.optimize() return model.objective_value, [[board[i][j].x for i in range(N)] for j in range(N)] def n_knights_min(N): if N < 2: return 1, "N" knightdeltas = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)] model = Model() board = [[model.add_var(var_type=BINARY) for j in range(N + 4)] for i in range(N + 4)] for i in range(N + 4): model += xsum(board[i][j] for j in [0, 1, N + 2, N + 3]) == 0 for j in range(N + 4): model += xsum(board[i][j] for i in [0, 1, N + 2, N + 3]) == 0 for i in range(2, N + 2): for j in range(2, N + 2): model += xsum([board[i][j]] + [board[i + d[0]][j + d[1]] for d in knightdeltas]) >= 1 model += xsum([board[i + d[0]][j + d[1]] for d in knightdeltas] + [100 * board[i][j]]) <= 100 model.objective = minimize(xsum(board[i][j] for i in range(2, N + 2) for j in range(2, N + 2))) model.optimize() minresult = model.objective_value return minresult, [[board[i][j].x for i in range(2, N + 2)] for j in range(2, N + 2)] if __name__ == '__main__': examples, pieces, chars = [[], [], []], ["Queens", "Bishops", "Knights"], ['Q', 'B', 'N'] print(" Squares Queens Bishops Knights") for nrows in range(1, 11): print(str(nrows * nrows).rjust(10), end='') minval, examples[0] = n_queens_min(nrows) print(str(int(minval)).rjust(10), end='') minval, examples[1] = n_bishops_min(nrows) print(str(int(minval)).rjust(10), end='') minval, examples[2] = n_knights_min(nrows) print(str(int(minval)).rjust(10)) if nrows == 10: print("\nExamples for N = 10:") for idx, piece in enumerate(chars): print(f"\n{pieces[idx]}:") for row in examples[idx]: for sqr in row: print(chars[idx] if sqr == 1 else '.', '', end = '') print() print()
Please provide an equivalent version of this Go code in Python.
package main import ( "bytes" "fmt" "log" ) func wordle(answer, guess string) []int { n := len(guess) if n != len(answer) { log.Fatal("The words must be of the same length.") } answerBytes := []byte(answer) result := make([]int, n) for i := 0; i < n; i++ { if guess[i] == answerBytes[i] { answerBytes[i] = '\000' result[i] = 2 } } for i := 0; i < n; i++ { ix := bytes.IndexByte(answerBytes, guess[i]) if ix >= 0 { answerBytes[ix] = '\000' result[i] = 1 } } return result } func main() { colors := []string{"grey", "yellow", "green"} pairs := [][]string{ {"ALLOW", "LOLLY"}, {"BULLY", "LOLLY"}, {"ROBIN", "ALERT"}, {"ROBIN", "SONIC"}, {"ROBIN", "ROBIN"}, } for _, pair := range pairs { res := wordle(pair[0], pair[1]) res2 := make([]string, len(res)) for i := 0; i < len(res); i++ { res2[i] = colors[res[i]] } fmt.Printf("%s v %s => %v => %v\n", pair[0], pair[1], res, res2) } }
from functools import reduce from operator import add def wordleScore(target, guess): return mapAccumL(amber)( *first(charCounts)( mapAccumL(green)( [], zip(target, guess) ) ) )[1] def green(residue, tg): t, g = tg return (residue, (g, 2)) if t == g else ( [t] + residue, (g, 0) ) def amber(tally, cn): c, n = cn return (tally, 2) if 2 == n else ( adjust( lambda x: x - 1, c, tally ), 1 ) if 0 < tally.get(c, 0) else (tally, 0) def main(): print(' -> '.join(['Target', 'Guess', 'Scores'])) print() print( '\n'.join([ wordleReport(*tg) for tg in [ ("ALLOW", "LOLLY"), ("CHANT", "LATTE"), ("ROBIN", "ALERT"), ("ROBIN", "SONIC"), ("ROBIN", "ROBIN"), ("BULLY", "LOLLY"), ("ADAPT", "SÅLÅD"), ("Ukraine", "Ukraíne"), ("BBAAB", "BBBBBAA"), ("BBAABBB", "AABBBAA") ] ]) ) def wordleReport(target, guess): scoreName = {2: 'green', 1: 'amber', 0: 'gray'} if 5 != len(target): return f'{target}: Expected 5 character target.' elif 5 != len(guess): return f'{guess}: Expected 5 character guess.' else: scores = wordleScore(target, guess) return ' -> '.join([ target, guess, repr(scores), ' '.join([ scoreName[n] for n in scores ]) ]) def adjust(f, k, dct): return dict( dct, **{k: f(dct[k]) if k in dct else None} ) def charCounts(s): return reduce( lambda a, c: insertWith(add)(c)(1)(a), list(s), {} ) def first(f): return lambda xy: (f(xy[0]), xy[1]) def insertWith(f): return lambda k: lambda x: lambda dct: dict( dct, **{k: f(dct[k], x) if k in dct else x} ) def mapAccumL(f): def nxt(a, x): return second(lambda v: a[1] + [v])( f(a[0], x) ) return lambda acc, xs: reduce( nxt, xs, (acc, []) ) def second(f): return lambda xy: (xy[0], f(xy[1])) if __name__ == '__main__': main()
Write the same code in Python as shown below in Go.
package main import ( "fmt" "rcu" "strings" ) var grid = [][]int { { 8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8}, {49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0}, {81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65}, {52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91}, {22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80}, {24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50}, {32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70}, {67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21}, {24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72}, {21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95}, {78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92}, {16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57}, {86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58}, {19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40}, { 4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66}, {88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69}, { 4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36}, {20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16}, {20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54}, { 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48}, } func main() { maxProd, maxR1, maxR2, maxC1, maxC2 := 0, 0, 0, 0, 0 var maxNums [4]int h, w := len(grid), len(grid[0]) for r := 0; r < h; r++ { for c := 0; c < w-4; c++ { prod := 1 for i := c; i < c+4; i++ { prod *= grid[r][i] } if prod > maxProd { maxProd = prod for n := 0; n < 4; n++ { maxNums[n] = grid[r][c+n] } maxR1, maxR2 = r, r maxC1, maxC2 = c, c+3 } } } for c := 0; c < w; c++ { for r := 0; r < h-4; r++ { prod := 1 for i := r; i < r+4; i++ { prod *= grid[i][c] } if prod > maxProd { maxProd = prod for n := 0; n < 4; n++ { maxNums[n] = grid[r+n][c] } maxR1, maxR2 = r, r+3 maxC1, maxC2 = c, c } } } fmt.Println("The greatest product of four adjacent numbers in the same direction (down or right) in the grid is:") var maxNumStrs [4]string for i := 0; i < 4; i++ { maxNumStrs[i] = fmt.Sprintf("%d", maxNums[i]) } fmt.Printf(" %s = %s\n", strings.Join(maxNumStrs[:], " x "), rcu.Commatize(maxProd)) fmt.Print(" at indices (one based): ") for r := maxR1; r <= maxR2; r++ { for c := maxC1; c <= maxC2; c++ { fmt.Printf("(%d, %d) ", r+1, c+1) } } fmt.Println() }
from math import prod def maxproduct(mat, length): nrow, ncol = len(mat), len(mat[0]) maxprod, maxrow, maxcol, arr = 0, [0, 0], [0, 0], [0] for row in range(nrow): for col in range(ncol): row2, col2 = row + length, col + length if row < nrow - length: array = [r[col] for r in mat[row:row2]] pro = prod(array) if pro > maxprod: maxprod, maxrow, maxcol, arr = pro, [row, row2], col, array if col < ncol - length: pro = prod(mat[row][col:col2]) if pro > maxprod: maxprod, maxrow, maxcol, arr = pro, row, [col, col2], mat[row][col:col2] print(f"The max {length}-product is {maxprod}, product of {arr} at row {maxrow}, col {maxcol}.") MATRIX = [ [ 8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8], [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0], [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65], [52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91], [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80], [24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50], [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70], [67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21], [24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72], [21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95], [78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92], [16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57], [86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58], [19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40], [ 4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66], [88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69], [ 4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36], [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16], [20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54], [ 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48] ] for n in range(2, 6): maxproduct(MATRIX, n)
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(504) var nprimes []int fmt.Println("Neighbour primes < 500:") for i := 0; i < len(primes)-1; i++ { p := primes[i]*primes[i+1] + 2 if rcu.IsPrime(p) { nprimes = append(nprimes, primes[i]) } } rcu.PrintTable(nprimes, 10, 3, false) fmt.Println("\nFound", len(nprimes), "such primes.") }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': print("p q pq+2") print("-----------------------") for p in range(2, 499): if not isPrime(p): continue q = p + 1 while not isPrime(q): q += 1 if not isPrime(2 + p*q): continue print(p, "\t", q, "\t", 2+p*q)
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(504) var nprimes []int fmt.Println("Neighbour primes < 500:") for i := 0; i < len(primes)-1; i++ { p := primes[i]*primes[i+1] + 2 if rcu.IsPrime(p) { nprimes = append(nprimes, primes[i]) } } rcu.PrintTable(nprimes, 10, 3, false) fmt.Println("\nFound", len(nprimes), "such primes.") }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': print("p q pq+2") print("-----------------------") for p in range(2, 499): if not isPrime(p): continue q = p + 1 while not isPrime(q): q += 1 if not isPrime(2 + p*q): continue print(p, "\t", q, "\t", 2+p*q)
Write the same algorithm in Python as shown in this Go implementation.
package main import "fmt" type Resistor struct { symbol rune resistance, voltage float64 a, b *Resistor } func (r *Resistor) res() float64 { switch r.symbol { case '+': return r.a.res() + r.b.res() case '*': return 1 / (1/r.a.res() + 1/r.b.res()) default: return r.resistance } } func (r *Resistor) setVoltage(voltage float64) { switch r.symbol { case '+': ra := r.a.res() rb := r.b.res() r.a.setVoltage(ra / (ra + rb) * voltage) r.b.setVoltage(rb / (ra + rb) * voltage) case '*': r.a.setVoltage(voltage) r.b.setVoltage(voltage) } r.voltage = voltage } func (r *Resistor) current() float64 { return r.voltage / r.res() } func (r *Resistor) effect() float64 { return r.current() * r.voltage } func (r *Resistor) report(level string) { fmt.Printf("%8.3f %8.3f %8.3f %8.3f %s%c\n", r.res(), r.voltage, r.current(), r.effect(), level, r.symbol) if r.a != nil { r.a.report(level + "| ") } if r.b != nil { r.b.report(level + "| ") } } func (r *Resistor) add(other *Resistor) *Resistor { return &Resistor{'+', 0, 0, r, other} } func (r *Resistor) mul(other *Resistor) *Resistor { return &Resistor{'*', 0, 0, r, other} } func main() { var r [10]*Resistor resistances := []float64{6, 8, 4, 8, 4, 6, 8, 10, 6, 2} for i := 0; i < 10; i++ { r[i] = &Resistor{'r', resistances[i], 0, nil, nil} } node := r[7].add(r[9]).mul(r[8]).add(r[6]).mul(r[5]).add(r[4]).mul(r[3]).add(r[2]).mul(r[1]).add(r[0]) node.setVoltage(18) fmt.Println(" Ohm Volt Ampere Watt Network tree") node.report("") }
import strutils, strformat type Node = ref object kind: char resistance: float voltage: float a: Node b: Node proc res(node: Node): float = if node.kind == '+': return node.a.res + node.b.res if node.kind == '*': return 1 / (1 / node.a.res + 1 / node.b.res) node.resistance proc current(node: Node): float = node.voltage / node.res proc effect (node: Node): float = node.current * node.voltage proc report(node: Node, level: string = "") = echo fmt"{node.res:8.3f} {node.voltage:8.3f} {node.current:8.3f} {node.effect:8.3f} {level}{node.kind}" if node.kind in "+*": node.a.report level & "| " node.b.report level & "| " proc setVoltage(node: Node, voltage: float) = node.voltage = voltage if node.kind == '+': let ra = node.a.res let rb = node.b.res node.a.setVoltage ra / (ra+rb) * voltage node.b.setVoltage rb / (ra+rb) * voltage if node.kind == '*': node.a.setVoltage voltage node.b.setVoltage voltage proc build(tokens: seq[string]): Node = var stack: seq[Node] for token in tokens: stack.add if token == "+": Node(kind: '+', a: stack.pop, b: stack.pop) elif token == "*": Node(kind: '*', a: stack.pop, b: stack.pop) else: Node(kind: 'r', resistance: parseFloat(token)) stack.pop proc calculate(voltage: float, tokens: seq[string]): Node = echo "" echo " Ohm Volt Ampere Watt Network tree" let node = build tokens node.setVoltage voltage node.report node
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "rcu" ) func genUpsideDown(limit int) chan int { ch := make(chan int) wrappings := [][2]int{ {1, 9}, {2, 8}, {3, 7}, {4, 6}, {5, 5}, {6, 4}, {7, 3}, {8, 2}, {9, 1}, } evens := []int{19, 28, 37, 46, 55, 64, 73, 82, 91} odds := []int{5} oddIndex := 0 evenIndex := 0 ndigits := 1 pow := 100 count := 0 go func() { for count < limit { if ndigits%2 == 1 { if len(odds) > oddIndex { ch <- odds[oddIndex] count++ oddIndex++ } else { var nextOdds []int for _, w := range wrappings { for _, i := range odds { nextOdds = append(nextOdds, w[0]*pow+i*10+w[1]) } } odds = nextOdds ndigits++ pow *= 10 oddIndex = 0 } } else { if len(evens) > evenIndex { ch <- evens[evenIndex] count++ evenIndex++ } else { var nextEvens []int for _, w := range wrappings { for _, i := range evens { nextEvens = append(nextEvens, w[0]*pow+i*10+w[1]) } } evens = nextEvens ndigits++ pow *= 10 evenIndex = 0 } } } close(ch) }() return ch } func main() { const limit = 50_000_000 count := 0 var ud50s []int pow := 50 for n := range genUpsideDown(limit) { count++ if count < 50 { ud50s = append(ud50s, n) } else if count == 50 { ud50s = append(ud50s, n) fmt.Println("First 50 upside down numbers:") rcu.PrintTable(ud50s, 10, 5, true) fmt.Println() pow = 500 } else if count == pow { fmt.Printf("%sth : %s\n", rcu.Commatize(pow), rcu.Commatize(n)) pow *= 10 } } }
def gen_upside_down_number(): wrappings = [[1, 9], [2, 8], [3, 7], [4, 6], [5, 5], [6, 4], [7, 3], [8, 2], [9, 1]] evens = [19, 28, 37, 46, 55, 64, 73, 82, 91] odds = [5] odd_index, even_index = 0, 0 ndigits = 1 while True: if ndigits % 2 == 1: if len(odds) > odd_index: yield odds[odd_index] odd_index += 1 else: odds = sorted([hi * 10**(ndigits + 1) + 10 * i + lo for i in odds for hi, lo in wrappings]) ndigits += 1 odd_index = 0 else: if len(evens) > even_index: yield evens[even_index] even_index += 1 else: evens = sorted([hi * 10**(ndigits + 1) + 10 * i + lo for i in evens for hi, lo in wrappings]) ndigits += 1 even_index = 0 print('First fifty upside-downs:') for (udcount, udnumber) in enumerate(gen_upside_down_number()): if udcount < 50: print(f'{udnumber : 5}', end='\n' if (udcount + 1) % 10 == 0 else '') elif udcount == 499: print(f'\nFive hundredth: {udnumber: ,}') elif udcount == 4999: print(f'\nFive thousandth: {udnumber: ,}') elif udcount == 49_999: print(f'\nFifty thousandth: {udnumber: ,}') elif udcount == 499_999: print(f'\nFive hundred thousandth: {udnumber: ,}') elif udcount == 4_999_999: print(f'\nFive millionth: {udnumber: ,}') break
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" ) const MAXITER = 151 func minkowski(x float64) float64 { if x > 1 || x < 0 { return math.Floor(x) + minkowski(x-math.Floor(x)) } p := uint64(x) q := uint64(1) r := p + 1 s := uint64(1) d := 1.0 y := float64(p) for { d = d / 2 if y+d == y { break } m := p + r if m < 0 || p < 0 { break } n := q + s if n < 0 { break } if x < float64(m)/float64(n) { r = m s = n } else { y = y + d p = m q = n } } return y + d } func minkowskiInv(x float64) float64 { if x > 1 || x < 0 { return math.Floor(x) + minkowskiInv(x-math.Floor(x)) } if x == 1 || x == 0 { return x } contFrac := []uint32{0} curr := uint32(0) count := uint32(1) i := 0 for { x *= 2 if curr == 0 { if x < 1 { count++ } else { i++ t := contFrac contFrac = make([]uint32, i+1) copy(contFrac, t) contFrac[i-1] = count count = 1 curr = 1 x-- } } else { if x > 1 { count++ x-- } else { i++ t := contFrac contFrac = make([]uint32, i+1) copy(contFrac, t) contFrac[i-1] = count count = 1 curr = 0 } } if x == math.Floor(x) { contFrac[i] = count break } if i == MAXITER { break } } ret := 1.0 / float64(contFrac[i]) for j := i - 1; j >= 0; j-- { ret = float64(contFrac[j]) + 1.0/ret } return 1.0 / ret } func main() { fmt.Printf("%19.16f %19.16f\n", minkowski(0.5*(1+math.Sqrt(5))), 5.0/3.0) fmt.Printf("%19.16f %19.16f\n", minkowskiInv(-5.0/9.0), (math.Sqrt(13)-7)/6) fmt.Printf("%19.16f %19.16f\n", minkowski(minkowskiInv(0.718281828)), minkowskiInv(minkowski(0.1213141516171819))) }
print( "{:19.16f} {:19.16f}".format( minkowski(minkowski_inv(4.04145188432738056)), minkowski_inv(minkowski(4.04145188432738056)), ) )
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( ed "github.com/Ernyoke/Imger/edgedetection" "github.com/Ernyoke/Imger/imgio" "log" ) func main() { img, err := imgio.ImreadRGBA("Valve_original_(1).png") if err != nil { log.Fatal("Could not read image", err) } cny, err := ed.CannyRGBA(img, 15, 45, 5) if err != nil { log.Fatal("Could not perform Canny Edge detection") } err = imgio.Imwrite(cny, "Valve_canny_(1).png") if err != nil { log.Fatal("Could not write Canny image to disk") } }
import numpy as np from scipy.ndimage.filters import convolve, gaussian_filter from scipy.misc import imread, imshow def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31): im = np.array(im, dtype=float) im2 = gaussian_filter(im, blur) im3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) im3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]]) grad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5) theta = np.arctan2(im3v, im3h) thetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 gradSup = grad.copy() for r in range(im.shape[0]): for c in range(im.shape[1]): if r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1: gradSup[r, c] = 0 continue tq = thetaQ[r, c] % 4 if tq == 0: if grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]: gradSup[r, c] = 0 if tq == 1: if grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]: gradSup[r, c] = 0 if tq == 2: if grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]: gradSup[r, c] = 0 if tq == 3: if grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]: gradSup[r, c] = 0 strongEdges = (gradSup > highThreshold) thresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold) finalEdges = strongEdges.copy() currentPixels = [] for r in range(1, im.shape[0]-1): for c in range(1, im.shape[1]-1): if thresholdedEdges[r, c] != 1: continue localPatch = thresholdedEdges[r-1:r+2,c-1:c+2] patchMax = localPatch.max() if patchMax == 2: currentPixels.append((r, c)) finalEdges[r, c] = 1 while len(currentPixels) > 0: newPix = [] for r, c in currentPixels: for dr in range(-1, 2): for dc in range(-1, 2): if dr == 0 and dc == 0: continue r2 = r+dr c2 = c+dc if thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0: newPix.append((r2, c2)) finalEdges[r2, c2] = 1 currentPixels = newPix return finalEdges if __name__=="__main__": im = imread("test.jpg", mode="L") finalEdges = CannyEdgeDetector(im) imshow(finalEdges)
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "math/rand" "time" ) var suits = []string{"♣", "♦", "♥", "♠"} var faces = []string{"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"} var cards = make([]string, 52) var ranks = make([]int, 52) func init() { for i := 0; i < 52; i++ { cards[i] = fmt.Sprintf("%s%s", faces[i%13], suits[i/13]) ranks[i] = i % 13 } } func war() { deck := make([]int, 52) for i := 0; i < 52; i++ { deck[i] = i } rand.Shuffle(52, func(i, j int) { deck[i], deck[j] = deck[j], deck[i] }) hand1 := make([]int, 26, 52) hand2 := make([]int, 26, 52) for i := 0; i < 26; i++ { hand1[25-i] = deck[2*i] hand2[25-i] = deck[2*i+1] } for len(hand1) > 0 && len(hand2) > 0 { card1 := hand1[0] copy(hand1[0:], hand1[1:]) hand1[len(hand1)-1] = 0 hand1 = hand1[0 : len(hand1)-1] card2 := hand2[0] copy(hand2[0:], hand2[1:]) hand2[len(hand2)-1] = 0 hand2 = hand2[0 : len(hand2)-1] played1 := []int{card1} played2 := []int{card2} numPlayed := 2 for { fmt.Printf("%s\t%s\t", cards[card1], cards[card2]) if ranks[card1] > ranks[card2] { hand1 = append(hand1, played1...) hand1 = append(hand1, played2...) fmt.Printf("Player 1 takes the %d cards. Now has %d.\n", numPlayed, len(hand1)) break } else if ranks[card1] < ranks[card2] { hand2 = append(hand2, played2...) hand2 = append(hand2, played1...) fmt.Printf("Player 2 takes the %d cards. Now has %d.\n", numPlayed, len(hand2)) break } else { fmt.Println("War!") if len(hand1) < 2 { fmt.Println("Player 1 has insufficient cards left.") hand2 = append(hand2, played2...) hand2 = append(hand2, played1...) hand2 = append(hand2, hand1...) hand1 = hand1[0:0] break } if len(hand2) < 2 { fmt.Println("Player 2 has insufficient cards left.") hand1 = append(hand1, played1...) hand1 = append(hand1, played2...) hand1 = append(hand1, hand2...) hand2 = hand2[0:0] break } fdCard1 := hand1[0] card1 = hand1[1] copy(hand1[0:], hand1[2:]) hand1[len(hand1)-1] = 0 hand1[len(hand1)-2] = 0 hand1 = hand1[0 : len(hand1)-2] played1 = append(played1, fdCard1, card1) fdCard2 := hand2[0] card2 = hand2[1] copy(hand2[0:], hand2[2:]) hand2[len(hand2)-1] = 0 hand2[len(hand2)-2] = 0 hand2 = hand2[0 : len(hand2)-2] played2 = append(played2, fdCard2, card2) numPlayed += 4 fmt.Println("? \t? \tFace down cards.") } } } if len(hand1) == 52 { fmt.Println("Player 1 wins the game!") } else { fmt.Println("Player 2 wins the game!") } } func main() { rand.Seed(time.Now().UnixNano()) war() }
from numpy.random import shuffle SUITS = ['♣', '♦', '♥', '♠'] FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] DECK = [f + s for f in FACES for s in SUITS] CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK))) class WarCardGame: def __init__(self): deck = DECK.copy() shuffle(deck) self.deck1, self.deck2 = deck[:26], deck[26:] self.pending = [] def turn(self): if len(self.deck1) == 0 or len(self.deck2) == 0: return self.gameover() card1, card2 = self.deck1.pop(0), self.deck2.pop(0) rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2] print("{:10}{:10}".format(card1, card2), end='') if rank1 > rank2: print('Player 1 takes the cards.') self.deck1.extend([card1, card2]) self.deck1.extend(self.pending) self.pending = [] elif rank1 < rank2: print('Player 2 takes the cards.') self.deck2.extend([card2, card1]) self.deck2.extend(self.pending) self.pending = [] else: print('Tie!') if len(self.deck1) == 0 or len(self.deck2) == 0: return self.gameover() card3, card4 = self.deck1.pop(0), self.deck2.pop(0) self.pending.extend([card1, card2, card3, card4]) print("{:10}{:10}".format("?", "?"), 'Cards are face down.', sep='') return self.turn() return True def gameover(self): if len(self.deck2) == 0: if len(self.deck1) == 0: print('\nGame ends as a tie.') else: print('\nPlayer 1 wins the game.') else: print('\nPlayer 2 wins the game.') return False if __name__ == '__main__': WG = WarCardGame() while WG.turn(): continue
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "math/rand" "time" ) var suits = []string{"♣", "♦", "♥", "♠"} var faces = []string{"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"} var cards = make([]string, 52) var ranks = make([]int, 52) func init() { for i := 0; i < 52; i++ { cards[i] = fmt.Sprintf("%s%s", faces[i%13], suits[i/13]) ranks[i] = i % 13 } } func war() { deck := make([]int, 52) for i := 0; i < 52; i++ { deck[i] = i } rand.Shuffle(52, func(i, j int) { deck[i], deck[j] = deck[j], deck[i] }) hand1 := make([]int, 26, 52) hand2 := make([]int, 26, 52) for i := 0; i < 26; i++ { hand1[25-i] = deck[2*i] hand2[25-i] = deck[2*i+1] } for len(hand1) > 0 && len(hand2) > 0 { card1 := hand1[0] copy(hand1[0:], hand1[1:]) hand1[len(hand1)-1] = 0 hand1 = hand1[0 : len(hand1)-1] card2 := hand2[0] copy(hand2[0:], hand2[1:]) hand2[len(hand2)-1] = 0 hand2 = hand2[0 : len(hand2)-1] played1 := []int{card1} played2 := []int{card2} numPlayed := 2 for { fmt.Printf("%s\t%s\t", cards[card1], cards[card2]) if ranks[card1] > ranks[card2] { hand1 = append(hand1, played1...) hand1 = append(hand1, played2...) fmt.Printf("Player 1 takes the %d cards. Now has %d.\n", numPlayed, len(hand1)) break } else if ranks[card1] < ranks[card2] { hand2 = append(hand2, played2...) hand2 = append(hand2, played1...) fmt.Printf("Player 2 takes the %d cards. Now has %d.\n", numPlayed, len(hand2)) break } else { fmt.Println("War!") if len(hand1) < 2 { fmt.Println("Player 1 has insufficient cards left.") hand2 = append(hand2, played2...) hand2 = append(hand2, played1...) hand2 = append(hand2, hand1...) hand1 = hand1[0:0] break } if len(hand2) < 2 { fmt.Println("Player 2 has insufficient cards left.") hand1 = append(hand1, played1...) hand1 = append(hand1, played2...) hand1 = append(hand1, hand2...) hand2 = hand2[0:0] break } fdCard1 := hand1[0] card1 = hand1[1] copy(hand1[0:], hand1[2:]) hand1[len(hand1)-1] = 0 hand1[len(hand1)-2] = 0 hand1 = hand1[0 : len(hand1)-2] played1 = append(played1, fdCard1, card1) fdCard2 := hand2[0] card2 = hand2[1] copy(hand2[0:], hand2[2:]) hand2[len(hand2)-1] = 0 hand2[len(hand2)-2] = 0 hand2 = hand2[0 : len(hand2)-2] played2 = append(played2, fdCard2, card2) numPlayed += 4 fmt.Println("? \t? \tFace down cards.") } } } if len(hand1) == 52 { fmt.Println("Player 1 wins the game!") } else { fmt.Println("Player 2 wins the game!") } } func main() { rand.Seed(time.Now().UnixNano()) war() }
from numpy.random import shuffle SUITS = ['♣', '♦', '♥', '♠'] FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] DECK = [f + s for f in FACES for s in SUITS] CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK))) class WarCardGame: def __init__(self): deck = DECK.copy() shuffle(deck) self.deck1, self.deck2 = deck[:26], deck[26:] self.pending = [] def turn(self): if len(self.deck1) == 0 or len(self.deck2) == 0: return self.gameover() card1, card2 = self.deck1.pop(0), self.deck2.pop(0) rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2] print("{:10}{:10}".format(card1, card2), end='') if rank1 > rank2: print('Player 1 takes the cards.') self.deck1.extend([card1, card2]) self.deck1.extend(self.pending) self.pending = [] elif rank1 < rank2: print('Player 2 takes the cards.') self.deck2.extend([card2, card1]) self.deck2.extend(self.pending) self.pending = [] else: print('Tie!') if len(self.deck1) == 0 or len(self.deck2) == 0: return self.gameover() card3, card4 = self.deck1.pop(0), self.deck2.pop(0) self.pending.extend([card1, card2, card3, card4]) print("{:10}{:10}".format("?", "?"), 'Cards are face down.', sep='') return self.turn() return True def gameover(self): if len(self.deck2) == 0: if len(self.deck1) == 0: print('\nGame ends as a tie.') else: print('\nPlayer 1 wins the game.') else: print('\nPlayer 2 wins the game.') return False if __name__ == '__main__': WG = WarCardGame() while WG.turn(): continue
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "container/heap" "image" "image/color" "image/png" "log" "math" "os" "sort" ) func main() { f, err := os.Open("Quantum_frog.png") if err != nil { log.Fatal(err) } img, err := png.Decode(f) if ec := f.Close(); err != nil { log.Fatal(err) } else if ec != nil { log.Fatal(ec) } fq, err := os.Create("frog16.png") if err != nil { log.Fatal(err) } if err = png.Encode(fq, quant(img, 16)); err != nil { log.Fatal(err) } } func quant(img image.Image, nq int) image.Image { qz := newQuantizer(img, nq) qz.cluster() return qz.Paletted() } type quantizer struct { img image.Image cs []cluster px []point ch chValues eq []point } type cluster struct { px []point widestCh int chRange uint32 } type point struct{ x, y int } type chValues []uint32 type queue []*cluster const ( rx = iota gx bx ) func newQuantizer(img image.Image, nq int) *quantizer { b := img.Bounds() npx := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y) qz := &quantizer{ img: img, ch: make(chValues, npx), cs: make([]cluster, nq), } c := &qz.cs[0] px := make([]point, npx) c.px = px i := 0 for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { px[i].x = x px[i].y = y i++ } } return qz } func (qz *quantizer) cluster() { pq := new(queue) c := &qz.cs[0] for i := 1; ; { qz.setColorRange(c) if c.chRange > 0 { heap.Push(pq, c) } if len(*pq) == 0 { qz.cs = qz.cs[:i] break } s := heap.Pop(pq).(*cluster) c = &qz.cs[i] i++ m := qz.Median(s) qz.Split(s, c, m) if i == len(qz.cs) { break } qz.setColorRange(s) if s.chRange > 0 { heap.Push(pq, s) } } } func (q *quantizer) setColorRange(c *cluster) { var maxR, maxG, maxB uint32 minR := uint32(math.MaxUint32) minG := uint32(math.MaxUint32) minB := uint32(math.MaxUint32) for _, p := range c.px { r, g, b, _ := q.img.At(p.x, p.y).RGBA() if r < minR { minR = r } if r > maxR { maxR = r } if g < minG { minG = g } if g > maxG { maxG = g } if b < minB { minB = b } if b > maxB { maxB = b } } s := gx min := minG max := maxG if maxR-minR > max-min { s = rx min = minR max = maxR } if maxB-minB > max-min { s = bx min = minB max = maxB } c.widestCh = s c.chRange = max - min } func (q *quantizer) Median(c *cluster) uint32 { px := c.px ch := q.ch[:len(px)] switch c.widestCh { case rx: for i, p := range c.px { ch[i], _, _, _ = q.img.At(p.x, p.y).RGBA() } case gx: for i, p := range c.px { _, ch[i], _, _ = q.img.At(p.x, p.y).RGBA() } case bx: for i, p := range c.px { _, _, ch[i], _ = q.img.At(p.x, p.y).RGBA() } } sort.Sort(ch) half := len(ch) / 2 m := ch[half] if len(ch)%2 == 0 { m = (m + ch[half-1]) / 2 } return m } func (q *quantizer) Split(s, c *cluster, m uint32) { px := s.px var v uint32 i := 0 lt := 0 gt := len(px) - 1 eq := q.eq[:0] for i <= gt { r, g, b, _ := q.img.At(px[i].x, px[i].y).RGBA() switch s.widestCh { case rx: v = r case gx: v = g case bx: v = b } switch { case v < m: px[lt] = px[i] lt++ i++ case v > m: px[gt], px[i] = px[i], px[gt] gt-- default: eq = append(eq, px[i]) i++ } } if len(eq) > 0 { copy(px[lt:], eq) if len(px)-i < lt { i = lt } q.eq = eq } s.px = px[:i] c.px = px[i:] } func (qz *quantizer) Paletted() *image.Paletted { cp := make(color.Palette, len(qz.cs)) pi := image.NewPaletted(qz.img.Bounds(), cp) for i := range qz.cs { px := qz.cs[i].px var rsum, gsum, bsum int64 for _, p := range px { r, g, b, _ := qz.img.At(p.x, p.y).RGBA() rsum += int64(r) gsum += int64(g) bsum += int64(b) } n64 := int64(len(px)) cp[i] = color.NRGBA64{ uint16(rsum / n64), uint16(gsum / n64), uint16(bsum / n64), 0xffff, } for _, p := range px { pi.SetColorIndex(p.x, p.y, uint8(i)) } } return pi } func (c chValues) Len() int { return len(c) } func (c chValues) Less(i, j int) bool { return c[i] < c[j] } func (c chValues) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (q queue) Len() int { return len(q) } func (q queue) Less(i, j int) bool { return len(q[j].px) < len(q[i].px) } func (q queue) Swap(i, j int) { q[i], q[j] = q[j], q[i] } func (pq *queue) Push(x interface{}) { c := x.(*cluster) *pq = append(*pq, c) } func (pq *queue) Pop() interface{} { q := *pq n := len(q) - 1 c := q[n] *pq = q[:n] return c }
from PIL import Image if __name__=="__main__": im = Image.open("frog.png") im2 = im.quantize(16) im2.show()
Generate an equivalent Python version of this Go code.
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } 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() { rand.Seed(time.Now().UnixNano()) modifier := func(x float64) float64 { if x < 0.5 { return 2 * (0.5 - x) } return 2 * (x - 0.5) } const ( N = 100000 NUM_BINS = 20 HIST_CHAR = "■" HIST_CHAR_SIZE = 125 ) bins := make([]int, NUM_BINS) binSize := 1.0 / NUM_BINS for i := 0; i < N; i++ { rn := rng(modifier) bn := int(math.Floor(rn / binSize)) bins[bn]++ } fmt.Println("Modified random distribution with", commatize(N), "samples in range [0, 1):\n") fmt.Println(" Range Number of samples within that range") for i := 0; i < NUM_BINS; i++ { hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE))) fi := float64(i) fmt.Printf("%4.2f ..< %4.2f %s %s\n", binSize*fi, binSize*(fi+1), hist, commatize(bins[i])) } }
import random from typing import List, Callable, Optional def modifier(x: float) -> float: return 2*(.5 - x) if x < 0.5 else 2*(x - .5) def modified_random_distribution(modifier: Callable[[float], float], n: int) -> List[float]: d: List[float] = [] while len(d) < n: r1 = prob = random.random() if random.random() < modifier(prob): d.append(r1) return d if __name__ == '__main__': from collections import Counter data = modified_random_distribution(modifier, 50_000) bins = 15 counts = Counter(d // (1 / bins) for d in data) mx = max(counts.values()) print(" BIN, COUNTS, DELTA: HISTOGRAM\n") last: Optional[float] = None for b, count in sorted(counts.items()): delta = 'N/A' if last is None else str(count - last) print(f" {b / bins:5.2f}, {count:4}, {delta:>4}: " f"{' last = count
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } 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() { rand.Seed(time.Now().UnixNano()) modifier := func(x float64) float64 { if x < 0.5 { return 2 * (0.5 - x) } return 2 * (x - 0.5) } const ( N = 100000 NUM_BINS = 20 HIST_CHAR = "■" HIST_CHAR_SIZE = 125 ) bins := make([]int, NUM_BINS) binSize := 1.0 / NUM_BINS for i := 0; i < N; i++ { rn := rng(modifier) bn := int(math.Floor(rn / binSize)) bins[bn]++ } fmt.Println("Modified random distribution with", commatize(N), "samples in range [0, 1):\n") fmt.Println(" Range Number of samples within that range") for i := 0; i < NUM_BINS; i++ { hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE))) fi := float64(i) fmt.Printf("%4.2f ..< %4.2f %s %s\n", binSize*fi, binSize*(fi+1), hist, commatize(bins[i])) } }
import random from typing import List, Callable, Optional def modifier(x: float) -> float: return 2*(.5 - x) if x < 0.5 else 2*(x - .5) def modified_random_distribution(modifier: Callable[[float], float], n: int) -> List[float]: d: List[float] = [] while len(d) < n: r1 = prob = random.random() if random.random() < modifier(prob): d.append(r1) return d if __name__ == '__main__': from collections import Counter data = modified_random_distribution(modifier, 50_000) bins = 15 counts = Counter(d // (1 / bins) for d in data) mx = max(counts.values()) print(" BIN, COUNTS, DELTA: HISTOGRAM\n") last: Optional[float] = None for b, count in sorted(counts.items()): delta = 'N/A' if last is None else str(count - last) print(f" {b / bins:5.2f}, {count:4}, {delta:>4}: " f"{' last = count
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } 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() { rand.Seed(time.Now().UnixNano()) modifier := func(x float64) float64 { if x < 0.5 { return 2 * (0.5 - x) } return 2 * (x - 0.5) } const ( N = 100000 NUM_BINS = 20 HIST_CHAR = "■" HIST_CHAR_SIZE = 125 ) bins := make([]int, NUM_BINS) binSize := 1.0 / NUM_BINS for i := 0; i < N; i++ { rn := rng(modifier) bn := int(math.Floor(rn / binSize)) bins[bn]++ } fmt.Println("Modified random distribution with", commatize(N), "samples in range [0, 1):\n") fmt.Println(" Range Number of samples within that range") for i := 0; i < NUM_BINS; i++ { hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE))) fi := float64(i) fmt.Printf("%4.2f ..< %4.2f %s %s\n", binSize*fi, binSize*(fi+1), hist, commatize(bins[i])) } }
import random from typing import List, Callable, Optional def modifier(x: float) -> float: return 2*(.5 - x) if x < 0.5 else 2*(x - .5) def modified_random_distribution(modifier: Callable[[float], float], n: int) -> List[float]: d: List[float] = [] while len(d) < n: r1 = prob = random.random() if random.random() < modifier(prob): d.append(r1) return d if __name__ == '__main__': from collections import Counter data = modified_random_distribution(modifier, 50_000) bins = 15 counts = Counter(d // (1 / bins) for d in data) mx = max(counts.values()) print(" BIN, COUNTS, DELTA: HISTOGRAM\n") last: Optional[float] = None for b, count in sorted(counts.items()): delta = 'N/A' if last is None else str(count - last) print(f" {b / bins:5.2f}, {count:4}, {delta:>4}: " f"{' last = count
Write the same code in Python as shown below in Go.
package main import ( "fmt" "math" "sort" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { lists := [][]int{ {3, 4, 34, 25, 9, 12, 36, 56, 36}, {2, 8, 81, 169, 34, 55, 76, 49, 7}, {75, 121, 75, 144, 35, 16, 46, 35}, } var squares []int for _, list := range lists { for _, e := range list { if isSquare(e) { squares = append(squares, e) } } } sort.Ints(squares) fmt.Println(squares) }
import math print("working...") list = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)] Squares = [] def issquare(x): for p in range(x): if x == p*p: return 1 for n in range(3): for m in range(len(list[n])): if issquare(list[n][m]): Squares.append(list[n][m]) Squares.sort() print(Squares) print("done...")
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "math" "sort" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { lists := [][]int{ {3, 4, 34, 25, 9, 12, 36, 56, 36}, {2, 8, 81, 169, 34, 55, 76, 49, 7}, {75, 121, 75, 144, 35, 16, 46, 35}, } var squares []int for _, list := range lists { for _, e := range list { if isSquare(e) { squares = append(squares, e) } } } sort.Ints(squares) fmt.Println(squares) }
import math print("working...") list = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)] Squares = [] def issquare(x): for p in range(x): if x == p*p: return 1 for n in range(3): for m in range(len(list[n])): if issquare(list[n][m]): Squares.append(list[n][m]) Squares.sort() print(Squares) print("done...")
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math/big" "strconv" "strings" ) var suffixes = " KMGTPEZYXWVU" var ggl = googol() func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } return g } func suffize(arg string) { fields := strings.Fields(arg) a := fields[0] if a == "" { a = "0" } var places, base int var frac, radix string switch len(fields) { case 1: places = -1 base = 10 case 2: places, _ = strconv.Atoi(fields[1]) base = 10 frac = strconv.Itoa(places) case 3: if fields[1] == "," { places = 0 frac = "," } else { places, _ = strconv.Atoi(fields[1]) frac = strconv.Itoa(places) } base, _ = strconv.Atoi(fields[2]) if base != 2 && base != 10 { base = 10 } radix = strconv.Itoa(base) } a = strings.Replace(a, ",", "", -1) sign := "" if a[0] == '+' || a[0] == '-' { sign = string(a[0]) a = a[1:] } b := new(big.Float).SetPrec(500) d := new(big.Float).SetPrec(500) b.SetString(a) g := false if b.Cmp(ggl) >= 0 { g = true } if !g && base == 2 { d.SetUint64(1024) } else if !g && base == 10 { d.SetUint64(1000) } else { d.Set(ggl) } c := 0 for b.Cmp(d) >= 0 && c < 12 { b.Quo(b, d) c++ } var suffix string if !g { suffix = string(suffixes[c]) } else { suffix = "googol" } if base == 2 { suffix += "i" } fmt.Println(" input number =", fields[0]) fmt.Println(" fraction digs =", frac) fmt.Println("specified radix =", radix) fmt.Print(" new number = ") if places >= 0 { fmt.Printf("%s%.*f%s\n", sign, places, b, suffix) } else { fmt.Printf("%s%s%s\n", sign, b.Text('g', 50), suffix) } fmt.Println() } func main() { tests := []string{ "87,654,321", "-998,877,665,544,332,211,000 3", "+112,233 0", "16,777,216 1", "456,789,100,000,000", "456,789,100,000,000 2 10", "456,789,100,000,000 5 2", "456,789,100,000.000e+00 0 10", "+16777216 , 2", "1.2e101", "446,835,273,728 1", "1e36", "1e39", } for _, test := range tests { suffize(test) } }
import math import os def suffize(num, digits=None, base=10): suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol'] exponent_distance = 10 if base == 2 else 3 num = num.strip().replace(',', '') num_sign = num[0] if num[0] in '+-' else '' num = abs(float(num)) if base == 10 and num >= 1e100: suffix_index = 13 num /= 1e100 elif num > 1: magnitude = math.floor(math.log(num, base)) suffix_index = min(math.floor(magnitude / exponent_distance), 12) num /= base ** (exponent_distance * suffix_index) else: suffix_index = 0 if digits is not None: num_str = f'{num:.{digits}f}' else: num_str = f'{num:.3f}'.strip('0').strip('.') return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '') tests = [('87,654,321',), ('-998,877,665,544,332,211,000', 3), ('+112,233', 0), ('16,777,216', 1), ('456,789,100,000,000', 2), ('456,789,100,000,000', 2, 10), ('456,789,100,000,000', 5, 2), ('456,789,100,000.000e+00', 0, 10), ('+16777216', None, 2), ('1.2e101',)] for test in tests: print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "math/big" "strconv" "strings" ) var suffixes = " KMGTPEZYXWVU" var ggl = googol() func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } return g } func suffize(arg string) { fields := strings.Fields(arg) a := fields[0] if a == "" { a = "0" } var places, base int var frac, radix string switch len(fields) { case 1: places = -1 base = 10 case 2: places, _ = strconv.Atoi(fields[1]) base = 10 frac = strconv.Itoa(places) case 3: if fields[1] == "," { places = 0 frac = "," } else { places, _ = strconv.Atoi(fields[1]) frac = strconv.Itoa(places) } base, _ = strconv.Atoi(fields[2]) if base != 2 && base != 10 { base = 10 } radix = strconv.Itoa(base) } a = strings.Replace(a, ",", "", -1) sign := "" if a[0] == '+' || a[0] == '-' { sign = string(a[0]) a = a[1:] } b := new(big.Float).SetPrec(500) d := new(big.Float).SetPrec(500) b.SetString(a) g := false if b.Cmp(ggl) >= 0 { g = true } if !g && base == 2 { d.SetUint64(1024) } else if !g && base == 10 { d.SetUint64(1000) } else { d.Set(ggl) } c := 0 for b.Cmp(d) >= 0 && c < 12 { b.Quo(b, d) c++ } var suffix string if !g { suffix = string(suffixes[c]) } else { suffix = "googol" } if base == 2 { suffix += "i" } fmt.Println(" input number =", fields[0]) fmt.Println(" fraction digs =", frac) fmt.Println("specified radix =", radix) fmt.Print(" new number = ") if places >= 0 { fmt.Printf("%s%.*f%s\n", sign, places, b, suffix) } else { fmt.Printf("%s%s%s\n", sign, b.Text('g', 50), suffix) } fmt.Println() } func main() { tests := []string{ "87,654,321", "-998,877,665,544,332,211,000 3", "+112,233 0", "16,777,216 1", "456,789,100,000,000", "456,789,100,000,000 2 10", "456,789,100,000,000 5 2", "456,789,100,000.000e+00 0 10", "+16777216 , 2", "1.2e101", "446,835,273,728 1", "1e36", "1e39", } for _, test := range tests { suffize(test) } }
import math import os def suffize(num, digits=None, base=10): suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol'] exponent_distance = 10 if base == 2 else 3 num = num.strip().replace(',', '') num_sign = num[0] if num[0] in '+-' else '' num = abs(float(num)) if base == 10 and num >= 1e100: suffix_index = 13 num /= 1e100 elif num > 1: magnitude = math.floor(math.log(num, base)) suffix_index = min(math.floor(magnitude / exponent_distance), 12) num /= base ** (exponent_distance * suffix_index) else: suffix_index = 0 if digits is not None: num_str = f'{num:.{digits}f}' else: num_str = f'{num:.3f}'.strip('0').strip('.') return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '') tests = [('87,654,321',), ('-998,877,665,544,332,211,000', 3), ('+112,233', 0), ('16,777,216', 1), ('456,789,100,000,000', 2), ('456,789,100,000,000', 2, 10), ('456,789,100,000,000', 5, 2), ('456,789,100,000.000e+00', 0, 10), ('+16777216', None, 2), ('1.2e101',)] for test in tests: print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "sort" ) func reverse(s string) string { var r = []rune(s) for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func longestPalSubstring(s string) []string { var le = len(s) if le <= 1 { return []string{s} } targetLen := le var longest []string i := 0 for { j := i + targetLen - 1 if j < le { ss := s[i : j+1] if reverse(ss) == ss { longest = append(longest, ss) } i++ } else { if len(longest) > 0 { return longest } i = 0 targetLen-- } } return longest } func distinct(sa []string) []string { sort.Strings(sa) duplicated := make([]bool, len(sa)) for i := 1; i < len(sa); i++ { if sa[i] == sa[i-1] { duplicated[i] = true } } var res []string for i := 0; i < len(sa); i++ { if !duplicated[i] { res = append(res, sa[i]) } } return res } func main() { strings := []string{"babaccd", "rotator", "reverse", "forever", "several", "palindrome", "abaracadaraba"} fmt.Println("The palindromic substrings having the longest length are:") for _, s := range strings { longest := distinct(longestPalSubstring(s)) fmt.Printf("  %-13s Length %d -> %v\n", s, len(longest[0]), longest) } }
def longestPalindromes(s): k = s.lower() palindromes = [ palExpansion(k)(ab) for ab in palindromicNuclei(k) ] maxLength = max([ len(x) for x in palindromes ]) if palindromes else 1 return ( [ x for x in palindromes if maxLength == len(x) ] if palindromes else list(s), maxLength ) if s else ([], 0) def palindromicNuclei(s): cs = list(s) return [ (i, 1 + i) for (i, (a, b)) in enumerate(zip(cs, cs[1:])) if a == b ] + [ (i, 2 + i) for (i, (a, b, c)) in enumerate(zip(cs, cs[1:], cs[2:])) if a == c ] def palExpansion(s): iEnd = len(s) - 1 def limit(ij): i, j = ij return 0 == i or iEnd == j or s[i-1] != s[j+1] def expansion(ij): i, j = ij return (i - 1, 1 + j) def go(ij): ab = until(limit)(expansion)(ij) return s[ab[0]:ab[1] + 1] return go def main(): print( fTable(main.__doc__ + ':\n')(repr)(repr)( longestPalindromes )([ 'three old rotators', 'never reverse', 'stable was I ere I saw elbatrosses', 'abracadabra', 'drome', 'the abbatial palace', '' ]) ) def until(p): def go(f): def g(x): v = x while not p(v): v = f(v) return v return g return go def fTable(s): def gox(xShow): def gofx(fxShow): def gof(f): def goxs(xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) def arrowed(x, y): return y.rjust(w, ' ') + ' -> ' + ( fxShow(f(x)) ) return s + '\n' + '\n'.join( map(arrowed, xs, ys) ) return goxs return gof return gofx return gox if __name__ == '__main__': main()
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "bufio" "fmt" "log" "math/rand" "os" "strconv" "strings" "time" ) var cave = map[int][3]int{ 1: {2, 3, 4}, 2: {1, 5, 6}, 3: {1, 7, 8}, 4: {1, 9, 10}, 5: {2, 9, 11}, 6: {2, 7, 12}, 7: {3, 6, 13}, 8: {3, 10, 14}, 9: {4, 5, 15}, 10: {4, 8, 16}, 11: {5, 12, 17}, 12: {6, 11, 18}, 13: {7, 14, 18}, 14: {8, 13, 19}, 15: {9, 16, 17}, 16: {10, 15, 19}, 17: {11, 20, 15}, 18: {12, 13, 20}, 19: {14, 16, 20}, 20: {17, 18, 19}, } var player, wumpus, bat1, bat2, pit1, pit2 int var arrows = 5 func isEmpty(r int) bool { if r != player && r != wumpus && r != bat1 && r != bat2 && r != pit1 && r != pit2 { return true } return false } func sense(adj [3]int) { bat := false pit := false for _, ar := range adj { if ar == wumpus { fmt.Println("You smell something terrible nearby.") } switch ar { case bat1, bat2: if !bat { fmt.Println("You hear a rustling.") bat = true } case pit1, pit2: if !pit { fmt.Println("You feel a cold wind blowing from a nearby cavern.") pit = true } } } fmt.Println() } func check(err error) { if err != nil { log.Fatal(err) } } func plural(n int) string { if n != 1 { return "s" } return "" } func main() { rand.Seed(time.Now().UnixNano()) player = 1 wumpus = rand.Intn(19) + 2 bat1 = rand.Intn(19) + 2 for { bat2 = rand.Intn(19) + 2 if bat2 != bat1 { break } } for { pit1 = rand.Intn(19) + 2 if pit1 != bat1 && pit1 != bat2 { break } } for { pit2 = rand.Intn(19) + 2 if pit2 != bat1 && pit2 != bat2 && pit2 != pit1 { break } } scanner := bufio.NewScanner(os.Stdin) for { fmt.Printf("\nYou are in room %d with %d arrow%s left\n", player, arrows, plural(arrows)) adj := cave[player] fmt.Printf("The adjacent rooms are %v\n", adj) sense(adj) var room int for { fmt.Print("Choose an adjacent room : ") scanner.Scan() room, _ = strconv.Atoi(scanner.Text()) if room != adj[0] && room != adj[1] && room != adj[2] { fmt.Println("Invalid response, try again") } else { break } } check(scanner.Err()) var action byte for { fmt.Print("Walk or shoot w/s : ") scanner.Scan() reply := strings.ToLower(scanner.Text()) if len(reply) != 1 || (len(reply) == 1 && reply[0] != 'w' && reply[0] != 's') { fmt.Println("Invalid response, try again") } else { action = reply[0] break } } check(scanner.Err()) if action == 'w' { player = room switch player { case wumpus: fmt.Println("You have been eaten by the Wumpus and lost the game!") return case pit1, pit2: fmt.Println("You have fallen down a bottomless pit and lost the game!") return case bat1, bat2: for { room = rand.Intn(19) + 2 if isEmpty(room) { fmt.Println("A bat has transported you to a random empty room") player = room break } } } } else { if room == wumpus { fmt.Println("You have killed the Wumpus and won the game!!") return } else { chance := rand.Intn(4) if chance > 0 { wumpus = cave[wumpus][rand.Intn(3)] if player == wumpus { fmt.Println("You have been eaten by the Wumpus and lost the game!") return } } } arrows-- if arrows == 0 { fmt.Println("You have run out of arrows and lost the game!") return } } } }
import random class WumpusGame(object): def __init__(self, edges=[]): if edges: cave = {} N = max([edges[i][0] for i in range(len(edges))]) for i in range(N): exits = [edge[1] for edge in edges if edge[0] == i] cave[i] = exits else: cave = {1: [2,3,4], 2: [1,5,6], 3: [1,7,8], 4: [1,9,10], 5:[2,9,11], 6: [2,7,12], 7: [3,6,13], 8: [3,10,14], 9: [4,5,15], 10: [4,8,16], 11: [5,12,17], 12: [6,11,18], 13: [7,14,18], 14: [8,13,19], 15: [9,16,17], 16: [10,15,19], 17: [11,20,15], 18: [12,13,20], 19: [14,16,20], 20: [17,18,19]} self.cave = cave self.threats = {} self.arrows = 5 self.arrow_travel_distance = 5 self.player_pos = -1 def get_safe_rooms(self): return list(set(self.cave.keys()).difference(self.threats.keys())) def populate_cave(self): for threat in ['bat', 'bat', 'pit', 'pit', 'wumpus']: pos = random.choice(self.get_safe_rooms()) self.threats[pos] = threat self.player_pos = random.choice(self.get_safe_rooms()) def breadth_first_search(self, source, target, max_depth=5): graph = self.cave depth = 0 def search(stack, visited, target, depth): if stack == []: return False, -1 if target in stack: return True, depth visited = visited + stack stack = list(set([graph[v][i] for v in stack for i in range(len(graph[v]))]).difference(visited)) depth += 1 if depth > max_depth: return False, depth else: return search(stack, visited, target, depth) return search([source], [], target, depth) def print_warning(self, threat): if threat == 'bat': print("You hear a rustling.") elif threat == 'pit': print("You feel a cold wind blowing from a nearby cavern.") elif threat == 'wumpus': print("You smell something terrible nearby.") def get_players_input(self): while 1: inpt = input("Shoot or move (S-M)? ") try: mode = str(inpt).lower() assert mode in ['s', 'm', 'q'] break except (ValueError, AssertionError): print("This is not a valid action: pick 'S' to shoot and 'M' to move.") if mode == 'q': return 'q', 0 while 1: inpt = input("Where to? ") try: target = int(inpt) except ValueError: print("This is not even a real number.") continue if mode == 'm': try: assert target in self.cave[self.player_pos] break except AssertionError: print("You cannot walk that far. Please use one of the tunnels.") elif mode == 's': try: bfs = self.breadth_first_search(self.player_pos, target) assert bfs[0] == True break except AssertionError: if bfs[1] == -1: print("There is no room with this number in the cave. Your arrow travels randomly.") target = random.choice(self.cave.keys()) if bfs[1] > self.arrow_travel_distance: print("Arrows aren't that croocked.") return mode, target def enter_room(self, room_number): print("Entering room {}...".format(room_number)) if self.threats.get(room_number) == 'bat': print("You encounter a bat, it transports you to a random empty room.") new_pos = random.choice(self.get_safe_rooms()) return self.enter_room(new_pos) elif self.threats.get(room_number) == 'wumpus': print("Wumpus eats you.") return -1 elif self.threats.get(room_number) == 'pit': print("You fall into a pit.") return -1 for i in self.cave[room_number]: self.print_warning(self.threats.get(i)) return room_number def shoot_room(self, room_number): print("Shooting an arrow into room {}...".format(room_number)) self.arrows -= 1 threat = self.threats.get(room_number) if threat in ['bat', 'wumpus']: del self.threats[room_number] if threat == 'wumpus': print("Hurra, you killed the wumpus!") return -1 elif threat == 'bat': print("You killed a bat.") elif threat in ['pit', None]: print("This arrow is lost.") if self.arrows < 1: print("Your quiver is empty.") return -1 if random.random() < 0.75: for room_number, threat in self.threats.items(): if threat == 'wumpus': wumpus_pos = room_number new_pos = random.choice(list(set(self.cave[wumpus_pos]).difference(self.threats.keys()))) del self.threats[room_number] self.threats[new_pos] = 'wumpus' if new_pos == self.player_pos: print("Wumpus enters your room and eats you!") return -1 return self.player_pos def gameloop(self): print("HUNT THE WUMPUS") print("===============") print() self.populate_cave() self.enter_room(self.player_pos) while 1: print("You are in room {}.".format(self.player_pos), end=" ") print("Tunnels lead to: {0} {1} {2}".format(*self.cave[self.player_pos])) inpt = self.get_players_input() print() if inpt[0] == 'm': target = inpt[1] self.player_pos = self.enter_room(target) elif inpt[0] == 's': target = inpt[1] self.player_pos = self.shoot_room(target) elif inpt[0] == 'q': self.player_pos = -1 if self.player_pos == -1: break print() print("Game over!") if __name__ == '__main__': WG = WumpusGame() WG.gameloop()
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "bytes" "fmt" "io/ioutil" "log" "runtime" ) func main() { fileName1 := "rodgers.txt" fileName2 := "rodgers_reversed.txt" lineBreak := "\n" if runtime.GOOS == "windows" { lineBreak = "\r\n" } b, err := ioutil.ReadFile(fileName1) if err != nil { log.Fatal(err) } lines := bytes.Split(b, []byte(lineBreak)) if len(lines[len(lines)-1]) == 0 { lines = lines[:len(lines)-1] } for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 { lines[i], lines[j] = lines[j], lines[i] } b = bytes.Join(lines, []byte(lineBreak)) if err = ioutil.WriteFile(fileName2, b, 0o666); err != nil { log.Fatal(err) } b, err = ioutil.ReadFile(fileName2) if err != nil { log.Fatal(err) } fmt.Println(string(b)) }
import sys if len(sys.argv)!=2: print("Usage : python " + sys.argv[0] + " <filename>") exit() dataFile = open(sys.argv[1],"r") fileData = dataFile.read().split('\n') dataFile.close() [print(i) for i in fileData[::-1]]
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "log" ) func minimum(a []int) int { min := a[0] for i := 1; i < len(a); i++ { if a[i] < min { min = a[i] } } return min } func sum(a []int) int { s := 0 for _, i := range a { s = s + i } return s } func hourglassFlipper(hourglasses []int, target int) (int, []int) { flippers := make([]int, len(hourglasses)) copy(flippers, hourglasses) var series []int for iter := 0; iter < 10000; iter++ { n := minimum(flippers) series = append(series, n) for i := 0; i < len(flippers); i++ { flippers[i] -= n } for i, flipper := range flippers { if flipper == 0 { flippers[i] = hourglasses[i] } } for start := len(series) - 1; start >= 0; start-- { if sum(series[start:]) == target { return start, series } } } log.Fatal("Unable to find an answer within 10,000 iterations.") return 0, nil } func main() { fmt.Print("Flip an hourglass every time it runs out of grains, ") fmt.Println("and note the interval in time.") hgs := [][]int{{4, 7}, {5, 7, 31}} ts := []int{9, 36} for i := 0; i < len(hgs); i++ { start, series := hourglassFlipper(hgs[i], ts[i]) end := len(series) - 1 fmt.Println("\nSeries:", series) fmt.Printf("Use hourglasses from indices %d to %d (inclusive) to sum ", start, end) fmt.Println(ts[i], "using", hgs[i]) } }
def hourglass_puzzle(): t4 = 0 while t4 < 10_000: t7_left = 7 - t4 % 7 if t7_left == 9 - 4: break t4 += 4 else: print('Not found') return print(f) hourglass_puzzle()
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "log" ) func minimum(a []int) int { min := a[0] for i := 1; i < len(a); i++ { if a[i] < min { min = a[i] } } return min } func sum(a []int) int { s := 0 for _, i := range a { s = s + i } return s } func hourglassFlipper(hourglasses []int, target int) (int, []int) { flippers := make([]int, len(hourglasses)) copy(flippers, hourglasses) var series []int for iter := 0; iter < 10000; iter++ { n := minimum(flippers) series = append(series, n) for i := 0; i < len(flippers); i++ { flippers[i] -= n } for i, flipper := range flippers { if flipper == 0 { flippers[i] = hourglasses[i] } } for start := len(series) - 1; start >= 0; start-- { if sum(series[start:]) == target { return start, series } } } log.Fatal("Unable to find an answer within 10,000 iterations.") return 0, nil } func main() { fmt.Print("Flip an hourglass every time it runs out of grains, ") fmt.Println("and note the interval in time.") hgs := [][]int{{4, 7}, {5, 7, 31}} ts := []int{9, 36} for i := 0; i < len(hgs); i++ { start, series := hourglassFlipper(hgs[i], ts[i]) end := len(series) - 1 fmt.Println("\nSeries:", series) fmt.Printf("Use hourglasses from indices %d to %d (inclusive) to sum ", start, end) fmt.Println(ts[i], "using", hgs[i]) } }
def hourglass_puzzle(): t4 = 0 while t4 < 10_000: t7_left = 7 - t4 % 7 if t7_left == 9 - 4: break t4 += 4 else: print('Not found') return print(f) hourglass_puzzle()
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "sort" ) func main() { strings := []string{"1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"} u := make(map[rune]int) for _, s := range strings { m := make(map[rune]int) for _, c := range s { m[c]++ } for k, v := range m { if v == 1 { u[k]++ } } } var chars []rune for k, v := range u { if v == 3 { chars = append(chars, k) } } sort.Slice(chars, func(i, j int) bool { return chars[i] < chars[j] }) fmt.Println(string(chars)) }
LIST = ["1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"] print(sorted([ch for ch in set([c for c in ''.join(LIST)]) if all(w.count(ch) == 1 for w in LIST)]))
Preserve the algorithm and functionality while converting the code from Go to Python.
package fib import "fmt" type Value interface { LT(Value) bool } type Node struct { value Value parent *Node child *Node prev, next *Node rank int mark bool } func (n Node) Value() Value { return n.value } type Heap struct{ *Node } func MakeHeap() *Heap { return &Heap{} } func (h *Heap) Insert(v Value) *Node { x := &Node{value: v} if h.Node == nil { x.next = x x.prev = x h.Node = x } else { meld1(h.Node, x) if x.value.LT(h.value) { h.Node = x } } return x } func meld1(list, single *Node) { list.prev.next = single single.prev = list.prev single.next = list list.prev = single } func (h *Heap) Union(h2 *Heap) { switch { case h.Node == nil: *h = *h2 case h2.Node != nil: meld2(h.Node, h2.Node) if h2.value.LT(h.value) { *h = *h2 } } h2.Node = nil } func meld2(a, b *Node) { a.prev.next = b b.prev.next = a a.prev, b.prev = b.prev, a.prev } func (h Heap) Minimum() (min Value, ok bool) { if h.Node == nil { return } return h.value, true } func (h *Heap) ExtractMin() (min Value, ok bool) { if h.Node == nil { return } min = h.value roots := map[int]*Node{} add := func(r *Node) { r.prev = r r.next = r for { x, ok := roots[r.rank] if !ok { break } delete(roots, r.rank) if x.value.LT(r.value) { r, x = x, r } x.parent = r x.mark = false if r.child == nil { x.next = x x.prev = x r.child = x } else { meld1(r.child, x) } r.rank++ } roots[r.rank] = r } for r := h.next; r != h.Node; { n := r.next add(r) r = n } if c := h.child; c != nil { c.parent = nil r := c.next add(c) for r != c { n := r.next r.parent = nil add(r) r = n } } if len(roots) == 0 { h.Node = nil return min, true } var mv *Node var d int for d, mv = range roots { break } delete(roots, d) mv.next = mv mv.prev = mv for _, r := range roots { r.prev = mv r.next = mv.next mv.next.prev = r mv.next = r if r.value.LT(mv.value) { mv = r } } h.Node = mv return min, true } func (h *Heap) DecreaseKey(n *Node, v Value) error { if n.value.LT(v) { return fmt.Errorf("DecreaseKey new value greater than existing value") } n.value = v if n == h.Node { return nil } p := n.parent if p == nil { if v.LT(h.value) { h.Node = n } return nil } h.cutAndMeld(n) return nil } func (h Heap) cut(x *Node) { p := x.parent p.rank-- if p.rank == 0 { p.child = nil } else { p.child = x.next x.prev.next = x.next x.next.prev = x.prev } if p.parent == nil { return } if !p.mark { p.mark = true return } h.cutAndMeld(p) } func (h Heap) cutAndMeld(x *Node) { h.cut(x) x.parent = nil meld1(h.Node, x) } func (h *Heap) Delete(n *Node) { p := n.parent if p == nil { if n == h.Node { h.ExtractMin() return } n.prev.next = n.next n.next.prev = n.prev } else { h.cut(n) } c := n.child if c == nil { return } for { c.parent = nil c = c.next if c == n.child { break } } meld2(h.Node, c) } func (h Heap) Vis() { if h.Node == nil { fmt.Println("<empty>") return } var f func(*Node, string) f = func(n *Node, pre string) { pc := "│ " for x := n; ; x = x.next { if x.next != n { fmt.Print(pre, "├─") } else { fmt.Print(pre, "└─") pc = " " } if x.child == nil { fmt.Println("╴", x.value) } else { fmt.Println("┐", x.value) f(x.child, pre+pc) } if x.next == n { break } } } f(h.Node, "") }
class FibonacciHeap: class Node: def __init__(self, data): self.data = data self.parent = self.child = self.left = self.right = None self.degree = 0 self.mark = False def iterate(self, head): node = stop = head flag = False while True: if node == stop and flag is True: break elif node == stop: flag = True yield node node = node.right root_list, min_node = None, None total_nodes = 0 def find_min(self): return self.min_node def extract_min(self): z = self.min_node if z is not None: if z.child is not None: children = [x for x in self.iterate(z.child)] for i in xrange(0, len(children)): self.merge_with_root_list(children[i]) children[i].parent = None self.remove_from_root_list(z) if z == z.right: self.min_node = self.root_list = None else: self.min_node = z.right self.consolidate() self.total_nodes -= 1 return z def insert(self, data): n = self.Node(data) n.left = n.right = n self.merge_with_root_list(n) if self.min_node is None or n.data < self.min_node.data: self.min_node = n self.total_nodes += 1 def decrease_key(self, x, k): if k > x.data: return None x.data = k y = x.parent if y is not None and x.data < y.data: self.cut(x, y) self.cascading_cut(y) if x.data < self.min_node.data: self.min_node = x def merge(self, h2): H = FibonacciHeap() H.root_list, H.min_node = self.root_list, self.min_node last = h2.root_list.left h2.root_list.left = H.root_list.left H.root_list.left.right = h2.root_list H.root_list.left = last H.root_list.left.right = H.root_list if h2.min_node.data < H.min_node.data: H.min_node = h2.min_node H.total_nodes = self.total_nodes + h2.total_nodes return H def cut(self, x, y): self.remove_from_child_list(y, x) y.degree -= 1 self.merge_with_root_list(x) x.parent = None x.mark = False def cascading_cut(self, y): z = y.parent if z is not None: if y.mark is False: y.mark = True else: self.cut(y, z) self.cascading_cut(z) def consolidate(self): A = [None] * self.total_nodes nodes = [w for w in self.iterate(self.root_list)] for w in xrange(0, len(nodes)): x = nodes[w] d = x.degree while A[d] != None: y = A[d] if x.data > y.data: temp = x x, y = y, temp self.heap_link(y, x) A[d] = None d += 1 A[d] = x for i in xrange(0, len(A)): if A[i] is not None: if A[i].data < self.min_node.data: self.min_node = A[i] def heap_link(self, y, x): self.remove_from_root_list(y) y.left = y.right = y self.merge_with_child_list(x, y) x.degree += 1 y.parent = x y.mark = False def merge_with_root_list(self, node): if self.root_list is None: self.root_list = node else: node.right = self.root_list.right node.left = self.root_list self.root_list.right.left = node self.root_list.right = node def merge_with_child_list(self, parent, node): if parent.child is None: parent.child = node else: node.right = parent.child.right node.left = parent.child parent.child.right.left = node parent.child.right = node def remove_from_root_list(self, node): if node == self.root_list: self.root_list = node.right node.left.right = node.right node.right.left = node.left def remove_from_child_list(self, parent, node): if parent.child == parent.child.right: parent.child = None elif parent.child == node: parent.child = node.right node.right.parent = parent node.left.right = node.right node.right.left = node.left
Write a version of this Go function in Python with identical behavior.
package main import ( "fmt" "strconv" "strings" "time" ) var sacred = strings.Fields("Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw") var civil = strings.Fields("Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muwan’ Pax K’ayab Kumk’u Wayeb’") var ( date1 = time.Date(2012, time.December, 21, 0, 0, 0, 0, time.UTC) date2 = time.Date(2019, time.April, 2, 0, 0, 0, 0, time.UTC) ) func tzolkin(date time.Time) (int, string) { diff := int(date.Sub(date1).Hours()) / 24 rem := diff % 13 if rem < 0 { rem = 13 + rem } var num int if rem <= 9 { num = rem + 4 } else { num = rem - 9 } rem = diff % 20 if rem <= 0 { rem = 20 + rem } return num, sacred[rem-1] } func haab(date time.Time) (string, string) { diff := int(date.Sub(date2).Hours()) / 24 rem := diff % 365 if rem < 0 { rem = 365 + rem } month := civil[(rem+1)/20] last := 20 if month == "Wayeb’" { last = 5 } d := rem%20 + 1 if d < last { return strconv.Itoa(d), month } return "Chum", month } func longCount(date time.Time) string { diff := int(date.Sub(date1).Hours()) / 24 diff += 13 * 400 * 360 baktun := diff / (400 * 360) diff %= 400 * 360 katun := diff / (20 * 360) diff %= 20 * 360 tun := diff / 360 diff %= 360 winal := diff / 20 kin := diff % 20 return fmt.Sprintf("%d.%d.%d.%d.%d", baktun, katun, tun, winal, kin) } func lord(date time.Time) string { diff := int(date.Sub(date1).Hours()) / 24 rem := diff % 9 if rem <= 0 { rem = 9 + rem } return fmt.Sprintf("G%d", rem) } func main() { const shortForm = "2006-01-02" dates := []string{ "2004-06-19", "2012-12-18", "2012-12-21", "2019-01-19", "2019-03-27", "2020-02-29", "2020-03-01", "2071-05-16", } fmt.Println(" Gregorian Tzolk’in Haab’ Long Lord of") fmt.Println(" Date # Name Day Month Count the Night") fmt.Println("---------- -------- ------------- -------------- ---------") for _, dt := range dates { date, _ := time.Parse(shortForm, dt) n, s := tzolkin(date) d, m := haab(date) lc := longCount(date) l := lord(date) fmt.Printf("%s %2d %-8s %4s %-9s  %-14s %s\n", dt, n, s, d, m, lc, l) } }
import datetime def g2m(date, gtm_correlation=True): correlation = 584283 if gtm_correlation else 584285 long_count_days = [144000, 7200, 360, 20, 1] tzolkin_months = ['Imix’', 'Ik’', 'Ak’bal', 'K’an', 'Chikchan', 'Kimi', 'Manik’', 'Lamat', 'Muluk', 'Ok', 'Chuwen', 'Eb', 'Ben', 'Hix', 'Men', 'K’ib’', 'Kaban', 'Etz’nab’', 'Kawak', 'Ajaw'] haad_months = ['Pop', 'Wo’', 'Sip', 'Sotz’', 'Sek', 'Xul', 'Yaxk’in', 'Mol', 'Ch’en', 'Yax', 'Sak’', 'Keh', 'Mak', 'K’ank’in', 'Muwan', 'Pax', 'K’ayab', 'Kumk’u', 'Wayeb’'] gregorian_days = datetime.datetime.strptime(date, '%Y-%m-%d').toordinal() julian_days = gregorian_days + 1721425 long_date = list() remainder = julian_days - correlation for days in long_count_days: result, remainder = divmod(remainder, days) long_date.append(int(result)) long_date = '.'.join(['{:02d}'.format(d) for d in long_date]) tzolkin_month = (julian_days + 16) % 20 tzolkin_day = ((julian_days + 5) % 13) + 1 haab_month = int(((julian_days + 65) % 365) / 20) haab_day = ((julian_days + 65) % 365) % 20 haab_day = haab_day if haab_day else 'Chum' lord_number = (julian_days - correlation) % 9 lord_number = lord_number if lord_number else 9 round_date = f'{tzolkin_day} {tzolkin_months[tzolkin_month]} {haab_day} {haad_months[haab_month]} G{lord_number}' return long_date, round_date if __name__ == '__main__': dates = ['2004-06-19', '2012-12-18', '2012-12-21', '2019-01-19', '2019-03-27', '2020-02-29', '2020-03-01'] for date in dates: long, round = g2m(date) print(date, long, round)
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "math/big" "strconv" "strings" ) func main() { var res []int64 for n := 0; n <= 50; n++ { ns := strconv.Itoa(n) k := int64(1) for { bk := big.NewInt(k) s := bk.Exp(bk, bk, nil).String() if strings.Contains(s, ns) { res = append(res, k) break } k++ } } fmt.Println("The smallest positive integers K where K ^ K contains N (0..50) are:") for i, n := range res { fmt.Printf("%2d ", n) if (i+1)%17 == 0 { fmt.Println() } } }
import sys if len(sys.argv)!=2: print("Usage : python " + sys.argv[0] + " <whole number>") exit() numLimit = int(sys.argv[1]) resultSet = {} base = 1 while len(resultSet)!=numLimit: result = base**base for i in range(0,numLimit): if str(i) in str(result) and i not in resultSet: resultSet[i] = base base+=1 [print(resultSet[i], end=' ') for i in sorted(resultSet)]
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 } } fmt.Println("The first 50 Sophie Germain primes are:") for i := 0; i < len(sgp); i++ { fmt.Printf("%5s ", rcu.Commatize(sgp[i])) if (i+1)%10 == 0 { fmt.Println() } } }
print("working...") row = 0 limit = 1500 Sophie = [] def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True for n in range(2,limit): p = 2*n + 1 if isPrime(n) and isPrime(p): Sophie.append(n) print("Found ",end = "") print(len(Sophie),end = "") print(" Safe and Sophie primes.") print(Sophie) print("done...")
Write the same code in Python as shown below in Go.
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 } } fmt.Println("The first 50 Sophie Germain primes are:") for i := 0; i < len(sgp); i++ { fmt.Printf("%5s ", rcu.Commatize(sgp[i])) if (i+1)%10 == 0 { fmt.Println() } } }
print("working...") row = 0 limit = 1500 Sophie = [] def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True for n in range(2,limit): p = 2*n + 1 if isPrime(n) and isPrime(p): Sophie.append(n) print("Found ",end = "") print(len(Sophie),end = "") print(" Safe and Sophie primes.") print(Sophie) print("done...")
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "bufio" "fmt" "golang.org/x/crypto/ssh/terminal" "log" "os" "regexp" "strconv" ) type Color struct{ r, g, b int } type ColorEx struct { color Color code string } var colors = []ColorEx{ {Color{15, 0, 0}, "31"}, {Color{0, 15, 0}, "32"}, {Color{15, 15, 0}, "33"}, {Color{0, 0, 15}, "34"}, {Color{15, 0, 15}, "35"}, {Color{0, 15, 15}, "36"}, } func squareDist(c1, c2 Color) int { xd := c2.r - c1.r yd := c2.g - c1.g zd := c2.b - c1.b return xd*xd + yd*yd + zd*zd } func printColor(s string) { n := len(s) k := 0 for i := 0; i < n/3; i++ { j := i * 3 c1 := s[j] c2 := s[j+1] c3 := s[j+2] k = j + 3 r, err := strconv.ParseInt(fmt.Sprintf("0x%c", c1), 0, 64) check(err) g, err := strconv.ParseInt(fmt.Sprintf("0x%c", c2), 0, 64) check(err) b, err := strconv.ParseInt(fmt.Sprintf("0x%c", c3), 0, 64) check(err) rgb := Color{int(r), int(g), int(b)} m := 676 colorCode := "" for _, cex := range colors { sqd := squareDist(cex.color, rgb) if sqd < m { colorCode = cex.code m = sqd } } fmt.Printf("\033[%s;1m%c%c%c\033[00m", colorCode, c1, c2, c3) } for j := k; j < n; j++ { c := s[j] fmt.Printf("\033[0;1m%c\033[00m", c) } } var ( r = regexp.MustCompile("^([A-Fa-f0-9]+)([ \t]+.+)$") scanner = bufio.NewScanner(os.Stdin) err error ) func colorChecksum() { for scanner.Scan() { line := scanner.Text() if r.MatchString(line) { submatches := r.FindStringSubmatch(line) s1 := submatches[1] s2 := submatches[2] printColor(s1) fmt.Println(s2) } else { fmt.Println(line) } } check(scanner.Err()) } func cat() { for scanner.Scan() { line := scanner.Text() fmt.Println(line) } check(scanner.Err()) } func check(err error) { if err != nil { log.Fatal(err) } } func main() { if terminal.IsTerminal(int(os.Stdout.Fd())) { colorChecksum() } else { cat() } }
from __future__ import unicode_literals import argparse import fileinput import os import sys from functools import partial from itertools import count from itertools import takewhile ANSI_RESET = "\u001b[0m" RED = (255, 0, 0) GREEN = (0, 255, 0) YELLOW = (255, 255, 0) BLUE = (0, 0, 255) MAGENTA = (255, 0, 255) CYAN = (0, 255, 255) ANSI_PALETTE = { RED: "\u001b[31m", GREEN: "\u001b[32m", YELLOW: "\u001b[33m", BLUE: "\u001b[34m", MAGENTA: "\u001b[35m", CYAN: "\u001b[36m", } _8BIT_PALETTE = { (0xAF, 0x00, 0x00): "\u001b[38;5;124m", (0xAF, 0x00, 0x5F): "\u001b[38;5;125m", (0xAF, 0x00, 0x87): "\u001b[38;5;126m", (0xAF, 0x00, 0xAF): "\u001b[38;5;127m", (0xAF, 0x00, 0xD7): "\u001b[38;5;128m", (0xAF, 0x00, 0xFF): "\u001b[38;5;129m", (0xAF, 0x5F, 0x00): "\u001b[38;5;130m", (0xAF, 0x5F, 0x5F): "\u001b[38;5;131m", (0xAF, 0x5F, 0x87): "\u001b[38;5;132m", (0xAF, 0x5F, 0xAF): "\u001b[38;5;133m", (0xAF, 0x5F, 0xD7): "\u001b[38;5;134m", (0xAF, 0x5F, 0xFF): "\u001b[38;5;135m", (0xAF, 0x87, 0x00): "\u001b[38;5;136m", (0xAF, 0x87, 0x5F): "\u001b[38;5;137m", (0xAF, 0x87, 0x87): "\u001b[38;5;138m", (0xAF, 0x87, 0xAF): "\u001b[38;5;139m", (0xAF, 0x87, 0xD7): "\u001b[38;5;140m", (0xAF, 0x87, 0xFF): "\u001b[38;5;141m", (0xAF, 0xAF, 0x00): "\u001b[38;5;142m", (0xAF, 0xAF, 0x5F): "\u001b[38;5;143m", (0xAF, 0xAF, 0x87): "\u001b[38;5;144m", (0xAF, 0xAF, 0xAF): "\u001b[38;5;145m", (0xAF, 0xAF, 0xD7): "\u001b[38;5;146m", (0xAF, 0xAF, 0xFF): "\u001b[38;5;147m", (0xAF, 0xD7, 0x00): "\u001b[38;5;148m", (0xAF, 0xD7, 0x5F): "\u001b[38;5;149m", (0xAF, 0xD7, 0x87): "\u001b[38;5;150m", (0xAF, 0xD7, 0xAF): "\u001b[38;5;151m", (0xAF, 0xD7, 0xD7): "\u001b[38;5;152m", (0xAF, 0xD7, 0xFF): "\u001b[38;5;153m", (0xAF, 0xFF, 0x00): "\u001b[38;5;154m", (0xAF, 0xFF, 0x5F): "\u001b[38;5;155m", (0xAF, 0xFF, 0x87): "\u001b[38;5;156m", (0xAF, 0xFF, 0xAF): "\u001b[38;5;157m", (0xAF, 0xFF, 0xD7): "\u001b[38;5;158m", (0xAF, 0xFF, 0xFF): "\u001b[38;5;159m", } def error(msg): sys.stderr.write(msg) sys.stderr.write(os.linesep) sys.exit(1) def rgb(group): nibbles_per_channel = len(group) // 3 max_val = 16 ** nibbles_per_channel - 1 nibbles = chunked(group, nibbles_per_channel) return tuple((int(n, 16) * 255) // max_val for n in nibbles) def distance(color, other): return sum((o - s) ** 2 for s, o in zip(color, other)) def chunked(seq, n): return takewhile(len, (seq[i : i + n] for i in count(0, n))) def escape(group, palette): key = partial(distance, other=rgb(group.ljust(3, "0"))) ansi_color = min(palette, key=key) return "".join([palette[ansi_color], group, ANSI_RESET]) def colorize(line, group_size=3, palette=ANSI_PALETTE): checksum, filename = line.split(None, 1) escaped = [escape(group, palette) for group in chunked(checksum, group_size)] sys.stdout.write(" ".join(["".join(escaped), filename])) def html_colorize(checksum, group_size=3, palette=ANSI_PALETTE): def span(group): key = partial(distance, other=rgb(group.ljust(3, "0"))) ansi_color = min(palette, key=key) int_val = int.from_bytes(ansi_color, byteorder="big") hex_val = hex(int_val)[2:].rjust(6, "0") return '<span style="color: checksum, filename = line.split(None, 1) escaped = [span(group) for group in chunked(checksum, group_size)] sys.stdout.write(" ".join(["".join(escaped), filename])) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Color checksum.") parser.add_argument( "-n", type=int, default=3, help="Color the checksum in groups of size N. Defaults to 3.", ) parser.add_argument( "-e", "--extended-palette", action="store_true", help="Use the extended 8-bit palette. Defaults to False.", ) parser.add_argument( "--html", action="store_true", help="Output checksum groups wrapped with 'span' tags instead of ANSI escape sequences.", ) parser.add_argument("files", nargs="*", default="-", metavar="FILE") args = parser.parse_args() if sys.stdout.isatty(): palette = ANSI_PALETTE if args.extended_palette: palette = _8BIT_PALETTE colorize_func = colorize if args.html: colorize_func = html_colorize for line in fileinput.input(files=args.files): colorize_func(line, group_size=args.n, palette=palette) else: for line in fileinput.input(files=args.files): sys.stdout.write(line)
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "time" ) const ( chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" host = "localhost:8000" ) type database map[string]string type shortener struct { Long string `json:"long"` } func (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) { switch req.Method { case http.MethodPost: body, err := ioutil.ReadAll(req.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) return } var sh shortener err = json.Unmarshal(body, &sh) if err != nil { w.WriteHeader(http.StatusUnprocessableEntity) return } short := generateKey(8) db[short] = sh.Long fmt.Fprintf(w, "The shortened URL: http: case http.MethodGet: path := req.URL.Path[1:] if v, ok := db[path]; ok { http.Redirect(w, req, v, http.StatusFound) } else { w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "No such shortened url: http: } default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Unsupprted method: %s\n", req.Method) } } func generateKey(size int) string { key := make([]byte, size) le := len(chars) for i := 0; i < size; i++ { key[i] = chars[rand.Intn(le)] } return string(key) } func main() { rand.Seed(time.Now().UnixNano()) db := make(database) log.Fatal(http.ListenAndServe(host, db)) }
import sqlite3 import string import random from http import HTTPStatus from flask import Flask from flask import Blueprint from flask import abort from flask import current_app from flask import g from flask import jsonify from flask import redirect from flask import request from flask import url_for CHARS = frozenset(string.ascii_letters + string.digits) MIN_URL_SIZE = 8 RANDOM_ATTEMPTS = 3 def create_app(*, db=None, server_name=None) -> Flask: app = Flask(__name__) app.config.from_mapping( DATABASE=db or "shorten.sqlite", SERVER_NAME=server_name, ) with app.app_context(): init_db() app.teardown_appcontext(close_db) app.register_blueprint(shortener) return app def get_db(): if "db" not in g: g.db = sqlite3.connect(current_app.config["DATABASE"]) g.db.row_factory = sqlite3.Row return g.db def close_db(_): db = g.pop("db", None) if db is not None: db.close() def init_db(): db = get_db() with db: db.execute( "CREATE TABLE IF NOT EXISTS shorten (" "url TEXT PRIMARY KEY, " "short TEXT NOT NULL UNIQUE ON CONFLICT FAIL)" ) shortener = Blueprint("shorten", "short") def random_short(size=MIN_URL_SIZE): return "".join(random.sample(CHARS, size)) @shortener.errorhandler(HTTPStatus.NOT_FOUND) def short_url_not_found(_): return "short url not found", HTTPStatus.NOT_FOUND @shortener.route("/<path:key>", methods=("GET",)) def short(key): db = get_db() cursor = db.execute("SELECT url FROM shorten WHERE short = ?", (key,)) row = cursor.fetchone() if row is None: abort(HTTPStatus.NOT_FOUND) return redirect(row["url"], code=HTTPStatus.FOUND) class URLExistsError(Exception): class ShortCollisionError(Exception): def _insert_short(long_url, short): db = get_db() if ( db.execute("SELECT * FROM shorten WHERE url = ?", (long_url,)).fetchone() is not None ): raise URLExistsError(long_url) if ( db.execute("SELECT * FROM shorten WHERE short = ?", (short,)).fetchone() is not None ): raise ShortCollisionError(short) with db: db.execute("INSERT INTO shorten VALUES (?, ?)", (long_url, short)) def make_short(long_url): size = MIN_URL_SIZE attempts = 1 short = random_short(size=size) while True: try: _insert_short(long_url, short) except ShortCollisionError: if not attempts % RANDOM_ATTEMPTS: size += 1 attempts += 1 short = random_short(size=size) else: break return short @shortener.route("/", methods=("POST",)) def shorten(): data = request.get_json() if data is None: abort(HTTPStatus.BAD_REQUEST) long_url = data.get("long") if long_url is None: abort(HTTPStatus.BAD_REQUEST) db = get_db() cursor = db.execute("SELECT short FROM shorten WHERE url = ?", (long_url,)) row = cursor.fetchone() if row is not None: short_url = url_for("shorten.short", _external=True, key=row["short"]) status_code = HTTPStatus.OK else: short_url = url_for("shorten.short", _external=True, key=make_short(long_url)) status_code = HTTPStatus.CREATED mimetype = request.accept_mimetypes.best_match( matches=["text/plain", "application/json"], default="text/plain" ) if mimetype == "application/json": return jsonify(long=long_url, short=short_url), status_code else: return short_url, status_code if __name__ == "__main__": app = create_app() app.env = "development" app.run(debug=True)
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "time" ) const ( chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" host = "localhost:8000" ) type database map[string]string type shortener struct { Long string `json:"long"` } func (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) { switch req.Method { case http.MethodPost: body, err := ioutil.ReadAll(req.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) return } var sh shortener err = json.Unmarshal(body, &sh) if err != nil { w.WriteHeader(http.StatusUnprocessableEntity) return } short := generateKey(8) db[short] = sh.Long fmt.Fprintf(w, "The shortened URL: http: case http.MethodGet: path := req.URL.Path[1:] if v, ok := db[path]; ok { http.Redirect(w, req, v, http.StatusFound) } else { w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "No such shortened url: http: } default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Unsupprted method: %s\n", req.Method) } } func generateKey(size int) string { key := make([]byte, size) le := len(chars) for i := 0; i < size; i++ { key[i] = chars[rand.Intn(le)] } return string(key) } func main() { rand.Seed(time.Now().UnixNano()) db := make(database) log.Fatal(http.ListenAndServe(host, db)) }
import sqlite3 import string import random from http import HTTPStatus from flask import Flask from flask import Blueprint from flask import abort from flask import current_app from flask import g from flask import jsonify from flask import redirect from flask import request from flask import url_for CHARS = frozenset(string.ascii_letters + string.digits) MIN_URL_SIZE = 8 RANDOM_ATTEMPTS = 3 def create_app(*, db=None, server_name=None) -> Flask: app = Flask(__name__) app.config.from_mapping( DATABASE=db or "shorten.sqlite", SERVER_NAME=server_name, ) with app.app_context(): init_db() app.teardown_appcontext(close_db) app.register_blueprint(shortener) return app def get_db(): if "db" not in g: g.db = sqlite3.connect(current_app.config["DATABASE"]) g.db.row_factory = sqlite3.Row return g.db def close_db(_): db = g.pop("db", None) if db is not None: db.close() def init_db(): db = get_db() with db: db.execute( "CREATE TABLE IF NOT EXISTS shorten (" "url TEXT PRIMARY KEY, " "short TEXT NOT NULL UNIQUE ON CONFLICT FAIL)" ) shortener = Blueprint("shorten", "short") def random_short(size=MIN_URL_SIZE): return "".join(random.sample(CHARS, size)) @shortener.errorhandler(HTTPStatus.NOT_FOUND) def short_url_not_found(_): return "short url not found", HTTPStatus.NOT_FOUND @shortener.route("/<path:key>", methods=("GET",)) def short(key): db = get_db() cursor = db.execute("SELECT url FROM shorten WHERE short = ?", (key,)) row = cursor.fetchone() if row is None: abort(HTTPStatus.NOT_FOUND) return redirect(row["url"], code=HTTPStatus.FOUND) class URLExistsError(Exception): class ShortCollisionError(Exception): def _insert_short(long_url, short): db = get_db() if ( db.execute("SELECT * FROM shorten WHERE url = ?", (long_url,)).fetchone() is not None ): raise URLExistsError(long_url) if ( db.execute("SELECT * FROM shorten WHERE short = ?", (short,)).fetchone() is not None ): raise ShortCollisionError(short) with db: db.execute("INSERT INTO shorten VALUES (?, ?)", (long_url, short)) def make_short(long_url): size = MIN_URL_SIZE attempts = 1 short = random_short(size=size) while True: try: _insert_short(long_url, short) except ShortCollisionError: if not attempts % RANDOM_ATTEMPTS: size += 1 attempts += 1 short = random_short(size=size) else: break return short @shortener.route("/", methods=("POST",)) def shorten(): data = request.get_json() if data is None: abort(HTTPStatus.BAD_REQUEST) long_url = data.get("long") if long_url is None: abort(HTTPStatus.BAD_REQUEST) db = get_db() cursor = db.execute("SELECT short FROM shorten WHERE url = ?", (long_url,)) row = cursor.fetchone() if row is not None: short_url = url_for("shorten.short", _external=True, key=row["short"]) status_code = HTTPStatus.OK else: short_url = url_for("shorten.short", _external=True, key=make_short(long_url)) status_code = HTTPStatus.CREATED mimetype = request.accept_mimetypes.best_match( matches=["text/plain", "application/json"], default="text/plain" ) if mimetype == "application/json": return jsonify(long=long_url, short=short_url), status_code else: return short_url, status_code if __name__ == "__main__": app = create_app() app.env = "development" app.run(debug=True)
Please provide an equivalent version of this Go code in Python.
package main import ( "bytes" "errors" "flag" "fmt" "io" "io/ioutil" "log" "math/rand" "os" "time" ) const ( Rows = 3 Cols = 3 ) var vlog *log.Logger func main() { verbose := flag.Bool("v", false, "verbose") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } logOutput := ioutil.Discard if *verbose { logOutput = os.Stderr } vlog = log.New(logOutput, "hexapawn: ", 0) rand.Seed(time.Now().UnixNano()) wins := make(map[spot]int, 2) for { h := New() var s herGameState for c := false; h[stateIdx] == empty; c = !c { if c { h = s.Move(h) } else { h = h.HumanMove() } } fmt.Printf("Board:\n%v is a win for %v\n", h, h[stateIdx]) s.Result(h[stateIdx]) wins[h[stateIdx]]++ fmt.Printf("Wins: Black=%d, White=%d\n", wins[black], wins[white]) fmt.Println() } } func (h Hexapawn) HumanMove() Hexapawn { fmt.Print("Board:\n", h, "\n") var from, to int for { fmt.Print("Your move: ") _, err := fmt.Scanln(&from, &to) if err != nil { fmt.Println(err) if err == io.EOF { os.Exit(0) } continue } if err := h.doMove(white, from-1, to-1); err != nil { fmt.Println(err) continue } return h } } var herNextMove = make(map[Hexapawn][]move) type herGameState struct { h Hexapawn i int } func (s *herGameState) Move(h Hexapawn) Hexapawn { known := false moves := herNextMove[h] if moves == nil { moves = possibleMoves(black, h) herNextMove[h] = moves } else if len(moves) == 0 { vlog.Println("no good moves left to black, picking a random looser") known = true moves = possibleMoves(black, h) } vlog.Println("considering", moves) i := rand.Intn(len(moves)) if !known { s.h = h s.i = i } fmt.Println("Computer moves", moves[i]) if err := h.doMove(black, moves[i].from, moves[i].to); err != nil { panic(err) } return h } func (s herGameState) Result(winner spot) { if winner == black { return } moves := herNextMove[s.h] vlog.Printf("Training:\n%v will no longer do %v\n", s.h, moves[s.i]) herNextMove[s.h] = append(moves[:s.i], moves[s.i+1:]...) vlog.Println("will instead do one of:", herNextMove[s.h]) } type move struct{ from, to int } func (m move) String() string { return fmt.Sprintf("%d→%d", m.from+1, m.to+1) } var cachedMoves = []map[Hexapawn][]move{ black: make(map[Hexapawn][]move), white: make(map[Hexapawn][]move), } func possibleMoves(s spot, h Hexapawn) []move { m := cachedMoves[s][h] if m != nil { return m } m = make([]move, 0) for from := 0; from < Rows*Cols; from++ { for to := 0; to < Rows*Cols; to++ { if err := h.checkMove(s, from, to); err == nil { m = append(m, move{from, to}) } } } cachedMoves[s][h] = m vlog.Printf("caclulated possible moves for %v\n%v as %v\n", s, h, m) return m } func (h *Hexapawn) doMove(p spot, from, to int) error { if err := h.checkMove(p, from, to); err != nil { return err } h[from] = empty h[to] = p if (p == white && to/Rows == Rows-1) || (p == black && to/Rows == 0) { h[stateIdx] = p } else if len(possibleMoves(p.Other(), *h)) == 0 { h[stateIdx] = p } return nil } func (h *Hexapawn) checkMove(p spot, from, to int) error { if h[from] != p { return fmt.Errorf("No %v located at spot %v", p, from+1) } if h[to] == p { return fmt.Errorf("%v already occupies spot %v", p, to+1) } Δr := from/Rows - to/Rows if (p == white && Δr != -1) || (p == black && Δr != 1) { return errors.New("must move forward one row") } Δc := from%Rows - to%Rows capture := h[to] != empty if (capture || Δc != 0) && (!capture || (Δc != 1 && Δc != -1)) { return errors.New("ilegal move") } return nil } type Hexapawn [Rows*Cols + 1]spot func New() Hexapawn { return Hexapawn{ white, white, white, empty, empty, empty, black, black, black, } } func idx(r, c int) int { return r*Cols + c } const stateIdx = Rows * Cols func (h Hexapawn) String() string { var b bytes.Buffer for r := Rows - 1; r >= 0; r-- { for c := 0; c < Cols; c++ { b.WriteByte(h[idx(r, c)].Byte()) } b.WriteByte('\n') } return string(b.Next(Rows*(Cols+1) - 1)) } type spot uint8 const ( empty spot = iota black white ) func (s spot) String() string { switch s { case black: return "Black" case white: return "White" } panic(s) } func (s spot) Byte() byte { switch s { case empty: return '.' case black: return 'B' case white: return 'W' } panic(s) } func (s spot) Other() spot { if s == black { return white } return black }
import sys black_pawn = " \u265f " white_pawn = " \u2659 " empty_square = " " def draw_board(board_data): bg_black = "\u001b[48;5;237m" bg_white = "\u001b[48;5;245m" clear_to_eol = "\u001b[0m\u001b[K\n" board = ["1 ", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black, board_data[0][2], clear_to_eol, "2 ", bg_white, board_data[1][0], bg_black, board_data[1][1], bg_white, board_data[1][2], clear_to_eol, "3 ", bg_black, board_data[2][0], bg_white, board_data[2][1], bg_black, board_data[2][2], clear_to_eol, " A B C\n"]; sys.stdout.write("".join(board)) def get_movement_direction(colour): direction = -1 if colour == black_pawn: direction = 1 elif colour == white_pawn: direction = -1 else: raise ValueError("Invalid piece colour") return direction def get_other_colour(colour): if colour == black_pawn: return white_pawn elif colour == white_pawn: return black_pawn else: raise ValueError("Invalid piece colour") def get_allowed_moves(board_data, row, col): if board_data[row][col] == empty_square: return set() colour = board_data[row][col] other_colour = get_other_colour(colour) direction = get_movement_direction(colour) if (row + direction < 0 or row + direction > 2): return set() allowed_moves = set() if board_data[row + direction][col] == empty_square: allowed_moves.add('f') if col > 0 and board_data[row + direction][col - 1] == other_colour: allowed_moves.add('dl') if col < 2 and board_data[row + direction][col + 1] == other_colour: allowed_moves.add('dr') return allowed_moves def get_human_move(board_data, colour): direction = get_movement_direction(colour) while True: piece_posn = input(f'What {colour} do you want to move? ') valid_inputs = {'a1': (0,0), 'b1': (0,1), 'c1': (0,2), 'a2': (1,0), 'b2': (1,1), 'c2': (1,2), 'a3': (2,0), 'b3': (2,1), 'c3': (2,2)} if piece_posn not in valid_inputs: print("LOL that's not a valid position! Try again.") continue (row, col) = valid_inputs[piece_posn] piece = board_data[row][col] if piece == empty_square: print("What are you trying to pull, there's no piece in that space!") continue if piece != colour: print("LOL that's not your piece, try again!") continue allowed_moves = get_allowed_moves(board_data, row, col) if len(allowed_moves) == 0: print('LOL nice try. That piece has no valid moves.') continue move = list(allowed_moves)[0] if len(allowed_moves) > 1: move = input(f'What move do you want to make ({",".join(list(allowed_moves))})? ') if move not in allowed_moves: print('LOL that move is not allowed. Try again.') continue if move == 'f': board_data[row + direction][col] = board_data[row][col] elif move == 'dl': board_data[row + direction][col - 1] = board_data[row][col] elif move == 'dr': board_data[row + direction][col + 1] = board_data[row][col] board_data[row][col] = empty_square return board_data def is_game_over(board_data): if board_data[0][0] == white_pawn or board_data[0][1] == white_pawn or board_data[0][2] == white_pawn: return white_pawn if board_data[2][0] == black_pawn or board_data[2][1] == black_pawn or board_data[2][2] == black_pawn: return black_pawn white_count = 0 black_count = 0 black_allowed_moves = [] white_allowed_moves = [] for i in range(3): for j in range(3): moves = get_allowed_moves(board_data, i, j) if board_data[i][j] == white_pawn: white_count += 1 if len(moves) > 0: white_allowed_moves.append((i,j,moves)) if board_data[i][j] == black_pawn: black_count += 1 if len(moves) > 0: black_allowed_moves.append((i,j,moves)) if white_count == 0 or len(white_allowed_moves) == 0: return black_pawn if black_count == 0 or len(black_allowed_moves) == 0: return white_pawn return "LOL NOPE" def play_game(black_move, white_move): board_data = [[black_pawn, black_pawn, black_pawn], [empty_square, empty_square, empty_square], [white_pawn, white_pawn, white_pawn]] last_player = black_pawn next_player = white_pawn while is_game_over(board_data) == "LOL NOPE": draw_board(board_data) if (next_player == black_pawn): board_data = black_move(board_data, next_player) else: board_data = white_move(board_data, next_player) temp = last_player last_player = next_player next_player = temp winner = is_game_over(board_data) print(f'Congratulations {winner}!') play_game(get_human_move, get_human_move)
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "bytes" "errors" "flag" "fmt" "io" "io/ioutil" "log" "math/rand" "os" "time" ) const ( Rows = 3 Cols = 3 ) var vlog *log.Logger func main() { verbose := flag.Bool("v", false, "verbose") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } logOutput := ioutil.Discard if *verbose { logOutput = os.Stderr } vlog = log.New(logOutput, "hexapawn: ", 0) rand.Seed(time.Now().UnixNano()) wins := make(map[spot]int, 2) for { h := New() var s herGameState for c := false; h[stateIdx] == empty; c = !c { if c { h = s.Move(h) } else { h = h.HumanMove() } } fmt.Printf("Board:\n%v is a win for %v\n", h, h[stateIdx]) s.Result(h[stateIdx]) wins[h[stateIdx]]++ fmt.Printf("Wins: Black=%d, White=%d\n", wins[black], wins[white]) fmt.Println() } } func (h Hexapawn) HumanMove() Hexapawn { fmt.Print("Board:\n", h, "\n") var from, to int for { fmt.Print("Your move: ") _, err := fmt.Scanln(&from, &to) if err != nil { fmt.Println(err) if err == io.EOF { os.Exit(0) } continue } if err := h.doMove(white, from-1, to-1); err != nil { fmt.Println(err) continue } return h } } var herNextMove = make(map[Hexapawn][]move) type herGameState struct { h Hexapawn i int } func (s *herGameState) Move(h Hexapawn) Hexapawn { known := false moves := herNextMove[h] if moves == nil { moves = possibleMoves(black, h) herNextMove[h] = moves } else if len(moves) == 0 { vlog.Println("no good moves left to black, picking a random looser") known = true moves = possibleMoves(black, h) } vlog.Println("considering", moves) i := rand.Intn(len(moves)) if !known { s.h = h s.i = i } fmt.Println("Computer moves", moves[i]) if err := h.doMove(black, moves[i].from, moves[i].to); err != nil { panic(err) } return h } func (s herGameState) Result(winner spot) { if winner == black { return } moves := herNextMove[s.h] vlog.Printf("Training:\n%v will no longer do %v\n", s.h, moves[s.i]) herNextMove[s.h] = append(moves[:s.i], moves[s.i+1:]...) vlog.Println("will instead do one of:", herNextMove[s.h]) } type move struct{ from, to int } func (m move) String() string { return fmt.Sprintf("%d→%d", m.from+1, m.to+1) } var cachedMoves = []map[Hexapawn][]move{ black: make(map[Hexapawn][]move), white: make(map[Hexapawn][]move), } func possibleMoves(s spot, h Hexapawn) []move { m := cachedMoves[s][h] if m != nil { return m } m = make([]move, 0) for from := 0; from < Rows*Cols; from++ { for to := 0; to < Rows*Cols; to++ { if err := h.checkMove(s, from, to); err == nil { m = append(m, move{from, to}) } } } cachedMoves[s][h] = m vlog.Printf("caclulated possible moves for %v\n%v as %v\n", s, h, m) return m } func (h *Hexapawn) doMove(p spot, from, to int) error { if err := h.checkMove(p, from, to); err != nil { return err } h[from] = empty h[to] = p if (p == white && to/Rows == Rows-1) || (p == black && to/Rows == 0) { h[stateIdx] = p } else if len(possibleMoves(p.Other(), *h)) == 0 { h[stateIdx] = p } return nil } func (h *Hexapawn) checkMove(p spot, from, to int) error { if h[from] != p { return fmt.Errorf("No %v located at spot %v", p, from+1) } if h[to] == p { return fmt.Errorf("%v already occupies spot %v", p, to+1) } Δr := from/Rows - to/Rows if (p == white && Δr != -1) || (p == black && Δr != 1) { return errors.New("must move forward one row") } Δc := from%Rows - to%Rows capture := h[to] != empty if (capture || Δc != 0) && (!capture || (Δc != 1 && Δc != -1)) { return errors.New("ilegal move") } return nil } type Hexapawn [Rows*Cols + 1]spot func New() Hexapawn { return Hexapawn{ white, white, white, empty, empty, empty, black, black, black, } } func idx(r, c int) int { return r*Cols + c } const stateIdx = Rows * Cols func (h Hexapawn) String() string { var b bytes.Buffer for r := Rows - 1; r >= 0; r-- { for c := 0; c < Cols; c++ { b.WriteByte(h[idx(r, c)].Byte()) } b.WriteByte('\n') } return string(b.Next(Rows*(Cols+1) - 1)) } type spot uint8 const ( empty spot = iota black white ) func (s spot) String() string { switch s { case black: return "Black" case white: return "White" } panic(s) } func (s spot) Byte() byte { switch s { case empty: return '.' case black: return 'B' case white: return 'W' } panic(s) } func (s spot) Other() spot { if s == black { return white } return black }
import sys black_pawn = " \u265f " white_pawn = " \u2659 " empty_square = " " def draw_board(board_data): bg_black = "\u001b[48;5;237m" bg_white = "\u001b[48;5;245m" clear_to_eol = "\u001b[0m\u001b[K\n" board = ["1 ", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black, board_data[0][2], clear_to_eol, "2 ", bg_white, board_data[1][0], bg_black, board_data[1][1], bg_white, board_data[1][2], clear_to_eol, "3 ", bg_black, board_data[2][0], bg_white, board_data[2][1], bg_black, board_data[2][2], clear_to_eol, " A B C\n"]; sys.stdout.write("".join(board)) def get_movement_direction(colour): direction = -1 if colour == black_pawn: direction = 1 elif colour == white_pawn: direction = -1 else: raise ValueError("Invalid piece colour") return direction def get_other_colour(colour): if colour == black_pawn: return white_pawn elif colour == white_pawn: return black_pawn else: raise ValueError("Invalid piece colour") def get_allowed_moves(board_data, row, col): if board_data[row][col] == empty_square: return set() colour = board_data[row][col] other_colour = get_other_colour(colour) direction = get_movement_direction(colour) if (row + direction < 0 or row + direction > 2): return set() allowed_moves = set() if board_data[row + direction][col] == empty_square: allowed_moves.add('f') if col > 0 and board_data[row + direction][col - 1] == other_colour: allowed_moves.add('dl') if col < 2 and board_data[row + direction][col + 1] == other_colour: allowed_moves.add('dr') return allowed_moves def get_human_move(board_data, colour): direction = get_movement_direction(colour) while True: piece_posn = input(f'What {colour} do you want to move? ') valid_inputs = {'a1': (0,0), 'b1': (0,1), 'c1': (0,2), 'a2': (1,0), 'b2': (1,1), 'c2': (1,2), 'a3': (2,0), 'b3': (2,1), 'c3': (2,2)} if piece_posn not in valid_inputs: print("LOL that's not a valid position! Try again.") continue (row, col) = valid_inputs[piece_posn] piece = board_data[row][col] if piece == empty_square: print("What are you trying to pull, there's no piece in that space!") continue if piece != colour: print("LOL that's not your piece, try again!") continue allowed_moves = get_allowed_moves(board_data, row, col) if len(allowed_moves) == 0: print('LOL nice try. That piece has no valid moves.') continue move = list(allowed_moves)[0] if len(allowed_moves) > 1: move = input(f'What move do you want to make ({",".join(list(allowed_moves))})? ') if move not in allowed_moves: print('LOL that move is not allowed. Try again.') continue if move == 'f': board_data[row + direction][col] = board_data[row][col] elif move == 'dl': board_data[row + direction][col - 1] = board_data[row][col] elif move == 'dr': board_data[row + direction][col + 1] = board_data[row][col] board_data[row][col] = empty_square return board_data def is_game_over(board_data): if board_data[0][0] == white_pawn or board_data[0][1] == white_pawn or board_data[0][2] == white_pawn: return white_pawn if board_data[2][0] == black_pawn or board_data[2][1] == black_pawn or board_data[2][2] == black_pawn: return black_pawn white_count = 0 black_count = 0 black_allowed_moves = [] white_allowed_moves = [] for i in range(3): for j in range(3): moves = get_allowed_moves(board_data, i, j) if board_data[i][j] == white_pawn: white_count += 1 if len(moves) > 0: white_allowed_moves.append((i,j,moves)) if board_data[i][j] == black_pawn: black_count += 1 if len(moves) > 0: black_allowed_moves.append((i,j,moves)) if white_count == 0 or len(white_allowed_moves) == 0: return black_pawn if black_count == 0 or len(black_allowed_moves) == 0: return white_pawn return "LOL NOPE" def play_game(black_move, white_move): board_data = [[black_pawn, black_pawn, black_pawn], [empty_square, empty_square, empty_square], [white_pawn, white_pawn, white_pawn]] last_player = black_pawn next_player = white_pawn while is_game_over(board_data) == "LOL NOPE": draw_board(board_data) if (next_player == black_pawn): board_data = black_move(board_data, next_player) else: board_data = white_move(board_data, next_player) temp = last_player last_player = next_player next_player = temp winner = is_game_over(board_data) print(f'Congratulations {winner}!') play_game(get_human_move, get_human_move)
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "sort" ) type graph struct { nn int st int nbr [][]int } type nodeval struct { n int v int } func contains(s []int, n int) bool { for _, e := range s { if e == n { return true } } return false } func newGraph(nn, st int) graph { nbr := make([][]int, nn) return graph{nn, st, nbr} } func (g graph) addEdge(n1, n2 int) { n1, n2 = n1-g.st, n2-g.st g.nbr[n1] = append(g.nbr[n1], n2) if n1 != n2 { g.nbr[n2] = append(g.nbr[n2], n1) } } func (g graph) greedyColoring() []int { cols := make([]int, g.nn) for i := 1; i < g.nn; i++ { cols[i] = -1 } available := make([]bool, g.nn) for i := 1; i < g.nn; i++ { for _, j := range g.nbr[i] { if cols[j] != -1 { available[cols[j]] = true } } c := 0 for ; c < g.nn; c++ { if !available[c] { break } } cols[i] = c for _, j := range g.nbr[i] { if cols[j] != -1 { available[cols[j]] = false } } } return cols } func (g graph) wpColoring() []int { nvs := make([]nodeval, g.nn) for i := 0; i < g.nn; i++ { v := len(g.nbr[i]) if v == 1 && g.nbr[i][0] == i { v = 0 } nvs[i] = nodeval{i, v} } sort.Slice(nvs, func(i, j int) bool { return nvs[i].v > nvs[j].v }) cols := make([]int, g.nn) for i := range cols { cols[i] = -1 } currCol := 0 for f := 0; f < g.nn-1; f++ { h := nvs[f].n if cols[h] != -1 { continue } cols[h] = currCol outer: for i := f + 1; i < g.nn; i++ { j := nvs[i].n if cols[j] != -1 { continue } for k := f; k < i; k++ { l := nvs[k].n if cols[l] == -1 { continue } if contains(g.nbr[j], l) { continue outer } } cols[j] = currCol } currCol++ } return cols } func main() { fns := [](func(graph) []int){graph.greedyColoring, graph.wpColoring} titles := []string{"'Greedy'", "Welsh-Powell"} nns := []int{4, 8, 8, 8} starts := []int{0, 1, 1, 1} edges1 := [][2]int{{0, 1}, {1, 2}, {2, 0}, {3, 3}} edges2 := [][2]int{{1, 6}, {1, 7}, {1, 8}, {2, 5}, {2, 7}, {2, 8}, {3, 5}, {3, 6}, {3, 8}, {4, 5}, {4, 6}, {4, 7}} edges3 := [][2]int{{1, 4}, {1, 6}, {1, 8}, {3, 2}, {3, 6}, {3, 8}, {5, 2}, {5, 4}, {5, 8}, {7, 2}, {7, 4}, {7, 6}} edges4 := [][2]int{{1, 6}, {7, 1}, {8, 1}, {5, 2}, {2, 7}, {2, 8}, {3, 5}, {6, 3}, {3, 8}, {4, 5}, {4, 6}, {4, 7}} for j, fn := range fns { fmt.Println("Using the", titles[j], "algorithm:\n") for i, edges := range [][][2]int{edges1, edges2, edges3, edges4} { fmt.Println(" Example", i+1) g := newGraph(nns[i], starts[i]) for _, e := range edges { g.addEdge(e[0], e[1]) } cols := fn(g) ecount := 0 for _, e := range edges { if e[0] != e[1] { fmt.Printf(" Edge %d-%d -> Color %d, %d\n", e[0], e[1], cols[e[0]-g.st], cols[e[1]-g.st]) ecount++ } else { fmt.Printf(" Node %d -> Color %d\n", e[0], cols[e[0]-g.st]) } } maxCol := 0 for _, col := range cols { if col > maxCol { maxCol = col } } fmt.Println(" Number of nodes  :", nns[i]) fmt.Println(" Number of edges  :", ecount) fmt.Println(" Number of colors :", maxCol+1) fmt.Println() } } }
import re from collections import defaultdict from itertools import count connection_re = r class Graph: def __init__(self, name, connections): self.name = name self.connections = connections g = self.graph = defaultdict(list) matches = re.finditer(connection_re, connections, re.MULTILINE | re.VERBOSE) for match in matches: n1, n2, n = match.groups() if n: g[n] += [] else: g[n1].append(n2) g[n2].append(n1) def greedy_colour(self, order=None): "Greedy colourisation algo." if order is None: order = self.graph colour = self.colour = {} neighbours = self.graph for node in order: used_neighbour_colours = (colour[nbr] for nbr in neighbours[node] if nbr in colour) colour[node] = first_avail_int(used_neighbour_colours) self.pp_colours() return colour def pp_colours(self): print(f"\n{self.name}") c = self.colour e = canonical_edges = set() for n1, neighbours in sorted(self.graph.items()): if neighbours: for n2 in neighbours: edge = tuple(sorted([n1, n2])) if edge not in canonical_edges: print(f" {n1}-{n2}: Colour: {c[n1]}, {c[n2]}") canonical_edges.add(edge) else: print(f" {n1}: Colour: {c[n1]}") lc = len(set(c.values())) print(f" def first_avail_int(data): "return lowest int 0... not in data" d = set(data) for i in count(): if i not in d: return i if __name__ == '__main__': for name, connections in [ ('Ex1', "0-1 1-2 2-0 3"), ('Ex2', "1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7"), ('Ex3', "1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6"), ('Ex4', "1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7"), ]: g = Graph(name, connections) g.greedy_colour()
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "rcu" "sort" ) func main() { list := []int{2, 43, 81, 122, 63, 13, 7, 95, 103} var primes []int for _, e := range list { if rcu.IsPrime(e) { primes = append(primes, e) } } sort.Ints(primes) fmt.Println(primes) }
print("working...") print("Primes are:") def isprime(m): for i in range(2,int(m**0.5)+1): if m%i==0: return False return True Primes = [2,43,81,122,63,13,7,95,103] Temp = [] for n in range(len(Primes)): if isprime(Primes[n]): Temp.append(Primes[n]) Temp.sort() print(Temp) print("done...")
Port the following code from Go to Python with equivalent syntax and logic.
package main import "fmt" var cnt = 0 var cnt2 = 0 var wdth = 0 func factorial(n int) int { prod := 1 for i := 2; i <= n; i++ { prod *= i } return prod } func count(want int, used []int, sum int, have, uindices, rindices []int) { if sum == want { cnt++ cnt2 += factorial(len(used)) if cnt < 11 { uindicesStr := fmt.Sprintf("%v", uindices) fmt.Printf(" indices %*s => used %v\n", wdth, uindicesStr, used) } } else if sum < want && len(have) != 0 { thisCoin := have[0] index := rindices[0] rest := have[1:] rindices := rindices[1:] count(want, append(used, thisCoin), sum+thisCoin, rest, append(uindices, index), rindices) count(want, used, sum, rest, uindices, rindices) } } func countCoins(want int, coins []int, width int) { fmt.Printf("Sum %d from coins %v\n", want, coins) cnt = 0 cnt2 = 0 wdth = -width rindices := make([]int, len(coins)) for i := range rindices { rindices[i] = i } count(want, []int{}, 0, coins, []int{}, rindices) if cnt > 10 { fmt.Println(" .......") fmt.Println(" (only the first 10 ways generated are shown)") } fmt.Println("Number of ways - order unimportant :", cnt, "(as above)") fmt.Println("Number of ways - order important  :", cnt2, "(all perms of above indices)\n") } func main() { countCoins(6, []int{1, 2, 3, 4, 5}, 7) countCoins(6, []int{1, 1, 2, 3, 3, 4, 5}, 9) countCoins(40, []int{1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100}, 20) }
from itertools import product, compress fact = lambda n: n and n*fact(n - 1) or 1 combo_count = lambda total, coins, perm:\ sum(perm and fact(len(x)) or 1 for x in (list(compress(coins, c)) for c in product(*([(0, 1)]*len(coins)))) if sum(x) == total) cases = [(6, [1, 2, 3, 4, 5]), (6, [1, 1, 2, 3, 3, 4, 5]), (40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100])] for perm in [False, True]: print(f'Order matters: {perm}') for s, c in cases: print(f'{combo_count(s, c, perm):7d} ways for {s:2d} total from coins {c}') print()
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import "fmt" var cnt = 0 var cnt2 = 0 var wdth = 0 func factorial(n int) int { prod := 1 for i := 2; i <= n; i++ { prod *= i } return prod } func count(want int, used []int, sum int, have, uindices, rindices []int) { if sum == want { cnt++ cnt2 += factorial(len(used)) if cnt < 11 { uindicesStr := fmt.Sprintf("%v", uindices) fmt.Printf(" indices %*s => used %v\n", wdth, uindicesStr, used) } } else if sum < want && len(have) != 0 { thisCoin := have[0] index := rindices[0] rest := have[1:] rindices := rindices[1:] count(want, append(used, thisCoin), sum+thisCoin, rest, append(uindices, index), rindices) count(want, used, sum, rest, uindices, rindices) } } func countCoins(want int, coins []int, width int) { fmt.Printf("Sum %d from coins %v\n", want, coins) cnt = 0 cnt2 = 0 wdth = -width rindices := make([]int, len(coins)) for i := range rindices { rindices[i] = i } count(want, []int{}, 0, coins, []int{}, rindices) if cnt > 10 { fmt.Println(" .......") fmt.Println(" (only the first 10 ways generated are shown)") } fmt.Println("Number of ways - order unimportant :", cnt, "(as above)") fmt.Println("Number of ways - order important  :", cnt2, "(all perms of above indices)\n") } func main() { countCoins(6, []int{1, 2, 3, 4, 5}, 7) countCoins(6, []int{1, 1, 2, 3, 3, 4, 5}, 9) countCoins(40, []int{1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100}, 20) }
from itertools import product, compress fact = lambda n: n and n*fact(n - 1) or 1 combo_count = lambda total, coins, perm:\ sum(perm and fact(len(x)) or 1 for x in (list(compress(coins, c)) for c in product(*([(0, 1)]*len(coins)))) if sum(x) == total) cases = [(6, [1, 2, 3, 4, 5]), (6, [1, 1, 2, 3, 3, 4, 5]), (40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100])] for perm in [False, True]: print(f'Order matters: {perm}') for s, c in cases: print(f'{combo_count(s, c, perm):7d} ways for {s:2d} total from coins {c}') print()
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) type minmult struct { min int mult float64 } var abbrevs = map[string]minmult{ "PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12}, "GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100}, } var metric = map[string]float64{ "K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15, "E": 1e18, "Z": 1e21, "Y": 1e24, "X": 1e27, "W": 1e30, "V": 1e33, "U": 1e36, } var binary = map[string]float64{ "Ki": b(10), "Mi": b(20), "Gi": b(30), "Ti": b(40), "Pi": b(50), "Ei": b(60), "Zi": b(70), "Yi": b(80), "Xi": b(90), "Wi": b(100), "Vi": b(110), "Ui": b(120), } func b(e float64) float64 { return math.Pow(2, e) } func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } return g } func fact(num string, d int) int { prod := 1 n, _ := strconv.Atoi(num) for i := n; i > 0; i -= d { prod *= i } return prod } func parse(number string) *big.Float { bf := new(big.Float).SetPrec(500) t1 := new(big.Float).SetPrec(500) t2 := new(big.Float).SetPrec(500) var i int for i = len(number) - 1; i >= 0; i-- { if '0' <= number[i] && number[i] <= '9' { break } } num := number[:i+1] num = strings.Replace(num, ",", "", -1) suf := strings.ToUpper(number[i+1:]) if suf == "" { bf.SetString(num) return bf } if suf[0] == '!' { prod := fact(num, len(suf)) bf.SetInt64(int64(prod)) return bf } for k, v := range abbrevs { kk := strings.ToUpper(k) if strings.HasPrefix(kk, suf) && len(suf) >= v.min { t1.SetString(num) if k != "GOOGOLs" { t2.SetFloat64(v.mult) } else { t2 = googol() } bf.Mul(t1, t2) return bf } } bf.SetString(num) for k, v := range metric { for j := 0; j < len(suf); j++ { if k == suf[j:j+1] { if j < len(suf)-1 && suf[j+1] == 'I' { t1.SetFloat64(binary[k+"i"]) bf.Mul(bf, t1) j++ } else { t1.SetFloat64(v) bf.Mul(bf, t1) } } } } return bf } func commatize(s string) string { if len(s) == 0 { return "" } neg := s[0] == '-' if neg { s = s[1:] } frac := "" if ix := strings.Index(s, "."); ix >= 0 { frac = s[ix:] s = s[:ix] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if !neg { return s + frac } return "-" + s + frac } func process(numbers []string) { fmt.Print("numbers = ") for _, number := range numbers { fmt.Printf("%s ", number) } fmt.Print("\nresults = ") for _, number := range numbers { res := parse(number) t := res.Text('g', 50) fmt.Printf("%s ", commatize(t)) } fmt.Println("\n") } func main() { numbers := []string{"2greatGRo", "24Gros", "288Doz", "1,728pairs", "172.8SCOre"} process(numbers) numbers = []string{"1,567", "+1.567k", "0.1567e-2m"} process(numbers) numbers = []string{"25.123kK", "25.123m", "2.5123e-00002G"} process(numbers) numbers = []string{"25.123kiKI", "25.123Mi", "2.5123e-00002Gi", "+.25123E-7Ei"} process(numbers) numbers = []string{"-.25123e-34Vikki", "2e-77gooGols"} process(numbers) numbers = []string{"9!", "9!!", "9!!!", "9!!!!", "9!!!!!", "9!!!!!!", "9!!!!!!!", "9!!!!!!!!", "9!!!!!!!!!"} process(numbers) }
from functools import reduce from operator import mul from decimal import * getcontext().prec = MAX_PREC def expand(num): suffixes = [ ('greatgross', 7, 12, 3), ('gross', 2, 12, 2), ('dozens', 3, 12, 1), ('pairs', 4, 2, 1), ('scores', 3, 20, 1), ('googols', 6, 10, 100), ('ki', 2, 2, 10), ('mi', 2, 2, 20), ('gi', 2, 2, 30), ('ti', 2, 2, 40), ('pi', 2, 2, 50), ('ei', 2, 2, 60), ('zi', 2, 2, 70), ('yi', 2, 2, 80), ('xi', 2, 2, 90), ('wi', 2, 2, 100), ('vi', 2, 2, 110), ('ui', 2, 2, 120), ('k', 1, 10, 3), ('m', 1, 10, 6), ('g', 1, 10, 9), ('t', 1, 10, 12), ('p', 1, 10, 15), ('e', 1, 10, 18), ('z', 1, 10, 21), ('y', 1, 10, 24), ('x', 1, 10, 27), ('w', 1, 10, 30) ] num = num.replace(',', '').strip().lower() if num[-1].isdigit(): return float(num) for i, char in enumerate(reversed(num)): if char.isdigit(): input_suffix = num[-i:] num = Decimal(num[:-i]) break if input_suffix[0] == '!': return reduce(mul, range(int(num), 0, -len(input_suffix))) while len(input_suffix) > 0: for suffix, min_abbrev, base, power in suffixes: if input_suffix[:min_abbrev] == suffix[:min_abbrev]: for i in range(min_abbrev, len(input_suffix) + 1): if input_suffix[:i+1] != suffix[:i+1]: num *= base ** power input_suffix = input_suffix[i:] break break return num test = "2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre\n\ 1,567 +1.567k 0.1567e-2m\n\ 25.123kK 25.123m 2.5123e-00002G\n\ 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei\n\ -.25123e-34Vikki 2e-77gooGols\n\ 9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!" for test_line in test.split("\n"): test_cases = test_line.split() print("Input:", ' '.join(test_cases)) print("Output:", ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) type minmult struct { min int mult float64 } var abbrevs = map[string]minmult{ "PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12}, "GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100}, } var metric = map[string]float64{ "K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15, "E": 1e18, "Z": 1e21, "Y": 1e24, "X": 1e27, "W": 1e30, "V": 1e33, "U": 1e36, } var binary = map[string]float64{ "Ki": b(10), "Mi": b(20), "Gi": b(30), "Ti": b(40), "Pi": b(50), "Ei": b(60), "Zi": b(70), "Yi": b(80), "Xi": b(90), "Wi": b(100), "Vi": b(110), "Ui": b(120), } func b(e float64) float64 { return math.Pow(2, e) } func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } return g } func fact(num string, d int) int { prod := 1 n, _ := strconv.Atoi(num) for i := n; i > 0; i -= d { prod *= i } return prod } func parse(number string) *big.Float { bf := new(big.Float).SetPrec(500) t1 := new(big.Float).SetPrec(500) t2 := new(big.Float).SetPrec(500) var i int for i = len(number) - 1; i >= 0; i-- { if '0' <= number[i] && number[i] <= '9' { break } } num := number[:i+1] num = strings.Replace(num, ",", "", -1) suf := strings.ToUpper(number[i+1:]) if suf == "" { bf.SetString(num) return bf } if suf[0] == '!' { prod := fact(num, len(suf)) bf.SetInt64(int64(prod)) return bf } for k, v := range abbrevs { kk := strings.ToUpper(k) if strings.HasPrefix(kk, suf) && len(suf) >= v.min { t1.SetString(num) if k != "GOOGOLs" { t2.SetFloat64(v.mult) } else { t2 = googol() } bf.Mul(t1, t2) return bf } } bf.SetString(num) for k, v := range metric { for j := 0; j < len(suf); j++ { if k == suf[j:j+1] { if j < len(suf)-1 && suf[j+1] == 'I' { t1.SetFloat64(binary[k+"i"]) bf.Mul(bf, t1) j++ } else { t1.SetFloat64(v) bf.Mul(bf, t1) } } } } return bf } func commatize(s string) string { if len(s) == 0 { return "" } neg := s[0] == '-' if neg { s = s[1:] } frac := "" if ix := strings.Index(s, "."); ix >= 0 { frac = s[ix:] s = s[:ix] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if !neg { return s + frac } return "-" + s + frac } func process(numbers []string) { fmt.Print("numbers = ") for _, number := range numbers { fmt.Printf("%s ", number) } fmt.Print("\nresults = ") for _, number := range numbers { res := parse(number) t := res.Text('g', 50) fmt.Printf("%s ", commatize(t)) } fmt.Println("\n") } func main() { numbers := []string{"2greatGRo", "24Gros", "288Doz", "1,728pairs", "172.8SCOre"} process(numbers) numbers = []string{"1,567", "+1.567k", "0.1567e-2m"} process(numbers) numbers = []string{"25.123kK", "25.123m", "2.5123e-00002G"} process(numbers) numbers = []string{"25.123kiKI", "25.123Mi", "2.5123e-00002Gi", "+.25123E-7Ei"} process(numbers) numbers = []string{"-.25123e-34Vikki", "2e-77gooGols"} process(numbers) numbers = []string{"9!", "9!!", "9!!!", "9!!!!", "9!!!!!", "9!!!!!!", "9!!!!!!!", "9!!!!!!!!", "9!!!!!!!!!"} process(numbers) }
from functools import reduce from operator import mul from decimal import * getcontext().prec = MAX_PREC def expand(num): suffixes = [ ('greatgross', 7, 12, 3), ('gross', 2, 12, 2), ('dozens', 3, 12, 1), ('pairs', 4, 2, 1), ('scores', 3, 20, 1), ('googols', 6, 10, 100), ('ki', 2, 2, 10), ('mi', 2, 2, 20), ('gi', 2, 2, 30), ('ti', 2, 2, 40), ('pi', 2, 2, 50), ('ei', 2, 2, 60), ('zi', 2, 2, 70), ('yi', 2, 2, 80), ('xi', 2, 2, 90), ('wi', 2, 2, 100), ('vi', 2, 2, 110), ('ui', 2, 2, 120), ('k', 1, 10, 3), ('m', 1, 10, 6), ('g', 1, 10, 9), ('t', 1, 10, 12), ('p', 1, 10, 15), ('e', 1, 10, 18), ('z', 1, 10, 21), ('y', 1, 10, 24), ('x', 1, 10, 27), ('w', 1, 10, 30) ] num = num.replace(',', '').strip().lower() if num[-1].isdigit(): return float(num) for i, char in enumerate(reversed(num)): if char.isdigit(): input_suffix = num[-i:] num = Decimal(num[:-i]) break if input_suffix[0] == '!': return reduce(mul, range(int(num), 0, -len(input_suffix))) while len(input_suffix) > 0: for suffix, min_abbrev, base, power in suffixes: if input_suffix[:min_abbrev] == suffix[:min_abbrev]: for i in range(min_abbrev, len(input_suffix) + 1): if input_suffix[:i+1] != suffix[:i+1]: num *= base ** power input_suffix = input_suffix[i:] break break return num test = "2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre\n\ 1,567 +1.567k 0.1567e-2m\n\ 25.123kK 25.123m 2.5123e-00002G\n\ 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei\n\ -.25123e-34Vikki 2e-77gooGols\n\ 9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!" for test_line in test.split("\n"): test_cases = test_line.split() print("Input:", ' '.join(test_cases)) print("Output:", ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func genFactBaseNums(size int, countOnly bool) ([][]int, int) { var results [][]int count := 0 for n := 0; ; n++ { radix := 2 var res []int = nil if !countOnly { res = make([]int, size) } k := n for k > 0 { div := k / radix rem := k % radix if !countOnly { if radix <= size+1 { res[size-radix+1] = rem } } k = div radix++ } if radix > size+2 { break } count++ if !countOnly { results = append(results, res) } } return results, count } func mapToPerms(factNums [][]int) [][]int { var perms [][]int psize := len(factNums[0]) + 1 start := make([]int, psize) for i := 0; i < psize; i++ { start[i] = i } for _, fn := range factNums { perm := make([]int, psize) copy(perm, start) for m := 0; m < len(fn); m++ { g := fn[m] if g == 0 { continue } first := m last := m + g for i := 1; i <= g; i++ { temp := perm[first] for j := first + 1; j <= last; j++ { perm[j-1] = perm[j] } perm[last] = temp } } perms = append(perms, perm) } return perms } func join(is []int, sep string) string { ss := make([]string, len(is)) for i := 0; i < len(is); i++ { ss[i] = strconv.Itoa(is[i]) } return strings.Join(ss, sep) } func undot(s string) []int { ss := strings.Split(s, ".") is := make([]int, len(ss)) for i := 0; i < len(ss); i++ { is[i], _ = strconv.Atoi(ss[i]) } return is } func main() { rand.Seed(time.Now().UnixNano()) factNums, _ := genFactBaseNums(3, false) perms := mapToPerms(factNums) for i, fn := range factNums { fmt.Printf("%v -> %v\n", join(fn, "."), join(perms[i], "")) } _, count := genFactBaseNums(10, true) fmt.Println("\nPermutations generated =", count) fmt.Println("compared to 11! which =", factorial(11)) fmt.Println() fbn51s := []string{ "39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0", "51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1", } factNums = [][]int{undot(fbn51s[0]), undot(fbn51s[1])} perms = mapToPerms(factNums) shoe := []rune("A♠K♠Q♠J♠T♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥T♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦T♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣T♣9♣8♣7♣6♣5♣4♣3♣2♣") cards := make([]string, 52) for i := 0; i < 52; i++ { cards[i] = string(shoe[2*i : 2*i+2]) if cards[i][0] == 'T' { cards[i] = "10" + cards[i][1:] } } for i, fbn51 := range fbn51s { fmt.Println(fbn51) for _, d := range perms[i] { fmt.Print(cards[d]) } fmt.Println("\n") } fbn51 := make([]int, 51) for i := 0; i < 51; i++ { fbn51[i] = rand.Intn(52 - i) } fmt.Println(join(fbn51, ".")) perms = mapToPerms([][]int{fbn51}) for _, d := range perms[0] { fmt.Print(cards[d]) } fmt.Println() }
import math def apply_perm(omega,fbn): for m in range(len(fbn)): g = fbn[m] if g > 0: new_first = omega[m+g] omega[m+1:m+g+1] = omega[m:m+g] omega[m] = new_first return omega def int_to_fbn(i): current = i divisor = 2 new_fbn = [] while current > 0: remainder = current % divisor current = current // divisor new_fbn.append(remainder) divisor += 1 return list(reversed(new_fbn)) def leading_zeros(l,n): if len(l) < n: return(([0] * (n - len(l))) + l) else: return l def get_fbn(n): max = math.factorial(n) for i in range(max): current = i divisor = 1 new_fbn = int_to_fbn(i) yield leading_zeros(new_fbn,n-1) def print_write(f, line): print(line) f.write(str(line)+'\n') def dot_format(l): if len(l) < 1: return "" dot_string = str(l[0]) for e in l[1:]: dot_string += "."+str(e) return dot_string def str_format(l): if len(l) < 1: return "" new_string = "" for e in l: new_string += str(e) return new_string with open("output.html", "w", encoding="utf-8") as f: f.write("<pre>\n") omega=[0,1,2,3] four_list = get_fbn(4) for l in four_list: print_write(f,dot_format(l)+' -> '+str_format(apply_perm(omega[:],l))) print_write(f," ") num_permutations = 0 for p in get_fbn(11): num_permutations += 1 if num_permutations % 1000000 == 0: print_write(f,"permutations so far = "+str(num_permutations)) print_write(f," ") print_write(f,"Permutations generated = "+str(num_permutations)) print_write(f,"compared to 11! which = "+str(math.factorial(11))) print_write(f," ") shoe = [] for suit in [u"\u2660",u"\u2665",u"\u2666",u"\u2663"]: for value in ['A','K','Q','J','10','9','8','7','6','5','4','3','2']: shoe.append(value+suit) print_write(f,str_format(shoe)) p1 = [39,49,7,47,29,30,2,12,10,3,29,37,33,17,12,31,29,34,17,25,2,4,25,4,1,14,20,6,21,18,1,1,1,4,0,5,15,12,4,3,10,10,9,1,6,5,5,3,0,0,0] p2 = [51,48,16,22,3,0,19,34,29,1,36,30,12,32,12,29,30,26,14,21,8,12,1,3,10,4,7,17,6,21,8,12,15,15,13,15,7,3,12,11,9,5,5,6,6,3,4,0,3,2,1] print_write(f," ") print_write(f,dot_format(p1)) print_write(f," ") print_write(f,str_format(apply_perm(shoe[:],p1))) print_write(f," ") print_write(f,dot_format(p2)) print_write(f," ") print_write(f,str_format(apply_perm(shoe[:],p2))) import random max = math.factorial(52) random_int = random.randint(0, max-1) myperm = leading_zeros(int_to_fbn(random_int),51) print(len(myperm)) print_write(f," ") print_write(f,dot_format(myperm)) print_write(f," ") print_write(f,str_format(apply_perm(shoe[:],myperm))) f.write("</pre>\n")
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "math" "math/cmplx" ) func dft(x []complex128) []complex128 { N := len(x) y := make([]complex128, N) for k := 0; k < N; k++ { for n := 0; n < N; n++ { t := -1i * 2 * complex(math.Pi*float64(k)*float64(n)/float64(N), 0) y[k] += x[n] * cmplx.Exp(t) } } return y } func idft(y []complex128) []float64 { N := len(y) x := make([]complex128, N) for n := 0; n < N; n++ { for k := 0; k < N; k++ { t := 1i * 2 * complex(math.Pi*float64(k)*float64(n)/float64(N), 0) x[n] += y[k] * cmplx.Exp(t) } x[n] /= complex(float64(N), 0) if math.Abs(imag(x[n])) < 1e-14 { x[n] = complex(real(x[n]), 0) } } z := make([]float64, N) for i, c := range x { z[i] = float64(real(c)) } return z } func main() { z := []float64{2, 3, 5, 7, 11} x := make([]complex128, len(z)) fmt.Println("Original sequence:", z) for i, n := range z { x[i] = complex(n, 0) } y := dft(x) fmt.Println("\nAfter applying the Discrete Fourier Transform:") fmt.Printf("%0.14g", y) fmt.Println("\n\nAfter applying the Inverse Discrete Fourier Transform to the above transform:") z = idft(y) fmt.Printf("%0.14g", z) fmt.Println() }
import cmath def dft( x ): N = len( x ) result = [] for k in range( N ): r = 0 for n in range( N ): t = -2j * cmath.pi * k * n / N r += x[n] * cmath.exp( t ) result.append( r ) return result def idft( y ): N = len( y ) result = [] for n in range( N ): r = 0 for k in range( N ): t = 2j * cmath.pi * k * n / N r += y[k] * cmath.exp( t ) r /= N+0j result.append( r ) return result if __name__ == "__main__": x = [ 2, 3, 5, 7, 11 ] print( "vals: " + ' '.join( f"{f:11.2f}" for f in x )) y = dft( x ) print( "DFT: " + ' '.join( f"{f:11.2f}" for f in y )) z = idft( y ) print( "inverse:" + ' '.join( f"{f:11.2f}" for f in z )) print( " - real:" + ' '.join( f"{f.real:11.2f}" for f in z )) N = 8 print( f"Complex signals, 1-4 cycles in {N} samples; energy into successive DFT bins" ) for rot in (0, 1, 2, 3, -4, -3, -2, -1): if rot > N/2: print( "Signal change frequency exceeds sample rate and will result in artifacts") sig = [ cmath.rect( 1, cmath.pi*2*rot/N*i ) for i in range( N ) ] print( f"{rot:2} cycle" + ' '.join( f"{f:11.2f}" for f in sig )) dft_sig = dft( sig ) print( f" DFT: " + ' '.join( f"{f:11.2f}" for f in dft_sig )) print( f" ABS: " + ' '.join( f"{abs(f):11.2f}" for f in dft_sig ))
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "sort" ) func firstMissingPositive(a []int) int { var b []int for _, e := range a { if e > 0 { b = append(b, e) } } sort.Ints(b) le := len(b) if le == 0 || b[0] > 1 { return 1 } for i := 1; i < le; i++ { if b[i]-b[i-1] > 1 { return b[i-1] + 1 } } return b[le-1] + 1 } func main() { fmt.Println("The first missing positive integers for the following arrays are:\n") aa := [][]int{ {1, 2, 0}, {3, 4, -1, 1}, {7, 8, 9, 11, 12}, {1, 2, 3, 4, 5}, {-6, -5, -2, -1}, {5, -5}, {-2}, {1}, {}} for _, a := range aa { fmt.Println(a, "->", firstMissingPositive(a)) } }
from itertools import count def firstGap(xs): return next(x for x in count(1) if x not in xs) def main(): print('\n'.join([ f'{repr(xs)} -> {firstGap(xs)}' for xs in [ [1, 2, 0], [3, 4, -1, 1], [7, 8, 9, 11, 12] ] ])) if __name__ == '__main__': main()
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" "regexp" "strings" ) var names = map[string]int64{ "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16, "seventeen": 17, "eighteen": 18, "nineteen": 19, "twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90, "hundred": 100, "thousand": 1000, "million": 1000000, "billion": 1000000000, "trillion": 1000000000000, "quadrillion": 1000000000000000, "quintillion": 1000000000000000000, } var seps = regexp.MustCompile(`,|-| and | `) var zeros = regexp.MustCompile(`^(zero|nought|nil|none|nothing)$`) func nameToNum(name string) (int64, error) { text := strings.ToLower(strings.TrimSpace(name)) isNegative := strings.HasPrefix(text, "minus ") if isNegative { text = text[6:] } if strings.HasPrefix(text, "a ") { text = "one" + text[1:] } words := seps.Split(text, -1) for i := len(words) - 1; i >= 0; i-- { if words[i] == "" { if i < len(words)-1 { copy(words[i:], words[i+1:]) } words = words[:len(words)-1] } } size := len(words) if size == 1 && zeros.MatchString(words[0]) { return 0, nil } var multiplier, lastNum, sum int64 = 1, 0, 0 for i := size - 1; i >= 0; i-- { num, ok := names[words[i]] if !ok { return 0, fmt.Errorf("'%s' is not a valid number", words[i]) } else { switch { case num == lastNum, num >= 1000 && lastNum >= 100: return 0, fmt.Errorf("'%s' is not a well formed numeric string", name) case num >= 1000: multiplier = num if i == 0 { sum += multiplier } case num >= 100: multiplier *= 100 if i == 0 { sum += multiplier } case num >= 20 && lastNum >= 10 && lastNum <= 90: return 0, fmt.Errorf("'%s' is not a well formed numeric string", name) case num >= 20: sum += num * multiplier case lastNum >= 1 && lastNum <= 90: return 0, fmt.Errorf("'%s' is not a well formed numeric string", name) default: sum += num * multiplier } } lastNum = num } if isNegative && sum == -sum { return math.MinInt64, nil } if sum < 0 { return 0, fmt.Errorf("'%s' is outside the range of an int64", name) } if isNegative { return -sum, nil } else { return sum, nil } } func main() { names := [...]string{ "none", "one", "twenty-five", "minus one hundred and seventeen", "hundred and fifty-six", "minus two thousand two", "nine thousand, seven hundred, one", "minus six hundred and twenty six thousand, eight hundred and fourteen", "four million, seven hundred thousand, three hundred and eighty-six", "fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four", "two hundred and one billion, twenty-one million, two thousand and one", "minus three hundred trillion, nine million, four hundred and one thousand and thirty-one", "seventeen quadrillion, one hundred thirty-seven", "a quintillion, eight trillion and five", "minus nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight", } for _, name := range names { num, err := nameToNum(name) if err != nil { fmt.Println(err) } else { fmt.Printf("%20d = %s\n", num, name) } } }
from spell_integer import spell_integer, SMALL, TENS, HUGE def int_from_words(num): words = num.replace(',','').replace(' and ', ' ').replace('-', ' ').split() if words[0] == 'minus': negmult = -1 words.pop(0) else: negmult = 1 small, total = 0, 0 for word in words: if word in SMALL: small += SMALL.index(word) elif word in TENS: small += TENS.index(word) * 10 elif word == 'hundred': small *= 100 elif word == 'thousand': total += small * 1000 small = 0 elif word in HUGE: total += small * 1000 ** HUGE.index(word) small = 0 else: raise ValueError("Don't understand %r part of %r" % (word, num)) return negmult * (total + small) if __name__ == '__main__': for n in range(-10000, 10000, 17): assert n == int_from_words(spell_integer(n)) for n in range(20): assert 13**n == int_from_words(spell_integer(13**n)) print('\n for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): txt = spell_integer(n) num = int_from_words(txt) print('%+4i <%s> %s' % (n, '==' if n == num else '??', txt)) print('') n = 201021002001 while n: txt = spell_integer(n) num = int_from_words(txt) print('%12i <%s> %s' % (n, '==' if n == num else '??', txt)) n //= -10 txt = spell_integer(n) num = int_from_words(txt) print('%12i <%s> %s' % (n, '==' if n == num else '??', txt)) print('')
Write the same code in Python as shown below in Go.
package main import ( "fmt" "math" "rcu" ) func magicConstant(n int) int { return (n*n + 1) * n / 2 } var ss = []string{ "\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079", } func superscript(n int) string { if n < 10 { return ss[n] } if n < 20 { return ss[1] + ss[n-10] } return ss[2] + ss[0] } func main() { fmt.Println("First 20 magic constants:") for n := 3; n <= 22; n++ { fmt.Printf("%5d ", magicConstant(n)) if (n-2)%10 == 0 { fmt.Println() } } fmt.Println("\n1,000th magic constant:", rcu.Commatize(magicConstant(1002))) fmt.Println("\nSmallest order magic square with a constant greater than:") for i := 1; i <= 20; i++ { goal := math.Pow(10, float64(i)) order := int(math.Cbrt(goal*2)) + 1 fmt.Printf("10%-2s : %9s\n", superscript(i), rcu.Commatize(order)) } }
def a(n): n += 2 return n*(n**2 + 1)/2 def inv_a(x): k = 0 while k*(k**2+1)/2+2 < x: k+=1 return k if __name__ == '__main__': print("The first 20 magic constants are:"); for n in range(1, 20): print(int(a(n)), end = " "); print("\nThe 1,000th magic constant is:",int(a(1000))); for e in range(1, 20): print(f'10^{e}: {inv_a(10**e)}');
Write the same code in Python as shown below in Go.
package main import "fmt" func main() { denoms := []int{200, 100, 50, 20, 10, 5, 2, 1} coins := 0 amount := 988 remaining := 988 fmt.Println("The minimum number of coins needed to make a value of", amount, "is as follows:") for _, denom := range denoms { n := remaining / denom if n > 0 { coins += n fmt.Printf(" %3d x %d\n", denom, n) remaining %= denom if remaining == 0 { break } } } fmt.Println("\nA total of", coins, "coins in all.") }
def makechange(denominations = [1,2,5,10,20,50,100,200], total = 988): print(f"Available denominations: {denominations}. Total is to be: {total}.") coins, remaining = sorted(denominations, reverse=True), total for n in range(len(coins)): coinsused, remaining = divmod(remaining, coins[n]) if coinsused > 0: print(" ", coinsused, "*", coins[n]) makechange()
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "rcu" "strings" ) func main() { limit := 100_000 primes := rcu.Primes(limit * 10) var results []int for _, p := range primes { if p < 1000 || p > 99999 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "123") { results = append(results, p) } } climit := rcu.Commatize(limit) fmt.Printf("Primes under %s which contain '123' when expressed in decimal:\n", climit) for i, p := range results { fmt.Printf("%7s ", rcu.Commatize(p)) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\n\nFound", len(results), "such primes under", climit, "\b.") limit = 1_000_000 climit = rcu.Commatize(limit) count := len(results) for _, p := range primes { if p < 100_000 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "123") { count++ } } fmt.Println("\nFound", count, "such primes under", climit, "\b.") }
def prime(limite, mostrar): global columna columna = 0 for n in range(limite): strn = str(n) if isPrime(n) and ('123' in str(n)): columna += 1 if mostrar == True: print(n, end=" "); if columna % 8 == 0: print('') return columna if __name__ == "__main__": print("Números primos que contienen 123:") limite = 100000 prime(limite, True) print("\n\nEncontrados ", columna, " números primos por debajo de", limite) limite = 1000000 prime(limite, False) print("\n\nEncontrados ", columna, " números primos por debajo de", limite)
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "rcu" "strings" ) func main() { limit := 100_000 primes := rcu.Primes(limit * 10) var results []int for _, p := range primes { if p < 1000 || p > 99999 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "123") { results = append(results, p) } } climit := rcu.Commatize(limit) fmt.Printf("Primes under %s which contain '123' when expressed in decimal:\n", climit) for i, p := range results { fmt.Printf("%7s ", rcu.Commatize(p)) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\n\nFound", len(results), "such primes under", climit, "\b.") limit = 1_000_000 climit = rcu.Commatize(limit) count := len(results) for _, p := range primes { if p < 100_000 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "123") { count++ } } fmt.Println("\nFound", count, "such primes under", climit, "\b.") }
def prime(limite, mostrar): global columna columna = 0 for n in range(limite): strn = str(n) if isPrime(n) and ('123' in str(n)): columna += 1 if mostrar == True: print(n, end=" "); if columna % 8 == 0: print('') return columna if __name__ == "__main__": print("Números primos que contienen 123:") limite = 100000 prime(limite, True) print("\n\nEncontrados ", columna, " números primos por debajo de", limite) limite = 1000000 prime(limite, False) print("\n\nEncontrados ", columna, " números primos por debajo de", limite)
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "os" "sort" ) func main() { if len(os.Args) != 2 { fmt.Println("usage ff <go source filename>") return } src, err := ioutil.ReadFile(os.Args[1]) if err != nil { fmt.Println(err) return } fs := token.NewFileSet() a, err := parser.ParseFile(fs, os.Args[1], src, 0) if err != nil { fmt.Println(err) return } f := fs.File(a.Pos()) m := make(map[string]int) ast.Inspect(a, func(n ast.Node) bool { if ce, ok := n.(*ast.CallExpr); ok { start := f.Offset(ce.Pos()) end := f.Offset(ce.Lparen) m[string(src[start:end])]++ } return true }) cs := make(calls, 0, len(m)) for k, v := range m { cs = append(cs, &call{k, v}) } sort.Sort(cs) for i, c := range cs { fmt.Printf("%-20s %4d\n", c.expr, c.count) if i == 9 { break } } } type call struct { expr string count int } type calls []*call func (c calls) Len() int { return len(c) } func (c calls) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c calls) Less(i, j int) bool { return c[i].count > c[j].count }
import ast class CallCountingVisitor(ast.NodeVisitor): def __init__(self): self.calls = {} def visit_Call(self, node): if isinstance(node.func, ast.Name): fun_name = node.func.id call_count = self.calls.get(fun_name, 0) self.calls[fun_name] = call_count + 1 self.generic_visit(node) filename = input('Enter a filename to parse: ') with open(filename, encoding='utf-8') as f: contents = f.read() root = ast.parse(contents, filename=filename) visitor = CallCountingVisitor() visitor.visit(root) top10 = sorted(visitor.calls.items(), key=lambda x: x[1], reverse=True)[:10] for name, count in top10: print(name,'called',count,'times')
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "log" "math" "math/rand" "time" ) var minDelta = 1.0 func getMaxPrice(prices []float64) float64 { max := prices[0] for i := 1; i < len(prices); i++ { if prices[i] > max { max = prices[i] } } return max } func getPRangeCount(prices []float64, min, max float64) int { count := 0 for _, price := range prices { if price >= min && price <= max { count++ } } return count } func get5000(prices []float64, min, max float64, n int) (float64, int) { count := getPRangeCount(prices, min, max) delta := (max - min) / 2 for count != n && delta >= minDelta/2 { if count > n { max -= delta } else { max += delta } max = math.Floor(max) count = getPRangeCount(prices, min, max) delta /= 2 } return max, count } func getAll5000(prices []float64, min, max float64, n int) [][3]float64 { pmax, pcount := get5000(prices, min, max, n) res := [][3]float64{{min, pmax, float64(pcount)}} for pmax < max { pmin := pmax + 1 pmax, pcount = get5000(prices, pmin, max, n) if pcount == 0 { log.Fatal("Price list from", pmin, "has too many with same price.") } res = append(res, [3]float64{pmin, pmax, float64(pcount)}) } return res } func main() { rand.Seed(time.Now().UnixNano()) numPrices := 99000 + rand.Intn(2001) maxPrice := 1e5 prices := make([]float64, numPrices) for i := 0; i < numPrices; i++ { prices[i] = float64(rand.Intn(int(maxPrice) + 1)) } actualMax := getMaxPrice(prices) fmt.Println("Using", numPrices, "items with prices from 0 to", actualMax, "\b:") res := getAll5000(prices, 0, actualMax, 5000) fmt.Println("Split into", len(res), "bins of approx 5000 elements:") total := 0 for _, r := range res { min := int(r[0]) tmx := r[1] if tmx > actualMax { tmx = actualMax } max := int(tmx) cnt := int(r[2]) total += cnt fmt.Printf(" From %6d to %6d with %4d items\n", min, max, cnt) } if total != numPrices { fmt.Println("Something went wrong - grand total of", total, "doesn't equal", numPrices, "\b!") } }
import random price_list_size = random.choice(range(99_000, 101_000)) price_list = random.choices(range(100_000), k=price_list_size) delta_price = 1 def get_prange_count(startp, endp): return len([r for r in price_list if startp <= r <= endp]) def get_max_price(): return max(price_list) def get_5k(mn=0, mx=get_max_price(), num=5_000): "Binary search for num items between mn and mx, adjusting mx" count = get_prange_count(mn, mx) delta_mx = (mx - mn) / 2 while count != num and delta_mx >= delta_price / 2: mx += -delta_mx if count > num else +delta_mx mx = mx // 1 count, delta_mx = get_prange_count(mn, mx), delta_mx / 2 return mx, count def get_all_5k(mn=0, mx=get_max_price(), num=5_000): "Get all non-overlapping ranges" partmax, partcount = get_5k(mn, mx, num) result = [(mn, partmax, partcount)] while partmax < mx: partmin = partmax + delta_price partmax, partcount = get_5k(partmin, mx, num) assert partcount > 0, \ f"price_list from {partmin} with too many of the same price" result.append((partmin, partmax, partcount)) return result if __name__ == '__main__': print(f"Using {price_list_size} random prices from 0 to {get_max_price()}") result = get_all_5k() print(f"Splits into {len(result)} bins of approx 5000 elements") for mn, mx, count in result: print(f" From {mn:8.1f} ... {mx:8.1f} with {count} items.") if len(price_list) != sum(count for mn, mx, count in result): print("\nWhoops! Some items missing:")
Write a version of this Go function in Python with identical behavior.
package main import ( "fmt" big "github.com/ncw/gmp" ) func cullen(n uint) *big.Int { one := big.NewInt(1) bn := big.NewInt(int64(n)) res := new(big.Int).Lsh(one, n) res.Mul(res, bn) return res.Add(res, one) } func woodall(n uint) *big.Int { res := cullen(n) return res.Sub(res, big.NewInt(2)) } func main() { fmt.Println("First 20 Cullen numbers (n * 2^n + 1):") for n := uint(1); n <= 20; n++ { fmt.Printf("%d ", cullen(n)) } fmt.Println("\n\nFirst 20 Woodall numbers (n * 2^n - 1):") for n := uint(1); n <= 20; n++ { fmt.Printf("%d ", woodall(n)) } fmt.Println("\n\nFirst 5 Cullen primes (in terms of n):") count := 0 for n := uint(1); count < 5; n++ { cn := cullen(n) if cn.ProbablyPrime(15) { fmt.Printf("%d ", n) count++ } } fmt.Println("\n\nFirst 12 Woodall primes (in terms of n):") count = 0 for n := uint(1); count < 12; n++ { cn := woodall(n) if cn.ProbablyPrime(15) { fmt.Printf("%d ", n) count++ } } fmt.Println() }
print("working...") print("First 20 Cullen numbers:") for n in range(1,21): num = n*pow(2,n)+1 print(str(num),end= " ") print() print("First 20 Woodall numbers:") for n in range(1,21): num = n*pow(2,n)-1 print(str(num),end=" ") print() print("done...")
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "rcu" "strconv" "strings" ) func findFirst(list []int) (int, int) { for i, n := range list { if n > 1e7 { return n, i } } return -1, -1 } func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } return string(chars) } func main() { ranges := [][2]int{ {0, 0}, {101, 909}, {11011, 99099}, {1110111, 9990999}, {111101111, 119101111}, } var cyclops []int for _, r := range ranges { numDigits := len(fmt.Sprint(r[0])) center := numDigits / 2 for i := r[0]; i <= r[1]; i++ { digits := rcu.Digits(i, 10) if digits[center] == 0 { count := 0 for _, d := range digits { if d == 0 { count++ } } if count == 1 { cyclops = append(cyclops, i) } } } } fmt.Println("The first 50 cyclops numbers are:") for i, n := range cyclops[0:50] { fmt.Printf("%6s ", rcu.Commatize(n)) if (i+1)%10 == 0 { fmt.Println() } } n, i := findFirst(cyclops) ns, is := rcu.Commatize(n), rcu.Commatize(i) fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is) var primes []int for _, n := range cyclops { if rcu.IsPrime(n) { primes = append(primes, n) } } fmt.Println("\n\nThe first 50 prime cyclops numbers are:") for i, n := range primes[0:50] { fmt.Printf("%6s ", rcu.Commatize(n)) if (i+1)%10 == 0 { fmt.Println() } } n, i = findFirst(primes) ns, is = rcu.Commatize(n), rcu.Commatize(i) fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is) var bpcyclops []int var ppcyclops []int for _, p := range primes { ps := fmt.Sprint(p) split := strings.Split(ps, "0") noMiddle, _ := strconv.Atoi(split[0] + split[1]) if rcu.IsPrime(noMiddle) { bpcyclops = append(bpcyclops, p) } if ps == reverse(ps) { ppcyclops = append(ppcyclops, p) } } fmt.Println("\n\nThe first 50 blind prime cyclops numbers are:") for i, n := range bpcyclops[0:50] { fmt.Printf("%6s ", rcu.Commatize(n)) if (i+1)%10 == 0 { fmt.Println() } } n, i = findFirst(bpcyclops) ns, is = rcu.Commatize(n), rcu.Commatize(i) fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is) fmt.Println("\n\nThe first 50 palindromic prime cyclops numbers are:\n") for i, n := range ppcyclops[0:50] { fmt.Printf("%9s ", rcu.Commatize(n)) if (i+1)%8 == 0 { fmt.Println() } } n, i = findFirst(ppcyclops) ns, is = rcu.Commatize(n), rcu.Commatize(i) fmt.Printf("\n\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is) }
from sympy import isprime def print50(a, width=8): for i, n in enumerate(a): print(f'{n: {width},}', end='\n' if (i + 1) % 10 == 0 else '') def generate_cyclops(maxdig=9): yield 0 for d in range((maxdig + 1) // 2): arr = [str(i) for i in range(10**d, 10**(d+1)) if not('0' in str(i))] for left in arr: for right in arr: yield int(left + '0' + right) def generate_prime_cyclops(): for c in generate_cyclops(): if isprime(c): yield c def generate_blind_prime_cyclops(): for c in generate_prime_cyclops(): cstr = str(c) mid = len(cstr) // 2 if isprime(int(cstr[:mid] + cstr[mid+1:])): yield c def generate_palindromic_cyclops(maxdig=9): for d in range((maxdig + 1) // 2): arr = [str(i) for i in range(10**d, 10**(d+1)) if not('0' in str(i))] for s in arr: yield int(s + '0' + s[::-1]) def generate_palindromic_prime_cyclops(): for c in generate_palindromic_cyclops(): if isprime(c): yield c print('The first 50 cyclops numbers are:') gen = generate_cyclops() print50([next(gen) for _ in range(50)]) for i, c in enumerate(generate_cyclops()): if c > 10000000: print( f'\nThe next cyclops number after 10,000,000 is {c} at position {i:,}.') break print('\nThe first 50 prime cyclops numbers are:') gen = generate_prime_cyclops() print50([next(gen) for _ in range(50)]) for i, c in enumerate(generate_prime_cyclops()): if c > 10000000: print( f'\nThe next prime cyclops number after 10,000,000 is {c} at position {i:,}.') break print('\nThe first 50 blind prime cyclops numbers are:') gen = generate_blind_prime_cyclops() print50([next(gen) for _ in range(50)]) for i, c in enumerate(generate_blind_prime_cyclops()): if c > 10000000: print( f'\nThe next blind prime cyclops number after 10,000,000 is {c} at position {i:,}.') break print('\nThe first 50 palindromic prime cyclops numbers are:') gen = generate_palindromic_prime_cyclops() print50([next(gen) for _ in range(50)], 11) for i, c in enumerate(generate_palindromic_prime_cyclops()): if c > 10000000: print( f'\nThe next palindromic prime cyclops number after 10,000,000 is {c} at position {i}.') break
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "rcu" ) func main() { c := rcu.PrimeSieve(5505, false) var triples [][3]int fmt.Println("Prime triplets: p, p + 2, p + 6 where p < 5,500:") for i := 3; i < 5500; i += 2 { if !c[i] && !c[i+2] && !c[i+6] { triples = append(triples, [3]int{i, i + 2, i + 6}) } } for _, triple := range triples { var t [3]string for i := 0; i < 3; i++ { t[i] = rcu.Commatize(triple[i]) } fmt.Printf("%5s %5s %5s\n", t[0], t[1], t[2]) } fmt.Println("\nFound", len(triples), "such prime triplets.") }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 5499, 2): if not isPrime(p+6): continue if not isPrime(p+2): continue if not isPrime(p): continue print(f'[{p} {p+2} {p+6}]')
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "rcu" ) func main() { c := rcu.PrimeSieve(5505, false) var triples [][3]int fmt.Println("Prime triplets: p, p + 2, p + 6 where p < 5,500:") for i := 3; i < 5500; i += 2 { if !c[i] && !c[i+2] && !c[i+6] { triples = append(triples, [3]int{i, i + 2, i + 6}) } } for _, triple := range triples { var t [3]string for i := 0; i < 3; i++ { t[i] = rcu.Commatize(triple[i]) } fmt.Printf("%5s %5s %5s\n", t[0], t[1], t[2]) } fmt.Println("\nFound", len(triples), "such prime triplets.") }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 5499, 2): if not isPrime(p+6): continue if not isPrime(p+2): continue if not isPrime(p): continue print(f'[{p} {p+2} {p+6}]')
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "fmt" "log" "strings" ) var glyphs = []rune("♜♞♝♛♚♖♘♗♕♔") var names = map[rune]string{'R': "rook", 'N': "knight", 'B': "bishop", 'Q': "queen", 'K': "king"} var g2lMap = map[rune]string{ '♜': "R", '♞': "N", '♝': "B", '♛': "Q", '♚': "K", '♖': "R", '♘': "N", '♗': "B", '♕': "Q", '♔': "K", } var ntable = map[string]int{"01": 0, "02": 1, "03": 2, "04": 3, "12": 4, "13": 5, "14": 6, "23": 7, "24": 8, "34": 9} func g2l(pieces string) string { lets := "" for _, p := range pieces { lets += g2lMap[p] } return lets } func spid(pieces string) int { pieces = g2l(pieces) if len(pieces) != 8 { log.Fatal("There must be exactly 8 pieces.") } for _, one := range "KQ" { count := 0 for _, p := range pieces { if p == one { count++ } } if count != 1 { log.Fatalf("There must be one %s.", names[one]) } } for _, two := range "RNB" { count := 0 for _, p := range pieces { if p == two { count++ } } if count != 2 { log.Fatalf("There must be two %s.", names[two]) } } r1 := strings.Index(pieces, "R") r2 := strings.Index(pieces[r1+1:], "R") + r1 + 1 k := strings.Index(pieces, "K") if k < r1 || k > r2 { log.Fatal("The king must be between the rooks.") } b1 := strings.Index(pieces, "B") b2 := strings.Index(pieces[b1+1:], "B") + b1 + 1 if (b2-b1)%2 == 0 { log.Fatal("The bishops must be on opposite color squares.") } piecesN := strings.ReplaceAll(pieces, "Q", "") piecesN = strings.ReplaceAll(piecesN, "B", "") n1 := strings.Index(piecesN, "N") n2 := strings.Index(piecesN[n1+1:], "N") + n1 + 1 np := fmt.Sprintf("%d%d", n1, n2) N := ntable[np] piecesQ := strings.ReplaceAll(pieces, "B", "") Q := strings.Index(piecesQ, "Q") D := strings.Index("0246", fmt.Sprintf("%d", b1)) L := strings.Index("1357", fmt.Sprintf("%d", b2)) if D == -1 { D = strings.Index("0246", fmt.Sprintf("%d", b2)) L = strings.Index("1357", fmt.Sprintf("%d", b1)) } return 96*N + 16*Q + 4*D + L } func main() { for _, pieces := range []string{"♕♘♖♗♗♘♔♖", "♖♘♗♕♔♗♘♖", "♖♕♘♗♗♔♖♘", "♖♘♕♗♗♔♖♘"} { fmt.Printf("%s or %s has SP-ID of %d\n", pieces, g2l(pieces), spid(pieces)) } }
def validate_position(candidate: str): assert ( len(candidate) == 8 ), f"candidate position has invalide len = {len(candidate)}" valid_pieces = {"R": 2, "N": 2, "B": 2, "Q": 1, "K": 1} assert { piece for piece in candidate } == valid_pieces.keys(), f"candidate position contains invalid pieces" for piece_type in valid_pieces.keys(): assert ( candidate.count(piece_type) == valid_pieces[piece_type] ), f"piece type '{piece_type}' has invalid count" bishops_pos = [index for index, value in enumerate(candidate) if value == "B"] assert ( bishops_pos[0] % 2 != bishops_pos[1] % 2 ), f"candidate position has both bishops in the same color" assert [piece for piece in candidate if piece in "RK"] == [ "R", "K", "R", ], "candidate position has K outside of RR" def calc_position(start_pos: str): try: validate_position(start_pos) except AssertionError: raise AssertionError subset_step1 = [piece for piece in start_pos if piece not in "QB"] nights_positions = [ index for index, value in enumerate(subset_step1) if value == "N" ] nights_table = { (0, 1): 0, (0, 2): 1, (0, 3): 2, (0, 4): 3, (1, 2): 4, (1, 3): 5, (1, 4): 6, (2, 3): 7, (2, 4): 8, (3, 4): 9, } N = nights_table.get(tuple(nights_positions)) subset_step2 = [piece for piece in start_pos if piece != "B"] Q = subset_step2.index("Q") dark_squares = [ piece for index, piece in enumerate(start_pos) if index in range(0, 9, 2) ] light_squares = [ piece for index, piece in enumerate(start_pos) if index in range(1, 9, 2) ] D = dark_squares.index("B") L = light_squares.index("B") return 4 * (4 * (6*N + Q) + D) + L if __name__ == '__main__': for example in ["QNRBBNKR", "RNBQKBNR", "RQNBBKRN", "RNQBBKRN"]: print(f'Position: {example}; Chess960 PID= {calc_position(example)}')
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "log" ) var endings = [][]string{ {"o", "as", "at", "amus", "atis", "ant"}, {"eo", "es", "et", "emus", "etis", "ent"}, {"o", "is", "it", "imus", "itis", "unt"}, {"io", "is", "it", "imus", "itis", "iunt"}, } var infinEndings = []string{"are", "ēre", "ere", "ire"} var pronouns = []string{"I", "you (singular)", "he, she or it", "we", "you (plural)", "they"} var englishEndings = []string{"", "", "s", "", "", ""} func conjugate(infinitive, english string) { letters := []rune(infinitive) le := len(letters) if le < 4 { log.Fatal("Infinitive is too short for a regular verb.") } infinEnding := string(letters[le-3:]) conj := -1 for i, s := range infinEndings { if s == infinEnding { conj = i break } } if conj == -1 { log.Fatalf("Infinitive ending -%s not recognized.", infinEnding) } stem := string(letters[:le-3]) fmt.Printf("Present indicative tense, active voice, of '%s' to '%s':\n", infinitive, english) for i, ending := range endings[conj] { fmt.Printf(" %s%-4s %s %s%s\n", stem, ending, pronouns[i], english, englishEndings[i]) } fmt.Println() } func main() { pairs := [][2]string{{"amare", "love"}, {"vidēre", "see"}, {"ducere", "lead"}, {"audire", "hear"}} for _, pair := range pairs { conjugate(pair[0], pair[1]) } }
def conjugate(infinitive): if not infinitive[-3:] == "are": print("'", infinitive, "' non prima coniugatio verbi.\n", sep='') return False stem = infinitive[0:-3] if len(stem) == 0: print("\'", infinitive, "\' non satis diu conjugatus\n", sep='') return False print("Praesens indicativi temporis of '", infinitive, "':", sep='') for ending in ("o", "as", "at", "amus", "atis", "ant"): print(" ", stem, ending, sep='') print() if __name__ == '__main__': for infinitive in ("amare", "dare", "qwerty", "are"): conjugate(infinitive)
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "log" ) var endings = [][]string{ {"o", "as", "at", "amus", "atis", "ant"}, {"eo", "es", "et", "emus", "etis", "ent"}, {"o", "is", "it", "imus", "itis", "unt"}, {"io", "is", "it", "imus", "itis", "iunt"}, } var infinEndings = []string{"are", "ēre", "ere", "ire"} var pronouns = []string{"I", "you (singular)", "he, she or it", "we", "you (plural)", "they"} var englishEndings = []string{"", "", "s", "", "", ""} func conjugate(infinitive, english string) { letters := []rune(infinitive) le := len(letters) if le < 4 { log.Fatal("Infinitive is too short for a regular verb.") } infinEnding := string(letters[le-3:]) conj := -1 for i, s := range infinEndings { if s == infinEnding { conj = i break } } if conj == -1 { log.Fatalf("Infinitive ending -%s not recognized.", infinEnding) } stem := string(letters[:le-3]) fmt.Printf("Present indicative tense, active voice, of '%s' to '%s':\n", infinitive, english) for i, ending := range endings[conj] { fmt.Printf(" %s%-4s %s %s%s\n", stem, ending, pronouns[i], english, englishEndings[i]) } fmt.Println() } func main() { pairs := [][2]string{{"amare", "love"}, {"vidēre", "see"}, {"ducere", "lead"}, {"audire", "hear"}} for _, pair := range pairs { conjugate(pair[0], pair[1]) } }
def conjugate(infinitive): if not infinitive[-3:] == "are": print("'", infinitive, "' non prima coniugatio verbi.\n", sep='') return False stem = infinitive[0:-3] if len(stem) == 0: print("\'", infinitive, "\' non satis diu conjugatus\n", sep='') return False print("Praesens indicativi temporis of '", infinitive, "':", sep='') for ending in ("o", "as", "at", "amus", "atis", "ant"): print(" ", stem, ending, sep='') print() if __name__ == '__main__': for infinitive in ("amare", "dare", "qwerty", "are"): conjugate(infinitive)
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "math/big" "rcu" "sort" ) func main() { primes := rcu.Primes(379) primorial := big.NewInt(1) var fortunates []int bPrime := new(big.Int) for _, prime := range primes { bPrime.SetUint64(uint64(prime)) primorial.Mul(primorial, bPrime) for j := 3; ; j += 2 { jj := big.NewInt(int64(j)) bPrime.Add(primorial, jj) if bPrime.ProbablyPrime(5) { fortunates = append(fortunates, j) break } } } m := make(map[int]bool) for _, f := range fortunates { m[f] = true } fortunates = fortunates[:0] for k := range m { fortunates = append(fortunates, k) } sort.Ints(fortunates) fmt.Println("After sorting, the first 50 distinct fortunate numbers are:") for i, f := range fortunates[0:50] { fmt.Printf("%3d ", f) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() }
from sympy.ntheory.generate import primorial from sympy.ntheory import isprime def fortunate_number(n): i = 3 primorial_ = primorial(n) while True: if isprime(primorial_ + i): return i i += 2 fortunate_numbers = set() for i in range(1, 76): fortunate_numbers.add(fortunate_number(i)) first50 = sorted(list(fortunate_numbers))[:50] print('The first 50 fortunate numbers:') print(('{:<3} ' * 10).format(*(first50[:10]))) print(('{:<3} ' * 10).format(*(first50[10:20]))) print(('{:<3} ' * 10).format(*(first50[20:30]))) print(('{:<3} ' * 10).format(*(first50[30:40]))) print(('{:<3} ' * 10).format(*(first50[40:])))
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "math" "sort" "strings" ) func sortedOutline(originalOutline []string, ascending bool) { outline := make([]string, len(originalOutline)) copy(outline, originalOutline) indent := "" del := "\x7f" sep := "\x00" var messages []string if strings.TrimLeft(outline[0], " \t") != outline[0] { fmt.Println(" outline structure is unclear") return } for i := 1; i < len(outline); i++ { line := outline[i] lc := len(line) if strings.HasPrefix(line, " ") || strings.HasPrefix(line, " \t") || line[0] == '\t' { lc2 := len(strings.TrimLeft(line, " \t")) currIndent := line[0 : lc-lc2] if indent == "" { indent = currIndent } else { correctionNeeded := false if (strings.ContainsRune(currIndent, '\t') && !strings.ContainsRune(indent, '\t')) || (!strings.ContainsRune(currIndent, '\t') && strings.ContainsRune(indent, '\t')) { m := fmt.Sprintf("corrected inconsistent whitespace use at line %q", line) messages = append(messages, indent+m) correctionNeeded = true } else if len(currIndent)%len(indent) != 0 { m := fmt.Sprintf("corrected inconsistent indent width at line %q", line) messages = append(messages, indent+m) correctionNeeded = true } if correctionNeeded { mult := int(math.Round(float64(len(currIndent)) / float64(len(indent)))) outline[i] = strings.Repeat(indent, mult) + line[lc-lc2:] } } } } levels := make([]int, len(outline)) levels[0] = 1 margin := "" for level := 1; ; level++ { allPos := true for i := 1; i < len(levels); i++ { if levels[i] == 0 { allPos = false break } } if allPos { break } mc := len(margin) for i := 1; i < len(outline); i++ { if levels[i] == 0 { line := outline[i] if strings.HasPrefix(line, margin) && line[mc] != ' ' && line[mc] != '\t' { levels[i] = level } } } margin += indent } lines := make([]string, len(outline)) lines[0] = outline[0] var nodes []string for i := 1; i < len(outline); i++ { if levels[i] > levels[i-1] { if len(nodes) == 0 { nodes = append(nodes, outline[i-1]) } else { nodes = append(nodes, sep+outline[i-1]) } } else if levels[i] < levels[i-1] { j := levels[i-1] - levels[i] nodes = nodes[0 : len(nodes)-j] } if len(nodes) > 0 { lines[i] = strings.Join(nodes, "") + sep + outline[i] } else { lines[i] = outline[i] } } if ascending { sort.Strings(lines) } else { maxLen := len(lines[0]) for i := 1; i < len(lines); i++ { if len(lines[i]) > maxLen { maxLen = len(lines[i]) } } for i := 0; i < len(lines); i++ { lines[i] = lines[i] + strings.Repeat(del, maxLen-len(lines[i])) } sort.Sort(sort.Reverse(sort.StringSlice(lines))) } for i := 0; i < len(lines); i++ { s := strings.Split(lines[i], sep) lines[i] = s[len(s)-1] if !ascending { lines[i] = strings.TrimRight(lines[i], del) } } if len(messages) > 0 { fmt.Println(strings.Join(messages, "\n")) fmt.Println() } fmt.Println(strings.Join(lines, "\n")) } func main() { outline := []string{ "zeta", " beta", " gamma", " lambda", " kappa", " mu", " delta", "alpha", " theta", " iota", " epsilon", } outline2 := make([]string, len(outline)) for i := 0; i < len(outline); i++ { outline2[i] = strings.ReplaceAll(outline[i], " ", "\t") } outline3 := []string{ "alpha", " epsilon", " iota", " theta", "zeta", " beta", " delta", " gamma", " \t kappa", " lambda", " mu", } outline4 := []string{ "zeta", " beta", " gamma", " lambda", " kappa", " mu", " delta", "alpha", " theta", " iota", " epsilon", } fmt.Println("Four space indented outline, ascending sort:") sortedOutline(outline, true) fmt.Println("\nFour space indented outline, descending sort:") sortedOutline(outline, false) fmt.Println("\nTab indented outline, ascending sort:") sortedOutline(outline2, true) fmt.Println("\nTab indented outline, descending sort:") sortedOutline(outline2, false) fmt.Println("\nFirst unspecified outline, ascending sort:") sortedOutline(outline3, true) fmt.Println("\nFirst unspecified outline, descending sort:") sortedOutline(outline3, false) fmt.Println("\nSecond unspecified outline, ascending sort:") sortedOutline(outline4, true) fmt.Println("\nSecond unspecified outline, descending sort:") sortedOutline(outline4, false) }
from itertools import chain, product, takewhile, tee from functools import cmp_to_key, reduce def sortedOutline(cmp): def go(outlineText): indentTuples = indentTextPairs( outlineText.splitlines() ) return bindLR( minimumIndent(enumerate(indentTuples)) )(lambda unitIndent: Right( outlineFromForest( unitIndent, nest(foldTree( lambda x: lambda xs: Node(x)( sorted(xs, key=cmp_to_key(cmp)) ) )(Node('')( forestFromIndentLevels( indentLevelsFromLines( unitIndent )(indentTuples) ) ))) ) )) return go def main(): ascending = comparing(root) descending = flip(ascending) spacedOutline = tabbedOutline = confusedOutline = raggedOutline = def displaySort(kcmp): k, cmp = kcmp return [ tested(cmp, k, label)( outline ) for (label, outline) in [ ('4-space indented', spacedOutline), ('tab indented', tabbedOutline), ('Unknown 1', confusedOutline), ('Unknown 2', raggedOutline) ] ] def tested(cmp, cmpName, outlineName): def go(outline): print('\n' + outlineName, cmpName + ':') either(print)(print)( sortedOutline(cmp)(outline) ) return go ap([ displaySort ])([ ("(A -> Z)", ascending), ("(Z -> A)", descending) ]) def forestFromIndentLevels(tuples): def go(xs): if xs: intIndent, v = xs[0] firstTreeLines, rest = span( lambda x: intIndent < x[0] )(xs[1:]) return [Node(v)(go(firstTreeLines))] + go(rest) else: return [] return go(tuples) def indentLevelsFromLines(indentUnit): def go(xs): w = len(indentUnit) return [ (len(x[0]) // w, x[1]) for x in xs ] return go def indentTextPairs(xs): def indentAndText(s): pfx = list(takewhile(lambda c: c.isspace(), s)) return (pfx, s[len(pfx):]) return [indentAndText(x) for x in xs] def outlineFromForest(tabString, forest): def go(indent): def serial(node): return [indent + root(node)] + list( concatMap( go(tabString + indent) )(nest(node)) ) return serial return '\n'.join( concatMap(go(''))(forest) ) def minimumIndent(indexedPrefixes): (xs, ts) = tee(indexedPrefixes) (ys, zs) = tee(ts) def mindentLR(charSet): if list(charSet): def w(x): return len(x[1][0]) unit = min(filter(w, ys), key=w)[1][0] unitWidth = len(unit) def widthCheck(a, ix): wx = len(ix[1][0]) return a if (a or 0 == wx) else ( ix[0] if 0 != wx % unitWidth else a ) oddLine = reduce(widthCheck, zs, None) return Left( 'Inconsistent indentation width at line ' + ( str(1 + oddLine) ) ) if oddLine else Right(''.join(unit)) else: return Right('') def tabSpaceCheck(a, ics): charSet = a[0].union(set(ics[1][0])) return a if a[1] else ( charSet, ics[0] if 1 < len(charSet) else None ) indentCharSet, mbAnomalyLine = reduce( tabSpaceCheck, xs, (set([]), None) ) return bindLR( Left( 'Mixed indent characters found in line ' + str( 1 + mbAnomalyLine ) ) if mbAnomalyLine else Right(list(indentCharSet)) )(mindentLR) def Left(x): return {'type': 'Either', 'Right': None, 'Left': x} def Right(x): return {'type': 'Either', 'Left': None, 'Right': x} def Node(v): return lambda xs: {'type': 'Tree', 'root': v, 'nest': xs} def ap(fs): def go(xs): return [ f(x) for (f, x) in product(fs, xs) ] return go def bindLR(m): def go(mf): return ( mf(m.get('Right')) if None is m.get('Left') else m ) return go def comparing(f): def go(x, y): fx = f(x) fy = f(y) return -1 if fx < fy else (1 if fx > fy else 0) return go def concatMap(f): def go(xs): return chain.from_iterable(map(f, xs)) return go def either(fl): return lambda fr: lambda e: fl(e['Left']) if ( None is e['Right'] ) else fr(e['Right']) def flip(f): return lambda a, b: f(b, a) def foldTree(f): def go(node): return f(root(node))([ go(x) for x in nest(node) ]) return go def nest(t): return t.get('nest') def root(t): return t.get('root') def span(p): def match(ab): b = ab[1] return not b or not p(b[0]) def f(ab): a, b = ab return a + [b[0]], b[1:] def go(xs): return until(match)(f)(([], xs)) return go def until(p): def go(f): def g(x): v = x while not p(v): v = f(v) return v return g return go if __name__ == '__main__': main()
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "math/big" "rcu" ) func lcm(n int) *big.Int { lcm := big.NewInt(1) t := new(big.Int) for _, p := range rcu.Primes(n) { f := p for f*p <= n { f *= p } lcm.Mul(lcm, t.SetUint64(uint64(f))) } return lcm } func main() { fmt.Println("The LCMs of the numbers 1 to N inclusive is:") for _, i := range []int{10, 20, 200, 2000} { fmt.Printf("%4d: %s\n", i, lcm(i)) } }
from math import gcd from functools import reduce def lcm(a, b): return 0 if 0 == a or 0 == b else ( abs(a * b) // gcd(a, b) ) for i in [10, 20, 200, 2000]: print(str(i) + ':', reduce(lcm, range(1, i + 1)))
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "math" "rcu" ) func contains(a []int, f int) bool { for _, e := range a { if e == f { return true } } return false } func main() { const euler = 0.57721566490153286 primes := rcu.Primes(1 << 31) pc := len(primes) sum := 0.0 fmt.Println("Primes added M") fmt.Println("------------ --------------") for i, p := range primes { rp := 1.0 / float64(p) sum += math.Log(1.0-rp) + rp c := i + 1 if (c%1e7) == 0 || c == pc { fmt.Printf("%11s %0.12f\n", rcu.Commatize(c), sum+euler) } } }
from math import log def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': Euler = 0.57721566490153286 m = 0 for x in range(2, 10_000_000): if isPrime(x): m += log(1-(1/x)) + (1/x) print("MM =", Euler + m)
Write the same algorithm in Python as shown in this Go implementation.
var i int var u rune for i, u = range "voilà" { fmt.Println(i, u) }
u = 'abcdé' print(ord(u[-1]))
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func commas(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() { c := sieve(15999) fmt.Println("Quadrat special primes under 16,000:") fmt.Println(" Prime1 Prime2 Gap Sqrt") lastQuadSpecial := 3 gap := 1 count := 1 fmt.Printf("%7d %7d %6d %4d\n", 2, 3, 1, 1) for i := 5; i < 16000; i += 2 { if c[i] { continue } gap = i - lastQuadSpecial if isSquare(gap) { sqrt := int(math.Sqrt(float64(gap))) fmt.Printf("%7s %7s %6s %4d\n", commas(lastQuadSpecial), commas(i), commas(gap), sqrt) lastQuadSpecial = i count++ } } fmt.Println("\n", count+1, "such primes found.") }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 j = 1 print(2, end = " "); while True: while True: if isPrime(p + j*j): break j += 1 p += j*j if p > 16000: break print(p, end = " "); j = 1
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func commas(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() { c := sieve(15999) fmt.Println("Quadrat special primes under 16,000:") fmt.Println(" Prime1 Prime2 Gap Sqrt") lastQuadSpecial := 3 gap := 1 count := 1 fmt.Printf("%7d %7d %6d %4d\n", 2, 3, 1, 1) for i := 5; i < 16000; i += 2 { if c[i] { continue } gap = i - lastQuadSpecial if isSquare(gap) { sqrt := int(math.Sqrt(float64(gap))) fmt.Printf("%7s %7s %6s %4d\n", commas(lastQuadSpecial), commas(i), commas(gap), sqrt) lastQuadSpecial = i count++ } } fmt.Println("\n", count+1, "such primes found.") }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 j = 1 print(2, end = " "); while True: while True: if isPrime(p + j*j): break j += 1 p += j*j if p > 16000: break print(p, end = " "); j = 1
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "strings" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func getPerms(input []string) [][]string { perms := [][]string{input} le := len(input) a := make([]string, le) copy(a, input) n := le - 1 fact := factorial(n + 1) for c := 1; c < fact; c++ { i := n - 1 j := n for i >= 0 && a[i] > a[i+1] { i-- } if i == -1 { i = n } for a[j] < a[i] { j-- } a[i], a[j] = a[j], a[i] j = n i++ if i == n+1 { i = 0 } for i < j { a[i], a[j] = a[j], a[i] i++ j-- } b := make([]string, le) copy(b, a) perms = append(perms, b) } return perms } func distinct(slist []string) []string { distinctSet := make(map[string]int, len(slist)) i := 0 for _, s := range slist { if _, ok := distinctSet[s]; !ok { distinctSet[s] = i i++ } } result := make([]string, len(distinctSet)) for s, i := range distinctSet { result[i] = s } return result } func printCounts(seq string) { bases := [][]rune{{'A', 0}, {'C', 0}, {'G', 0}, {'T', 0}} for _, c := range seq { for _, base := range bases { if c == base[0] { base[1]++ } } } sum := 0 fmt.Println("\nNucleotide counts for", seq, "\b:\n") for _, base := range bases { fmt.Printf("%10c%12d\n", base[0], base[1]) sum += int(base[1]) } le := len(seq) fmt.Printf("%10s%12d\n", "Other", le-sum) fmt.Printf(" ____________________\n%14s%8d\n", "Total length", le) } func headTailOverlap(s1, s2 string) int { for start := 0; ; start++ { ix := strings.IndexByte(s1[start:], s2[0]) if ix == -1 { return 0 } else { start += ix } if strings.HasPrefix(s2, s1[start:]) { return len(s1) - start } } } func deduplicate(slist []string) []string { var filtered []string arr := distinct(slist) for i, s1 := range arr { withinLarger := false for j, s2 := range arr { if j != i && strings.Contains(s2, s1) { withinLarger = true break } } if !withinLarger { filtered = append(filtered, s1) } } return filtered } func shortestCommonSuperstring(slist []string) string { ss := deduplicate(slist) shortestSuper := strings.Join(ss, "") for _, perm := range getPerms(ss) { sup := perm[0] for i := 0; i < len(ss)-1; i++ { overlapPos := headTailOverlap(perm[i], perm[i+1]) sup += perm[i+1][overlapPos:] } if len(sup) < len(shortestSuper) { shortestSuper = sup } } return shortestSuper } func main() { testSequences := [][]string{ {"TA", "AAG", "TA", "GAA", "TA"}, {"CATTAGGG", "ATTAG", "GGG", "TA"}, {"AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA"}, { "ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT", "GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT", "GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC", "CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC", "GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT", "TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA", }, } for _, test := range testSequences { scs := shortestCommonSuperstring(test) printCounts(scs) } }
import os from collections import Counter from functools import reduce from itertools import permutations BASES = ("A", "C", "G", "T") def deduplicate(sequences): sequences = set(sequences) duplicates = set() for s, t in permutations(sequences, 2): if s != t and s in t: duplicates.add(s) return sequences - duplicates def smash(s, t): for i in range(len(s)): if t.startswith(s[i:]): return s[:i] + t return s + t def shortest_superstring(sequences): sequences = deduplicate(sequences) shortest = "".join(sequences) for perm in permutations(sequences): superstring = reduce(smash, perm) if len(superstring) < len(shortest): shortest = superstring return shortest def shortest_superstrings(sequences): sequences = deduplicate(sequences) shortest = set(["".join(sequences)]) shortest_length = sum(len(s) for s in sequences) for perm in permutations(sequences): superstring = reduce(smash, perm) superstring_length = len(superstring) if superstring_length < shortest_length: shortest.clear() shortest.add(superstring) shortest_length = superstring_length elif superstring_length == shortest_length: shortest.add(superstring) return shortest def print_report(sequence): buf = [f"Nucleotide counts for {sequence}:\n"] counts = Counter(sequence) for base in BASES: buf.append(f"{base:>10}{counts.get(base, 0):>12}") other = sum(v for k, v in counts.items() if k not in BASES) buf.append(f"{'Other':>10}{other:>12}") buf.append(" " * 5 + "_" * 17) buf.append(f"{'Total length':>17}{sum(counts.values()):>5}") print(os.linesep.join(buf), "\n") if __name__ == "__main__": test_cases = [ ("TA", "AAG", "TA", "GAA", "TA"), ("CATTAGGG", "ATTAG", "GGG", "TA"), ("AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA"), ( "ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT", "GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT", "GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC", "CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC", "GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT", "TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA", ), ] for case in test_cases: for superstring in shortest_superstrings(case): print_report(superstring)
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "log" "math" ) type Matrix [][]float64 func (m Matrix) rows() int { return len(m) } func (m Matrix) cols() int { return len(m[0]) } func (m Matrix) add(m2 Matrix) Matrix { if m.rows() != m2.rows() || m.cols() != m2.cols() { log.Fatal("Matrices must have the same dimensions.") } c := make(Matrix, m.rows()) for i := 0; i < m.rows(); i++ { c[i] = make([]float64, m.cols()) for j := 0; j < m.cols(); j++ { c[i][j] = m[i][j] + m2[i][j] } } return c } func (m Matrix) sub(m2 Matrix) Matrix { if m.rows() != m2.rows() || m.cols() != m2.cols() { log.Fatal("Matrices must have the same dimensions.") } c := make(Matrix, m.rows()) for i := 0; i < m.rows(); i++ { c[i] = make([]float64, m.cols()) for j := 0; j < m.cols(); j++ { c[i][j] = m[i][j] - m2[i][j] } } return c } func (m Matrix) mul(m2 Matrix) Matrix { if m.cols() != m2.rows() { log.Fatal("Cannot multiply these matrices.") } c := make(Matrix, m.rows()) for i := 0; i < m.rows(); i++ { c[i] = make([]float64, m2.cols()) for j := 0; j < m2.cols(); j++ { for k := 0; k < m2.rows(); k++ { c[i][j] += m[i][k] * m2[k][j] } } } return c } func (m Matrix) toString(p int) string { s := make([]string, m.rows()) pow := math.Pow(10, float64(p)) for i := 0; i < m.rows(); i++ { t := make([]string, m.cols()) for j := 0; j < m.cols(); j++ { r := math.Round(m[i][j]*pow) / pow t[j] = fmt.Sprintf("%g", r) if t[j] == "-0" { t[j] = "0" } } s[i] = fmt.Sprintf("%v", t) } return fmt.Sprintf("%v", s) } func params(r, c int) [4][6]int { return [4][6]int{ {0, r, 0, c, 0, 0}, {0, r, c, 2 * c, 0, c}, {r, 2 * r, 0, c, r, 0}, {r, 2 * r, c, 2 * c, r, c}, } } func toQuarters(m Matrix) [4]Matrix { r := m.rows() / 2 c := m.cols() / 2 p := params(r, c) var quarters [4]Matrix for k := 0; k < 4; k++ { q := make(Matrix, r) for i := p[k][0]; i < p[k][1]; i++ { q[i-p[k][4]] = make([]float64, c) for j := p[k][2]; j < p[k][3]; j++ { q[i-p[k][4]][j-p[k][5]] = m[i][j] } } quarters[k] = q } return quarters } func fromQuarters(q [4]Matrix) Matrix { r := q[0].rows() c := q[0].cols() p := params(r, c) r *= 2 c *= 2 m := make(Matrix, r) for i := 0; i < c; i++ { m[i] = make([]float64, c) } for k := 0; k < 4; k++ { for i := p[k][0]; i < p[k][1]; i++ { for j := p[k][2]; j < p[k][3]; j++ { m[i][j] = q[k][i-p[k][4]][j-p[k][5]] } } } return m } func strassen(a, b Matrix) Matrix { if a.rows() != a.cols() || b.rows() != b.cols() || a.rows() != b.rows() { log.Fatal("Matrices must be square and of equal size.") } if a.rows() == 0 || (a.rows()&(a.rows()-1)) != 0 { log.Fatal("Size of matrices must be a power of two.") } if a.rows() == 1 { return a.mul(b) } qa := toQuarters(a) qb := toQuarters(b) p1 := strassen(qa[1].sub(qa[3]), qb[2].add(qb[3])) p2 := strassen(qa[0].add(qa[3]), qb[0].add(qb[3])) p3 := strassen(qa[0].sub(qa[2]), qb[0].add(qb[1])) p4 := strassen(qa[0].add(qa[1]), qb[3]) p5 := strassen(qa[0], qb[1].sub(qb[3])) p6 := strassen(qa[3], qb[2].sub(qb[0])) p7 := strassen(qa[2].add(qa[3]), qb[0]) var q [4]Matrix q[0] = p1.add(p2).sub(p4).add(p6) q[1] = p4.add(p5) q[2] = p6.add(p7) q[3] = p2.sub(p3).add(p5).sub(p7) return fromQuarters(q) } func main() { a := Matrix{{1, 2}, {3, 4}} b := Matrix{{5, 6}, {7, 8}} c := Matrix{{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}} d := Matrix{{4, -3, 4.0 / 3, -1.0 / 4}, {-13.0 / 3, 19.0 / 4, -7.0 / 3, 11.0 / 24}, {3.0 / 2, -2, 7.0 / 6, -1.0 / 4}, {-1.0 / 6, 1.0 / 4, -1.0 / 6, 1.0 / 24}} e := Matrix{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} f := Matrix{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}} fmt.Println("Using 'normal' matrix multiplication:") fmt.Printf(" a * b = %v\n", a.mul(b)) fmt.Printf(" c * d = %v\n", c.mul(d).toString(6)) fmt.Printf(" e * f = %v\n", e.mul(f)) fmt.Println("\nUsing 'Strassen' matrix multiplication:") fmt.Printf(" a * b = %v\n", strassen(a, b)) fmt.Printf(" c * d = %v\n", strassen(c, d).toString(6)) fmt.Printf(" e * f = %v\n", strassen(e, f)) }
from __future__ import annotations from itertools import chain from typing import List from typing import NamedTuple from typing import Optional class Shape(NamedTuple): rows: int cols: int class Matrix(List): @classmethod def block(cls, blocks) -> Matrix: m = Matrix() for hblock in blocks: for row in zip(*hblock): m.append(list(chain.from_iterable(row))) return m def dot(self, b: Matrix) -> Matrix: assert self.shape.cols == b.shape.rows m = Matrix() for row in self: new_row = [] for c in range(len(b[0])): col = [b[r][c] for r in range(len(b))] new_row.append(sum(x * y for x, y in zip(row, col))) m.append(new_row) return m def __matmul__(self, b: Matrix) -> Matrix: return self.dot(b) def __add__(self, b: Matrix) -> Matrix: assert self.shape == b.shape rows, cols = self.shape return Matrix( [[self[i][j] + b[i][j] for j in range(cols)] for i in range(rows)] ) def __sub__(self, b: Matrix) -> Matrix: assert self.shape == b.shape rows, cols = self.shape return Matrix( [[self[i][j] - b[i][j] for j in range(cols)] for i in range(rows)] ) def strassen(self, b: Matrix) -> Matrix: rows, cols = self.shape assert rows == cols, "matrices must be square" assert self.shape == b.shape, "matrices must be the same shape" assert rows and (rows & rows - 1) == 0, "shape must be a power of 2" if rows == 1: return self.dot(b) p = rows // 2 a11 = Matrix([n[:p] for n in self[:p]]) a12 = Matrix([n[p:] for n in self[:p]]) a21 = Matrix([n[:p] for n in self[p:]]) a22 = Matrix([n[p:] for n in self[p:]]) b11 = Matrix([n[:p] for n in b[:p]]) b12 = Matrix([n[p:] for n in b[:p]]) b21 = Matrix([n[:p] for n in b[p:]]) b22 = Matrix([n[p:] for n in b[p:]]) m1 = (a11 + a22).strassen(b11 + b22) m2 = (a21 + a22).strassen(b11) m3 = a11.strassen(b12 - b22) m4 = a22.strassen(b21 - b11) m5 = (a11 + a12).strassen(b22) m6 = (a21 - a11).strassen(b11 + b12) m7 = (a12 - a22).strassen(b21 + b22) c11 = m1 + m4 - m5 + m7 c12 = m3 + m5 c21 = m2 + m4 c22 = m1 - m2 + m3 + m6 return Matrix.block([[c11, c12], [c21, c22]]) def round(self, ndigits: Optional[int] = None) -> Matrix: return Matrix([[round(i, ndigits) for i in row] for row in self]) @property def shape(self) -> Shape: cols = len(self[0]) if self else 0 return Shape(len(self), cols) def examples(): a = Matrix( [ [1, 2], [3, 4], ] ) b = Matrix( [ [5, 6], [7, 8], ] ) c = Matrix( [ [1, 1, 1, 1], [2, 4, 8, 16], [3, 9, 27, 81], [4, 16, 64, 256], ] ) d = Matrix( [ [4, -3, 4 / 3, -1 / 4], [-13 / 3, 19 / 4, -7 / 3, 11 / 24], [3 / 2, -2, 7 / 6, -1 / 4], [-1 / 6, 1 / 4, -1 / 6, 1 / 24], ] ) e = Matrix( [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ] ) f = Matrix( [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) print("Naive matrix multiplication:") print(f" a * b = {a @ b}") print(f" c * d = {(c @ d).round()}") print(f" e * f = {e @ f}") print("Strassen's matrix multiplication:") print(f" a * b = {a.strassen(b)}") print(f" c * d = {c.strassen(d).round()}") print(f" e * f = {e.strassen(f)}") if __name__ == "__main__": examples()
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "math" "os" "strconv" "text/template" ) func sqr(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(f*f, 'f', -1, 64) } func sqrt(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64) } func main() { f := template.FuncMap{"sqr": sqr, "sqrt": sqrt} t := template.Must(template.New("").Funcs(f).Parse(`. = {{.}} square: {{sqr .}} square root: {{sqrt .}} `)) t.Execute(os.Stdout, "3") }
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
Please provide an equivalent version of this Go code in Python.
package main import ( "math" "os" "strconv" "text/template" ) func sqr(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(f*f, 'f', -1, 64) } func sqrt(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64) } func main() { f := template.FuncMap{"sqr": sqr, "sqrt": sqrt} t := template.Must(template.New("").Funcs(f).Parse(`. = {{.}} square: {{sqr .}} square root: {{sqrt .}} `)) t.Execute(os.Stdout, "3") }
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
Generate an equivalent Python version of this Go code.
package main import ( "bufio" "fmt" "log" "os" ) type SomeStruct struct { runtimeFields map[string]string } func check(err error) { if err != nil { log.Fatal(err) } } func main() { ss := SomeStruct{make(map[string]string)} scanner := bufio.NewScanner(os.Stdin) fmt.Println("Create two fields at runtime: ") for i := 1; i <= 2; i++ { fmt.Printf(" Field #%d:\n", i) fmt.Print(" Enter name  : ") scanner.Scan() name := scanner.Text() fmt.Print(" Enter value : ") scanner.Scan() value := scanner.Text() check(scanner.Err()) ss.runtimeFields[name] = value fmt.Println() } for { fmt.Print("Which field do you want to inspect ? ") scanner.Scan() name := scanner.Text() check(scanner.Err()) value, ok := ss.runtimeFields[name] if !ok { fmt.Println("There is no field of that name, try again") } else { fmt.Printf("Its value is '%s'\n", value) return } } }
class empty(object): pass e = empty()
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "sort" ) func contains(s []int, f int) bool { for _, e := range s { if e == f { return true } } return false } func sliceEqual(s1, s2 []int) bool { for i := 0; i < len(s1); i++ { if s1[i] != s2[i] { return false } } return true } func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func perimEqual(p1, p2 []int) bool { le := len(p1) if le != len(p2) { return false } for _, p := range p1 { if !contains(p2, p) { return false } } c := make([]int, le) copy(c, p1) for r := 0; r < 2; r++ { for i := 0; i < le; i++ { if sliceEqual(c, p2) { return true } t := c[le-1] copy(c[1:], c[0:le-1]) c[0] = t } reverse(c) } return false } type edge [2]int func faceToPerim(face []edge) []int { le := len(face) if le == 0 { return nil } edges := make([]edge, le) for i := 0; i < le; i++ { if face[i][1] <= face[i][0] { return nil } edges[i] = face[i] } sort.Slice(edges, func(i, j int) bool { if edges[i][0] != edges[j][0] { return edges[i][0] < edges[j][0] } return edges[i][1] < edges[j][1] }) var perim []int first, last := edges[0][0], edges[0][1] perim = append(perim, first, last) copy(edges, edges[1:]) edges = edges[0 : le-1] le-- outer: for le > 0 { for i, e := range edges { found := false if e[0] == last { perim = append(perim, e[1]) last, found = e[1], true } else if e[1] == last { perim = append(perim, e[0]) last, found = e[0], true } if found { copy(edges[i:], edges[i+1:]) edges = edges[0 : le-1] le-- if last == first { if le == 0 { break outer } else { return nil } } continue outer } } } return perim[0 : len(perim)-1] } func main() { fmt.Println("Perimeter format equality checks:") areEqual := perimEqual([]int{8, 1, 3}, []int{1, 3, 8}) fmt.Printf(" Q == R is %t\n", areEqual) areEqual = perimEqual([]int{18, 8, 14, 10, 12, 17, 19}, []int{8, 14, 10, 12, 17, 19, 18}) fmt.Printf(" U == V is %t\n", areEqual) e := []edge{{7, 11}, {1, 11}, {1, 7}} f := []edge{{11, 23}, {1, 17}, {17, 23}, {1, 11}} g := []edge{{8, 14}, {17, 19}, {10, 12}, {10, 14}, {12, 17}, {8, 18}, {18, 19}} h := []edge{{1, 3}, {9, 11}, {3, 11}, {1, 11}} fmt.Println("\nEdge to perimeter format translations:") for i, face := range [][]edge{e, f, g, h} { perim := faceToPerim(face) if perim == nil { fmt.Printf(" %c => Invalid edge format\n", i + 'E') } else { fmt.Printf(" %c => %v\n", i + 'E', perim) } } }
def perim_equal(p1, p2): if len(p1) != len(p2) or set(p1) != set(p2): return False if any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))): return True p2 = p2[::-1] return any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))) def edge_to_periphery(e): edges = sorted(e) p = list(edges.pop(0)) if edges else [] last = p[-1] if p else None while edges: for n, (i, j) in enumerate(edges): if i == last: p.append(j) last = j edges.pop(n) break elif j == last: p.append(i) last = i edges.pop(n) break else: return ">>>Error! Invalid edge format<<<" return p[:-1] if __name__ == '__main__': print('Perimeter format equality checks:') for eq_check in [ { 'Q': (8, 1, 3), 'R': (1, 3, 8)}, { 'U': (18, 8, 14, 10, 12, 17, 19), 'V': (8, 14, 10, 12, 17, 19, 18)} ]: (n1, p1), (n2, p2) = eq_check.items() eq = '==' if perim_equal(p1, p2) else '!=' print(' ', n1, eq, n2) print('\nEdge to perimeter format translations:') edge_d = { 'E': {(1, 11), (7, 11), (1, 7)}, 'F': {(11, 23), (1, 17), (17, 23), (1, 11)}, 'G': {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}, 'H': {(1, 3), (9, 11), (3, 11), (1, 11)} } for name, edges in edge_d.items(): print(f" {name}: {edges}\n -> {edge_to_periphery(edges)}")
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "math" "strconv" "strings" ) func argmax(m [][]float64, i int) int { col := make([]float64, len(m)) max, maxx := -1.0, -1 for x := 0; x < len(m); x++ { col[x] = math.Abs(m[x][i]) if col[x] > max { max = col[x] maxx = x } } return maxx } func gauss(m [][]float64) []float64 { n, p := len(m), len(m[0]) for i := 0; i < n; i++ { k := i + argmax(m[i:n], i) m[i], m[k] = m[k], m[i] t := 1 / m[i][i] for j := i + 1; j < p; j++ { m[i][j] *= t } for j := i + 1; j < n; j++ { t = m[j][i] for l := i + 1; l < p; l++ { m[j][l] -= t * m[i][l] } } } for i := n - 1; i >= 0; i-- { for j := 0; j < i; j++ { m[j][p-1] -= m[j][i] * m[i][p-1] } } col := make([]float64, len(m)) for x := 0; x < len(m); x++ { col[x] = m[x][p-1] } return col } func network(n, k0, k1 int, s string) float64 { m := make([][]float64, n) for i := 0; i < n; i++ { m[i] = make([]float64, n+1) } for _, resistor := range strings.Split(s, "|") { rarr := strings.Fields(resistor) a, _ := strconv.Atoi(rarr[0]) b, _ := strconv.Atoi(rarr[1]) ri, _ := strconv.Atoi(rarr[2]) r := 1.0 / float64(ri) m[a][a] += r m[b][b] += r if a > 0 { m[a][b] -= r } if b > 0 { m[b][a] -= r } } m[k0][k0] = 1 m[k1][n] = 1 return gauss(m)[k1] } func main() { var fa [4]float64 fa[0] = network(7, 0, 1, "0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8") fa[1] = network(9, 0, 8, "0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1") fa[2] = network(16, 0, 15, "0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1") fa[3] = network(4, 0, 3, "0 1 150|0 2 50|1 3 300|2 3 250") for _, f := range fa { fmt.Printf("%.6g\n", f) } }
from fractions import Fraction def gauss(m): n, p = len(m), len(m[0]) for i in range(n): k = max(range(i, n), key = lambda x: abs(m[x][i])) m[i], m[k] = m[k], m[i] t = 1 / m[i][i] for j in range(i + 1, p): m[i][j] *= t for j in range(i + 1, n): t = m[j][i] for k in range(i + 1, p): m[j][k] -= t * m[i][k] for i in range(n - 1, -1, -1): for j in range(i): m[j][-1] -= m[j][i] * m[i][-1] return [row[-1] for row in m] def network(n,k0,k1,s): m = [[0] * (n+1) for i in range(n)] resistors = s.split('|') for resistor in resistors: a,b,r = resistor.split(' ') a,b,r = int(a), int(b), Fraction(1,int(r)) m[a][a] += r m[b][b] += r if a > 0: m[a][b] -= r if b > 0: m[b][a] -= r m[k0][k0] = Fraction(1, 1) m[k1][-1] = Fraction(1, 1) return gauss(m)[k1] assert 10 == network(7,0,1,"0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8") assert 3/2 == network(3*3,0,3*3-1,"0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1") assert Fraction(13,7) == network(4*4,0,4*4-1,"0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1") assert 180 == network(4,0,3,"0 1 150|0 2 50|1 3 300|2 3 250")
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/rand" "regexp" "time" ) const base = "ACGT" func findDnaSubsequence(dnaSize, chunkSize int) { dnaSeq := make([]byte, dnaSize) for i := 0; i < dnaSize; i++ { dnaSeq[i] = base[rand.Intn(4)] } dnaStr := string(dnaSeq) dnaSubseq := make([]byte, 4) for i := 0; i < 4; i++ { dnaSubseq[i] = base[rand.Intn(4)] } dnaSubstr := string(dnaSubseq) fmt.Println("DNA sequnence:") for i := chunkSize; i <= len(dnaStr); i += chunkSize { start := i - chunkSize fmt.Printf("%3d..%3d: %s\n", start+1, i, dnaStr[start:i]) } fmt.Println("\nSubsequence to locate:", dnaSubstr) var r = regexp.MustCompile(dnaSubstr) var matches = r.FindAllStringIndex(dnaStr, -1) if len(matches) == 0 { fmt.Println("No matches found.") } else { fmt.Println("Matches found at the following indices:") for _, m := range matches { fmt.Printf("%3d..%-3d\n", m[0]+1, m[1]) } } } func main() { rand.Seed(time.Now().UnixNano()) findDnaSubsequence(200, 20) fmt.Println() findDnaSubsequence(600, 40) }
from random import choice import regex as re import time def generate_sequence(n: int ) -> str: return "".join([ choice(['A','C','G','T']) for _ in range(n) ]) def dna_findall(needle: str, haystack: str) -> None: if sum(1 for _ in re.finditer(needle, haystack, overlapped=True)) == 0: print("No matches found") else: print(f"Found {needle} at the following indices: ") for match in re.finditer(needle, haystack, overlapped=True): print(f"{match.start()}:{match.end()} ") dna_seq = generate_sequence(200) sample_seq = generate_sequence(4) c = 1 for i in dna_seq: print(i, end="") if c % 20 != 0 else print(f"{i}") c += 1 print(f"\nSearch Sample: {sample_seq}") dna_findall(sample_seq, dna_seq)
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "fmt" "os" "sort" "strings" "text/template" ) func main() { const t = `[[[{{index .P 1}}, {{index .P 2}}], [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], {{index .P 5}}]] ` type S struct { P map[int]string } var s S s.P = map[int]string{ 0: "'Payload#0'", 1: "'Payload#1'", 2: "'Payload#2'", 3: "'Payload#3'", 4: "'Payload#4'", 5: "'Payload#5'", 6: "'Payload#6'", } tmpl := template.Must(template.New("").Parse(t)) tmpl.Execute(os.Stdout, s) var unused []int for k, _ := range s.P { if !strings.Contains(t, fmt.Sprintf("{{index .P %d}}", k)) { unused = append(unused, k) } } sort.Ints(unused) fmt.Println("\nThe unused payloads have indices of :", unused) }
from pprint import pprint as pp class Template(): def __init__(self, structure): self.structure = structure self.used_payloads, self.missed_payloads = [], [] def inject_payload(self, id2data): def _inject_payload(substruct, i2d, used, missed): used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d) missed.extend(f'?? for x in substruct if type(x) is not tuple and x not in i2d) return tuple(_inject_payload(x, i2d, used, missed) if type(x) is tuple else i2d.get(x, f'?? for x in substruct) ans = _inject_payload(self.structure, id2data, self.used_payloads, self.missed_payloads) self.unused_payloads = sorted(set(id2data.values()) - set(self.used_payloads)) self.missed_payloads = sorted(set(self.missed_payloads)) return ans if __name__ == '__main__': index2data = {p: f'Payload print(" print('\n '.join(list(index2data.values()))) for structure in [ (((1, 2), (3, 4, 1), 5),), (((1, 2), (10, 4, 1), 5),)]: print("\n\n pp(structure, width=13) print("\n TEMPLATE WITH PAYLOADS:") t = Template(structure) out = t.inject_payload(index2data) pp(out) print("\n UNUSED PAYLOADS:\n ", end='') unused = t.unused_payloads print('\n '.join(unused) if unused else '-') print(" MISSING PAYLOADS:\n ", end='') missed = t.missed_payloads print('\n '.join(missed) if missed else '-')
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "log" "os/exec" "raster" ) func main() { c := exec.Command("convert", "Unfilledcirc.png", "-depth", "1", "ppm:-") pipe, err := c.StdoutPipe() if err != nil { log.Fatal(err) } if err = c.Start(); err != nil { log.Fatal(err) } b, err := raster.ReadPpmFrom(pipe) if err != nil { log.Fatal(err) } if err = b.WritePpmFile("Unfilledcirc.ppm"); err != nil { log.Fatal(err) } }
from PIL import Image im = Image.open("boxes_1.jpg") im.save("boxes_1v2.ppm")
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "log" "os/exec" "raster" ) func main() { c := exec.Command("convert", "Unfilledcirc.png", "-depth", "1", "ppm:-") pipe, err := c.StdoutPipe() if err != nil { log.Fatal(err) } if err = c.Start(); err != nil { log.Fatal(err) } b, err := raster.ReadPpmFrom(pipe) if err != nil { log.Fatal(err) } if err = b.WritePpmFile("Unfilledcirc.ppm"); err != nil { log.Fatal(err) } }
from PIL import Image im = Image.open("boxes_1.jpg") im.save("boxes_1v2.ppm")
Convert this Go block to Python, preserving its control flow and logic.
package main import "fmt" type rs232p9 uint16 const ( CD9 rs232p9 = 1 << iota RD9 TD9 DTR9 SG9 DSR9 RTS9 CTS9 RI9 ) func main() { p := RI9 | TD9 | CD9 fmt.Printf("Type=%T value=%#04x\n", p, p) }
from ctypes import Structure, c_int rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split() rs232_25pin = ( "_0 PG TD RD RTS CTS DSR SG CD pos neg" "_11 SCD SCS STD TC SRD RC" "_18 SRS DTR SQD RI DRS XTC" ).split() class RS232_9pin(Structure): _fields_ = [(__, c_int, 1) for __ in rs232_9pin] class RS232_25pin(Structure): _fields_ = [(__, c_int, 1) for __ in rs232_25pin]
Port the provided Go code into Python while preserving the original functionality.
package main import "fmt" type rs232p9 uint16 const ( CD9 rs232p9 = 1 << iota RD9 TD9 DTR9 SG9 DSR9 RTS9 CTS9 RI9 ) func main() { p := RI9 | TD9 | CD9 fmt.Printf("Type=%T value=%#04x\n", p, p) }
from ctypes import Structure, c_int rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split() rs232_25pin = ( "_0 PG TD RD RTS CTS DSR SG CD pos neg" "_11 SCD SCS STD TC SRD RC" "_18 SRS DTR SQD RI DRS XTC" ).split() class RS232_9pin(Structure): _fields_ = [(__, c_int, 1) for __ in rs232_9pin] class RS232_25pin(Structure): _fields_ = [(__, c_int, 1) for __ in rs232_25pin]
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" "rcu" ) func main() { limit := int(math.Log(1e7) * 1e7 * 1.2) primes := rcu.Primes(limit) fmt.Println("The first 20 pairs of natural numbers whose sum is prime are:") for i := 1; i <= 20; i++ { p := primes[i] hp := p / 2 fmt.Printf("%2d + %2d = %2d\n", hp, hp+1, p) } fmt.Println("\nThe 10 millionth such pair is:") p := primes[1e7] hp := p / 2 fmt.Printf("%2d + %2d = %2d\n", hp, hp+1, p) }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == "__main__": n = 0 num = 0 print('The first 20 pairs of numbers whose sum is prime:') while True: n += 1 suma = 2*n+1 if isPrime(suma): num += 1 if num < 21: print('{:2}'.format(n), "+", '{:2}'.format(n+1), "=", '{:2}'.format(suma)) else: break
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "errors" "flag" "fmt" "log" "math/rand" "strings" "time" ) func main() { log.SetPrefix("mastermind: ") log.SetFlags(0) colours := flag.Int("colours", 6, "number of colours to use (2-20)") flag.IntVar(colours, "colors", 6, "alias for colours") holes := flag.Int("holes", 4, "number of holes (the code length, 4-10)") guesses := flag.Int("guesses", 12, "number of guesses allowed (7-20)") unique := flag.Bool("unique", false, "disallow duplicate colours in the code") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMastermind(*colours, *holes, *guesses, *unique) if err != nil { log.Fatal(err) } err = m.Play() if err != nil { log.Fatal(err) } } type mastermind struct { colours int holes int guesses int unique bool code string past []string scores []string } func NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) { if colours < 2 || colours > 20 { return nil, errors.New("colours must be between 2 and 20 inclusive") } if holes < 4 || holes > 10 { return nil, errors.New("holes must be between 4 and 10 inclusive") } if guesses < 7 || guesses > 20 { return nil, errors.New("guesses must be between 7 and 20 inclusive") } if unique && holes > colours { return nil, errors.New("holes must be > colours when using unique") } return &mastermind{ colours: colours, holes: holes, guesses: guesses, unique: unique, past: make([]string, 0, guesses), scores: make([]string, 0, guesses), }, nil } func (m *mastermind) Play() error { m.generateCode() fmt.Printf("A set of %s has been selected as the code.\n", m.describeCode(m.unique)) fmt.Printf("You have %d guesses.\n", m.guesses) for len(m.past) < m.guesses { guess, err := m.inputGuess() if err != nil { return err } fmt.Println() m.past = append(m.past, guess) str, won := m.scoreString(m.score(guess)) if won { plural := "es" if len(m.past) == 1 { plural = "" } fmt.Printf("You found the code in %d guess%s.\n", len(m.past), plural) return nil } m.scores = append(m.scores, str) m.printHistory() fmt.Println() } fmt.Printf("You are out of guesses. The code was %s.\n", m.code) return nil } const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" const blacks = "XXXXXXXXXX" const whites = "OOOOOOOOOO" const nones = "----------" func (m *mastermind) describeCode(unique bool) string { ustr := "" if unique { ustr = " unique" } return fmt.Sprintf("%d%s letters (from 'A' to %q)", m.holes, ustr, charset[m.colours-1], ) } func (m *mastermind) printHistory() { for i, g := range m.past { fmt.Printf("-----%s---%[1]s--\n", nones[:m.holes]) fmt.Printf("%2d: %s : %s\n", i+1, g, m.scores[i]) } } func (m *mastermind) generateCode() { code := make([]byte, m.holes) if m.unique { p := rand.Perm(m.colours) for i := range code { code[i] = charset[p[i]] } } else { for i := range code { code[i] = charset[rand.Intn(m.colours)] } } m.code = string(code) } func (m *mastermind) inputGuess() (string, error) { var input string for { fmt.Printf("Enter guess #%d: ", len(m.past)+1) if _, err := fmt.Scanln(&input); err != nil { return "", err } input = strings.ToUpper(strings.TrimSpace(input)) if m.validGuess(input) { return input, nil } fmt.Printf("A guess must consist of %s.\n", m.describeCode(false)) } } func (m *mastermind) validGuess(input string) bool { if len(input) != m.holes { return false } for i := 0; i < len(input); i++ { c := input[i] if c < 'A' || c > charset[m.colours-1] { return false } } return true } func (m *mastermind) score(guess string) (black, white int) { scored := make([]bool, m.holes) for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { black++ scored[i] = true } } for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { continue } for j := 0; j < len(m.code); j++ { if i != j && !scored[j] && guess[i] == m.code[j] { white++ scored[j] = true } } } return } func (m *mastermind) scoreString(black, white int) (string, bool) { none := m.holes - black - white return blacks[:black] + whites[:white] + nones[:none], black == m.holes }
import random def encode(correct, guess): output_arr = [''] * len(correct) for i, (correct_char, guess_char) in enumerate(zip(correct, guess)): output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-' return ''.join(output_arr) def safe_int_input(prompt, min_val, max_val): while True: user_input = input(prompt) try: user_input = int(user_input) except ValueError: continue if min_val <= user_input <= max_val: return user_input def play_game(): print("Welcome to Mastermind.") print("You will need to guess a random code.") print("For each guess, you will receive a hint.") print("In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.") print() number_of_letters = safe_int_input("Select a number of possible letters for the code (2-20): ", 2, 20) code_length = safe_int_input("Select a length for the code (4-10): ", 4, 10) letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters] code = ''.join(random.choices(letters, k=code_length)) guesses = [] while True: print() guess = input(f"Enter a guess of length {code_length} ({letters}): ").upper().strip() if len(guess) != code_length or any([char not in letters for char in guess]): continue elif guess == code: print(f"\nYour guess {guess} was correct!") break else: guesses.append(f"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}") for i_guess in guesses: print("------------------------------------") print(i_guess) print("------------------------------------") if __name__ == '__main__': play_game()
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "errors" "flag" "fmt" "log" "math/rand" "strings" "time" ) func main() { log.SetPrefix("mastermind: ") log.SetFlags(0) colours := flag.Int("colours", 6, "number of colours to use (2-20)") flag.IntVar(colours, "colors", 6, "alias for colours") holes := flag.Int("holes", 4, "number of holes (the code length, 4-10)") guesses := flag.Int("guesses", 12, "number of guesses allowed (7-20)") unique := flag.Bool("unique", false, "disallow duplicate colours in the code") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMastermind(*colours, *holes, *guesses, *unique) if err != nil { log.Fatal(err) } err = m.Play() if err != nil { log.Fatal(err) } } type mastermind struct { colours int holes int guesses int unique bool code string past []string scores []string } func NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) { if colours < 2 || colours > 20 { return nil, errors.New("colours must be between 2 and 20 inclusive") } if holes < 4 || holes > 10 { return nil, errors.New("holes must be between 4 and 10 inclusive") } if guesses < 7 || guesses > 20 { return nil, errors.New("guesses must be between 7 and 20 inclusive") } if unique && holes > colours { return nil, errors.New("holes must be > colours when using unique") } return &mastermind{ colours: colours, holes: holes, guesses: guesses, unique: unique, past: make([]string, 0, guesses), scores: make([]string, 0, guesses), }, nil } func (m *mastermind) Play() error { m.generateCode() fmt.Printf("A set of %s has been selected as the code.\n", m.describeCode(m.unique)) fmt.Printf("You have %d guesses.\n", m.guesses) for len(m.past) < m.guesses { guess, err := m.inputGuess() if err != nil { return err } fmt.Println() m.past = append(m.past, guess) str, won := m.scoreString(m.score(guess)) if won { plural := "es" if len(m.past) == 1 { plural = "" } fmt.Printf("You found the code in %d guess%s.\n", len(m.past), plural) return nil } m.scores = append(m.scores, str) m.printHistory() fmt.Println() } fmt.Printf("You are out of guesses. The code was %s.\n", m.code) return nil } const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" const blacks = "XXXXXXXXXX" const whites = "OOOOOOOOOO" const nones = "----------" func (m *mastermind) describeCode(unique bool) string { ustr := "" if unique { ustr = " unique" } return fmt.Sprintf("%d%s letters (from 'A' to %q)", m.holes, ustr, charset[m.colours-1], ) } func (m *mastermind) printHistory() { for i, g := range m.past { fmt.Printf("-----%s---%[1]s--\n", nones[:m.holes]) fmt.Printf("%2d: %s : %s\n", i+1, g, m.scores[i]) } } func (m *mastermind) generateCode() { code := make([]byte, m.holes) if m.unique { p := rand.Perm(m.colours) for i := range code { code[i] = charset[p[i]] } } else { for i := range code { code[i] = charset[rand.Intn(m.colours)] } } m.code = string(code) } func (m *mastermind) inputGuess() (string, error) { var input string for { fmt.Printf("Enter guess #%d: ", len(m.past)+1) if _, err := fmt.Scanln(&input); err != nil { return "", err } input = strings.ToUpper(strings.TrimSpace(input)) if m.validGuess(input) { return input, nil } fmt.Printf("A guess must consist of %s.\n", m.describeCode(false)) } } func (m *mastermind) validGuess(input string) bool { if len(input) != m.holes { return false } for i := 0; i < len(input); i++ { c := input[i] if c < 'A' || c > charset[m.colours-1] { return false } } return true } func (m *mastermind) score(guess string) (black, white int) { scored := make([]bool, m.holes) for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { black++ scored[i] = true } } for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { continue } for j := 0; j < len(m.code); j++ { if i != j && !scored[j] && guess[i] == m.code[j] { white++ scored[j] = true } } } return } func (m *mastermind) scoreString(black, white int) (string, bool) { none := m.holes - black - white return blacks[:black] + whites[:white] + nones[:none], black == m.holes }
import random def encode(correct, guess): output_arr = [''] * len(correct) for i, (correct_char, guess_char) in enumerate(zip(correct, guess)): output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-' return ''.join(output_arr) def safe_int_input(prompt, min_val, max_val): while True: user_input = input(prompt) try: user_input = int(user_input) except ValueError: continue if min_val <= user_input <= max_val: return user_input def play_game(): print("Welcome to Mastermind.") print("You will need to guess a random code.") print("For each guess, you will receive a hint.") print("In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.") print() number_of_letters = safe_int_input("Select a number of possible letters for the code (2-20): ", 2, 20) code_length = safe_int_input("Select a length for the code (4-10): ", 4, 10) letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters] code = ''.join(random.choices(letters, k=code_length)) guesses = [] while True: print() guess = input(f"Enter a guess of length {code_length} ({letters}): ").upper().strip() if len(guess) != code_length or any([char not in letters for char in guess]): continue elif guess == code: print(f"\nYour guess {guess} was correct!") break else: guesses.append(f"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}") for i_guess in guesses: print("------------------------------------") print(i_guess) print("------------------------------------") if __name__ == '__main__': play_game()
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "math" ) func main() { list := []float64{1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3} maxDiff := -1.0 var maxPairs [][2]float64 for i := 1; i < len(list); i++ { diff := math.Abs(list[i-1] - list[i]) if diff > maxDiff { maxDiff = diff maxPairs = [][2]float64{{list[i-1], list[i]}} } else if diff == maxDiff { maxPairs = append(maxPairs, [2]float64{list[i-1], list[i]}) } } fmt.Println("The maximum difference between adjacent pairs of the list is:", maxDiff) fmt.Println("The pairs with this difference are:", maxPairs) }
def maxDeltas(ns): pairs = [ (abs(a - b), (a, b)) for a, b in zip(ns, ns[1:]) ] delta = max(pairs, key=lambda ab: ab[0])[0] return [ ab for ab in pairs if delta == ab[0] ] def main(): maxPairs = maxDeltas([ 1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3 ]) for ab in maxPairs: print(ab) if __name__ == '__main__': main()
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "rcu" "strconv" "strings" ) func main() { count := 0 k := 11 * 11 var res []int for count < 20 { if k%3 == 0 || k%5 == 0 || k%7 == 0 { k += 2 continue } factors := rcu.PrimeFactors(k) if len(factors) > 1 { s := strconv.Itoa(k) includesAll := true prev := -1 for _, f := range factors { if f == prev { continue } fs := strconv.Itoa(f) if strings.Index(s, fs) == -1 { includesAll = false break } } if includesAll { res = append(res, k) count++ } } k += 2 } for _, e := range res[0:10] { fmt.Printf("%10s ", rcu.Commatize(e)) } fmt.Println() for _, e := range res[10:20] { fmt.Printf("%10s ", rcu.Commatize(e)) } fmt.Println() }
from sympy import isprime, factorint def contains_its_prime_factors_all_over_7(n): if n < 10 or isprime(n): return False strn = str(n) pfacs = factorint(n).keys() return all(f > 9 and str(f) in strn for f in pfacs) found = 0 for n in range(1_000_000_000): if contains_its_prime_factors_all_over_7(n): found += 1 print(f'{n: 12,}', end = '\n' if found % 10 == 0 else '') if found == 20: break
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "rcu" "strconv" "strings" ) func main() { count := 0 k := 11 * 11 var res []int for count < 20 { if k%3 == 0 || k%5 == 0 || k%7 == 0 { k += 2 continue } factors := rcu.PrimeFactors(k) if len(factors) > 1 { s := strconv.Itoa(k) includesAll := true prev := -1 for _, f := range factors { if f == prev { continue } fs := strconv.Itoa(f) if strings.Index(s, fs) == -1 { includesAll = false break } } if includesAll { res = append(res, k) count++ } } k += 2 } for _, e := range res[0:10] { fmt.Printf("%10s ", rcu.Commatize(e)) } fmt.Println() for _, e := range res[10:20] { fmt.Printf("%10s ", rcu.Commatize(e)) } fmt.Println() }
from sympy import isprime, factorint def contains_its_prime_factors_all_over_7(n): if n < 10 or isprime(n): return False strn = str(n) pfacs = factorint(n).keys() return all(f > 9 and str(f) in strn for f in pfacs) found = 0 for n in range(1_000_000_000): if contains_its_prime_factors_all_over_7(n): found += 1 print(f'{n: 12,}', end = '\n' if found % 10 == 0 else '') if found == 20: break
Translate the given Go code snippet into Python without altering its behavior.
package main import "fmt" type FCNode struct { name string weight int coverage float64 children []*FCNode parent *FCNode } func newFCN(name string, weight int, coverage float64) *FCNode { return &FCNode{name, weight, coverage, nil, nil} } func (n *FCNode) addChildren(nodes []*FCNode) { for _, node := range nodes { node.parent = n n.children = append(n.children, node) } n.updateCoverage() } func (n *FCNode) setCoverage(value float64) { if n.coverage != value { n.coverage = value if n.parent != nil { n.parent.updateCoverage() } } } func (n *FCNode) updateCoverage() { v1 := 0.0 v2 := 0 for _, node := range n.children { v1 += float64(node.weight) * node.coverage v2 += node.weight } n.setCoverage(v1 / float64(v2)) } func (n *FCNode) show(level int) { indent := level * 4 nl := len(n.name) + indent fmt.Printf("%*s%*s %3d | %8.6f |\n", nl, n.name, 32-nl, "|", n.weight, n.coverage) if len(n.children) == 0 { return } for _, child := range n.children { child.show(level + 1) } } var houses = []*FCNode{ newFCN("house1", 40, 0), newFCN("house2", 60, 0), } var house1 = []*FCNode{ newFCN("bedrooms", 1, 0.25), newFCN("bathrooms", 1, 0), newFCN("attic", 1, 0.75), newFCN("kitchen", 1, 0.1), newFCN("living_rooms", 1, 0), newFCN("basement", 1, 0), newFCN("garage", 1, 0), newFCN("garden", 1, 0.8), } var house2 = []*FCNode{ newFCN("upstairs", 1, 0), newFCN("groundfloor", 1, 0), newFCN("basement", 1, 0), } var h1Bathrooms = []*FCNode{ newFCN("bathroom1", 1, 0.5), newFCN("bathroom2", 1, 0), newFCN("outside_lavatory", 1, 1), } var h1LivingRooms = []*FCNode{ newFCN("lounge", 1, 0), newFCN("dining_room", 1, 0), newFCN("conservatory", 1, 0), newFCN("playroom", 1, 1), } var h2Upstairs = []*FCNode{ newFCN("bedrooms", 1, 0), newFCN("bathroom", 1, 0), newFCN("toilet", 1, 0), newFCN("attics", 1, 0.6), } var h2Groundfloor = []*FCNode{ newFCN("kitchen", 1, 0), newFCN("living_rooms", 1, 0), newFCN("wet_room_&_toilet", 1, 0), newFCN("garage", 1, 0), newFCN("garden", 1, 0.9), newFCN("hot_tub_suite", 1, 1), } var h2Basement = []*FCNode{ newFCN("cellars", 1, 1), newFCN("wine_cellar", 1, 1), newFCN("cinema", 1, 0.75), } var h2UpstairsBedrooms = []*FCNode{ newFCN("suite_1", 1, 0), newFCN("suite_2", 1, 0), newFCN("bedroom_3", 1, 0), newFCN("bedroom_4", 1, 0), } var h2GroundfloorLivingRooms = []*FCNode{ newFCN("lounge", 1, 0), newFCN("dining_room", 1, 0), newFCN("conservatory", 1, 0), newFCN("playroom", 1, 0), } func main() { cleaning := newFCN("cleaning", 1, 0) house1[1].addChildren(h1Bathrooms) house1[4].addChildren(h1LivingRooms) houses[0].addChildren(house1) h2Upstairs[0].addChildren(h2UpstairsBedrooms) house2[0].addChildren(h2Upstairs) h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms) house2[1].addChildren(h2Groundfloor) house2[2].addChildren(h2Basement) houses[1].addChildren(house2) cleaning.addChildren(houses) topCoverage := cleaning.coverage fmt.Printf("TOP COVERAGE = %8.6f\n\n", topCoverage) fmt.Println("NAME HIERARCHY | WEIGHT | COVERAGE |") cleaning.show(0) h2Basement[2].setCoverage(1) diff := cleaning.coverage - topCoverage fmt.Println("\nIf the coverage of the Cinema node were increased from 0.75 to 1") fmt.Print("the top level coverage would increase by ") fmt.Printf("%8.6f to %8.6f\n", diff, topCoverage+diff) h2Basement[2].setCoverage(0.75) }
from itertools import zip_longest fc2 = NAME, WT, COV = 0, 1, 2 def right_type(txt): try: return float(txt) except ValueError: return txt def commas_to_list(the_list, lines, start_indent=0): for n, line in lines: indent = 0 while line.startswith(' ' * (4 * indent)): indent += 1 indent -= 1 fields = [right_type(f) for f in line.strip().split(',')] if indent == start_indent: the_list.append(fields) elif indent > start_indent: lst = [fields] sub = commas_to_list(lst, lines, indent) the_list[-1] = (the_list[-1], lst) if sub not in (None, ['']) : the_list.append(sub) else: return fields if fields else None return None def pptreefields(lst, indent=0, widths=['%-32s', '%-8g', '%-10g']): lhs = ' ' * (4 * indent) for item in lst: if type(item) != tuple: name, *rest = item print(widths[0] % (lhs + name), end='|') for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]): if type(item) == str: width = width[:-1] + 's' print(width % item, end='|') print() else: item, children = item name, *rest = item print(widths[0] % (lhs + name), end='|') for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]): if type(item) == str: width = width[:-1] + 's' print(width % item, end='|') print() pptreefields(children, indent+1) def default_field(node_list): node_list[WT] = node_list[WT] if node_list[WT] else 1.0 node_list[COV] = node_list[COV] if node_list[COV] else 0.0 def depth_first(tree, visitor=default_field): for item in tree: if type(item) == tuple: item, children = item depth_first(children, visitor) visitor(item) def covercalc(tree): sum_covwt, sum_wt = 0, 0 for item in tree: if type(item) == tuple: item, children = item item[COV] = covercalc(children) sum_wt += item[WT] sum_covwt += item[COV] * item[WT] cov = sum_covwt / sum_wt return cov if __name__ == '__main__': lstc = [] commas_to_list(lstc, ((n, ln) for n, ln in enumerate(fc2.split('\n')))) depth_first(lstc) print('\n\nTOP COVERAGE = %f\n' % covercalc(lstc)) depth_first(lstc) pptreefields(['NAME_HIERARCHY WEIGHT COVERAGE'.split()] + lstc)
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "log" "math" "math/rand" "time" ) type Point struct{ x, y float64 } type Circle struct { c Point r float64 } func (p Point) String() string { return fmt.Sprintf("(%f, %f)", p.x, p.y) } func distSq(a, b Point) float64 { return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) } func getCircleCenter(bx, by, cx, cy float64) Point { b := bx*bx + by*by c := cx*cx + cy*cy d := bx*cy - by*cx return Point{(cy*b - by*c) / (2 * d), (bx*c - cx*b) / (2 * d)} } func (ci Circle) contains(p Point) bool { return distSq(ci.c, p) <= ci.r*ci.r } func (ci Circle) encloses(ps []Point) bool { for _, p := range ps { if !ci.contains(p) { return false } } return true } func (ci Circle) String() string { return fmt.Sprintf("{%v, %f}", ci.c, ci.r) } func circleFrom3(a, b, c Point) Circle { i := getCircleCenter(b.x-a.x, b.y-a.y, c.x-a.x, c.y-a.y) i.x += a.x i.y += a.y return Circle{i, math.Sqrt(distSq(i, a))} } func circleFrom2(a, b Point) Circle { c := Point{(a.x + b.x) / 2, (a.y + b.y) / 2} return Circle{c, math.Sqrt(distSq(a, b)) / 2} } func secTrivial(rs []Point) Circle { size := len(rs) if size > 3 { log.Fatal("There shouldn't be more than 3 points.") } if size == 0 { return Circle{Point{0, 0}, 0} } if size == 1 { return Circle{rs[0], 0} } if size == 2 { return circleFrom2(rs[0], rs[1]) } for i := 0; i < 2; i++ { for j := i + 1; j < 3; j++ { c := circleFrom2(rs[i], rs[j]) if c.encloses(rs) { return c } } } return circleFrom3(rs[0], rs[1], rs[2]) } func welzlHelper(ps, rs []Point, n int) Circle { rc := make([]Point, len(rs)) copy(rc, rs) if n == 0 || len(rc) == 3 { return secTrivial(rc) } idx := rand.Intn(n) p := ps[idx] ps[idx], ps[n-1] = ps[n-1], p d := welzlHelper(ps, rc, n-1) if d.contains(p) { return d } rc = append(rc, p) return welzlHelper(ps, rc, n-1) } func welzl(ps []Point) Circle { var pc = make([]Point, len(ps)) copy(pc, ps) rand.Shuffle(len(pc), func(i, j int) { pc[i], pc[j] = pc[j], pc[i] }) return welzlHelper(pc, []Point{}, len(pc)) } func main() { rand.Seed(time.Now().UnixNano()) tests := [][]Point{ {Point{0, 0}, Point{0, 1}, Point{1, 0}}, {Point{5, -2}, Point{-3, -2}, Point{-2, 5}, Point{1, 6}, Point{0, 2}}, } for _, test := range tests { fmt.Println(welzl(test)) } }
import numpy as np class ProjectorStack: def __init__(self, vec): self.vs = np.array(vec) def push(self, v): if len(self.vs) == 0: self.vs = np.array([v]) else: self.vs = np.append(self.vs, [v], axis=0) return self def pop(self): if len(self.vs) > 0: ret, self.vs = self.vs[-1], self.vs[:-1] return ret def __mul__(self, v): s = np.zeros(len(v)) for vi in self.vs: s = s + vi * np.dot(vi, v) return s class GaertnerBoundary: def __init__(self, pts): self.projector = ProjectorStack([]) self.centers, self.square_radii = np.array([]), np.array([]) self.empty_center = np.array([np.NaN for _ in pts[0]]) def push_if_stable(bound, pt): if len(bound.centers) == 0: bound.square_radii = np.append(bound.square_radii, 0.0) bound.centers = np.array([pt]) return True q0, center = bound.centers[0], bound.centers[-1] C, r2 = center - q0, bound.square_radii[-1] Qm, M = pt - q0, bound.projector Qm_bar = M * Qm residue, e = Qm - Qm_bar, sqdist(Qm, C) - r2 z, tol = 2 * sqnorm(residue), np.finfo(float).eps * max(r2, 1.0) isstable = np.abs(z) > tol if isstable: center_new = center + (e / z) * residue r2new = r2 + (e * e) / (2 * z) bound.projector.push(residue / np.linalg.norm(residue)) bound.centers = np.append(bound.centers, np.array([center_new]), axis=0) bound.square_radii = np.append(bound.square_radii, r2new) return isstable def pop(bound): n = len(bound.centers) bound.centers = bound.centers[:-1] bound.square_radii = bound.square_radii[:-1] if n >= 2: bound.projector.pop() return bound class NSphere: def __init__(self, c, sqr): self.center = np.array(c) self.sqradius = sqr def isinside(pt, nsphere, atol=1e-6, rtol=0.0): r2, R2 = sqdist(pt, nsphere.center), nsphere.sqradius return r2 <= R2 or np.isclose(r2, R2, atol=atol**2,rtol=rtol**2) def allinside(pts, nsphere, atol=1e-6, rtol=0.0): for p in pts: if not isinside(p, nsphere, atol, rtol): return False return True def move_to_front(pts, i): pt = pts[i] for j in range(len(pts)): pts[j], pt = pt, np.array(pts[j]) if j == i: break return pts def dist(p1, p2): return np.linalg.norm(p1 - p2) def sqdist(p1, p2): return sqnorm(p1 - p2) def sqnorm(p): return np.sum(np.array([x * x for x in p])) def ismaxlength(bound): len(bound.centers) == len(bound.empty_center) + 1 def makeNSphere(bound): if len(bound.centers) == 0: return NSphere(bound.empty_center, 0.0) return NSphere(bound.centers[-1], bound.square_radii[-1]) def _welzl(pts, pos, bdry): support_count, nsphere = 0, makeNSphere(bdry) if ismaxlength(bdry): return nsphere, 0 for i in range(pos): if not isinside(pts[i], nsphere): isstable = push_if_stable(bdry, pts[i]) if isstable: nsphere, s = _welzl(pts, i, bdry) pop(bdry) move_to_front(pts, i) support_count = s + 1 return nsphere, support_count def find_max_excess(nsphere, pts, k1): err_max, k_max = -np.Inf, k1 - 1 for (k, pt) in enumerate(pts[k_max:]): err = sqdist(pt, nsphere.center) - nsphere.sqradius if err > err_max: err_max, k_max = err, k + k1 return err_max, k_max - 1 def welzl(points, maxiterations=2000): pts, eps = np.array(points, copy=True), np.finfo(float).eps bdry, t = GaertnerBoundary(pts), 1 nsphere, s = _welzl(pts, t, bdry) for i in range(maxiterations): e, k = find_max_excess(nsphere, pts, t + 1) if e <= eps: break pt = pts[k] push_if_stable(bdry, pt) nsphere_new, s_new = _welzl(pts, s, bdry) pop(bdry) move_to_front(pts, k) nsphere = nsphere_new t, s = s + 1, s_new + 1 return nsphere if __name__ == '__main__': TESTDATA =[ np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0]]), np.array([[5.0, -2.0], [-3.0, -2.0], [-2.0, 5.0], [1.0, 6.0], [0.0, 2.0]]), np.array([[2.0, 4.0, -1.0], [1.0, 5.0, -3.0], [8.0, -4.0, 1.0], [3.0, 9.0, -5.0]]), np.random.normal(size=(8, 5)) ] for test in TESTDATA: nsphere = welzl(test) print("For points: ", test) print(" Center is at: ", nsphere.center) print(" Radius is: ", np.sqrt(nsphere.sqradius), "\n")
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "strconv" "strings" "unicode/utf8" ) func sign(n int) int { switch { case n < 0: return -1 case n > 0: return 1 } return 0 } func abs(n int) int { if n < 0 { return -n } return n } func parseRange(r string) []string { if r == "" { return []string{"{}"} } sp := strings.Split(r, "..") if len(sp) == 1 { return []string{"{" + r + "}"} } sta := sp[0] end := sp[1] inc := "1" if len(sp) > 2 { inc = sp[2] } n1, ok1 := strconv.Atoi(sta) n2, ok2 := strconv.Atoi(end) n3, ok3 := strconv.Atoi(inc) if ok3 != nil { return []string{"{" + r + "}"} } numeric := (ok1 == nil) && (ok2 == nil) if !numeric { if (ok1 == nil && ok2 != nil) || (ok1 != nil && ok2 == nil) { return []string{"{" + r + "}"} } if utf8.RuneCountInString(sta) != 1 || utf8.RuneCountInString(end) != 1 { return []string{"{" + r + "}"} } n1 = int(([]rune(sta))[0]) n2 = int(([]rune(end))[0]) } width := 1 if numeric { if len(sta) < len(end) { width = len(end) } else { width = len(sta) } } if n3 == 0 { if numeric { return []string{fmt.Sprintf("%0*d", width, n1)} } else { return []string{sta} } } var res []string asc := n1 < n2 if n3 < 0 { asc = !asc t := n1 d := abs(n1-n2) % (-n3) n1 = n2 - d*sign(n2-n1) n2 = t n3 = -n3 } i := n1 if asc { for ; i <= n2; i += n3 { if numeric { res = append(res, fmt.Sprintf("%0*d", width, i)) } else { res = append(res, string(rune(i))) } } } else { for ; i >= n2; i -= n3 { if numeric { res = append(res, fmt.Sprintf("%0*d", width, i)) } else { res = append(res, string(rune(i))) } } } return res } func rangeExpand(s string) []string { res := []string{""} rng := "" inRng := false for _, c := range s { if c == '{' && !inRng { inRng = true rng = "" } else if c == '}' && inRng { rngRes := parseRange(rng) rngLen := len(rngRes) var res2 []string for i := 0; i < len(res); i++ { for j := 0; j < rngLen; j++ { res2 = append(res2, res[i]+rngRes[j]) } } res = res2 inRng = false } else if inRng { rng += string(c) } else { for i := 0; i < len(res); i++ { res[i] += string(c) } } } if inRng { for i := 0; i < len(res); i++ { res[i] += "{" + rng } } return res } func main() { examples := []string{ "simpleNumberRising{1..3}.txt", "simpleAlphaDescending-{Z..X}.txt", "steppedDownAndPadded-{10..00..5}.txt", "minusSignFlipsSequence {030..20..-5}.txt", "reverseSteppedNumberRising{1..6..-2}.txt", "combined-{Q..P}{2..1}.txt", "emoji{🌵..🌶}{🌽..🌾}etc", "li{teral", "rangeless{}empty", "rangeless{random}string", "mixedNumberAlpha{5..k}", "steppedAlphaRising{P..Z..2}.txt", "stops after endpoint-{02..10..3}.txt", "steppedNumberRising{1..6..2}.txt", "steppedNumberDescending{20..9..2}", "steppedAlphaDescending-{Z..M..2}.txt", "reversedSteppedAlphaDescending-{Z..M..-2}.txt", } for _, s := range examples { fmt.Print(s, "->\n ") res := rangeExpand(s) fmt.Println(strings.Join(res, "\n ")) fmt.Println() } }
from __future__ import annotations import itertools import re from abc import ABC from abc import abstractmethod from typing import Iterable from typing import Optional RE_SPEC = [ ( "INT_RANGE", r"\{(?P<int_start>[0-9]+)..(?P<int_stop>[0-9]+)(?:(?:..)?(?P<int_step>-?[0-9]+))?}", ), ( "ORD_RANGE", r"\{(?P<ord_start>[^0-9])..(?P<ord_stop>[^0-9])(?:(?:..)?(?P<ord_step>-?[0-9]+))?}", ), ( "LITERAL", r".+?(?=\{|$)", ), ] RE_EXPRESSION = re.compile( "|".join(rf"(?P<{name}>{pattern})" for name, pattern in RE_SPEC) ) class Expression(ABC): @abstractmethod def expand(self, prefix: str) -> Iterable[str]: pass class Literal(Expression): def __init__(self, value: str): self.value = value def expand(self, prefix: str) -> Iterable[str]: return [f"{prefix}{self.value}"] class IntRange(Expression): def __init__( self, start: int, stop: int, step: Optional[int] = None, zfill: int = 0 ): self.start, self.stop, self.step = fix_range(start, stop, step) self.zfill = zfill def expand(self, prefix: str) -> Iterable[str]: return ( f"{prefix}{str(i).zfill(self.zfill)}" for i in range(self.start, self.stop, self.step) ) class OrdRange(Expression): def __init__(self, start: str, stop: str, step: Optional[int] = None): self.start, self.stop, self.step = fix_range(ord(start), ord(stop), step) def expand(self, prefix: str) -> Iterable[str]: return (f"{prefix}{chr(i)}" for i in range(self.start, self.stop, self.step)) def expand(expressions: Iterable[Expression]) -> Iterable[str]: expanded = [""] for expression in expressions: expanded = itertools.chain.from_iterable( [expression.expand(prefix) for prefix in expanded] ) return expanded def zero_fill(start, stop) -> int: def _zfill(s): if len(s) <= 1 or not s.startswith("0"): return 0 return len(s) return max(_zfill(start), _zfill(stop)) def fix_range(start, stop, step): if not step: if start <= stop: step = 1 else: step = -1 elif step < 0: start, stop = stop, start if start < stop: step = abs(step) else: start -= 1 stop -= 1 elif start > stop: step = -step if (start - stop) % step == 0: stop += step return start, stop, step def parse(expression: str) -> Iterable[Expression]: for match in RE_EXPRESSION.finditer(expression): kind = match.lastgroup if kind == "INT_RANGE": start = match.group("int_start") stop = match.group("int_stop") step = match.group("int_step") zfill = zero_fill(start, stop) if step is not None: step = int(step) yield IntRange(int(start), int(stop), step, zfill=zfill) elif kind == "ORD_RANGE": start = match.group("ord_start") stop = match.group("ord_stop") step = match.group("ord_step") if step is not None: step = int(step) yield OrdRange(start, stop, step) elif kind == "LITERAL": yield Literal(match.group()) def examples(): cases = [ r"simpleNumberRising{1..3}.txt", r"simpleAlphaDescending-{Z..X}.txt", r"steppedDownAndPadded-{10..00..5}.txt", r"minusSignFlipsSequence {030..20..-5}.txt", r"reverseSteppedNumberRising{1..6..-2}.txt", r"combined-{Q..P}{2..1}.txt", r"emoji{🌵..🌶}{🌽..🌾}etc", r"li{teral", r"rangeless{}empty", r"rangeless{random}string", r"steppedNumberRising{1..6..2}.txt", r"steppedNumberDescending{20..9..2}.txt", r"steppedAlphaDescending-{Z..M..2}.txt", r"reverseSteppedAlphaRising{A..F..-2}.txt", r"reversedSteppedAlphaDescending-{Z..M..-2}.txt", ] for case in cases: print(f"{case} ->") expressions = parse(case) for itm in expand(expressions): print(f"{' '*4}{itm}") print("") if __name__ == "__main__": examples()