Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "encoding/binary" "log" "math" "os" "strings" ) func main() { const ( sampleRate = 44100 duration = 8 dataLength = sampleRate * duration hdrSize = 44 fileLen = dataLength + hdrSize - 8 ) buf1 := make([]byte, 1) buf2 := make([]byte, 2) buf4 := make([]byte, 4) var sb strings.Builder sb.WriteString("RIFF") binary.LittleEndian.PutUint32(buf4, fileLen) sb.Write(buf4) sb.WriteString("WAVE") sb.WriteString("fmt ") binary.LittleEndian.PutUint32(buf4, 16) sb.Write(buf4) binary.LittleEndian.PutUint16(buf2, 1) sb.Write(buf2) sb.Write(buf2) binary.LittleEndian.PutUint32(buf4, sampleRate) sb.Write(buf4) sb.Write(buf4) sb.Write(buf2) binary.LittleEndian.PutUint16(buf2, 8) sb.Write(buf2) sb.WriteString("data") binary.LittleEndian.PutUint32(buf4, dataLength) sb.Write(buf4) wavhdr := []byte(sb.String()) f, err := os.Create("notes.wav") if err != nil { log.Fatal(err) } defer f.Close() f.Write(wavhdr) freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3} for j := 0; j < duration; j++ { freq := freqs[j] omega := 2 * math.Pi * freq for i := 0; i < dataLength/duration; i++ { y := 32 * math.Sin(omega*float64(i)/float64(sampleRate)) buf1[0] = byte(math.Round(y)) f.Write(buf1) } } }
>>> import winsound >>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]: winsound.Beep(int(note+.5), 500) >>>
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import "fmt" type item struct { string w, v int } var wants = []item{ {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, 60}, {"tin", 68, 45}, {"banana", 27, 60}, {"apple", 39, 40}, {"cheese", 23, 30}, {"beer", 52, 10}, {"suntan cream", 11, 70}, {"camera", 32, 30}, {"T-shirt", 24, 15}, {"trousers", 48, 10}, {"umbrella", 73, 40}, {"waterproof trousers", 42, 70}, {"waterproof overclothes", 43, 75}, {"note-case", 22, 80}, {"sunglasses", 7, 20}, {"towel", 18, 12}, {"socks", 4, 50}, {"book", 30, 10}, } const maxWt = 400 func main() { items, w, v := m(len(wants)-1, maxWt) fmt.Println(items) fmt.Println("weight:", w) fmt.Println("value:", v) } func m(i, w int) ([]string, int, int) { if i < 0 || w == 0 { return nil, 0, 0 } else if wants[i].w > w { return m(i-1, w) } i0, w0, v0 := m(i-1, w) i1, w1, v1 := m(i-1, w-wants[i].w) v1 += wants[i].v if v1 > v0 { return append(i1, wants[i].string), w1 + wants[i].w, v1 } return i0, w0, v0 }
from itertools import combinations def anycomb(items): ' return combinations of any length from the items ' return ( comb for r in range(1, len(items)+1) for comb in combinations(items, r) ) def totalvalue(comb): ' Totalise a particular combination of items' totwt = totval = 0 for item, wt, val in comb: totwt += wt totval += val return (totval, -totwt) if totwt <= 400 else (0, 0) items = ( ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160), ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40), ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30), ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40), ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75), ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12), ("socks", 4, 50), ("book", 30, 10), ) bagged = max( anycomb(items), key=totalvalue) print("Bagged the following items\n " + '\n '.join(sorted(item for item,_,_ in bagged))) val, wt = totalvalue(bagged) print("for a total value of %i and a total weight of %i" % (val, -wt))
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "sort" ) func getPrimes(max int) []int { if max < 2 { return []int{} } lprimes := []int{2} outer: for x := 3; x <= max; x += 2 { for _, p := range lprimes { if x%p == 0 { continue outer } } lprimes = append(lprimes, x) } return lprimes } func main() { const maxSum = 99 descendants := make([][]int64, maxSum+1) ancestors := make([][]int, maxSum+1) for i := 0; i <= maxSum; i++ { descendants[i] = []int64{} ancestors[i] = []int{} } primes := getPrimes(maxSum) for _, p := range primes { descendants[p] = append(descendants[p], int64(p)) for s := 1; s < len(descendants)-p; s++ { temp := make([]int64, len(descendants[s])) for i := 0; i < len(descendants[s]); i++ { temp[i] = int64(p) * descendants[s][i] } descendants[s+p] = append(descendants[s+p], temp...) } } for _, p := range append(primes, 4) { le := len(descendants[p]) if le == 0 { continue } descendants[p][le-1] = 0 descendants[p] = descendants[p][:le-1] } total := 0 for s := 1; s <= maxSum; s++ { x := descendants[s] sort.Slice(x, func(i, j int) bool { return x[i] < x[j] }) total += len(descendants[s]) index := 0 for ; index < len(descendants[s]); index++ { if descendants[s][index] > int64(maxSum) { break } } for _, d := range descendants[s][:index] { ancestors[d] = append(ancestors[s], s) } if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) { continue } temp := fmt.Sprintf("%v", ancestors[s]) fmt.Printf("%2d: %d Ancestor(s): %-14s", s, len(ancestors[s]), temp) le := len(descendants[s]) if le <= 10 { fmt.Printf("%5d Descendant(s): %v\n", le, descendants[s]) } else { fmt.Printf("%5d Descendant(s): %v\b ...]\n", le, descendants[s][:10]) } } fmt.Println("\nTotal descendants", total) }
from __future__ import print_function from itertools import takewhile maxsum = 99 def get_primes(max): if max < 2: return [] lprimes = [2] for x in range(3, max + 1, 2): for p in lprimes: if x % p == 0: break else: lprimes.append(x) return lprimes descendants = [[] for _ in range(maxsum + 1)] ancestors = [[] for _ in range(maxsum + 1)] primes = get_primes(maxsum) for p in primes: descendants[p].append(p) for s in range(1, len(descendants) - p): descendants[s + p] += [p * pr for pr in descendants[s]] for p in primes + [4]: descendants[p].pop() total = 0 for s in range(1, maxsum + 1): descendants[s].sort() for d in takewhile(lambda x: x <= maxsum, descendants[s]): ancestors[d] = ancestors[s] + [s] print([s], "Level:", len(ancestors[s])) print("Ancestors:", ancestors[s] if len(ancestors[s]) else "None") print("Descendants:", len(descendants[s]) if len(descendants[s]) else "None") if len(descendants[s]): print(descendants[s]) print() total += len(descendants[s]) print("Total descendants", total)
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import "fmt" type pair [2]int func cart2(a, b []int) []pair { p := make([]pair, len(a)*len(b)) i := 0 for _, a := range a { for _, b := range b { p[i] = pair{a, b} i++ } } return p } func main() { fmt.Println(cart2([]int{1, 2}, []int{3, 4})) fmt.Println(cart2([]int{3, 4}, []int{1, 2})) fmt.Println(cart2([]int{1, 2}, nil)) fmt.Println(cart2(nil, []int{1, 2})) }
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
Convert this Go block to Python, preserving its control flow and logic.
package main import "fmt" type pair [2]int func cart2(a, b []int) []pair { p := make([]pair, len(a)*len(b)) i := 0 for _, a := range a { for _, b := range b { p[i] = pair{a, b} i++ } } return p } func main() { fmt.Println(cart2([]int{1, 2}, []int{3, 4})) fmt.Println(cart2([]int{3, 4}, []int{1, 2})) fmt.Println(cart2([]int{1, 2}, nil)) fmt.Println(cart2(nil, []int{1, 2})) }
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
Change the following Go code into Python without altering its purpose.
package main import "fmt" type pair [2]int func cart2(a, b []int) []pair { p := make([]pair, len(a)*len(b)) i := 0 for _, a := range a { for _, b := range b { p[i] = pair{a, b} i++ } } return p } func main() { fmt.Println(cart2([]int{1, 2}, []int{3, 4})) fmt.Println(cart2([]int{3, 4}, []int{1, 2})) fmt.Println(cart2([]int{1, 2}, nil)) fmt.Println(cart2(nil, []int{1, 2})) }
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import "math" import "fmt" func cube(x float64) float64 { return math.Pow(x, 3) } type ffType func(float64) float64 func compose(f, g ffType) ffType { return func(x float64) float64 { return f(g(x)) } } func main() { funclist := []ffType{math.Sin, math.Cos, cube} funclisti := []ffType{math.Asin, math.Acos, math.Cbrt} for i := 0; i < 3; i++ { fmt.Println(compose(funclisti[i], funclist[i])(.5)) } }
>>> >>> from math import sin, cos, acos, asin >>> >>> cube = lambda x: x * x * x >>> croot = lambda x: x ** (1/3.0) >>> >>> >>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) ) >>> >>> funclist = [sin, cos, cube] >>> funclisti = [asin, acos, croot] >>> >>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)] [0.5, 0.4999999999999999, 0.5] >>>
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "strconv" ) func listProperDivisors(limit int) { if limit < 1 { return } width := len(strconv.Itoa(limit)) for i := 1; i <= limit; i++ { fmt.Printf("%*d -> ", width, i) if i == 1 { fmt.Println("(None)") continue } for j := 1; j <= i/2; j++ { if i%j == 0 { fmt.Printf(" %d", j) } } fmt.Println() } } func countProperDivisors(n int) int { if n < 2 { return 0 } count := 0 for i := 1; i <= n/2; i++ { if n%i == 0 { count++ } } return count } func main() { fmt.Println("The proper divisors of the following numbers are :\n") listProperDivisors(10) fmt.Println() maxCount := 0 most := []int{1} for n := 2; n <= 20000; n++ { count := countProperDivisors(n) if count == maxCount { most = append(most, n) } else if count > maxCount { maxCount = count most = most[0:1] most[0] = n } } fmt.Print("The following number(s) <= 20000 have the most proper divisors, ") fmt.Println("namely", maxCount, "\b\n") for _, n := range most { fmt.Println(n) } }
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x} ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "encoding/xml" "fmt" ) func xRemarks(r CharacterRemarks) (string, error) { b, err := xml.MarshalIndent(r, "", " ") return string(b), err } type CharacterRemarks struct { Character []crm } type crm struct { Name string `xml:"name,attr"` Remark string `xml:",chardata"` } func main() { x, err := xRemarks(CharacterRemarks{[]crm{ {`April`, `Bubbly: I'm > Tam and <= Emily`}, {`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`}, {`Emily`, `Short & shrift`}, }}) if err != nil { x = err.Error() } fmt.Println(x) }
>>> from xml.etree import ElementTree as ET >>> from itertools import izip >>> def characterstoxml(names, remarks): root = ET.Element("CharacterRemarks") for name, remark in izip(names, remarks): c = ET.SubElement(root, "Character", {'name': name}) c.text = remark return ET.tostring(root) >>> print characterstoxml( names = ["April", "Tam O'Shanter", "Emily"], remarks = [ "Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', 'Short & shrift' ] ).replace('><','>\n<')
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "log" "os/exec" ) var ( x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0} ) func main() { g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() if err != nil { log.Fatal(err) } if err = g.Start(); err != nil { log.Fatal(err) } fmt.Fprintln(w, "unset key; plot '-'") for i, xi := range x { fmt.Fprintf(w, "%d %f\n", xi, y[i]) } fmt.Fprintln(w, "e") w.Close() g.Wait() }
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] >>> import pylab >>> pylab.plot(x, y, 'bo') >>> pylab.savefig('qsort-range-10-9.png')
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "log" "os/exec" ) var ( x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0} ) func main() { g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() if err != nil { log.Fatal(err) } if err = g.Start(); err != nil { log.Fatal(err) } fmt.Fprintln(w, "unset key; plot '-'") for i, xi := range x { fmt.Fprintf(w, "%d %f\n", xi, y[i]) } fmt.Fprintln(w, "e") w.Close() g.Wait() }
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] >>> import pylab >>> pylab.plot(x, y, 'bo') >>> pylab.savefig('qsort-range-10-9.png')
Port the following code from Go to Python with equivalent syntax and logic.
package main import "fmt" import "regexp" func main() { str := "I am the original string" matched, _ := regexp.MatchString(".*string$", str) if matched { fmt.Println("ends with 'string'") } pattern := regexp.MustCompile("original") result := pattern.ReplaceAllString(str, "modified") fmt.Println(result) }
import re string = "This is a string" if re.search('string$', string): print("Ends with string.") string = re.sub(" a ", " another ", string) print(string)
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "sort" ) func main() { lower, upper := 0, 100 fmt.Printf(`Instructions: Think of integer number from %d (inclusive) to %d (exclusive) and I will guess it. After each guess, I will ask you if it is less than or equal to some number, and you will respond with "yes" or "no". `, lower, upper) answer := sort.Search(upper-lower, func (i int) bool { fmt.Printf("Is your number less than or equal to %d? ", lower+i) s := "" fmt.Scanf("%s", &s) return s != "" && s[0] == 'y' }) fmt.Printf("Your number is %d.\n", lower+answer) }
inclusive_range = mn, mx = (1, 10) print( % inclusive_range) i = 0 while True: i += 1 guess = (mn+mx)//2 txt = input("Guess %2i is: %2i. The score for which is (h,l,=): " % (i, guess)).strip().lower()[0] if txt not in 'hl=': print(" I don't understand your input of '%s' ?" % txt) continue if txt == 'h': mx = guess-1 if txt == 'l': mn = guess+1 if txt == '=': print(" Ye-Haw!!") break if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]): print("Please check your scoring as I cannot find the value") break print("\nThanks for keeping score.")
Change the following Go code into Python without altering its purpose.
package main import "fmt" func main() { keys := []string{"a", "b", "c"} vals := []int{1, 2, 3} hash := map[string]int{} for i, key := range keys { hash[key] = vals[i] } fmt.Println(hash) }
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = {key: value for key, value in zip(keys, values)}
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "sort" ) func getBins(limits, data []int) []int { n := len(limits) bins := make([]int, n+1) for _, d := range data { index := sort.SearchInts(limits, d) if index < len(limits) && d == limits[index] { index++ } bins[index]++ } return bins } func printBins(limits, bins []int) { n := len(limits) fmt.Printf(" < %3d = %2d\n", limits[0], bins[0]) for i := 1; i < n; i++ { fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i]) } fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n]) fmt.Println() } func main() { limitsList := [][]int{ {23, 37, 43, 53, 67, 83}, {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}, } dataList := [][]int{ { 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55, }, { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749, }, } for i := 0; i < len(limitsList); i++ { fmt.Println("Example", i+1, "\b\n") bins := getBins(limitsList[i], dataList[i]) printBins(limitsList[i], bins) } }
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}") if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "sort" ) func getBins(limits, data []int) []int { n := len(limits) bins := make([]int, n+1) for _, d := range data { index := sort.SearchInts(limits, d) if index < len(limits) && d == limits[index] { index++ } bins[index]++ } return bins } func printBins(limits, bins []int) { n := len(limits) fmt.Printf(" < %3d = %2d\n", limits[0], bins[0]) for i := 1; i < n; i++ { fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i]) } fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n]) fmt.Println() } func main() { limitsList := [][]int{ {23, 37, 43, 53, 67, 83}, {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}, } dataList := [][]int{ { 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55, }, { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749, }, } for i := 0; i < len(limitsList); i++ { fmt.Println("Example", i+1, "\b\n") bins := getBins(limitsList[i], dataList[i]) printBins(limitsList[i], bins) } }
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}") if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
Change the following Go code into Python without altering its purpose.
package main import ( "math" "raster" ) const ( width = 400 height = 300 depth = 8 angle = 12 length = 50 frac = .8 ) func main() { g := raster.NewGrmap(width, height) ftree(g, width/2, height*9/10, length, 0, depth) g.Bitmap().WritePpmFile("ftree.ppm") } func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) { x2 := x + distance*math.Sin(direction*math.Pi/180) y2 := y - distance*math.Cos(direction*math.Pi/180) g.AaLine(x, y, x2, y2) if depth > 0 { ftree(g, x2, y2, distance*frac, direction-angle, depth-1) ftree(g, x2, y2, distance*frac, direction+angle, depth-1) } }
def setup(): size(600, 600) background(0) stroke(255) drawTree(300, 550, 9) def drawTree(x, y, depth): fork_ang = radians(20) base_len = 10 if depth > 0: pushMatrix() translate(x, y - baseLen * depth) line(0, baseLen * depth, 0, 0) rotate(fork_ang) drawTree(0, 0, depth - 1) rotate(2 * -fork_ang) drawTree(0, 0, depth - 1) popMatrix()
Generate an equivalent Python version of this Go code.
package main import "github.com/fogleman/gg" var palette = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func pinstripe(dc *gg.Context) { w := dc.Width() h := dc.Height() / 4 for b := 1; b <= 4; b++ { for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 { dc.SetHexColor(palette[ci%8]) y := h * (b - 1) dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h)) dc.Fill() } } } func main() { dc := gg.NewContext(900, 600) pinstripe(dc) dc.SavePNG("color_pinstripe.png") }
from turtle import * colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"] screen = getscreen() left_edge = -screen.window_width()//2 right_edge = screen.window_width()//2 quarter_height = screen.window_height()//4 half_height = quarter_height * 2 speed("fastest") for quarter in range(4): pensize(quarter+1) colornum = 0 min_y = half_height - ((quarter + 1) * quarter_height) max_y = half_height - ((quarter) * quarter_height) for x in range(left_edge,right_edge,quarter+1): penup() pencolor(colors[colornum]) colornum = (colornum + 1) % len(colors) setposition(x,min_y) pendown() setposition(x,max_y) notused = input("Hit enter to continue: ")
Write the same code in Python as shown below in Go.
package main import ( "fmt" "strconv" ) var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} func anchorDay(y int) int { return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7 } func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) } var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} func main() { dates := []string{ "1800-01-06", "1875-03-29", "1915-12-07", "1970-12-23", "2043-05-14", "2077-02-12", "2101-04-02", } fmt.Println("Days of week given by Doomsday rule:") for _, date := range dates { y, _ := strconv.Atoi(date[0:4]) m, _ := strconv.Atoi(date[5:7]) m-- d, _ := strconv.Atoi(date[8:10]) a := anchorDay(y) f := firstDaysCommon[m] if isLeapYear(y) { f = firstDaysLeap[m] } w := d - f if w < 0 { w = 7 + w } dow := (a + w) % 7 fmt.Printf("%s -> %s\n", date, days[dow]) } }
from datetime import date from calendar import isleap def weekday(d): days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] dooms = [ [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5], [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] ] c = d.year // 100 r = d.year % 100 s = r // 12 t = r % 12 c_anchor = (5 * (c % 4) + 2) % 7 doomsday = (s + t + (t // 4) + c_anchor) % 7 anchorday = dooms[isleap(d.year)][d.month - 1] weekday = (doomsday + d.day - anchorday + 7) % 7 return days[weekday] dates = [date(*x) for x in [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23), (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)] ] for d in dates: tense = "was" if d < date.today() else "is" if d == date.today() else "will be" print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "strconv" ) var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} func anchorDay(y int) int { return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7 } func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) } var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} func main() { dates := []string{ "1800-01-06", "1875-03-29", "1915-12-07", "1970-12-23", "2043-05-14", "2077-02-12", "2101-04-02", } fmt.Println("Days of week given by Doomsday rule:") for _, date := range dates { y, _ := strconv.Atoi(date[0:4]) m, _ := strconv.Atoi(date[5:7]) m-- d, _ := strconv.Atoi(date[8:10]) a := anchorDay(y) f := firstDaysCommon[m] if isLeapYear(y) { f = firstDaysLeap[m] } w := d - f if w < 0 { w = 7 + w } dow := (a + w) % 7 fmt.Printf("%s -> %s\n", date, days[dow]) } }
from datetime import date from calendar import isleap def weekday(d): days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] dooms = [ [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5], [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] ] c = d.year // 100 r = d.year % 100 s = r // 12 t = r % 12 c_anchor = (5 * (c % 4) + 2) % 7 doomsday = (s + t + (t // 4) + c_anchor) % 7 anchorday = dooms[isleap(d.year)][d.month - 1] weekday = (doomsday + d.day - anchorday + 7) % 7 return days[weekday] dates = [date(*x) for x in [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23), (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)] ] for d in dates: tense = "was" if d < date.today() else "is" if d == date.today() else "will be" print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math/rand" "time" ) func cocktailShakerSort(a []int) { var begin = 0 var end = len(a) - 2 for begin <= end { newBegin := end newEnd := begin for i := begin; i <= end; i++ { if a[i] > a[i+1] { a[i+1], a[i] = a[i], a[i+1] newEnd = i } } end = newEnd - 1 for i := end; i >= begin; i-- { if a[i] > a[i+1] { a[i+1], a[i] = a[i], a[i+1] newBegin = i } } begin = newBegin + 1 } } func cocktailSort(a []int) { last := len(a) - 1 for { swapped := false for i := 0; i < last; i++ { if a[i] > a[i+1] { a[i], a[i+1] = a[i+1], a[i] swapped = true } } if !swapped { return } swapped = false for i := last - 1; i >= 0; i-- { if a[i] > a[i+1] { a[i], a[i+1] = a[i+1], a[i] swapped = true } } if !swapped { return } } } func main() { a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170} fmt.Println("Original array:", a) b := make([]int, len(a)) copy(b, a) cocktailSort(a) fmt.Println("Cocktail sort :", a) cocktailShakerSort(b) fmt.Println("C/Shaker sort :", b) rand.Seed(time.Now().UnixNano()) fmt.Println("\nRelative speed of the two sorts") fmt.Println(" N x faster (CSS v CS)") fmt.Println("----- -------------------") const runs = 10 for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} { sum := 0.0 for i := 1; i <= runs; i++ { nums := make([]int, n) for i := 0; i < n; i++ { rn := rand.Intn(100000) if i%2 == 1 { rn = -rn } nums[i] = rn } nums2 := make([]int, n) copy(nums2, nums) start := time.Now() cocktailSort(nums) elapsed := time.Since(start) start2 := time.Now() cocktailShakerSort(nums2) elapsed2 := time.Since(start2) sum += float64(elapsed) / float64(elapsed2) } fmt.Printf(" %2dk %0.3f\n", n/1000, sum/runs) } }
def cocktailshiftingbounds(A): beginIdx = 0 endIdx = len(A) - 1 while beginIdx <= endIdx: newBeginIdx = endIdx newEndIdx = beginIdx for ii in range(beginIdx,endIdx): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newEndIdx = ii endIdx = newEndIdx for ii in range(endIdx,beginIdx-1,-1): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newBeginIdx = ii beginIdx = newBeginIdx + 1 test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] cocktailshiftingbounds(test1) print(test1) test2=list('big fjords vex quick waltz nymph') cocktailshiftingbounds(test2) print(''.join(test2))
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "github.com/google/gxui" "github.com/google/gxui/drivers/gl" "github.com/google/gxui/math" "github.com/google/gxui/themes/dark" omath "math" "time" ) const ( ANIMATION_WIDTH int = 480 ANIMATION_HEIGHT int = 320 BALL_RADIUS float32 = 25.0 METER_PER_PIXEL float64 = 1.0 / 20.0 PHI_ZERO float64 = omath.Pi * 0.5 ) var ( l float64 = float64(ANIMATION_HEIGHT) * 0.5 freq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL)) ) type Pendulum interface { GetPhi() float64 } type mathematicalPendulum struct { start time.Time } func (p *mathematicalPendulum) GetPhi() float64 { if (p.start == time.Time{}) { p.start = time.Now() } t := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9) return PHI_ZERO * omath.Cos(t*freq) } type numericalPendulum struct { currentPhi float64 angAcc float64 angVel float64 lastTime time.Time } func (p *numericalPendulum) GetPhi() float64 { dt := 0.0 if (p.lastTime != time.Time{}) { dt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9) } p.lastTime = time.Now() p.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi) p.angVel += p.angAcc * dt p.currentPhi += p.angVel * dt return p.currentPhi } func draw(p Pendulum, canvas gxui.Canvas, x, y int) { attachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y} phi := p.GetPhi() ball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))} line := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}} canvas.DrawLines(line, gxui.DefaultPen) m := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)} rect := math.Rect{ball.Sub(m), ball.Add(m)} canvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow)) } func appMain(driver gxui.Driver) { theme := dark.CreateTheme(driver) window := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, "Pendulum") window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50)) image := theme.CreateImage() ticker := time.NewTicker(time.Millisecond * 15) pendulum := &mathematicalPendulum{} pendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}} go func() { for _ = range ticker.C { canvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT}) canvas.Clear(gxui.White) draw(pendulum, canvas, 0, 0) draw(pendulum2, canvas, 0, ANIMATION_HEIGHT) canvas.Complete() driver.Call(func() { image.SetCanvas(canvas) }) } }() window.AddChild(image) window.OnClose(ticker.Stop) window.OnClose(driver.Terminate) } func main() { gl.StartDriver(appMain) }
import pygame, sys from pygame.locals import * from math import sin, cos, radians pygame.init() WINDOWSIZE = 250 TIMETICK = 100 BOBSIZE = 15 window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE)) pygame.display.set_caption("Pendulum") screen = pygame.display.get_surface() screen.fill((255,255,255)) PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10) SWINGLENGTH = PIVOT[1]*4 class BobMass(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.theta = 45 self.dtheta = 0 self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)), PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)), 1,1) self.draw() def recomputeAngle(self): scaling = 3000.0/(SWINGLENGTH**2) firstDDtheta = -sin(radians(self.theta))*scaling midDtheta = self.dtheta + firstDDtheta midtheta = self.theta + (self.dtheta + midDtheta)/2.0 midDDtheta = -sin(radians(midtheta))*scaling midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2 midtheta = self.theta + (self.dtheta + midDtheta)/2 midDDtheta = -sin(radians(midtheta)) * scaling lastDtheta = midDtheta + midDDtheta lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 lastDDtheta = -sin(radians(lasttheta)) * scaling lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0 lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 self.dtheta = lastDtheta self.theta = lasttheta self.rect = pygame.Rect(PIVOT[0]- SWINGLENGTH*sin(radians(self.theta)), PIVOT[1]+ SWINGLENGTH*cos(radians(self.theta)),1,1) def draw(self): pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0) pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0) pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center) pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1])) def update(self): self.recomputeAngle() screen.fill((255,255,255)) self.draw() bob = BobMass() TICK = USEREVENT + 2 pygame.time.set_timer(TICK, TIMETICK) def input(events): for event in events: if event.type == QUIT: sys.exit(0) elif event.type == TICK: bob.update() while True: input(pygame.event.get()) pygame.display.flip()
Convert this Go snippet to Python and keep its semantics consistent.
package main import "fmt" func enc(b int) int { return b ^ b>>1 } func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return } func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) } }
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import "fmt" func enc(b int) int { return b ^ b>>1 } func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return } func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) } }
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import "fmt" func enc(b int) int { return b ^ b>>1 } func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return } func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) } }
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "archive/tar" "compress/gzip" "flag" "io" "log" "os" "time" ) func main() { filename := flag.String("file", "TAPE.FILE", "filename within TAR") data := flag.String("data", "", "data for file") outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)") gzipFlag := flag.Bool("gzip", false, "use gzip compression") flag.Parse() var w io.Writer = os.Stdout if *outfile != "" { f, err := os.Create(*outfile) if err != nil { log.Fatalf("opening/creating %q: %v", *outfile, err) } defer f.Close() w = f } if *gzipFlag { zw := gzip.NewWriter(w) defer zw.Close() w = zw } tw := tar.NewWriter(w) defer tw.Close() w = tw tw.WriteHeader(&tar.Header{ Name: *filename, Mode: 0660, Size: int64(len(*data)), ModTime: time.Now(), Typeflag: tar.TypeReg, Uname: "guest", Gname: "guest", }) _, err := w.Write([]byte(*data)) if err != nil { log.Fatal("writing data:", err) } }
>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n') ... >>>
Keep all operations the same but rewrite the snippet in Python.
package main import ( "archive/tar" "compress/gzip" "flag" "io" "log" "os" "time" ) func main() { filename := flag.String("file", "TAPE.FILE", "filename within TAR") data := flag.String("data", "", "data for file") outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)") gzipFlag := flag.Bool("gzip", false, "use gzip compression") flag.Parse() var w io.Writer = os.Stdout if *outfile != "" { f, err := os.Create(*outfile) if err != nil { log.Fatalf("opening/creating %q: %v", *outfile, err) } defer f.Close() w = f } if *gzipFlag { zw := gzip.NewWriter(w) defer zw.Close() w = zw } tw := tar.NewWriter(w) defer tw.Close() w = tw tw.WriteHeader(&tar.Header{ Name: *filename, Mode: 0660, Size: int64(len(*data)), ModTime: time.Now(), Typeflag: tar.TypeReg, Uname: "guest", Gname: "guest", }) _, err := w.Write([]byte(*data)) if err != nil { log.Fatal("writing data:", err) } }
>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n') ... >>>
Port the provided Go code into Python while preserving the original functionality.
package main import ( "sort" "container/heap" "fmt" ) type HeapHelper struct { container sort.Interface length int } func (self HeapHelper) Len() int { return self.length } func (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) } func (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) } func (self *HeapHelper) Push(x interface{}) { panic("impossible") } func (self *HeapHelper) Pop() interface{} { self.length-- return nil } func heapSort(a sort.Interface) { helper := HeapHelper{ a, a.Len() } heap.Init(&helper) for helper.length > 0 { heap.Pop(&helper) } } func main() { a := []int{170, 45, 75, -90, -802, 24, 2, 66} fmt.Println("before:", a) heapSort(sort.IntSlice(a)) fmt.Println("after: ", a) }
def heapsort(lst): for start in range((len(lst)-2)/2, -1, -1): siftdown(lst, start, len(lst)-1) for end in range(len(lst)-1, 0, -1): lst[end], lst[0] = lst[0], lst[end] siftdown(lst, 0, end - 1) return lst def siftdown(lst, start, end): root = start while True: child = root * 2 + 1 if child > end: break if child + 1 <= end and lst[child] < lst[child + 1]: child += 1 if lst[root] < lst[child]: lst[root], lst[child] = lst[child], lst[root] root = child else: break
Port the provided Go code into Python while preserving the original functionality.
package cards import ( "math/rand" ) type Suit uint8 const ( Spade Suit = 3 Heart Suit = 2 Diamond Suit = 1 Club Suit = 0 ) func (s Suit) String() string { const suites = "CDHS" return suites[s : s+1] } type Rank uint8 const ( Ace Rank = 1 Two Rank = 2 Three Rank = 3 Four Rank = 4 Five Rank = 5 Six Rank = 6 Seven Rank = 7 Eight Rank = 8 Nine Rank = 9 Ten Rank = 10 Jack Rank = 11 Queen Rank = 12 King Rank = 13 ) func (r Rank) String() string { const ranks = "A23456789TJQK" return ranks[r-1 : r] } type Card uint8 func NewCard(r Rank, s Suit) Card { return Card(13*uint8(s) + uint8(r-1)) } func (c Card) RankSuit() (Rank, Suit) { return Rank(c%13 + 1), Suit(c / 13) } func (c Card) Rank() Rank { return Rank(c%13 + 1) } func (c Card) Suit() Suit { return Suit(c / 13) } func (c Card) String() string { return c.Rank().String() + c.Suit().String() } type Deck []Card func NewDeck() Deck { d := make(Deck, 52) for i := range d { d[i] = Card(i) } return d } func (d Deck) String() string { s := "" for i, c := range d { switch { case i == 0: case i%13 == 0: s += "\n" default: s += " " } s += c.String() } return s } func (d Deck) Shuffle() { for i := range d { j := rand.Intn(i + 1) d[i], d[j] = d[j], d[i] } } func (d Deck) Contains(tc Card) bool { for _, c := range d { if c == tc { return true } } return false } func (d *Deck) AddDeck(decks ...Deck) { for _, o := range decks { *d = append(*d, o...) } } func (d *Deck) AddCard(c Card) { *d = append(*d, c) } func (d *Deck) Draw(n int) Deck { old := *d *d = old[n:] return old[:n:n] } func (d *Deck) DrawCard() (Card, bool) { if len(*d) == 0 { return 0, false } old := *d *d = old[1:] return old[0], true } func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) { for i := 0; i < cards; i++ { for j := range hands { if len(*d) == 0 { return hands, false } hands[j] = append(hands[j], (*d)[0]) *d = (*d)[1:] } } return hands, true }
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" ) func main() { var a [5]int fmt.Println("len(a) =", len(a)) fmt.Println("a =", a) a[0] = 3 fmt.Println("a =", a) fmt.Println("a[0] =", a[0]) s := a[:4] fmt.Println("s =", s) fmt.Println("len(s) =", len(s), " cap(s) =", cap(s)) s = s[:5] fmt.Println("s =", s) a[0] = 22 fmt.Println("a =", a) fmt.Println("s =", s) s = append(s, 4, 5, 6) fmt.Println("s =", s) fmt.Println("len(s) =", len(s), " cap(s) =", cap(s)) a[4] = -1 fmt.Println("a =", a) fmt.Println("s =", s) s = make([]int, 8) fmt.Println("s =", s) fmt.Println("len(s) =", len(s), " cap(s) =", cap(s)) }
array = [] array.append(1) array.append(3) array[0] = 2 print array[0]
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "strings" "unicode/utf8" ) var order = 3 var grain = "#" func main() { carpet := []string{grain} for ; order > 0; order-- { hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0])) middle := make([]string, len(carpet)) for i, s := range carpet { middle[i] = s + hole + s carpet[i] = strings.Repeat(s, 3) } carpet = append(append(carpet, middle...), carpet...) } for _, r := range carpet { fmt.Println(r) } }
def setup(): size(729, 729) fill(0) background(255) noStroke() rect(width / 3, height / 3, width / 3, width / 3) rectangles(width / 3, height / 3, width / 3) def rectangles(x, y, s): if s < 1: return xc, yc = x - s, y - s for row in range(3): for col in range(3): if not (row == 1 and col == 1): xx, yy = xc + row * s, yc + col * s delta = s / 3 rect(xx + delta, yy + delta, delta, delta) rectangles(xx + s / 3, yy + s / 3, s / 3)
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "math/rand" "sort" "time" ) func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} rand.Seed(time.Now().UnixNano()) fmt.Println("unsorted:", list) temp := make([]int, len(list)) copy(temp, list) for !sort.IntsAreSorted(temp) { for i, v := range rand.Perm(len(list)) { temp[i] = list[v] } } fmt.Println("sorted! ", temp) }
import random def bogosort(l): while not in_order(l): random.shuffle(l) return l def in_order(l): if not l: return True last = l[0] for x in l[1:]: if x < last: return False last = x return True
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "math" "sort" ) type Patient struct { id int lastName string } var patientDir = make(map[int]string) var patientIds []int func patientNew(id int, lastName string) Patient { patientDir[id] = lastName patientIds = append(patientIds, id) sort.Ints(patientIds) return Patient{id, lastName} } type DS struct { dates []string scores []float64 } type Visit struct { id int date string score float64 } var visitDir = make(map[int]DS) func visitNew(id int, date string, score float64) Visit { if date == "" { date = "0000-00-00" } v, ok := visitDir[id] if ok { v.dates = append(v.dates, date) v.scores = append(v.scores, score) visitDir[id] = DS{v.dates, v.scores} } else { visitDir[id] = DS{[]string{date}, []float64{score}} } return Visit{id, date, score} } type Merge struct{ id int } func (m Merge) lastName() string { return patientDir[m.id] } func (m Merge) dates() []string { return visitDir[m.id].dates } func (m Merge) scores() []float64 { return visitDir[m.id].scores } func (m Merge) lastVisit() string { dates := m.dates() dates2 := make([]string, len(dates)) copy(dates2, dates) sort.Strings(dates2) return dates2[len(dates2)-1] } func (m Merge) scoreSum() float64 { sum := 0.0 for _, score := range m.scores() { if score != -1 { sum += score } } return sum } func (m Merge) scoreAvg() float64 { count := 0 for _, score := range m.scores() { if score != -1 { count++ } } return m.scoreSum() / float64(count) } func mergePrint(merges []Merge) { fmt.Println("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |") f := "| %d | %-7s | %s | %4s | %4s |\n" for _, m := range merges { _, ok := visitDir[m.id] if ok { lv := m.lastVisit() if lv == "0000-00-00" { lv = " " } scoreSum := m.scoreSum() ss := fmt.Sprintf("%4.1f", scoreSum) if scoreSum == 0 { ss = " " } scoreAvg := m.scoreAvg() sa := " " if !math.IsNaN(scoreAvg) { sa = fmt.Sprintf("%4.2f", scoreAvg) } fmt.Printf(f, m.id, m.lastName(), lv, ss, sa) } else { fmt.Printf(f, m.id, m.lastName(), " ", " ", " ") } } } func main() { patientNew(1001, "Hopper") patientNew(4004, "Wirth") patientNew(3003, "Kemeny") patientNew(2002, "Gosling") patientNew(5005, "Kurtz") visitNew(2002, "2020-09-10", 6.8) visitNew(1001, "2020-09-17", 5.5) visitNew(4004, "2020-09-24", 8.4) visitNew(2002, "2020-10-08", -1) visitNew(1001, "", 6.6) visitNew(3003, "2020-11-12", -1) visitNew(4004, "2020-11-05", 7.0) visitNew(1001, "2020-11-19", 5.3) merges := make([]Merge, len(patientIds)) for i, id := range patientIds { merges[i] = Merge{id} } mergePrint(merges) }
import pandas as pd df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".") df_visits = pd.read_csv (r'visits.csv', sep = ",", decimal=".") df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE']) df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left') df_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False) df_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']}) print(df_result)
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "math" ) type fdy func(float64, float64) float64 func eulerStep(f fdy, x, y, h float64) float64 { return y + h*f(x, y) } func newCoolingRate(k float64) func(float64) float64 { return func(deltaTemp float64) float64 { return -k * deltaTemp } } func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 { return func(time float64) float64 { return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time) } } func newCoolingRateDy(k, ambientTemp float64) fdy { crf := newCoolingRate(k) return func(_, objectTemp float64) float64 { return crf(objectTemp - ambientTemp) } } func main() { k := .07 tempRoom := 20. tempObject := 100. fcr := newCoolingRateDy(k, tempRoom) analytic := newTempFunc(k, tempRoom, tempObject) for _, deltaTime := range []float64{2, 5, 10} { fmt.Printf("Step size = %.1f\n", deltaTime) fmt.Println(" Time Euler's Analytic") temp := tempObject for time := 0.; time <= 100; time += deltaTime { fmt.Printf("%5.1f %7.3f %7.3f\n", time, temp, analytic(time)) temp = eulerStep(fcr, time, temp, deltaTime) } fmt.Println() } }
def euler(f,y0,a,b,h): t,y = a,y0 while t <= b: print "%6.3f %6.3f" % (t,y) t += h y += h * f(t,y) def newtoncooling(time, temp): return -0.07 * (temp - 20) euler(newtoncooling,100,0,100,10)
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "math" ) func remarkable(n int) int { return n + int(.5+math.Sqrt(float64(n))) } func main() { fmt.Println(" n r(n)") fmt.Println("--- ---") for n := 1; n <= 22; n++ { fmt.Printf("%3d %3d\n", n, remarkable(n)) } const limit = 1e6 fmt.Println("\nChecking for squares for n <", limit) next := 2 nextSq := 4 for n := 1; n < limit; n++ { r := remarkable(n) switch { case r == nextSq: panic(n) case r > nextSq: fmt.Println(nextSq, "didn't occur") next++ nextSq = next * next } } fmt.Println("No squares occur for n <", limit) }
>>> from math import floor, sqrt >>> def non_square(n): return n + floor(1/2 + sqrt(n)) >>> >>> print(*map(non_square, range(1, 23))) 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 >>> >>> def is_square(n): return sqrt(n).is_integer() >>> non_squares = map(non_square, range(1, 10 ** 6)) >>> next(filter(is_square, non_squares)) StopIteration Traceback (most recent call last) <ipython-input-45-f32645fc1c0a> in <module>() 1 non_squares = map(non_square, range(1, 10 ** 6)) ----> 2 next(filter(is_square, non_squares)) StopIteration:
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "strings" ) func main() { s := "ABCDEFGH" n, m := 2, 3 fmt.Println("Index: ", "01234567") fmt.Println("String:", s) fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m]) fmt.Printf("Start %d, to end: %s\n", n, s[n:]) fmt.Printf("All but last: %s\n", s[:len(s)-1]) dx := strings.IndexByte(s, 'D') fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m]) sx := strings.Index(s, "DE") fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m]) }
>>> s = 'abcdefgh' >>> n, m, char, chars = 2, 3, 'd', 'cd' >>> >>> s[n-1:n+m-1] 'bcd' >>> >>> s[n-1:] 'bcdefgh' >>> >>> s[:-1] 'abcdefg' >>> >>> indx = s.index(char) >>> s[indx:indx+m] 'def' >>> >>> indx = s.index(chars) >>> s[indx:indx+m] 'cde' >>>
Write the same code in Python as shown below in Go.
package main import ( "log" "sort" ) func main() { log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) log.Println(jortSort([]int{0, 1, 0, 0, 0, 0})) log.Println(jortSort([]int{1, 2, 4, 11, 22, 22})) log.Println(jortSort([]int{0, 0, 0, 1, 2, 2})) } func jortSort(a []int) bool { c := make([]int, len(a)) copy(c, a) sort.Ints(a) for k, v := range c { if v == a[k] { continue } else { return false } } return true }
>>> def jortsort(sequence): return list(sequence) == sorted(sequence) >>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']: print(f'jortsort({repr(data)}) is {jortsort(data)}') jortsort((1, 2, 4, 3)) is False jortsort((14, 6, 8)) is False jortsort(['a', 'c']) is True jortsort(['s', 'u', 'x']) is True jortsort('CVGH') is False jortsort('PQRST') is True >>>
Translate the given Go code snippet into Python without altering its behavior.
func isLeap(year int) bool { return year%400 == 0 || year%4 == 0 && year%100 != 0 }
import calendar calendar.isleap(year)
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "fmt" "math/big" ) func main() { var n, p int64 fmt.Printf("A sample of permutations from 1 to 12:\n") for n = 1; n < 13; n++ { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 10 to 60:\n") for n = 10; n < 61; n += 10 { p = n / 3 fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of permutations from 5 to 15000:\n") nArr := [...]int64{5, 50, 500, 1000, 5000, 15000} for _, n = range nArr { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 100 to 1000:\n") for n = 100; n < 1001; n += 100 { p = n / 3 fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) } } func fact(n *big.Int) *big.Int { if n.Sign() < 1 { return big.NewInt(0) } r := big.NewInt(1) i := big.NewInt(2) for i.Cmp(n) < 1 { r.Mul(r, i) i.Add(i, big.NewInt(1)) } return r } func perm(n, k *big.Int) *big.Int { r := fact(n) r.Div(r, fact(n.Sub(n, k))) return r } func comb(n, r *big.Int) *big.Int { if r.Cmp(n) == 1 { return big.NewInt(0) } if r.Cmp(n) == 0 { return big.NewInt(1) } c := fact(n) den := fact(n.Sub(n, r)) den.Mul(den, fact(r)) c.Div(c, den) return c }
from __future__ import print_function from scipy.misc import factorial as fact from scipy.misc import comb def perm(N, k, exact=0): return comb(N, k, exact) * fact(k, exact) exact=True print('Sample Perms 1..12') for N in range(1, 13): k = max(N-2, 1) print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\n') print('\n\nSample Combs 10..60') for N in range(10, 61, 10): k = N-2 print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\n') exact=False print('\n\nSample Perms 5..1500 Using FP approximations') for N in [5, 15, 150, 1500, 15000]: k = N-2 print('%iP%i =' % (N, k), perm(N, k, exact)) print('\nSample Combs 100..1000 Using FP approximations') for N in range(100, 1001, 100): k = N-2 print('%iC%i =' % (N, k), comb(N, k, exact))
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "fmt" "sort" "strconv" ) func lexOrder(n int) []int { first, last, k := 1, n, n if n < 1 { first, last, k = n, 1, 2-n } strs := make([]string, k) for i := first; i <= last; i++ { strs[i-first] = strconv.Itoa(i) } sort.Strings(strs) ints := make([]int, k) for i := 0; i < k; i++ { ints[i], _ = strconv.Atoi(strs[i]) } return ints } func main() { fmt.Println("In lexicographical order:\n") for _, n := range []int{0, 5, 13, 21, -22} { fmt.Printf("%3d: %v\n", n, lexOrder(n)) } }
n=13 print(sorted(range(1,n+1), key=str))
Convert this Go block to Python, preserving its control flow and logic.
package main import "fmt" func main() { for _, n := range []int64{12, 1048576, 9e18, -2, 0} { fmt.Println(say(n)) } } var small = [...]string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"} var tens = [...]string{"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"} var illions = [...]string{"", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion"} func say(n int64) string { var t string if n < 0 { t = "negative " n = -n } switch { case n < 20: t += small[n] case n < 100: t += tens[n/10] s := n % 10 if s > 0 { t += "-" + small[s] } case n < 1000: t += small[n/100] + " hundred" s := n % 100 if s > 0 { t += " " + say(s) } default: sx := "" for i := 0; n > 0; i++ { p := n % 1000 n /= 1000 if p > 0 { ix := say(p) + illions[i] if sx != "" { ix += " " + sx } sx = ix } } t += sx } return t }
TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")] def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num) if __name__ == '__main__': for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): print('%+4i -> %s' % (n, spell_integer(n))) print('') n = 201021002001 while n: print('%-12i -> %s' % (n, spell_integer(n))) n //= -10 print('%-12i -> %s' % (n, spell_integer(n))) print('')
Generate an equivalent Python version of this Go code.
package main import ( "fmt" "os" "sort" ) func main() { if len(os.Args) == 1 { compareStrings("abcd", "123456789", "abcdef", "1234567") } else { strings := os.Args[1:] compareStrings(strings...) } } func compareStrings(strings ...string) { sort.SliceStable(strings, func(i, j int) bool { return len(strings[i]) > len(strings[j]) }) for _, s := range strings { fmt.Printf("%d: %s\n", len(s), s) } }
A = 'I am string' B = 'I am string too' if len(A) > len(B): print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings') print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings') elif len(A) < len(B): print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings') print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings') else: print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string') print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 { for i := inc; i < len(a); i++ { j, temp := i, a[i] for ; j >= inc && a[j-inc] > temp; j -= inc { a[j] = a[j-inc] } a[j] = temp } } fmt.Println("after: ", a) }
def shell(seq): inc = len(seq) // 2 while inc: for i, el in enumerate(seq[inc:], inc): while i >= inc and seq[i - inc] > el: seq[i] = seq[i - inc] i -= inc seq[i] = el inc = 1 if inc == 2 else inc * 5 // 11
Transform the following Go implementation into Python, maintaining the same output and logic.
type dlNode struct { int next, prev *dlNode } type dlList struct { members map[*dlNode]int head, tail **dlNode }
from collections import deque some_list = deque(["a", "b", "c"]) print(some_list) some_list.appendleft("Z") print(some_list) for value in reversed(some_list): print(value)
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "io/ioutil" "sort" "unicode" ) const file = "unixdict.txt" func main() { bs, err := ioutil.ReadFile(file) if err != nil { fmt.Println(err) return } m := make(map[rune]int) for _, r := range string(bs) { m[r]++ } lfs := make(lfList, 0, len(m)) for l, f := range m { lfs = append(lfs, &letterFreq{l, f}) } sort.Sort(lfs) fmt.Println("file:", file) fmt.Println("letter frequency") for _, lf := range lfs { if unicode.IsGraphic(lf.rune) { fmt.Printf(" %c %7d\n", lf.rune, lf.freq) } else { fmt.Printf("%U %7d\n", lf.rune, lf.freq) } } } type letterFreq struct { rune freq int } type lfList []*letterFreq func (lfs lfList) Len() int { return len(lfs) } func (lfs lfList) Less(i, j int) bool { switch fd := lfs[i].freq - lfs[j].freq; { case fd < 0: return false case fd > 0: return true } return lfs[i].rune < lfs[j].rune } func (lfs lfList) Swap(i, j int) { lfs[i], lfs[j] = lfs[j], lfs[i] }
import collections, sys def filecharcount(openfile): return sorted(collections.Counter(c for l in openfile for c in l).items()) f = open(sys.argv[1]) print(filecharcount(f))
Maintain the same structure and functionality when rewriting this code in Python.
package main import "fmt" var tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97} var ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98} func main() { all := make([]int, len(tr)+len(ct)) copy(all, tr) copy(all[len(tr):], ct) var sumAll int for _, r := range all { sumAll += r } sd := func(trc []int) int { var sumTr int for _, x := range trc { sumTr += all[x] } return sumTr*len(ct) - (sumAll-sumTr)*len(tr) } a := make([]int, len(tr)) for i, _ := range a { a[i] = i } sdObs := sd(a) var nLe, nGt int comb(len(all), len(tr), func(c []int) { if sd(c) > sdObs { nGt++ } else { nLe++ } }) pc := 100 / float64(nLe+nGt) fmt.Printf("differences <= observed: %f%%\n", float64(nLe)*pc) fmt.Printf("differences > observed: %f%%\n", float64(nGt)*pc) } func comb(n, m int, emit func([]int)) { s := make([]int, m) last := m - 1 var rc func(int, int) rc = func(i, next int) { for j := next; j < n; j++ { s[i] = j if i == last { emit(s) } else { rc(i+1, j+1) } } return } rc(0, 0) }
from itertools import combinations as comb def statistic(ab, a): sumab, suma = sum(ab), sum(a) return ( suma / len(a) - (sumab -suma) / (len(ab) - len(a)) ) def permutationTest(a, b): ab = a + b Tobs = statistic(ab, a) under = 0 for count, perm in enumerate(comb(ab, len(a)), 1): if statistic(ab, perm) <= Tobs: under += 1 return under * 100. / count treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97] controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98] under = permutationTest(treatmentGroup, controlGroup) print("under=%.2f%%, over=%.2f%%" % (under, 100. - under))
Translate the given Go code snippet into Python without altering its behavior.
package main import "fmt" func möbius(to int) []int { if to < 1 { to = 1 } mobs := make([]int, to+1) primes := []int{2} for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { if p > j { break } if j%p == 0 { j /= p cp++ } if j%p == 0 { spf = true break } } if cp == 0 && i > 2 { cp = 1 primes = append(primes, i) } if !spf { if cp%2 == 0 { mobs[i] = 1 } else { mobs[i] = -1 } } } return mobs } func main() { mobs := möbius(199) fmt.Println("Möbius sequence - First 199 terms:") for i := 0; i < 200; i++ { if i == 0 { fmt.Print(" ") continue } if i%20 == 0 { fmt.Println() } fmt.Printf("  % d", mobs[i]) } }
def isPrime(n) : if (n < 2) : return False for i in range(2, n + 1) : if (i * i <= n and n % i == 0) : return False return True def mobius(N) : if (N == 1) : return 1 p = 0 for i in range(1, N + 1) : if (N % i == 0 and isPrime(i)) : if (N % (i * i) == 0) : return 0 else : p = p + 1 if(p % 2 != 0) : return -1 else : return 1 print("Mobius numbers from 1..99:") for i in range(1, 100): print(f"{mobius(i):>4}", end = '') if i % 20 == 0: print()
Convert this Go block to Python, preserving its control flow and logic.
package main import "fmt" import "strconv" func main() { i, _ := strconv.Atoi("1234") fmt.Println(strconv.Itoa(i + 1)) }
next = str(int('123') + 1)
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "strings" ) func stripchars(str, chr string) string { return strings.Map(func(r rune) rune { if strings.IndexRune(chr, r) < 0 { return r } return -1 }, str) } func main() { fmt.Println(stripchars("She was a soul stripper. She took my heart!", "aei")) }
>>> def stripchars(s, chars): ... return s.translate(None, chars) ... >>> stripchars("She was a soul stripper. She took my heart!", "aei") 'Sh ws soul strppr. Sh took my hrt!'
Convert this Go snippet to Python and keep its semantics consistent.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) if len(a) > 1 && !recurse(len(a) - 1) { panic("sorted permutation not found!") } fmt.Println("after: ", a) } func recurse(last int) bool { if last <= 0 { for i := len(a) - 1; a[i] >= a[i-1]; i-- { if i == 1 { return true } } return false } for i := 0; i <= last; i++ { a[i], a[last] = a[last], a[i] if recurse(last - 1) { return true } a[i], a[last] = a[last], a[i] } return false }
from itertools import permutations in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1])) perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math" ) func mean(v []float64) (m float64, ok bool) { if len(v) == 0 { return } var parts []float64 for _, x := range v { var i int for _, p := range parts { sum := p + x var err float64 switch ax, ap := math.Abs(x), math.Abs(p); { case ax < ap: err = x - (sum - p) case ap < ax: err = p - (sum - x) } if err != 0 { parts[i] = err i++ } x = sum } parts = append(parts[:i], x) } var sum float64 for _, x := range parts { sum += x } return sum / float64(len(v)), true } func main() { for _, v := range [][]float64{ []float64{}, []float64{math.Inf(1), math.Inf(1)}, []float64{math.Inf(1), math.Inf(-1)}, []float64{3, 1, 4, 1, 5, 9}, []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20}, []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11}, []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2}, } { fmt.Println("Vector:", v) if m, ok := mean(v); ok { fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m) } else { fmt.Println("Mean undefined\n") } } }
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "io" "os" "strconv" "strings" "text/tabwriter" ) func readTable(table string) ([]string, []int) { fields := strings.Fields(table) var commands []string var minLens []int for i, max := 0, len(fields); i < max; { cmd := fields[i] cmdLen := len(cmd) i++ if i < max { num, err := strconv.Atoi(fields[i]) if err == nil && 1 <= num && num < cmdLen { cmdLen = num i++ } } commands = append(commands, cmd) minLens = append(minLens, cmdLen) } return commands, minLens } func validateCommands(commands []string, minLens []int, words []string) []string { var results []string for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func printResults(words []string, results []string) { wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0) io.WriteString(wr, "user words:") for _, word := range words { io.WriteString(wr, "\t"+word) } io.WriteString(wr, "\n") io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n") wr.Flush() } func main() { const table = "" + "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" commands, minLens := readTable(table) words := strings.Fields(sentence) results := validateCommands(commands, minLens, words) printResults(words, results) }
command_table_text = user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() input_iter = iter(command_table_text.split()) word = None try: while True: if word is None: word = next(input_iter) abbr_len = next(input_iter, len(word)) try: command_table[word] = int(abbr_len) word = None except ValueError: command_table[word] = len(word) word = abbr_len except StopIteration: pass return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
Port the provided Go code into Python while preserving the original functionality.
package main import ( "io" "os" "strconv" "strings" "text/tabwriter" ) func readTable(table string) ([]string, []int) { fields := strings.Fields(table) var commands []string var minLens []int for i, max := 0, len(fields); i < max; { cmd := fields[i] cmdLen := len(cmd) i++ if i < max { num, err := strconv.Atoi(fields[i]) if err == nil && 1 <= num && num < cmdLen { cmdLen = num i++ } } commands = append(commands, cmd) minLens = append(minLens, cmdLen) } return commands, minLens } func validateCommands(commands []string, minLens []int, words []string) []string { var results []string for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func printResults(words []string, results []string) { wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0) io.WriteString(wr, "user words:") for _, word := range words { io.WriteString(wr, "\t"+word) } io.WriteString(wr, "\n") io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n") wr.Flush() } func main() { const table = "" + "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" commands, minLens := readTable(table) words := strings.Fields(sentence) results := validateCommands(commands, minLens, words) printResults(words, results) }
command_table_text = user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() input_iter = iter(command_table_text.split()) word = None try: while True: if word is None: word = next(input_iter) abbr_len = next(input_iter, len(word)) try: command_table[word] = int(abbr_len) word = None except ValueError: command_table[word] = len(word) word = abbr_len except StopIteration: pass return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" "strings" ) func main(){ fmt.Println(H("1223334444")) } func H(data string) (entropy float64) { if data == "" { return 0 } for i := 0; i < 256; i++ { px := float64(strings.Count(data, string(byte(i)))) / float64(len(data)) if px > 0 { entropy += -px * math.Log2(px) } } return entropy }
from __future__ import division import math def hist(source): hist = {}; l = 0; for e in source: l += 1 if e not in hist: hist[e] = 0 hist[e] += 1 return (l,hist) def entropy(hist,l): elist = [] for v in hist.values(): c = v / l elist.append(-c * math.log(c ,2)) return sum(elist) def printHist(h): flip = lambda (k,v) : (v,k) h = sorted(h.iteritems(), key = flip) print 'Sym\thi\tfi\tInf' for (k,v) in h: print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) source = "1223334444" (l,h) = hist(source); print '.[Results].' print 'Length',l print 'Entropy:', entropy(h, l) printHist(h)
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "errors" "fmt" ) func TokenizeString(s string, sep, escape rune) (tokens []string, err error) { var runes []rune inEscape := false for _, r := range s { switch { case inEscape: inEscape = false fallthrough default: runes = append(runes, r) case r == escape: inEscape = true case r == sep: tokens = append(tokens, string(runes)) runes = runes[:0] } } tokens = append(tokens, string(runes)) if inEscape { err = errors.New("invalid terminal escape") } return tokens, err } func main() { const sample = "one^|uno||three^^^^|four^^^|^cuatro|" const separator = '|' const escape = '^' fmt.Printf("Input: %q\n", sample) tokens, err := TokenizeString(sample, separator, escape) if err != nil { fmt.Println("error:", err) } else { fmt.Printf("Tokens: %q\n", tokens) } }
def token_with_escape(a, escape = '^', separator = '|'): result = [] token = '' state = 0 for c in a: if state == 0: if c == escape: state = 1 elif c == separator: result.append(token) token = '' else: token += c elif state == 1: token += c state = 0 result.append(token) return result
Write a version of this Go function in Python with identical behavior.
package main import "fmt" 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 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 printHelper(cat string, le, lim, max int) (int, int, string) { cle, clim := commatize(le), commatize(lim) if cat != "unsexy primes" { cat = "sexy prime " + cat } fmt.Printf("Number of %s less than %s = %s\n", cat, clim, cle) last := max if le < last { last = le } verb := "are" if last == 1 { verb = "is" } return le, last, verb } func main() { lim := 1000035 sv := sieve(lim - 1) var pairs [][2]int var trips [][3]int var quads [][4]int var quins [][5]int var unsexy = []int{2, 3} for i := 3; i < lim; i += 2 { if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] { unsexy = append(unsexy, i) continue } if i < lim-6 && !sv[i] && !sv[i+6] { pair := [2]int{i, i + 6} pairs = append(pairs, pair) } else { continue } if i < lim-12 && !sv[i+12] { trip := [3]int{i, i + 6, i + 12} trips = append(trips, trip) } else { continue } if i < lim-18 && !sv[i+18] { quad := [4]int{i, i + 6, i + 12, i + 18} quads = append(quads, quad) } else { continue } if i < lim-24 && !sv[i+24] { quin := [5]int{i, i + 6, i + 12, i + 18, i + 24} quins = append(quins, quin) } } le, n, verb := printHelper("pairs", len(pairs), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, pairs[le-n:]) le, n, verb = printHelper("triplets", len(trips), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, trips[le-n:]) le, n, verb = printHelper("quadruplets", len(quads), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quads[le-n:]) le, n, verb = printHelper("quintuplets", len(quins), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quins[le-n:]) le, n, verb = printHelper("unsexy primes", len(unsexy), lim, 10) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, unsexy[le-n:]) }
LIMIT = 1_000_035 def primes2(limit=LIMIT): if limit < 2: return [] if limit < 3: return [2] lmtbf = (limit - 3) // 2 buf = [True] * (lmtbf + 1) for i in range((int(limit ** 0.5) - 3) // 2 + 1): if buf[i]: p = i + i + 3 s = p * (i + 1) + i buf[s::p] = [False] * ((lmtbf - s) // p + 1) return [2] + [i + i + 3 for i, v in enumerate(buf) if v] primes = primes2(LIMIT +6) primeset = set(primes) primearray = [n in primeset for n in range(LIMIT)] s = [[] for x in range(4)] unsexy = [] for p in primes: if p > LIMIT: break if p + 6 in primeset and p + 6 < LIMIT: s[0].append((p, p+6)) elif p + 6 in primeset: break else: if p - 6 not in primeset: unsexy.append(p) continue if p + 12 in primeset and p + 12 < LIMIT: s[1].append((p, p+6, p+12)) else: continue if p + 18 in primeset and p + 18 < LIMIT: s[2].append((p, p+6, p+12, p+18)) else: continue if p + 24 in primeset and p + 24 < LIMIT: s[3].append((p, p+6, p+12, p+18, p+24)) print('"SEXY" PRIME GROUPINGS:') for sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()): print(f' {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq printfn "There are %d unsexy primes less than 1,000,035. The last 10 are:" n.Length Array.skip (n.Length-10) n |> Array.iter(fun n->printf "%d " n); printfn "" let ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...') for sx in sexy[-5:]: print(' ',sx) print(f'\nThere are {len(unsexy)} unsexy primes ending with ...') for usx in unsexy[-10:]: print(' ',usx)
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import "fmt" func main() { a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73} fmt.Println(a) fmt.Println(fd(a, 9)) } func fd(a []int, ord int) []int { for i := 0; i < ord; i++ { for j := 0; j < len(a)-i-1; j++ { a[j] = a[j+1] - a[j] } } return a[:len(a)-ord] }
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
Generate an equivalent Python version of this Go code.
func IsPrime(n int) bool { if n < 0 { n = -n } switch { case n == 2: return true case n < 2 || n % 2 == 0: return false default: for i = 3; i*i <= n; i += 2 { if n % i == 0 { return false } } } return true }
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
Keep all operations the same but rewrite the snippet in Python.
func IsPrime(n int) bool { if n < 0 { n = -n } switch { case n == 2: return true case n < 2 || n % 2 == 0: return false default: for i = 3; i*i <= n; i += 2 { if n % i == 0 { return false } } } return true }
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import "fmt" import "math/big" func main() { fmt.Println(new(big.Int).Binomial(5, 3)) fmt.Println(new(big.Int).Binomial(60, 30)) }
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import "fmt" func main() { var a []interface{} a = append(a, 3) a = append(a, "apples", "oranges") fmt.Println(a) }
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection="some string" x = collection[::-1] collection[::2] == "some string"[::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: "zero", 1: "one"} collection['zero'] = 2 collection = set([0, '1'])
Please provide an equivalent version of this Go code in Python.
start := &Ele{"tacos", nil} end := start.Append("burritos") end = end.Append("fajitas") end = end.Append("enchilatas") for iter := start; iter != nil; iter = iter.Next { fmt.Println(iter) }
for node in lst: print node.value
Maintain the same structure and functionality when rewriting this code in Python.
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import "os" func main() { os.Remove("input.txt") os.Remove("/input.txt") os.Remove("docs") os.Remove("/docs") os.RemoveAll("docs") os.RemoveAll("/docs") }
import os os.remove("output.txt") os.rmdir("docs") os.remove("/output.txt") os.rmdir("/docs")
Convert this Go block to Python, preserving its control flow and logic.
package ddate import ( "strconv" "strings" "time" ) const ( DefaultFmt = "Pungenday, Discord 5, 3131 YOLD" OldFmt = `Today is Pungenday, the 5th day of Discord in the YOLD 3131 Celebrate Mojoday` ) const ( protoLongSeason = "Discord" protoShortSeason = "Dsc" protoLongDay = "Pungenday" protoShortDay = "PD" protoOrdDay = "5" protoCardDay = "5th" protoHolyday = "Mojoday" protoYear = "3131" ) var ( longDay = []string{"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"} shortDay = []string{"SM", "BT", "PD", "PP", "SO"} longSeason = []string{ "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"} shortSeason = []string{"Chs", "Dsc", "Cfn", "Bcy", "Afm"} holyday = [][]string{{"Mungday", "Chaoflux"}, {"Mojoday", "Discoflux"}, {"Syaday", "Confuflux"}, {"Zaraday", "Bureflux"}, {"Maladay", "Afflux"}} ) type DiscDate struct { StTibs bool Dayy int Year int } func New(eris time.Time) DiscDate { t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(), eris.Second(), eris.Nanosecond(), eris.Location()) bob := int(eris.Sub(t).Hours()) / 24 raw := eris.Year() hastur := DiscDate{Year: raw + 1166} if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) { if bob > 59 { bob-- } else if bob == 59 { hastur.StTibs = true return hastur } } hastur.Dayy = bob return hastur } func (dd DiscDate) Format(f string) (r string) { var st, snarf string var dateElement bool f6 := func(proto, wibble string) { if !dateElement { snarf = r dateElement = true } if st > "" { r = "" } else { r += wibble } f = f[len(proto):] } f4 := func(proto, wibble string) { if dd.StTibs { st = "St. Tib's Day" } f6(proto, wibble) } season, day := dd.Dayy/73, dd.Dayy%73 for f > "" { switch { case strings.HasPrefix(f, protoLongDay): f4(protoLongDay, longDay[dd.Dayy%5]) case strings.HasPrefix(f, protoShortDay): f4(protoShortDay, shortDay[dd.Dayy%5]) case strings.HasPrefix(f, protoCardDay): funkychickens := "th" if day/10 != 1 { switch day % 10 { case 0: funkychickens = "st" case 1: funkychickens = "nd" case 2: funkychickens = "rd" } } f4(protoCardDay, strconv.Itoa(day+1)+funkychickens) case strings.HasPrefix(f, protoOrdDay): f4(protoOrdDay, strconv.Itoa(day+1)) case strings.HasPrefix(f, protoLongSeason): f6(protoLongSeason, longSeason[season]) case strings.HasPrefix(f, protoShortSeason): f6(protoShortSeason, shortSeason[season]) case strings.HasPrefix(f, protoHolyday): if day == 4 { r += holyday[season][0] } else if day == 49 { r += holyday[season][1] } f = f[len(protoHolyday):] case strings.HasPrefix(f, protoYear): r += strconv.Itoa(dd.Year) f = f[4:] default: r += f[:1] f = f[1:] } } if st > "" { r = snarf + st + r } return }
import datetime, calendar DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] def ddate(year, month, day): today = datetime.date(year, month, day) is_leap_year = calendar.isleap(year) if is_leap_year and month == 2 and day == 29: return "St. Tib's Day, YOLD " + (year + 1166) day_of_year = today.timetuple().tm_yday - 1 if is_leap_year and day_of_year >= 60: day_of_year -= 1 season, dday = divmod(day_of_year, 73) return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var n int = 3 var moves int = 0 a := make([][]int, n) for i := range a { a[i] = make([]int, n) for j := range a { a[i][j] = rand.Intn(2) } } b := make([][]int, len(a)) for i := range a { b[i] = make([]int, len(a[i])) copy(b[i], a[i]) } for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- { b = flipCol(b, rand.Intn(n) + 1) b = flipRow(b, rand.Intn(n) + 1) } fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) var rc rune var num int for { for{ fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n) _, err := fmt.Scanf("%c%d", &rc, &num) if err != nil { fmt.Println(err) continue } if num < 1 || num > n { fmt.Println("Wrong command!") continue } break } switch rc { case 'c': fmt.Printf("Column %v will be flipped\n", num) flipCol(b, num) case 'r': fmt.Printf("Row %v will be flipped\n", num) flipRow(b, num) default: fmt.Println("Wrong command!") continue } moves++ fmt.Println("\nMoves taken: ", moves) fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) if compareSlices(a, b) { fmt.Printf("Finished. You win with %d moves!\n", moves) break } } } func drawBoard (m [][]int) { fmt.Print(" ") for i := range m { fmt.Printf("%d ", i+1) } for i := range m { fmt.Println() fmt.Printf("%d ", i+1) for _, val := range m[i] { fmt.Printf(" %d", val) } } fmt.Print("\n") } func flipRow(m [][]int, row int) ([][]int) { for j := range m { m[row-1][j] ^= 1 } return m } func flipCol(m [][]int, col int) ([][]int) { for j := range m { m[j][col-1] ^= 1 } return m } func compareSlices(m [][]int, n[][]int) bool { o := true for i := range m { for j := range m { if m[i][j] != n[i][j] { o = false } } } return o }
from random import randrange from copy import deepcopy from string import ascii_lowercase try: input = raw_input except: pass N = 3 board = [[0]* N for i in range(N)] def setbits(board, count=1): for i in range(count): board[randrange(N)][randrange(N)] ^= 1 def shuffle(board, count=1): for i in range(count): if randrange(0, 2): fliprow(randrange(N)) else: flipcol(randrange(N)) def pr(board, comment=''): print(str(comment)) print(' ' + ' '.join(ascii_lowercase[i] for i in range(N))) print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line]) for j, line in enumerate(board, 1))) def init(board): setbits(board, count=randrange(N)+1) target = deepcopy(board) while board == target: shuffle(board, count=2 * N) prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], ascii_lowercase[N-1]) return target, prompt def fliprow(i): board[i-1][:] = [x ^ 1 for x in board[i-1] ] def flipcol(i): for row in board: row[i] ^= 1 if __name__ == '__main__': print(__doc__ % (N, N)) target, prompt = init(board) pr(target, 'Target configuration is:') print('') turns = 0 while board != target: turns += 1 pr(board, '%i:' % turns) ans = input(prompt).strip() if (len(ans) == 1 and ans in ascii_lowercase and ascii_lowercase.index(ans) < N): flipcol(ascii_lowercase.index(ans)) elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N: fliprow(int(ans)) elif ans == 'T': pr(target, 'Target configuration is:') turns -= 1 elif ans == 'X': break else: print(" I don't understand %r... Try again. " "(X to exit or T to show target)\n" % ans[:9]) turns -= 1 else: print('\nWell done!\nBye.')
Write the same code in Python as shown below in Go.
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var n int = 3 var moves int = 0 a := make([][]int, n) for i := range a { a[i] = make([]int, n) for j := range a { a[i][j] = rand.Intn(2) } } b := make([][]int, len(a)) for i := range a { b[i] = make([]int, len(a[i])) copy(b[i], a[i]) } for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- { b = flipCol(b, rand.Intn(n) + 1) b = flipRow(b, rand.Intn(n) + 1) } fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) var rc rune var num int for { for{ fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n) _, err := fmt.Scanf("%c%d", &rc, &num) if err != nil { fmt.Println(err) continue } if num < 1 || num > n { fmt.Println("Wrong command!") continue } break } switch rc { case 'c': fmt.Printf("Column %v will be flipped\n", num) flipCol(b, num) case 'r': fmt.Printf("Row %v will be flipped\n", num) flipRow(b, num) default: fmt.Println("Wrong command!") continue } moves++ fmt.Println("\nMoves taken: ", moves) fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) if compareSlices(a, b) { fmt.Printf("Finished. You win with %d moves!\n", moves) break } } } func drawBoard (m [][]int) { fmt.Print(" ") for i := range m { fmt.Printf("%d ", i+1) } for i := range m { fmt.Println() fmt.Printf("%d ", i+1) for _, val := range m[i] { fmt.Printf(" %d", val) } } fmt.Print("\n") } func flipRow(m [][]int, row int) ([][]int) { for j := range m { m[row-1][j] ^= 1 } return m } func flipCol(m [][]int, col int) ([][]int) { for j := range m { m[j][col-1] ^= 1 } return m } func compareSlices(m [][]int, n[][]int) bool { o := true for i := range m { for j := range m { if m[i][j] != n[i][j] { o = false } } } return o }
from random import randrange from copy import deepcopy from string import ascii_lowercase try: input = raw_input except: pass N = 3 board = [[0]* N for i in range(N)] def setbits(board, count=1): for i in range(count): board[randrange(N)][randrange(N)] ^= 1 def shuffle(board, count=1): for i in range(count): if randrange(0, 2): fliprow(randrange(N)) else: flipcol(randrange(N)) def pr(board, comment=''): print(str(comment)) print(' ' + ' '.join(ascii_lowercase[i] for i in range(N))) print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line]) for j, line in enumerate(board, 1))) def init(board): setbits(board, count=randrange(N)+1) target = deepcopy(board) while board == target: shuffle(board, count=2 * N) prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], ascii_lowercase[N-1]) return target, prompt def fliprow(i): board[i-1][:] = [x ^ 1 for x in board[i-1] ] def flipcol(i): for row in board: row[i] ^= 1 if __name__ == '__main__': print(__doc__ % (N, N)) target, prompt = init(board) pr(target, 'Target configuration is:') print('') turns = 0 while board != target: turns += 1 pr(board, '%i:' % turns) ans = input(prompt).strip() if (len(ans) == 1 and ans in ascii_lowercase and ascii_lowercase.index(ans) < N): flipcol(ascii_lowercase.index(ans)) elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N: fliprow(int(ans)) elif ans == 'T': pr(target, 'Target configuration is:') turns -= 1 elif ans == 'X': break else: print(" I don't understand %r... Try again. " "(X to exit or T to show target)\n" % ans[:9]) turns -= 1 else: print('\nWell done!\nBye.')
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Denom()) f.Sub(h, f.SetInt(&w)) y, _ := f.Float64() d := fmt.Sprintf("%.3f", y) fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n", i, &w, d[1:], d[2] == '0' || d[2] == '9') } }
from decimal import Decimal import math def h(n): 'Simple, reduced precision calculation' return math.factorial(n) / (2 * math.log(2) ** (n + 1)) def h2(n): 'Extended precision Hickerson function' return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1)) for n in range(18): x = h2(n) norm = str(x.normalize()) almostinteger = (' Nearly integer' if 'E' not in norm and ('.0' in norm or '.9' in norm) else ' NOT nearly integer!') print('n:%2i h:%s%s' % (n, norm, almostinteger))
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Denom()) f.Sub(h, f.SetInt(&w)) y, _ := f.Float64() d := fmt.Sprintf("%.3f", y) fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n", i, &w, d[1:], d[2] == '0' || d[2] == '9') } }
from decimal import Decimal import math def h(n): 'Simple, reduced precision calculation' return math.factorial(n) / (2 * math.log(2) ** (n + 1)) def h2(n): 'Extended precision Hickerson function' return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1)) for n in range(18): x = h2(n) norm = str(x.normalize()) almostinteger = (' Nearly integer' if 'E' not in norm and ('.0' in norm or '.9' in norm) else ' NOT nearly integer!') print('n:%2i h:%s%s' % (n, norm, almostinteger))
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "math" "math/rand" ) const nmax = 20 func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } } func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests } func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
from __future__ import division from math import factorial from random import randrange MAX_N = 20 TIMES = 1000000 def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1)) def test(n, times): count = 0 for i in range(times): x, bits = 1, 0 while not (bits & x): count += 1 bits |= x x = 1 << randrange(n) return count / times if __name__ == '__main__': print(" n\tavg\texp.\tdiff\n-------------------------------") for n in range(1, MAX_N+1): avg = test(n, TIMES) theory = analytical(n) diff = (avg / theory - 1) * 100 print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" "math/rand" ) const nmax = 20 func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } } func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests } func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
from __future__ import division from math import factorial from random import randrange MAX_N = 20 TIMES = 1000000 def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1)) def test(n, times): count = 0 for i in range(times): x, bits = 1, 0 while not (bits & x): count += 1 bits |= x x = 1 << randrange(n) return count / times if __name__ == '__main__': print(" n\tavg\texp.\tdiff\n-------------------------------") for n in range(1, MAX_N+1): avg = test(n, TIMES) theory = analytical(n) diff = (avg / theory - 1) * 100 print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math" "math/rand" ) const nmax = 20 func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } } func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests } func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
from __future__ import division from math import factorial from random import randrange MAX_N = 20 TIMES = 1000000 def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1)) def test(n, times): count = 0 for i in range(times): x, bits = 1, 0 while not (bits & x): count += 1 bits |= x x = 1 << randrange(n) return count / times if __name__ == '__main__': print(" n\tavg\texp.\tdiff\n-------------------------------") for n in range(1, MAX_N+1): avg = test(n, TIMES) theory = analytical(n) diff = (avg / theory - 1) * 100 print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" ) func main() { str := "Mary had a %s lamb" txt := "little" out := fmt.Sprintf(str, txt) fmt.Println(out) }
>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "container/heap" "sort" ) type IntPile []int func (self IntPile) Top() int { return self[len(self)-1] } func (self *IntPile) Pop() int { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x } type IntPilesHeap []IntPile func (self IntPilesHeap) Len() int { return len(self) } func (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() } func (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] } func (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) } func (self *IntPilesHeap) Pop() interface{} { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x } func patience_sort (n []int) { var piles []IntPile for _, x := range n { j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x }) if j != len(piles) { piles[j] = append(piles[j], x) } else { piles = append(piles, IntPile{ x }) } } hp := IntPilesHeap(piles) heap.Init(&hp) for i, _ := range n { smallPile := heap.Pop(&hp).(IntPile) n[i] = smallPile.Pop() if len(smallPile) != 0 { heap.Push(&hp, smallPile) } } if len(hp) != 0 { panic("something went wrong") } } func main() { a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1} patience_sort(a) fmt.Println(a) }
from functools import total_ordering from bisect import bisect_left from heapq import merge @total_ordering class Pile(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(n): piles = [] for x in n: new_pile = Pile([x]) i = bisect_left(piles, new_pile) if i != len(piles): piles[i].append(x) else: piles.append(new_pile) n[:] = merge(*[reversed(pile) for pile in piles]) if __name__ == "__main__": a = [4, 65, 2, -31, 0, 99, 83, 782, 1] patience_sort(a) print a
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "math/rand" "sort" "time" ) const bases = "ACGT" func mutate(dna string, w [3]int) string { le := len(dna) p := rand.Intn(le) r := rand.Intn(300) bytes := []byte(dna) switch { case r < w[0]: base := bases[rand.Intn(4)] fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base) bytes[p] = base case r < w[0]+w[1]: fmt.Printf(" Delete @%3d %q\n", p, bytes[p]) copy(bytes[p:], bytes[p+1:]) bytes = bytes[0 : le-1] default: base := bases[rand.Intn(4)] bytes = append(bytes, 0) copy(bytes[p+1:], bytes[p:]) fmt.Printf(" Insert @%3d %q\n", p, base) bytes[p] = base } return string(bytes) } func generate(le int) string { bytes := make([]byte, le) for i := 0; i < le; i++ { bytes[i] = bases[rand.Intn(4)] } return string(bytes) } func prettyPrint(dna string, rowLen int) { fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += rowLen { k := i + rowLen if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======\n") } func wstring(w [3]int) string { return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2]) } func main() { rand.Seed(time.Now().UnixNano()) dna := generate(250) prettyPrint(dna, 50) muts := 10 w := [3]int{100, 100, 100} fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w)) fmt.Printf("MUTATIONS (%d):\n", muts) for i := 0; i < muts; i++ { dna = mutate(dna, w) } fmt.Println() prettyPrint(dna, 50) }
import random from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") def seq_mutate(dna, count=1, kinds="IDSSSS", choice="ATCG" ): mutation = [] k2txt = dict(I='Insert', D='Delete', S='Substitute') for _ in range(count): kind = random.choice(kinds) index = random.randint(0, len(dna)) if kind == 'I': dna = dna[:index] + random.choice(choice) + dna[index:] elif kind == 'D' and dna: dna = dna[:index] + dna[index+1:] elif kind == 'S' and dna: dna = dna[:index] + random.choice(choice) + dna[index+1:] mutation.append((k2txt[kind], index)) return dna, mutation if __name__ == '__main__': length = 250 print("SEQUENCE:") sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length)) seq_pp(sequence) print("\n\nMUTATIONS:") mseq, m = seq_mutate(sequence, 10) for kind, index in m: print(f" {kind:>10} @{index}") print() seq_pp(mseq)
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/rand" "sort" "time" ) const bases = "ACGT" func mutate(dna string, w [3]int) string { le := len(dna) p := rand.Intn(le) r := rand.Intn(300) bytes := []byte(dna) switch { case r < w[0]: base := bases[rand.Intn(4)] fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base) bytes[p] = base case r < w[0]+w[1]: fmt.Printf(" Delete @%3d %q\n", p, bytes[p]) copy(bytes[p:], bytes[p+1:]) bytes = bytes[0 : le-1] default: base := bases[rand.Intn(4)] bytes = append(bytes, 0) copy(bytes[p+1:], bytes[p:]) fmt.Printf(" Insert @%3d %q\n", p, base) bytes[p] = base } return string(bytes) } func generate(le int) string { bytes := make([]byte, le) for i := 0; i < le; i++ { bytes[i] = bases[rand.Intn(4)] } return string(bytes) } func prettyPrint(dna string, rowLen int) { fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += rowLen { k := i + rowLen if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======\n") } func wstring(w [3]int) string { return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2]) } func main() { rand.Seed(time.Now().UnixNano()) dna := generate(250) prettyPrint(dna, 50) muts := 10 w := [3]int{100, 100, 100} fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w)) fmt.Printf("MUTATIONS (%d):\n", muts) for i := 0; i < muts; i++ { dna = mutate(dna, w) } fmt.Println() prettyPrint(dna, 50) }
import random from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") def seq_mutate(dna, count=1, kinds="IDSSSS", choice="ATCG" ): mutation = [] k2txt = dict(I='Insert', D='Delete', S='Substitute') for _ in range(count): kind = random.choice(kinds) index = random.randint(0, len(dna)) if kind == 'I': dna = dna[:index] + random.choice(choice) + dna[index:] elif kind == 'D' and dna: dna = dna[:index] + dna[index+1:] elif kind == 'S' and dna: dna = dna[:index] + random.choice(choice) + dna[index+1:] mutation.append((k2txt[kind], index)) return dna, mutation if __name__ == '__main__': length = 250 print("SEQUENCE:") sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length)) seq_pp(sequence) print("\n\nMUTATIONS:") mseq, m = seq_mutate(sequence, 10) for kind, index in m: print(f" {kind:>10} @{index}") print() seq_pp(mseq)
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } return count } func main() { fmt.Println("The first 100 tau numbers are:") count := 0 i := 1 for count < 100 { tf := countDivisors(i) if i%tf == 0 { fmt.Printf("%4d ", i) count++ if count%10 == 0 { fmt.Println() } } i++ } }
def tau(n): assert(isinstance(n, int) and 0 < n) ans, i, j = 0, 1, 1 while i*i <= n: if 0 == n%i: ans += 1 j = n//i if j != i: ans += 1 i += 1 return ans def is_tau_number(n): assert(isinstance(n, int)) if n <= 0: return False return 0 == n%tau(n) if __name__ == "__main__": n = 1 ans = [] while len(ans) < 100: if is_tau_number(n): ans.append(n) n += 1 print(ans)
Write a version of this Go function in Python with identical behavior.
package main import ( "fmt" "permute" ) func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += float64(s) * pr } return } func permanent(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += pr } return } var m2 = [][]float64{ {1, 2}, {3, 4}} var m3 = [][]float64{ {2, 9, 4}, {7, 5, 3}, {6, 1, 8}} func main() { fmt.Println(determinant(m2), permanent(m2)) fmt.Println(determinant(m3), permanent(m3)) }
from itertools import permutations from operator import mul from math import fsum from spermutations import spermutations def prod(lst): return reduce(mul, lst, 1) def perm(a): n = len(a) r = range(n) s = permutations(r) return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s) def det(a): n = len(a) r = range(n) s = spermutations(n) return fsum(sign * prod(a[i][sigma[i]] for i in r) for sigma, sign in s) if __name__ == '__main__': from pprint import pprint as pp for a in ( [ [1, 2], [3, 4]], [ [1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]], [ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]], ): print('') pp(a) print('Perm: %s Det: %s' % (perm(a), det(a)))
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "permute" ) func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += float64(s) * pr } return } func permanent(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += pr } return } var m2 = [][]float64{ {1, 2}, {3, 4}} var m3 = [][]float64{ {2, 9, 4}, {7, 5, 3}, {6, 1, 8}} func main() { fmt.Println(determinant(m2), permanent(m2)) fmt.Println(determinant(m3), permanent(m3)) }
from itertools import permutations from operator import mul from math import fsum from spermutations import spermutations def prod(lst): return reduce(mul, lst, 1) def perm(a): n = len(a) r = range(n) s = permutations(r) return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s) def det(a): n = len(a) r = range(n) s = spermutations(n) return fsum(sign * prod(a[i][sigma[i]] for i in r) for sigma, sign in s) if __name__ == '__main__': from pprint import pprint as pp for a in ( [ [1, 2], [3, 4]], [ [1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]], [ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]], ): print('') pp(a) print('Perm: %s Det: %s' % (perm(a), det(a)))
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "math/big" "time" ) var p []*big.Int var pd []int func partDiffDiff(n int) int { if n&1 == 1 { return (n + 1) / 2 } return n + 1 } func partDiff(n int) int { if n < 2 { return 1 } pd[n] = pd[n-1] + partDiffDiff(n-1) return pd[n] } func partitionsP(n int) { if n < 2 { return } psum := new(big.Int) for i := 1; i <= n; i++ { pdi := partDiff(i) if pdi > n { break } sign := int64(-1) if (i-1)%4 < 2 { sign = 1 } t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign)) psum.Add(psum, t) } p[n] = psum } func main() { start := time.Now() const N = 6666 p = make([]*big.Int, N+1) pd = make([]int, N+1) p[0], pd[0] = big.NewInt(1), 1 p[1], pd[1] = big.NewInt(1), 1 for n := 2; n <= N; n++ { partitionsP(n) } fmt.Printf("p[%d)] = %d\n", N, p[N]) fmt.Printf("Took %s\n", time.Since(start)) }
from itertools import islice def posd(): "diff between position numbers. 1, 2, 3... interleaved with 3, 5, 7..." count, odd = 1, 3 while True: yield count yield odd count, odd = count + 1, odd + 2 def pos_gen(): "position numbers. 1 3 2 5 7 4 9 ..." val = 1 diff = posd() while True: yield val val += next(diff) def plus_minus(): "yield (list_offset, sign) or zero for Partition calc" n, sign = 0, [1, 1] p_gen = pos_gen() out_on = next(p_gen) while True: n += 1 if n == out_on: next_sign = sign.pop(0) if not sign: sign = [-next_sign] * 2 yield -n, next_sign out_on = next(p_gen) else: yield 0 def part(n): "Partition numbers" p = [1] p_m = plus_minus() mods = [] for _ in range(n): next_plus_minus = next(p_m) if next_plus_minus: mods.append(next_plus_minus) p.append(sum(p[offset] * sign for offset, sign in mods)) return p[-1] print("(Intermediaries):") print(" posd:", list(islice(posd(), 10))) print(" pos_gen:", list(islice(pos_gen(), 10))) print(" plus_minus:", list(islice(plus_minus(), 15))) print("\nPartitions:", [part(x) for x in range(15)])
Port the provided Go code into Python while preserving the original functionality.
package main import ( "bytes" "fmt" "io/ioutil" "strings" ) var rows, cols int var rx, cx int var mn []int func main() { src, err := ioutil.ReadFile("ww.config") if err != nil { fmt.Println(err) return } srcRows := bytes.Split(src, []byte{'\n'}) rows = len(srcRows) for _, r := range srcRows { if len(r) > cols { cols = len(r) } } rx, cx = rows+2, cols+2 mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1} odd := make([]byte, rx*cx) even := make([]byte, rx*cx) for ri, r := range srcRows { copy(odd[(ri+1)*cx+1:], r) } for { print(odd) step(even, odd) fmt.Scanln() print(even) step(odd, even) fmt.Scanln() } } func print(grid []byte) { fmt.Println(strings.Repeat("__", cols)) fmt.Println() for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { if grid[r*cx+c] == 0 { fmt.Print(" ") } else { fmt.Printf(" %c", grid[r*cx+c]) } } fmt.Println() } } func step(dst, src []byte) { for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { x := r*cx + c dst[x] = src[x] switch dst[x] { case 'H': dst[x] = 't' case 't': dst[x] = '.' case '.': var nn int for _, n := range mn { if src[x+n] == 'H' { nn++ } } if nn == 1 || nn == 2 { dst[x] = 'H' } } } } }
from io import StringIO from collections import namedtuple from pprint import pprint as pp import copy WW = namedtuple('WW', 'world, w, h') head, tail, conductor, empty = allstates = 'Ht. ' infile = StringIO() def readfile(f): world = [row.rstrip('\r\n') for row in f] height = len(world) width = max(len(row) for row in world) nonrow = [ " %*s " % (-width, "") ] world = nonrow + \ [ " %*s " % (-width, row) for row in world ] + \ nonrow world = [list(row) for row in world] return WW(world, width, height) def newcell(currentworld, x, y): istate = currentworld[y][x] assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate if istate == head: ostate = tail elif istate == tail: ostate = conductor elif istate == empty: ostate = empty else: n = sum( currentworld[y+dy][x+dx] == head for dx,dy in ( (-1,-1), (-1,+0), (-1,+1), (+0,-1), (+0,+1), (+1,-1), (+1,+0), (+1,+1) ) ) ostate = head if 1 <= n <= 2 else conductor return ostate def nextgen(ww): 'compute next generation of wireworld' world, width, height = ww newworld = copy.deepcopy(world) for x in range(1, width+1): for y in range(1, height+1): newworld[y][x] = newcell(world, x, y) return WW(newworld, width, height) def world2string(ww): return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] ) ww = readfile(infile) infile.close() for gen in range(10): print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' ) print ( world2string(ww) ) ww = nextgen(ww)
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math" ) type xy struct { x, y float64 } type seg struct { p1, p2 xy } type poly struct { name string sides []seg } func inside(pt xy, pg poly) (i bool) { for _, side := range pg.sides { if rayIntersectsSegment(pt, side) { i = !i } } return } func rayIntersectsSegment(p xy, s seg) bool { var a, b xy if s.p1.y < s.p2.y { a, b = s.p1, s.p2 } else { a, b = s.p2, s.p1 } for p.y == a.y || p.y == b.y { p.y = math.Nextafter(p.y, math.Inf(1)) } if p.y < a.y || p.y > b.y { return false } if a.x > b.x { if p.x > a.x { return false } if p.x < b.x { return true } } else { if p.x > b.x { return false } if p.x < a.x { return true } } return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x) } var ( p1 = xy{0, 0} p2 = xy{10, 0} p3 = xy{10, 10} p4 = xy{0, 10} p5 = xy{2.5, 2.5} p6 = xy{7.5, 2.5} p7 = xy{7.5, 7.5} p8 = xy{2.5, 7.5} p9 = xy{0, 5} p10 = xy{10, 5} p11 = xy{3, 0} p12 = xy{7, 0} p13 = xy{7, 10} p14 = xy{3, 10} ) var tpg = []poly{ {"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}}, {"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}, {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}}, {"strange", []seg{{p1, p5}, {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}}, {"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13}, {p13, p14}, {p14, p9}, {p9, p11}}}, } var tpt = []xy{ {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10}, {1, 2}, {2, 1}, } func main() { for _, pg := range tpg { fmt.Printf("%s:\n", pg.name) for _, pt := range tpt { fmt.Println(pt, inside(pt, pg)) } } }
from collections import namedtuple from pprint import pprint as pp import sys Pt = namedtuple('Pt', 'x, y') Edge = namedtuple('Edge', 'a, b') Poly = namedtuple('Poly', 'name, edges') _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_info.min def rayintersectseg(p, edge): a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect def _odd(x): return x%2 == 1 def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges )) def polypp(poly): print ("\n Polygon(name='%s', edges=(" % poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[6:]))
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "math" ) type xy struct { x, y float64 } type seg struct { p1, p2 xy } type poly struct { name string sides []seg } func inside(pt xy, pg poly) (i bool) { for _, side := range pg.sides { if rayIntersectsSegment(pt, side) { i = !i } } return } func rayIntersectsSegment(p xy, s seg) bool { var a, b xy if s.p1.y < s.p2.y { a, b = s.p1, s.p2 } else { a, b = s.p2, s.p1 } for p.y == a.y || p.y == b.y { p.y = math.Nextafter(p.y, math.Inf(1)) } if p.y < a.y || p.y > b.y { return false } if a.x > b.x { if p.x > a.x { return false } if p.x < b.x { return true } } else { if p.x > b.x { return false } if p.x < a.x { return true } } return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x) } var ( p1 = xy{0, 0} p2 = xy{10, 0} p3 = xy{10, 10} p4 = xy{0, 10} p5 = xy{2.5, 2.5} p6 = xy{7.5, 2.5} p7 = xy{7.5, 7.5} p8 = xy{2.5, 7.5} p9 = xy{0, 5} p10 = xy{10, 5} p11 = xy{3, 0} p12 = xy{7, 0} p13 = xy{7, 10} p14 = xy{3, 10} ) var tpg = []poly{ {"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}}, {"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}, {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}}, {"strange", []seg{{p1, p5}, {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}}, {"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13}, {p13, p14}, {p14, p9}, {p9, p11}}}, } var tpt = []xy{ {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10}, {1, 2}, {2, 1}, } func main() { for _, pg := range tpg { fmt.Printf("%s:\n", pg.name) for _, pt := range tpt { fmt.Println(pt, inside(pt, pg)) } } }
from collections import namedtuple from pprint import pprint as pp import sys Pt = namedtuple('Pt', 'x, y') Edge = namedtuple('Edge', 'a, b') Poly = namedtuple('Poly', 'name, edges') _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_info.min def rayintersectseg(p, edge): a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect def _odd(x): return x%2 == 1 def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges )) def polypp(poly): print ("\n Polygon(name='%s', edges=(" % poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[6:]))
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { return p } L := (3 * p.x * p.x) / (2 * p.y) x := L*L - 2*p.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func add(p, q pt) pt { if p.x == q.x && p.y == q.y { return dbl(p) } if is_zero(p) { return q } if is_zero(q) { return p } L := (q.y - p.y) / (q.x - p.x) x := L*L - p.x - q.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func mul(p pt, n int) pt { r := zero() for i := 1; i <= n; i <<= 1 { if i&n != 0 { r = add(r, p) } p = dbl(p) } return r } func show(s string, p pt) { fmt.Printf("%s", s) if is_zero(p) { fmt.Println("Zero") } else { fmt.Printf("(%.3f, %.3f)\n", p.x, p.y) } } func from_y(y float64) pt { return pt{ x: math.Cbrt(y*y - bCoeff), y: y, } } func main() { a := from_y(1) b := from_y(2) show("a = ", a) show("b = ", b) c := add(a, b) show("c = a + b = ", c) d := neg(c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345)) }
class Point: b = 7 def __init__(self, x=float('inf'), y=float('inf')): self.x = x self.y = y def copy(self): return Point(self.x, self.y) def is_zero(self): return self.x > 1e20 or self.x < -1e20 def neg(self): return Point(self.x, -self.y) def dbl(self): if self.is_zero(): return self.copy() try: L = (3 * self.x * self.x) / (2 * self.y) except ZeroDivisionError: return Point() x = L * L - 2 * self.x return Point(x, L * (self.x - x) - self.y) def add(self, q): if self.x == q.x and self.y == q.y: return self.dbl() if self.is_zero(): return q.copy() if q.is_zero(): return self.copy() try: L = (q.y - self.y) / (q.x - self.x) except ZeroDivisionError: return Point() x = L * L - self.x - q.x return Point(x, L * (self.x - x) - self.y) def mul(self, n): p = self.copy() r = Point() i = 1 while i <= n: if i&n: r = r.add(p) p = p.dbl() i <<= 1 return r def __str__(self): return "({:.3f}, {:.3f})".format(self.x, self.y) def show(s, p): print(s, "Zero" if p.is_zero() else p) def from_y(y): n = y * y - Point.b x = n**(1./3) if n>=0 else -((-n)**(1./3)) return Point(x, y) a = from_y(1) b = from_y(2) show("a =", a) show("b =", b) c = a.add(b) show("c = a + b =", c) d = c.neg() show("d = -c =", d) show("c + d =", c.add(d)) show("a + b + d =", a.add(b.add(d))) show("a * 12345 =", a.mul(12345))
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { return p } L := (3 * p.x * p.x) / (2 * p.y) x := L*L - 2*p.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func add(p, q pt) pt { if p.x == q.x && p.y == q.y { return dbl(p) } if is_zero(p) { return q } if is_zero(q) { return p } L := (q.y - p.y) / (q.x - p.x) x := L*L - p.x - q.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func mul(p pt, n int) pt { r := zero() for i := 1; i <= n; i <<= 1 { if i&n != 0 { r = add(r, p) } p = dbl(p) } return r } func show(s string, p pt) { fmt.Printf("%s", s) if is_zero(p) { fmt.Println("Zero") } else { fmt.Printf("(%.3f, %.3f)\n", p.x, p.y) } } func from_y(y float64) pt { return pt{ x: math.Cbrt(y*y - bCoeff), y: y, } } func main() { a := from_y(1) b := from_y(2) show("a = ", a) show("b = ", b) c := add(a, b) show("c = a + b = ", c) d := neg(c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345)) }
class Point: b = 7 def __init__(self, x=float('inf'), y=float('inf')): self.x = x self.y = y def copy(self): return Point(self.x, self.y) def is_zero(self): return self.x > 1e20 or self.x < -1e20 def neg(self): return Point(self.x, -self.y) def dbl(self): if self.is_zero(): return self.copy() try: L = (3 * self.x * self.x) / (2 * self.y) except ZeroDivisionError: return Point() x = L * L - 2 * self.x return Point(x, L * (self.x - x) - self.y) def add(self, q): if self.x == q.x and self.y == q.y: return self.dbl() if self.is_zero(): return q.copy() if q.is_zero(): return self.copy() try: L = (q.y - self.y) / (q.x - self.x) except ZeroDivisionError: return Point() x = L * L - self.x - q.x return Point(x, L * (self.x - x) - self.y) def mul(self, n): p = self.copy() r = Point() i = 1 while i <= n: if i&n: r = r.add(p) p = p.dbl() i <<= 1 return r def __str__(self): return "({:.3f}, {:.3f})".format(self.x, self.y) def show(s, p): print(s, "Zero" if p.is_zero() else p) def from_y(y): n = y * y - Point.b x = n**(1./3) if n>=0 else -((-n)**(1./3)) return Point(x, y) a = from_y(1) b = from_y(2) show("a =", a) show("b =", b) c = a.add(b) show("c = a + b =", c) d = c.neg() show("d = -c =", d) show("c + d =", c.add(d)) show("a + b + d =", a.add(b.add(d))) show("a * 12345 =", a.mul(12345))
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { return p } L := (3 * p.x * p.x) / (2 * p.y) x := L*L - 2*p.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func add(p, q pt) pt { if p.x == q.x && p.y == q.y { return dbl(p) } if is_zero(p) { return q } if is_zero(q) { return p } L := (q.y - p.y) / (q.x - p.x) x := L*L - p.x - q.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func mul(p pt, n int) pt { r := zero() for i := 1; i <= n; i <<= 1 { if i&n != 0 { r = add(r, p) } p = dbl(p) } return r } func show(s string, p pt) { fmt.Printf("%s", s) if is_zero(p) { fmt.Println("Zero") } else { fmt.Printf("(%.3f, %.3f)\n", p.x, p.y) } } func from_y(y float64) pt { return pt{ x: math.Cbrt(y*y - bCoeff), y: y, } } func main() { a := from_y(1) b := from_y(2) show("a = ", a) show("b = ", b) c := add(a, b) show("c = a + b = ", c) d := neg(c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345)) }
class Point: b = 7 def __init__(self, x=float('inf'), y=float('inf')): self.x = x self.y = y def copy(self): return Point(self.x, self.y) def is_zero(self): return self.x > 1e20 or self.x < -1e20 def neg(self): return Point(self.x, -self.y) def dbl(self): if self.is_zero(): return self.copy() try: L = (3 * self.x * self.x) / (2 * self.y) except ZeroDivisionError: return Point() x = L * L - 2 * self.x return Point(x, L * (self.x - x) - self.y) def add(self, q): if self.x == q.x and self.y == q.y: return self.dbl() if self.is_zero(): return q.copy() if q.is_zero(): return self.copy() try: L = (q.y - self.y) / (q.x - self.x) except ZeroDivisionError: return Point() x = L * L - self.x - q.x return Point(x, L * (self.x - x) - self.y) def mul(self, n): p = self.copy() r = Point() i = 1 while i <= n: if i&n: r = r.add(p) p = p.dbl() i <<= 1 return r def __str__(self): return "({:.3f}, {:.3f})".format(self.x, self.y) def show(s, p): print(s, "Zero" if p.is_zero() else p) def from_y(y): n = y * y - Point.b x = n**(1./3) if n>=0 else -((-n)**(1./3)) return Point(x, y) a = from_y(1) b = from_y(2) show("a =", a) show("b =", b) c = a.add(b) show("c = a + b =", c) d = c.neg() show("d = -c =", d) show("c + d =", c.add(d)) show("a + b + d =", a.add(b.add(d))) show("a * 12345 =", a.mul(12345))
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.Count("the three truths", "th")) fmt.Println(strings.Count("ababababab", "abab")) }
>>> "the three truths".count("th") 3 >>> "ababababab".count("abab") 2
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "strings" ) func main() { c := "cat" d := "dog" if c == d { fmt.Println(c, "is bytewise identical to", d) } if c != d { fmt.Println(c, "is bytewise different from", d) } if c > d { fmt.Println(c, "is lexically bytewise greater than", d) } if c < d { fmt.Println(c, "is lexically bytewise less than", d) } if c >= d { fmt.Println(c, "is lexically bytewise greater than or equal to", d) } if c <= d { fmt.Println(c, "is lexically bytewise less than or equal to", d) } eqf := `when interpreted as UTF-8 and compared under Unicode simple case folding rules.` if strings.EqualFold(c, d) { fmt.Println(c, "equal to", d, eqf) } else { fmt.Println(c, "not equal to", d, eqf) } }
fun compare(a, b): print("\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}") if a < b: print("$a is strictly less than $b") if a <= b: print("$a is less than or equal to $b") if a > b: print("$a is strictly greater than $b") if a >= b: print("$a is greater than or equal to $b") if a == b: print("$a is equal to $b") if a != b: print("$a is not equal to $b") if a is b: print("$a has object identity with $b") if a is not b: print("$a has negated object identity with $b") compare("YUP", "YUP") compare('a', 'z') compare("24", "123") compare(24, 123) compare(5.0, 5)
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "io" "os" "strings" "time" ) func addNote(fn string, note string) error { f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return err } _, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n") if cErr := f.Close(); err == nil { err = cErr } return err } func showNotes(w io.Writer, fn string) error { f, err := os.Open(fn) if err != nil { if os.IsNotExist(err) { return nil } return err } _, err = io.Copy(w, f) f.Close() return err } func main() { const fn = "NOTES.TXT" var err error if len(os.Args) > 1 { err = addNote(fn, strings.Join(os.Args[1:], " ")) } else { err = showNotes(os.Stdout, fn) } if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
import sys, datetime, shutil if len(sys.argv) == 1: try: with open('notes.txt', 'r') as f: shutil.copyfileobj(f, sys.stdout) except IOError: pass else: with open('notes.txt', 'a') as f: f.write(datetime.datetime.now().isoformat() + '\n') f.write("\t%s\n" % ' '.join(sys.argv[1:]))
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "math" ) func main() { const nn = 32 const step = .05 xVal := make([]float64, nn) tSin := make([]float64, nn) tCos := make([]float64, nn) tTan := make([]float64, nn) for i := range xVal { xVal[i] = float64(i) * step tSin[i], tCos[i] = math.Sincos(xVal[i]) tTan[i] = tSin[i] / tCos[i] } iSin := thieleInterpolator(tSin, xVal) iCos := thieleInterpolator(tCos, xVal) iTan := thieleInterpolator(tTan, xVal) fmt.Printf("%16.14f\n", 6*iSin(.5)) fmt.Printf("%16.14f\n", 3*iCos(.5)) fmt.Printf("%16.14f\n", 4*iTan(1)) } func thieleInterpolator(x, y []float64) func(float64) float64 { n := len(x) ρ := make([][]float64, n) for i := range ρ { ρ[i] = make([]float64, n-i) ρ[i][0] = y[i] } for i := 0; i < n-1; i++ { ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0]) } for i := 2; i < n; i++ { for j := 0; j < n-i; j++ { ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2] } } ρ0 := ρ[0] return func(xin float64) float64 { var a float64 for i := n - 1; i > 1; i-- { a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a) } return y[0] + (xin-x[0])/(ρ0[1]+a) } }
import math def thieleInterpolator(x, y): ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)] for i in range(len(ρ)-1): ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0]) for i in range(2, len(ρ)): for j in range(len(ρ)-i): ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2] ρ0 = ρ[0] def t(xin): a = 0 for i in range(len(ρ0)-1, 1, -1): a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a) return y[0] + (xin-x[0]) / (ρ0[1]+a) return t xVal = [i*.05 for i in range(32)] tSin = [math.sin(x) for x in xVal] tCos = [math.cos(x) for x in xVal] tTan = [math.tan(x) for x in xVal] iSin = thieleInterpolator(tSin, xVal) iCos = thieleInterpolator(tCos, xVal) iTan = thieleInterpolator(tTan, xVal) print('{:16.14f}'.format(6*iSin(.5))) print('{:16.14f}'.format(3*iCos(.5))) print('{:16.14f}'.format(4*iTan(1)))
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s  %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d  %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s)) } }
>>> import math >>> from collections import Counter >>> >>> def entropy(s): ... p, lns = Counter(s), float(len(s)) ... return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) ... >>> >>> def fibword(nmax=37): ... fwords = ['1', '0'] ... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split())) ... def pr(n, fwords): ... while len(fwords) < n: ... fwords += [''.join(fwords[-2:][::-1])] ... v = fwords[n-1] ... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>')) ... for n in range(1, nmax+1): pr(n, fwords) ... >>> fibword() N Length Entropy Fibword 1 1 -0 1 2 1 -0 0 3 2 1 01 4 3 0.9182958 010 5 5 0.9709506 01001 6 8 0.954434 01001010 7 13 0.9612366 0100101001001 8 21 0.9587119 <too long> 9 34 0.9596869 <too long> 10 55 0.959316 <too long> 11 89 0.9594579 <too long> 12 144 0.9594038 <too long> 13 233 0.9594244 <too long> 14 377 0.9594165 <too long> 15 610 0.9594196 <too long> 16 987 0.9594184 <too long> 17 1597 0.9594188 <too long> 18 2584 0.9594187 <too long> 19 4181 0.9594187 <too long> 20 6765 0.9594187 <too long> 21 10946 0.9594187 <too long> 22 17711 0.9594187 <too long> 23 28657 0.9594187 <too long> 24 46368 0.9594187 <too long> 25 75025 0.9594187 <too long> 26 121393 0.9594187 <too long> 27 196418 0.9594187 <too long> 28 317811 0.9594187 <too long> 29 514229 0.9594187 <too long> 30 832040 0.9594187 <too long> 31 1346269 0.9594187 <too long> 32 2178309 0.9594187 <too long> 33 3524578 0.9594187 <too long> 34 5702887 0.9594187 <too long> 35 9227465 0.9594187 <too long> 36 14930352 0.9594187 <too long> 37 24157817 0.9594187 <too long> >>>
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s  %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d  %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s)) } }
>>> import math >>> from collections import Counter >>> >>> def entropy(s): ... p, lns = Counter(s), float(len(s)) ... return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) ... >>> >>> def fibword(nmax=37): ... fwords = ['1', '0'] ... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split())) ... def pr(n, fwords): ... while len(fwords) < n: ... fwords += [''.join(fwords[-2:][::-1])] ... v = fwords[n-1] ... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>')) ... for n in range(1, nmax+1): pr(n, fwords) ... >>> fibword() N Length Entropy Fibword 1 1 -0 1 2 1 -0 0 3 2 1 01 4 3 0.9182958 010 5 5 0.9709506 01001 6 8 0.954434 01001010 7 13 0.9612366 0100101001001 8 21 0.9587119 <too long> 9 34 0.9596869 <too long> 10 55 0.959316 <too long> 11 89 0.9594579 <too long> 12 144 0.9594038 <too long> 13 233 0.9594244 <too long> 14 377 0.9594165 <too long> 15 610 0.9594196 <too long> 16 987 0.9594184 <too long> 17 1597 0.9594188 <too long> 18 2584 0.9594187 <too long> 19 4181 0.9594187 <too long> 20 6765 0.9594187 <too long> 21 10946 0.9594187 <too long> 22 17711 0.9594187 <too long> 23 28657 0.9594187 <too long> 24 46368 0.9594187 <too long> 25 75025 0.9594187 <too long> 26 121393 0.9594187 <too long> 27 196418 0.9594187 <too long> 28 317811 0.9594187 <too long> 29 514229 0.9594187 <too long> 30 832040 0.9594187 <too long> 31 1346269 0.9594187 <too long> 32 2178309 0.9594187 <too long> 33 3524578 0.9594187 <too long> 34 5702887 0.9594187 <too long> 35 9227465 0.9594187 <too long> 36 14930352 0.9594187 <too long> 37 24157817 0.9594187 <too long> >>>
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "math" "strconv" "strings" ) func d2d(d float64) float64 { return math.Mod(d, 360) } func g2g(g float64) float64 { return math.Mod(g, 400) } func m2m(m float64) float64 { return math.Mod(m, 6400) } func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) } func d2g(d float64) float64 { return d2d(d) * 400 / 360 } func d2m(d float64) float64 { return d2d(d) * 6400 / 360 } func d2r(d float64) float64 { return d2d(d) * math.Pi / 180 } func g2d(g float64) float64 { return g2g(g) * 360 / 400 } func g2m(g float64) float64 { return g2g(g) * 6400 / 400 } func g2r(g float64) float64 { return g2g(g) * math.Pi / 200 } func m2d(m float64) float64 { return m2m(m) * 360 / 6400 } func m2g(m float64) float64 { return m2m(m) * 400 / 6400 } func m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 } func r2d(r float64) float64 { return r2r(r) * 180 / math.Pi } func r2g(r float64) float64 { return r2r(r) * 200 / math.Pi } func r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi } func s(f float64) string { wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), ".") if len(wf) == 1 { return fmt.Sprintf("%7s ", wf[0]) } le := len(wf[1]) if le > 7 { le = 7 } return fmt.Sprintf("%7s.%-7s", wf[0], wf[1][:le]) } func main() { angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ft := "%s %s %s %s %s\n" fmt.Printf(ft, " degrees ", "normalized degs", " gradians ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a))) } fmt.Printf(ft, "\n gradians ", "normalized grds", " degrees ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a))) } fmt.Printf(ft, "\n mils ", "normalized mils", " degrees ", " gradians ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a))) } fmt.Printf(ft, "\n radians ", "normalized rads", " degrees ", " gradians ", " mils ") for _, a := range angles { fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a))) } }
PI = 3.141592653589793 TWO_PI = 6.283185307179586 def normalize2deg(a): while a < 0: a += 360 while a >= 360: a -= 360 return a def normalize2grad(a): while a < 0: a += 400 while a >= 400: a -= 400 return a def normalize2mil(a): while a < 0: a += 6400 while a >= 6400: a -= 6400 return a def normalize2rad(a): while a < 0: a += TWO_PI while a >= TWO_PI: a -= TWO_PI return a def deg2grad(a): return a * 10.0 / 9.0 def deg2mil(a): return a * 160.0 / 9.0 def deg2rad(a): return a * PI / 180.0 def grad2deg(a): return a * 9.0 / 10.0 def grad2mil(a): return a * 16.0 def grad2rad(a): return a * PI / 200.0 def mil2deg(a): return a * 9.0 / 160.0 def mil2grad(a): return a / 16.0 def mil2rad(a): return a * PI / 3200.0 def rad2deg(a): return a * 180.0 / PI def rad2grad(a): return a * 200.0 / PI def rad2mil(a): return a * 3200.0 / PI
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "os" "path" ) func CommonPrefix(sep byte, paths ...string) string { switch len(paths) { case 0: return "" case 1: return path.Clean(paths[0]) } c := []byte(path.Clean(paths[0])) c = append(c, sep) for _, v := range paths[1:] { v = path.Clean(v) + string(sep) if len(v) < len(c) { c = c[:len(v)] } for i := 0; i < len(c); i++ { if v[i] != c[i] { c = c[:i] break } } } for i := len(c) - 1; i >= 0; i-- { if c[i] == sep { c = c[:i] break } } return string(c) } func main() { c := CommonPrefix(os.PathSeparator, "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", "/home "/home/user1/././tmp/covertly/foo", "/home/bob/../user1/tmp/coved/bar", ) if c == "" { fmt.Println("No common path") } else { fmt.Println("Common path:", c) } }
>>> import os >>> os.path.commonpath(['/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members']) '/home/user1/tmp'
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math" "math/rand" "time" ) func dice5() int { return rand.Intn(5) + 1 } func dice7() (i int) { for { i = 5*dice5() + dice5() if i < 27 { break } } return (i / 3) - 1 } func distCheck(f func() int, n int, repeats int, delta float64) (max float64, flatEnough bool) { count := make([]int, n) for i := 0; i < repeats; i++ { count[f()-1]++ } expected := float64(repeats) / float64(n) for _, c := range count { max = math.Max(max, math.Abs(float64(c)-expected)) } return max, max < delta } func main() { rand.Seed(time.Now().UnixNano()) const calls = 1000000 max, flatEnough := distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) max, flatEnough = distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) }
from collections import Counter from pprint import pprint as pp def distcheck(fn, repeats, delta): bin = Counter(fn() for i in range(repeats)) target = repeats // len(bin) deltacount = int(delta / 100. * target) assert all( abs(target - count) < deltacount for count in bin.values() ), "Bin distribution skewed from %i +/- %i: %s" % ( target, deltacount, [ (key, target - count) for key, count in sorted(bin.items()) ] ) pp(dict(bin))
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
computed = {} def sterling2(n, k): key = str(n) + "," + str(k) if key in computed.keys(): return computed[key] if n == k == 0: return 1 if (n > 0 and k == 0) or (n == 0 and k > 0): return 0 if n == k: return 1 if k > n: return 0 result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1) computed[key] = result return result print("Stirling numbers of the second kind:") MAX = 12 print("n/k".ljust(10), end="") for n in range(MAX + 1): print(str(n).rjust(10), end="") print() for n in range(MAX + 1): print(str(n).ljust(10), end="") for k in range(n + 1): print(str(sterling2(n, k)).rjust(10), end="") print() print("The maximum value of S2(100, k) = ") previous = 0 for k in range(1, 100 + 1): current = sterling2(100, k) if current > previous: previous = current else: print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1)) break
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
computed = {} def sterling2(n, k): key = str(n) + "," + str(k) if key in computed.keys(): return computed[key] if n == k == 0: return 1 if (n > 0 and k == 0) or (n == 0 and k > 0): return 0 if n == k: return 1 if k > n: return 0 result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1) computed[key] = result return result print("Stirling numbers of the second kind:") MAX = 12 print("n/k".ljust(10), end="") for n in range(MAX + 1): print(str(n).rjust(10), end="") print() for n in range(MAX + 1): print(str(n).ljust(10), end="") for k in range(n + 1): print(str(sterling2(n, k)).rjust(10), end="") print() print("The maximum value of S2(100, k) = ") previous = 0 for k in range(1, 100 + 1): current = sterling2(100, k) if current > previous: previous = current else: print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1)) break
Translate this program into Python but keep the logic exactly as in Go.
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
from itertools import islice class Recamans(): "Recamán's sequence generator callable class" def __init__(self): self.a = None self.n = None def __call__(self): "Recamán's sequence generator" nxt = 0 a, n = {nxt}, 0 self.a = a self.n = n yield nxt while True: an1, n = nxt, n + 1 nxt = an1 - n if nxt < 0 or nxt in a: nxt = an1 + n a.add(nxt) self.n = n yield nxt if __name__ == '__main__': recamans = Recamans() print("First fifteen members of Recamans sequence:", list(islice(recamans(), 15))) so_far = set() for term in recamans(): if term in so_far: print(f"First duplicate number in series is: a({recamans.n}) = {term}") break so_far.add(term) n = 1_000 setn = set(range(n + 1)) for _ in recamans(): if setn.issubset(recamans.a): print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})") break