Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same code in Python as shown below in Go.
package main import "fmt" import "io/ioutil" import "log" import "os" import "regexp" import "strings" func main() { err := fix() if err != nil { log.Fatalln(err) } } func fix() (err error) { buf, err := ioutil.ReadAll(os.Stdin) if err != nil { return err } out, err := Lang(string(buf)) if err != nil { ...
from re import sub testtexts = [ , , ] for txt in testtexts: text2 = sub(r'<lang\s+\"?([\w\d\s]+)\"?\s?>', r'<syntaxhighlight lang=\1>', txt) text2 = sub(r'<lang\s*>', r'<syntaxhighlight lang=text>', text2) text2 = sub(r'</lang\s*>', r'
Write the same code in Python as shown below in Go.
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { ...
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ ...
Produce a functionally identical Python code for the snippet given in Go.
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { ...
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ ...
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "strconv" ) func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd ...
def ownCalcPass (password, nonce, test=False) : start = True num1 = 0 num2 = 0 password = int(password) if test: print("password: %08x" % (password)) for c in nonce : if c != "0": if start: num2 = password start = False if test:...
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "bytes" "fmt" "io/ioutil" "log" "math/rand" "sort" "strings" "time" ) var adfgvx = "ADFGVX" var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func distinct(bs []byte) []byte { var u []byte for _, b := range bs { if !bytes.Contains(u, []byte{b}...
from random import shuffle, choice from itertools import product, accumulate from numpy import floor, sqrt class ADFGVX: def __init__(self, spoly, k, alph='ADFGVX'): self.polybius = list(spoly.upper()) self.pdim = int(floor(sqrt(len(self.polybius)))) self.key = list(k.upper()) ...
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "bytes" "fmt" "io/ioutil" "log" "math/rand" "sort" "strings" "time" ) var adfgvx = "ADFGVX" var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func distinct(bs []byte) []byte { var u []byte for _, b := range bs { if !bytes.Contains(u, []byte{b}...
from random import shuffle, choice from itertools import product, accumulate from numpy import floor, sqrt class ADFGVX: def __init__(self, spoly, k, alph='ADFGVX'): self.polybius = list(spoly.upper()) self.pdim = int(floor(sqrt(len(self.polybius)))) self.key = list(k.upper()) ...
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "math" ) type float float64 func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) } func main() { ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"} for _, x := range []float{float(-5), float(5)} { for _, e := range []floa...
from itertools import product xx = '-5 +5'.split() pp = '2 3'.split() texts = '-x**p -(x)**p (-x)**p -(x**p)'.split() print('Integer variable exponentiation') for x, p in product(xx, pp): print(f' x,p = {x:2},{p}; ', end=' ') x, p = int(x), int(p) print('; '.join(f"{t} =={eval(t):4}" for t in texts)) pr...
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "math" ) type float float64 func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) } func main() { ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"} for _, x := range []float{float(-5), float(5)} { for _, e := range []floa...
from itertools import product xx = '-5 +5'.split() pp = '2 3'.split() texts = '-x**p -(x)**p (-x)**p -(x**p)'.split() print('Integer variable exponentiation') for x, p in product(xx, pp): print(f' x,p = {x:2},{p}; ', end=' ') x, p = int(x), int(p) print('; '.join(f"{t} =={eval(t):4}" for t in texts)) pr...
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "strings" ) func isDigit(b byte) bool { return '0' <= b && b <= '9' } func separateHouseNumber(address string) (street string, house string) { length := len(address) fields := strings.Fields(address) size := len(fields) last := fields[size-1] penult := fiel...
Plataanstraat 5 split as (Plataanstraat, 5) Straat 12 split as (Straat, 12) Straat 12 II split as (Straat, 12 II) Dr. J. Straat 12 split as (Dr. J. Straat , 12) Dr. J. Straat 12 a split as (Dr. J. Straat, 12 a) Dr. J. Straat 12-14 split as (Dr. J. Straat, 12...
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "strings" ) type nNode struct { name string children []nNode } type iNode struct { level int name string } func toNest(iNodes []iNode, start, level int, n *nNode) { if level == 0 { n.name = iNodes[0].name } for i := start + 1; i < len(iNod...
import itertools import re import sys from collections import deque from typing import NamedTuple RE_OUTLINE = re.compile(r"^((?: |\t)*)(.+)$", re.M) COLORS = itertools.cycle( [ " " " " " ] ) class Node: def __init__(self, indent, value, parent, children=None)...
Generate a Python translation of this Go snippet without changing its computational steps.
package main import "fmt" func indexOf(l []int, n int) int { for i := 0; i < len(l); i++ { if l[i] == n { return i } } return -1 } func common2(l1, l2 []int) []int { c1, c2 := len(l1), len(l2) shortest, longest := l1, l2 if c1 > c2 { shortest, longest ...
def common_list_elements(*lists): return list(set.intersection(*(set(list_) for list_ in lists))) if __name__ == "__main__": test_cases = [ ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]), ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]), ] for c...
Port the provided Go code into Python while preserving the original functionality.
package main import "fmt" func indexOf(l []int, n int) int { for i := 0; i < len(l); i++ { if l[i] == n { return i } } return -1 } func common2(l1, l2 []int) []int { c1, c2 := len(l1), len(l2) shortest, longest := l1, l2 if c1 > c2 { shortest, longest ...
def common_list_elements(*lists): return list(set.intersection(*(set(list_) for list_ in lists))) if __name__ == "__main__": test_cases = [ ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]), ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]), ] for c...
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "math" ) type mwriter struct { value float64 log string } func (m mwriter) bind(f func(v float64) mwriter) mwriter { n := f(m.value) n.log = m.log + n.log return n } func unit(v float64, s string) mwriter { return mwriter{v, fmt.Sprintf("  %-17s: %g\n", ...
from __future__ import annotations import functools import math import os from typing import Any from typing import Callable from typing import Generic from typing import List from typing import TypeVar from typing import Union T = TypeVar("T") class Writer(Generic[T]): def __init__(self, value: Union[T, Wri...
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "math" "strings" "time" ) var board [][]bool var diag1, diag2 [][]int var diag1Lookup, diag2Lookup []bool var n, minCount int var layout string func isAttacked(piece string, row, col int) bool { if piece == "Q" { for i := 0; i < n; i++ { if board[i]...
from mip import Model, BINARY, xsum, minimize def n_queens_min(N): if N < 4: brd = [[0 for i in range(N)] for j in range(N)] brd[0 if N < 2 else 1][0 if N < 2 else 1] = 1 return 1, brd model = Model() board = [[model.add_var(var_type=BINARY) for j in range(N)] for i in range...
Please provide an equivalent version of this Go code in Python.
package main import ( "bytes" "fmt" "log" ) func wordle(answer, guess string) []int { n := len(guess) if n != len(answer) { log.Fatal("The words must be of the same length.") } answerBytes := []byte(answer) result := make([]int, n) for i := 0; i < n; i++ { if guess...
from functools import reduce from operator import add def wordleScore(target, guess): return mapAccumL(amber)( *first(charCounts)( mapAccumL(green)( [], zip(target, guess) ) ) )[1] def green(residue, tg): t, g = tg return (residue...
Write the same code in Python as shown below in Go.
package main import ( "fmt" "rcu" "strings" ) var grid = [][]int { { 8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8}, {49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0}, {81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3...
from math import prod def maxproduct(mat, length): nrow, ncol = len(mat), len(mat[0]) maxprod, maxrow, maxcol, arr = 0, [0, 0], [0, 0], [0] for row in range(nrow): for col in range(ncol): row2, col2 = row + length, col + length if row < nrow - length: ...
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(504) var nprimes []int fmt.Println("Neighbour primes < 500:") for i := 0; i < len(primes)-1; i++ { p := primes[i]*primes[i+1] + 2 if rcu.IsPrime(p) { nprimes = append(nprimes, primes[i]) ...
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': print("p q pq+2") print("-----------------------") for p in range(2, 499): if not isPrime(p): continue q = p...
Rewrite the snippet below in Python so it works the same as the original Go code.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(504) var nprimes []int fmt.Println("Neighbour primes < 500:") for i := 0; i < len(primes)-1; i++ { p := primes[i]*primes[i+1] + 2 if rcu.IsPrime(p) { nprimes = append(nprimes, primes[i]) ...
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': print("p q pq+2") print("-----------------------") for p in range(2, 499): if not isPrime(p): continue q = p...
Write the same algorithm in Python as shown in this Go implementation.
package main import "fmt" type Resistor struct { symbol rune resistance, voltage float64 a, b *Resistor } func (r *Resistor) res() float64 { switch r.symbol { case '+': return r.a.res() + r.b.res() case '*': return 1 / (1/r.a.res() + 1/r.b.res()) ...
import strutils, strformat type Node = ref object kind: char resistance: float voltage: float a: Node b: Node proc res(node: Node): float = if node.kind == '+': return node.a.res + node.b.res if node.kind == '*': return 1 / (1 / node.a.res + 1 / node.b.res) node.resistance proc current(...
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "rcu" ) func genUpsideDown(limit int) chan int { ch := make(chan int) wrappings := [][2]int{ {1, 9}, {2, 8}, {3, 7}, {4, 6}, {5, 5}, {6, 4}, {7, 3}, {8, 2}, {9, 1}, } evens := []int{19, 28, 37, 46, 55, 64, 73, 82, 91} odds := []int{5} oddInde...
def gen_upside_down_number(): wrappings = [[1, 9], [2, 8], [3, 7], [4, 6], [5, 5], [6, 4], [7, 3], [8, 2], [9, 1]] evens = [19, 28, 37, 46, 55, 64, 73, 82, 91] odds = [5] odd_index, even_index = 0, 0 ndigits = 1 while True: if ndigits % 2 == 1: if len...
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" ) const MAXITER = 151 func minkowski(x float64) float64 { if x > 1 || x < 0 { return math.Floor(x) + minkowski(x-math.Floor(x)) } p := uint64(x) q := uint64(1) r := p + 1 s := uint64(1) d := 1.0 y := float64(p) for { d = d...
print( "{:19.16f} {:19.16f}".format( minkowski(minkowski_inv(4.04145188432738056)), minkowski_inv(minkowski(4.04145188432738056)), ) )
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( ed "github.com/Ernyoke/Imger/edgedetection" "github.com/Ernyoke/Imger/imgio" "log" ) func main() { img, err := imgio.ImreadRGBA("Valve_original_(1).png") if err != nil { log.Fatal("Could not read image", err) } cny, err := ed.CannyRGBA(img, 15, 45, 5) if ...
import numpy as np from scipy.ndimage.filters import convolve, gaussian_filter from scipy.misc import imread, imshow def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31): im = np.array(im, dtype=float) im2 = gaussian_filter(im, blur) im3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) ...
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "math/rand" "time" ) var suits = []string{"♣", "♦", "♥", "♠"} var faces = []string{"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"} var cards = make([]string, 52) var ranks = make([]int, 52) func init() { for i := 0; i < 52; i++ { cards[i] = fmt.Spr...
from numpy.random import shuffle SUITS = ['♣', '♦', '♥', '♠'] FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] DECK = [f + s for f in FACES for s in SUITS] CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK))) class WarCardGame: def __init__(self): deck =...
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "math/rand" "time" ) var suits = []string{"♣", "♦", "♥", "♠"} var faces = []string{"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"} var cards = make([]string, 52) var ranks = make([]int, 52) func init() { for i := 0; i < 52; i++ { cards[i] = fmt.Spr...
from numpy.random import shuffle SUITS = ['♣', '♦', '♥', '♠'] FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] DECK = [f + s for f in FACES for s in SUITS] CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK))) class WarCardGame: def __init__(self): deck =...
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "container/heap" "image" "image/color" "image/png" "log" "math" "os" "sort" ) func main() { f, err := os.Open("Quantum_frog.png") if err != nil { log.Fatal(err) } img, err := png.Decode(f) if ec := f.Close(); err != nil { log.Fa...
from PIL import Image if __name__=="__main__": im = Image.open("frog.png") im2 = im.quantize(16) im2.show()
Generate an equivalent Python version of this Go code.
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } func commatize(n int) string { s :=...
import random from typing import List, Callable, Optional def modifier(x: float) -> float: return 2*(.5 - x) if x < 0.5 else 2*(x - .5) def modified_random_distribution(modifier: Callable[[float], float], n: int) -> List[float]: d: List[float] = [] while len(d)...
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } func commatize(n int) string { s :=...
import random from typing import List, Callable, Optional def modifier(x: float) -> float: return 2*(.5 - x) if x < 0.5 else 2*(x - .5) def modified_random_distribution(modifier: Callable[[float], float], n: int) -> List[float]: d: List[float] = [] while len(d)...
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } func commatize(n int) string { s :=...
import random from typing import List, Callable, Optional def modifier(x: float) -> float: return 2*(.5 - x) if x < 0.5 else 2*(x - .5) def modified_random_distribution(modifier: Callable[[float], float], n: int) -> List[float]: d: List[float] = [] while len(d)...
Write the same code in Python as shown below in Go.
package main import ( "fmt" "math" "sort" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { lists := [][]int{ {3, 4, 34, 25, 9, 12, 36, 56, 36}, {2, 8, 81, 169, 34, 55, 76, 49, 7}, {75, 121, 75, 144, 35, 16, 46, 35}, } ...
import math print("working...") list = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)] Squares = [] def issquare(x): for p in range(x): if x == p*p: return 1 for n in range(3): for m in range(len(list[n])): if issquare(list[n][m]): Squares.append(list[n][m]) Squares.sor...
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "math" "sort" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { lists := [][]int{ {3, 4, 34, 25, 9, 12, 36, 56, 36}, {2, 8, 81, 169, 34, 55, 76, 49, 7}, {75, 121, 75, 144, 35, 16, 46, 35}, } ...
import math print("working...") list = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)] Squares = [] def issquare(x): for p in range(x): if x == p*p: return 1 for n in range(3): for m in range(len(list[n])): if issquare(list[n][m]): Squares.append(list[n][m]) Squares.sor...
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math/big" "strconv" "strings" ) var suffixes = " KMGTPEZYXWVU" var ggl = googol() func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } ...
import math import os def suffize(num, digits=None, base=10): suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol'] exponent_distance = 10 if base == 2 else 3 num = num.strip().replace(',', '') num_sign = num[0] if num[0] in '+-' else '' num = abs(float(num)) ...
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "math/big" "strconv" "strings" ) var suffixes = " KMGTPEZYXWVU" var ggl = googol() func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } ...
import math import os def suffize(num, digits=None, base=10): suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol'] exponent_distance = 10 if base == 2 else 3 num = num.strip().replace(',', '') num_sign = num[0] if num[0] in '+-' else '' num = abs(float(num)) ...
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "sort" ) func reverse(s string) string { var r = []rune(s) for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func longestPalSubstring(s string) []string { var le = len(s) if le <= 1 { return []str...
def longestPalindromes(s): k = s.lower() palindromes = [ palExpansion(k)(ab) for ab in palindromicNuclei(k) ] maxLength = max([ len(x) for x in palindromes ]) if palindromes else 1 return ( [ x for x in palindromes if maxLength == len(x) ...
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "bufio" "fmt" "log" "math/rand" "os" "strconv" "strings" "time" ) var cave = map[int][3]int{ 1: {2, 3, 4}, 2: {1, 5, 6}, 3: {1, 7, 8}, 4: {1, 9, 10}, 5: {2, 9, 11}, 6: {2, 7, 12}, 7: {3, 6, 13}, 8: {3, 10, 14}, 9: {4, 5, 15}, 10: {4, 8, 16}, 11: {5, 12...
import random class WumpusGame(object): def __init__(self, edges=[]): if edges: cave = {} N = max([edges[i][0] for i in range(len(edges))]) for i in range(N): exits = [edge[1] for edge in edges if edge[0] == i] cave[i] = exits else: cave = {1: [2,3,4], 2: [1,5,6], 3: [1,7,8], 4: [1...
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "bytes" "fmt" "io/ioutil" "log" "runtime" ) func main() { fileName1 := "rodgers.txt" fileName2 := "rodgers_reversed.txt" lineBreak := "\n" if runtime.GOOS == "windows" { lineBreak = "\r\n" } b, err := ioutil.ReadFile(fileName1) if err ...
import sys if len(sys.argv)!=2: print("Usage : python " + sys.argv[0] + " <filename>") exit() dataFile = open(sys.argv[1],"r") fileData = dataFile.read().split('\n') dataFile.close() [print(i) for i in fileData[::-1]]
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "log" ) func minimum(a []int) int { min := a[0] for i := 1; i < len(a); i++ { if a[i] < min { min = a[i] } } return min } func sum(a []int) int { s := 0 for _, i := range a { s = s + i } return s } func hourglass...
def hourglass_puzzle(): t4 = 0 while t4 < 10_000: t7_left = 7 - t4 % 7 if t7_left == 9 - 4: break t4 += 4 else: print('Not found') return print(f) hourglass_puzzle()
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "log" ) func minimum(a []int) int { min := a[0] for i := 1; i < len(a); i++ { if a[i] < min { min = a[i] } } return min } func sum(a []int) int { s := 0 for _, i := range a { s = s + i } return s } func hourglass...
def hourglass_puzzle(): t4 = 0 while t4 < 10_000: t7_left = 7 - t4 % 7 if t7_left == 9 - 4: break t4 += 4 else: print('Not found') return print(f) hourglass_puzzle()
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "sort" ) func main() { strings := []string{"1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"} u := make(map[rune]int) for _, s := range strings { m := make(map[rune]int) for _, c := range s { m[c]++ } for k, v := range m {...
LIST = ["1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"] print(sorted([ch for ch in set([c for c in ''.join(LIST)]) if all(w.count(ch) == 1 for w in LIST)]))
Preserve the algorithm and functionality while converting the code from Go to Python.
package fib import "fmt" type Value interface { LT(Value) bool } type Node struct { value Value parent *Node child *Node prev, next *Node rank int mark bool } func (n Node) Value() Value { return n.value } type Heap struct{ *Node } func MakeHeap() *Heap { ret...
class FibonacciHeap: class Node: def __init__(self, data): self.data = data self.parent = self.child = self.left = self.right = None self.degree = 0 self.mark = False def iterate(self, head): node = stop = head f...
Write a version of this Go function in Python with identical behavior.
package main import ( "fmt" "strconv" "strings" "time" ) var sacred = strings.Fields("Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw") var civil = strings.Fields("Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muw...
import datetime def g2m(date, gtm_correlation=True): correlation = 584283 if gtm_correlation else 584285 long_count_days = [144000, 7200, 360, 20, 1] tzolkin_months = ['Imix’', 'Ik’', 'Ak’bal', 'K’an', 'Chikchan', 'Kimi', 'Manik’', 'Lamat', 'Muluk', 'Ok', 'Chuwen', 'Eb'...
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "math/big" "strconv" "strings" ) func main() { var res []int64 for n := 0; n <= 50; n++ { ns := strconv.Itoa(n) k := int64(1) for { bk := big.NewInt(k) s := bk.Exp(bk, bk, nil).String() if strings.Contains(...
import sys if len(sys.argv)!=2: print("Usage : python " + sys.argv[0] + " <whole number>") exit() numLimit = int(sys.argv[1]) resultSet = {} base = 1 while len(resultSet)!=numLimit: result = base**base for i in range(0,numLimit): if str(i) in str(result) and i not in resultSet: ...
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 ...
print("working...") row = 0 limit = 1500 Sophie = [] def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True for n in range(2,limit): p = 2*n + 1 if isPrime(n) and isPrime(p): Sophie.append(n) print("Found ",end = "") print(len(Sophie),end = "") print(" Sa...
Write the same code in Python as shown below in Go.
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 ...
print("working...") row = 0 limit = 1500 Sophie = [] def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True for n in range(2,limit): p = 2*n + 1 if isPrime(n) and isPrime(p): Sophie.append(n) print("Found ",end = "") print(len(Sophie),end = "") print(" Sa...
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "bufio" "fmt" "golang.org/x/crypto/ssh/terminal" "log" "os" "regexp" "strconv" ) type Color struct{ r, g, b int } type ColorEx struct { color Color code string } var colors = []ColorEx{ {Color{15, 0, 0}, "31"}, {Color{0, 15, 0}, "32"}, {Color{15...
from __future__ import unicode_literals import argparse import fileinput import os import sys from functools import partial from itertools import count from itertools import takewhile ANSI_RESET = "\u001b[0m" RED = (255, 0, 0) GREEN = (0, 255, 0) YELLOW = (255, 255, 0) BLUE = (0, 0, 255) MAGENTA = (255, 0, 255)...
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "time" ) const ( chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" host = "localhost:8000" ) type database map[string]string type shortener struct { Long string `json...
import sqlite3 import string import random from http import HTTPStatus from flask import Flask from flask import Blueprint from flask import abort from flask import current_app from flask import g from flask import jsonify from flask import redirect from flask import request from flask import url_for CHARS = froz...
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "time" ) const ( chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" host = "localhost:8000" ) type database map[string]string type shortener struct { Long string `json...
import sqlite3 import string import random from http import HTTPStatus from flask import Flask from flask import Blueprint from flask import abort from flask import current_app from flask import g from flask import jsonify from flask import redirect from flask import request from flask import url_for CHARS = froz...
Please provide an equivalent version of this Go code in Python.
package main import ( "bytes" "errors" "flag" "fmt" "io" "io/ioutil" "log" "math/rand" "os" "time" ) const ( Rows = 3 Cols = 3 ) var vlog *log.Logger func main() { verbose := flag.Bool("v", false, "verbose") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } logOutput := ioutil.Disc...
import sys black_pawn = " \u265f " white_pawn = " \u2659 " empty_square = " " def draw_board(board_data): bg_black = "\u001b[48;5;237m" bg_white = "\u001b[48;5;245m" clear_to_eol = "\u001b[0m\u001b[K\n" board = ["1 ", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black,...
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "bytes" "errors" "flag" "fmt" "io" "io/ioutil" "log" "math/rand" "os" "time" ) const ( Rows = 3 Cols = 3 ) var vlog *log.Logger func main() { verbose := flag.Bool("v", false, "verbose") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } logOutput := ioutil.Disc...
import sys black_pawn = " \u265f " white_pawn = " \u2659 " empty_square = " " def draw_board(board_data): bg_black = "\u001b[48;5;237m" bg_white = "\u001b[48;5;245m" clear_to_eol = "\u001b[0m\u001b[K\n" board = ["1 ", bg_black, board_data[0][0], bg_white, board_data[0][1], bg_black,...
Write the same algorithm in Python as shown in this Go implementation.
package main import ( "fmt" "sort" ) type graph struct { nn int st int nbr [][]int } type nodeval struct { n int v int } func contains(s []int, n int) bool { for _, e := range s { if e == n { return true } } return false } func newG...
import re from collections import defaultdict from itertools import count connection_re = r class Graph: def __init__(self, name, connections): self.name = name self.connections = connections g = self.graph = defaultdict(list) matches = re.finditer(connection_re, connections, ...
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "rcu" "sort" ) func main() { list := []int{2, 43, 81, 122, 63, 13, 7, 95, 103} var primes []int for _, e := range list { if rcu.IsPrime(e) { primes = append(primes, e) } } sort.Ints(primes) fmt.Println(primes) }
print("working...") print("Primes are:") def isprime(m): for i in range(2,int(m**0.5)+1): if m%i==0: return False return True Primes = [2,43,81,122,63,13,7,95,103] Temp = [] for n in range(len(Primes)): if isprime(Primes[n]): Temp.append(Primes[n]) Temp.sort() print(Temp) print("done....
Port the following code from Go to Python with equivalent syntax and logic.
package main import "fmt" var cnt = 0 var cnt2 = 0 var wdth = 0 func factorial(n int) int { prod := 1 for i := 2; i <= n; i++ { prod *= i } return prod } func count(want int, used []int, sum int, have, uindices, rindices []int) { if sum == want { cnt++ cnt2 += factori...
from itertools import product, compress fact = lambda n: n and n*fact(n - 1) or 1 combo_count = lambda total, coins, perm:\ sum(perm and fact(len(x)) or 1 for x in (list(compress(coins, c)) for c in product(*([(0, 1)]*len(coins)))) ...
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import "fmt" var cnt = 0 var cnt2 = 0 var wdth = 0 func factorial(n int) int { prod := 1 for i := 2; i <= n; i++ { prod *= i } return prod } func count(want int, used []int, sum int, have, uindices, rindices []int) { if sum == want { cnt++ cnt2 += factori...
from itertools import product, compress fact = lambda n: n and n*fact(n - 1) or 1 combo_count = lambda total, coins, perm:\ sum(perm and fact(len(x)) or 1 for x in (list(compress(coins, c)) for c in product(*([(0, 1)]*len(coins)))) ...
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) type minmult struct { min int mult float64 } var abbrevs = map[string]minmult{ "PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12}, "GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100}, } var metr...
from functools import reduce from operator import mul from decimal import * getcontext().prec = MAX_PREC def expand(num): suffixes = [ ('greatgross', 7, 12, 3), ('gross', 2, 12, 2), ('dozens', 3, 12, 1), ('pairs', 4, 2, 1), ('scores', 3, 20, 1), ('googols',...
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) type minmult struct { min int mult float64 } var abbrevs = map[string]minmult{ "PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12}, "GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100}, } var metr...
from functools import reduce from operator import mul from decimal import * getcontext().prec = MAX_PREC def expand(num): suffixes = [ ('greatgross', 7, 12, 3), ('gross', 2, 12, 2), ('dozens', 3, 12, 1), ('pairs', 4, 2, 1), ('scores', 3, 20, 1), ('googols',...
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func genFactBaseNums(size int, countOnly bool) ([][]int, int) { var results [][]int count := 0 for n :...
import math def apply_perm(omega,fbn): for m in range(len(fbn)): g = fbn[m] if g > 0: new_first = omega[m+g] omega[m+1:m+g+1] = omega[m:m+g] omega[m] = new_first return omega def int...
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "math" "math/cmplx" ) func dft(x []complex128) []complex128 { N := len(x) y := make([]complex128, N) for k := 0; k < N; k++ { for n := 0; n < N; n++ { t := -1i * 2 * complex(math.Pi*float64(k)*float64(n)/float64(N), 0) y[k] += x[n] * ...
import cmath def dft( x ): N = len( x ) result = [] for k in range( N ): r = 0 for n in range( N ): t = -2j * cmath.pi * k * n / N r += x[n] * cmath.exp( t ...
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "sort" ) func firstMissingPositive(a []int) int { var b []int for _, e := range a { if e > 0 { b = append(b, e) } } sort.Ints(b) le := len(b) if le == 0 || b[0] > 1 { return 1 } for i := 1; i < le; i++ { if...
from itertools import count def firstGap(xs): return next(x for x in count(1) if x not in xs) def main(): print('\n'.join([ f'{repr(xs)} -> {firstGap(xs)}' for xs in [ [1, 2, 0], [3, 4, -1, 1], [7, 8, 9, 11, 12] ] ])) if __name__ == '...
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" "regexp" "strings" ) var names = map[string]int64{ "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": ...
from spell_integer import spell_integer, SMALL, TENS, HUGE def int_from_words(num): words = num.replace(',','').replace(' and ', ' ').replace('-', ' ').split() if words[0] == 'minus': negmult = -1 words.pop(0) else: negmult = 1 small, total = 0, 0 for word in words: ...
Write the same code in Python as shown below in Go.
package main import ( "fmt" "math" "rcu" ) func magicConstant(n int) int { return (n*n + 1) * n / 2 } var ss = []string{ "\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079", } func superscript(n int) string { if n < 10 { return ss[n]...
def a(n): n += 2 return n*(n**2 + 1)/2 def inv_a(x): k = 0 while k*(k**2+1)/2+2 < x: k+=1 return k if __name__ == '__main__': print("The first 20 magic constants are:"); for n in range(1, 20): print(int(a(n)), end = " "); print("\nThe 1,000th magic constant is:",in...
Write the same code in Python as shown below in Go.
package main import "fmt" func main() { denoms := []int{200, 100, 50, 20, 10, 5, 2, 1} coins := 0 amount := 988 remaining := 988 fmt.Println("The minimum number of coins needed to make a value of", amount, "is as follows:") for _, denom := range denoms { n := remaining / denom ...
def makechange(denominations = [1,2,5,10,20,50,100,200], total = 988): print(f"Available denominations: {denominations}. Total is to be: {total}.") coins, remaining = sorted(denominations, reverse=True), total for n in range(len(coins)): coinsused, remaining = divmod(remaining, coins[n]) if ...
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "rcu" "strings" ) func main() { limit := 100_000 primes := rcu.Primes(limit * 10) var results []int for _, p := range primes { if p < 1000 || p > 99999 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "1...
def prime(limite, mostrar): global columna columna = 0 for n in range(limite): strn = str(n) if isPrime(n) and ('123' in str(n)): columna += 1 if mostrar == True: print(n, end=" "); if columna % 8 == 0: ...
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "rcu" "strings" ) func main() { limit := 100_000 primes := rcu.Primes(limit * 10) var results []int for _, p := range primes { if p < 1000 || p > 99999 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "1...
def prime(limite, mostrar): global columna columna = 0 for n in range(limite): strn = str(n) if isPrime(n) and ('123' in str(n)): columna += 1 if mostrar == True: print(n, end=" "); if columna % 8 == 0: ...
Change the following Go code into Python without altering its purpose.
package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "os" "sort" ) func main() { if len(os.Args) != 2 { fmt.Println("usage ff <go source filename>") return } src, err := ioutil.ReadFile(os.Args[1]) if err != nil { fmt.Println(err) ...
import ast class CallCountingVisitor(ast.NodeVisitor): def __init__(self): self.calls = {} def visit_Call(self, node): if isinstance(node.func, ast.Name): fun_name = node.func.id call_count = self.calls.get(fun_name, 0) self.calls[fun_name] = call_count + 1...
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "fmt" "log" "math" "math/rand" "time" ) var minDelta = 1.0 func getMaxPrice(prices []float64) float64 { max := prices[0] for i := 1; i < len(prices); i++ { if prices[i] > max { max = prices[i] } } return max } func getPRangeCount(...
import random price_list_size = random.choice(range(99_000, 101_000)) price_list = random.choices(range(100_000), k=price_list_size) delta_price = 1 def get_prange_count(startp, endp): return len([r for r in price_list if startp <= r <= endp]) def get_max_price(): return max(price_list) def get_5k(...
Write a version of this Go function in Python with identical behavior.
package main import ( "fmt" big "github.com/ncw/gmp" ) func cullen(n uint) *big.Int { one := big.NewInt(1) bn := big.NewInt(int64(n)) res := new(big.Int).Lsh(one, n) res.Mul(res, bn) return res.Add(res, one) } func woodall(n uint) *big.Int { res := cullen(n) return res.Sub(res, bi...
print("working...") print("First 20 Cullen numbers:") for n in range(1,21): num = n*pow(2,n)+1 print(str(num),end= " ") print() print("First 20 Woodall numbers:") for n in range(1,21): num = n*pow(2,n)-1 print(str(num),end=" ") print() print("done...")
Convert the following code from Go to Python, ensuring the logic remains intact.
package main import ( "fmt" "rcu" "strconv" "strings" ) func findFirst(list []int) (int, int) { for i, n := range list { if n > 1e7 { return n, i } } return -1, -1 } func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; ...
from sympy import isprime def print50(a, width=8): for i, n in enumerate(a): print(f'{n: {width},}', end='\n' if (i + 1) % 10 == 0 else '') def generate_cyclops(maxdig=9): yield 0 for d in range((maxdig + 1) // 2): arr = [str(i) for i in range(10**d, 10**(d+1)) if not('0' in str(i))] ...
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "rcu" ) func main() { c := rcu.PrimeSieve(5505, false) var triples [][3]int fmt.Println("Prime triplets: p, p + 2, p + 6 where p < 5,500:") for i := 3; i < 5500; i += 2 { if !c[i] && !c[i+2] && !c[i+6] { triples = append(triples, [3]int{i, i + 2,...
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 5499, 2): if not isPrime(p+6): continue if not isPrime(p+2): continue if not isPrime(p): ...
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "rcu" ) func main() { c := rcu.PrimeSieve(5505, false) var triples [][3]int fmt.Println("Prime triplets: p, p + 2, p + 6 where p < 5,500:") for i := 3; i < 5500; i += 2 { if !c[i] && !c[i+2] && !c[i+6] { triples = append(triples, [3]int{i, i + 2,...
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 5499, 2): if not isPrime(p+6): continue if not isPrime(p+2): continue if not isPrime(p): ...
Transform the following Go implementation into Python, maintaining the same output and logic.
package main import ( "fmt" "log" "strings" ) var glyphs = []rune("♜♞♝♛♚♖♘♗♕♔") var names = map[rune]string{'R': "rook", 'N': "knight", 'B': "bishop", 'Q': "queen", 'K': "king"} var g2lMap = map[rune]string{ '♜': "R", '♞': "N", '♝': "B", '♛': "Q", '♚': "K", '♖': "R", '♘': "N", '♗': "B", '♕': "Q", ...
def validate_position(candidate: str): assert ( len(candidate) == 8 ), f"candidate position has invalide len = {len(candidate)}" valid_pieces = {"R": 2, "N": 2, "B": 2, "Q": 1, "K": 1} assert { piece for piece in candidate } == valid_pieces.keys(), f"candidate position contains inv...
Can you help me rewrite this code in Python instead of Go, keeping it the same logically?
package main import ( "fmt" "log" ) var endings = [][]string{ {"o", "as", "at", "amus", "atis", "ant"}, {"eo", "es", "et", "emus", "etis", "ent"}, {"o", "is", "it", "imus", "itis", "unt"}, {"io", "is", "it", "imus", "itis", "iunt"}, } var infinEndings = []string{"are", "ēre", "ere", "ire"} v...
def conjugate(infinitive): if not infinitive[-3:] == "are": print("'", infinitive, "' non prima coniugatio verbi.\n", sep='') return False stem = infinitive[0:-3] if len(stem) == 0: print("\'", infinitive, "\' non satis diu conjugatus\n", sep='') return False p...
Maintain the same structure and functionality when rewriting this code in Python.
package main import ( "fmt" "log" ) var endings = [][]string{ {"o", "as", "at", "amus", "atis", "ant"}, {"eo", "es", "et", "emus", "etis", "ent"}, {"o", "is", "it", "imus", "itis", "unt"}, {"io", "is", "it", "imus", "itis", "iunt"}, } var infinEndings = []string{"are", "ēre", "ere", "ire"} v...
def conjugate(infinitive): if not infinitive[-3:] == "are": print("'", infinitive, "' non prima coniugatio verbi.\n", sep='') return False stem = infinitive[0:-3] if len(stem) == 0: print("\'", infinitive, "\' non satis diu conjugatus\n", sep='') return False p...
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "math/big" "rcu" "sort" ) func main() { primes := rcu.Primes(379) primorial := big.NewInt(1) var fortunates []int bPrime := new(big.Int) for _, prime := range primes { bPrime.SetUint64(uint64(prime)) primorial.Mul(primorial, bPrime) ...
from sympy.ntheory.generate import primorial from sympy.ntheory import isprime def fortunate_number(n): i = 3 primorial_ = primorial(n) while True: if isprime(primorial_ + i): return i i += 2 fortunate_numbers = set() for i in range(1, 76): fortunate_numbers....
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "math" "sort" "strings" ) func sortedOutline(originalOutline []string, ascending bool) { outline := make([]string, len(originalOutline)) copy(outline, originalOutline) indent := "" del := "\x7f" sep := "\x00" var messages []string if strings.Tri...
from itertools import chain, product, takewhile, tee from functools import cmp_to_key, reduce def sortedOutline(cmp): def go(outlineText): indentTuples = indentTextPairs( outlineText.splitlines() ) return bindLR( minimumIndent(enumerate(indentTuples)) ...
Produce a functionally identical Python code for the snippet given in Go.
package main import ( "fmt" "math/big" "rcu" ) func lcm(n int) *big.Int { lcm := big.NewInt(1) t := new(big.Int) for _, p := range rcu.Primes(n) { f := p for f*p <= n { f *= p } lcm.Mul(lcm, t.SetUint64(uint64(f))) } return lcm } func main()...
from math import gcd from functools import reduce def lcm(a, b): return 0 if 0 == a or 0 == b else ( abs(a * b) // gcd(a, b) ) for i in [10, 20, 200, 2000]: print(str(i) + ':', reduce(lcm, range(1, i + 1)))
Keep all operations the same but rewrite the snippet in Python.
package main import ( "fmt" "math" "rcu" ) func contains(a []int, f int) bool { for _, e := range a { if e == f { return true } } return false } func main() { const euler = 0.57721566490153286 primes := rcu.Primes(1 << 31) pc := len(primes) sum := 0...
from math import log def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': Euler = 0.57721566490153286 m = 0 for x in range(2, 10_000_000): if isPrime(x): m += log(1-(1/x)) + (1/x) ...
Write the same algorithm in Python as shown in this Go implementation.
var i int var u rune for i, u = range "voilà" { fmt.Println(i, u) }
u = 'abcdé' print(ord(u[-1]))
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] =...
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 j = 1 print(2, end = " "); while True: while True: if isPrime(p + j*j): break j += 1 ...
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] =...
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 j = 1 print(2, end = " "); while True: while True: if isPrime(p + j*j): break j += 1 ...
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "strings" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func getPerms(input []string) [][]string { perms := [][]string{input} le := len(input) a := make([]string, le) copy(a, input) n := le...
import os from collections import Counter from functools import reduce from itertools import permutations BASES = ("A", "C", "G", "T") def deduplicate(sequences): sequences = set(sequences) duplicates = set() for s, t in permutations(sequences, 2): if s != t and s in t: duplica...
Preserve the algorithm and functionality while converting the code from Go to Python.
package main import ( "fmt" "log" "math" ) type Matrix [][]float64 func (m Matrix) rows() int { return len(m) } func (m Matrix) cols() int { return len(m[0]) } func (m Matrix) add(m2 Matrix) Matrix { if m.rows() != m2.rows() || m.cols() != m2.cols() { log.Fatal("Matrices must have the same d...
from __future__ import annotations from itertools import chain from typing import List from typing import NamedTuple from typing import Optional class Shape(NamedTuple): rows: int cols: int class Matrix(List): @classmethod def block(cls, blocks) -> Matrix: m = Matrix() ...
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "math" "os" "strconv" "text/template" ) func sqr(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(f*f, 'f', -1, 64) } func sqrt(x string) string { f, err := strconv.ParseFloat(x, 64) i...
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
Please provide an equivalent version of this Go code in Python.
package main import ( "math" "os" "strconv" "text/template" ) func sqr(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(f*f, 'f', -1, 64) } func sqrt(x string) string { f, err := strconv.ParseFloat(x, 64) i...
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
Generate an equivalent Python version of this Go code.
package main import ( "bufio" "fmt" "log" "os" ) type SomeStruct struct { runtimeFields map[string]string } func check(err error) { if err != nil { log.Fatal(err) } } func main() { ss := SomeStruct{make(map[string]string)} scanner := bufio.NewScanner(os.Stdin) fmt.Pri...
class empty(object): pass e = empty()
Please provide an equivalent version of this Go code in Python.
package main import ( "fmt" "sort" ) func contains(s []int, f int) bool { for _, e := range s { if e == f { return true } } return false } func sliceEqual(s1, s2 []int) bool { for i := 0; i < len(s1); i++ { if s1[i] != s2[i] { return false ...
def perim_equal(p1, p2): if len(p1) != len(p2) or set(p1) != set(p2): return False if any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))): return True p2 = p2[::-1] return any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))) def edge_to_periphery(e): edges = sorted(e) p =...
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "math" "strconv" "strings" ) func argmax(m [][]float64, i int) int { col := make([]float64, len(m)) max, maxx := -1.0, -1 for x := 0; x < len(m); x++ { col[x] = math.Abs(m[x][i]) if col[x] > max { max = col[x] maxx = x ...
from fractions import Fraction def gauss(m): n, p = len(m), len(m[0]) for i in range(n): k = max(range(i, n), key = lambda x: abs(m[x][i])) m[i], m[k] = m[k], m[i] t = 1 / m[i][i] for j in range(i + 1, p): m[i][j] *= t for j in range(i + 1, n): t = m[j][i] for k in range(i + 1, p): m[j][k] -= t * m[i...
Ensure the translated Python code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/rand" "regexp" "time" ) const base = "ACGT" func findDnaSubsequence(dnaSize, chunkSize int) { dnaSeq := make([]byte, dnaSize) for i := 0; i < dnaSize; i++ { dnaSeq[i] = base[rand.Intn(4)] } dnaStr := string(dnaSeq) dnaSubseq := make([]byte...
from random import choice import regex as re import time def generate_sequence(n: int ) -> str: return "".join([ choice(['A','C','G','T']) for _ in range(n) ]) def dna_findall(needle: str, haystack: str) -> None: if sum(1 for _ in re.finditer(needle, haystack, overlapped=True)) == 0: print("No mat...
Change the programming language of this snippet from Go to Python without modifying what it does.
package main import ( "fmt" "os" "sort" "strings" "text/template" ) func main() { const t = `[[[{{index .P 1}}, {{index .P 2}}], [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], {{index .P 5}}]] ` type S struct { P map[int]string } var s S s.P = map[int]string{ ...
from pprint import pprint as pp class Template(): def __init__(self, structure): self.structure = structure self.used_payloads, self.missed_payloads = [], [] def inject_payload(self, id2data): def _inject_payload(substruct, i2d, used, missed): used.extend(i2d[x...
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "log" "os/exec" "raster" ) func main() { c := exec.Command("convert", "Unfilledcirc.png", "-depth", "1", "ppm:-") pipe, err := c.StdoutPipe() if err != nil { log.Fatal(err) } if err = c.Start(); err != nil { log.Fatal(err) } b, err := ...
from PIL import Image im = Image.open("boxes_1.jpg") im.save("boxes_1v2.ppm")
Translate the given Go code snippet into Python without altering its behavior.
package main import ( "log" "os/exec" "raster" ) func main() { c := exec.Command("convert", "Unfilledcirc.png", "-depth", "1", "ppm:-") pipe, err := c.StdoutPipe() if err != nil { log.Fatal(err) } if err = c.Start(); err != nil { log.Fatal(err) } b, err := ...
from PIL import Image im = Image.open("boxes_1.jpg") im.save("boxes_1v2.ppm")
Convert this Go block to Python, preserving its control flow and logic.
package main import "fmt" type rs232p9 uint16 const ( CD9 rs232p9 = 1 << iota RD9 TD9 DTR9 SG9 DSR9 RTS9 CTS9 RI9 ) func main() { ...
from ctypes import Structure, c_int rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split() rs232_25pin = ( "_0 PG TD RD RTS CTS DSR SG CD pos neg" "_11 SCD SCS STD TC SRD RC" "_18 SRS DTR SQD RI DRS XTC" ).split() class RS232_9pin(Structure): _fields_ = [(__, c_int, 1) fo...
Port the provided Go code into Python while preserving the original functionality.
package main import "fmt" type rs232p9 uint16 const ( CD9 rs232p9 = 1 << iota RD9 TD9 DTR9 SG9 DSR9 RTS9 CTS9 RI9 ) func main() { ...
from ctypes import Structure, c_int rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split() rs232_25pin = ( "_0 PG TD RD RTS CTS DSR SG CD pos neg" "_11 SCD SCS STD TC SRD RC" "_18 SRS DTR SQD RI DRS XTC" ).split() class RS232_9pin(Structure): _fields_ = [(__, c_int, 1) fo...
Rewrite this program in Python while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" "rcu" ) func main() { limit := int(math.Log(1e7) * 1e7 * 1.2) primes := rcu.Primes(limit) fmt.Println("The first 20 pairs of natural numbers whose sum is prime are:") for i := 1; i <= 20; i++ { p := primes[i] hp := p / 2 fmt.Print...
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == "__main__": n = 0 num = 0 print('The first 20 pairs of numbers whose sum is prime:') while True: n += 1 suma = 2*n+1 if isPrime(suma...
Produce a language-to-language conversion: from Go to Python, same semantics.
package main import ( "errors" "flag" "fmt" "log" "math/rand" "strings" "time" ) func main() { log.SetPrefix("mastermind: ") log.SetFlags(0) colours := flag.Int("colours", 6, "number of colours to use (2-20)") flag.IntVar(colours, "colors", 6, "alias for colours") holes := flag.Int("holes", 4, "number of ...
import random def encode(correct, guess): output_arr = [''] * len(correct) for i, (correct_char, guess_char) in enumerate(zip(correct, guess)): output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-' return ''.join(output_arr) def safe_int_input(prompt, min...
Generate a Python translation of this Go snippet without changing its computational steps.
package main import ( "errors" "flag" "fmt" "log" "math/rand" "strings" "time" ) func main() { log.SetPrefix("mastermind: ") log.SetFlags(0) colours := flag.Int("colours", 6, "number of colours to use (2-20)") flag.IntVar(colours, "colors", 6, "alias for colours") holes := flag.Int("holes", 4, "number of ...
import random def encode(correct, guess): output_arr = [''] * len(correct) for i, (correct_char, guess_char) in enumerate(zip(correct, guess)): output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-' return ''.join(output_arr) def safe_int_input(prompt, min...
Port the following code from Go to Python with equivalent syntax and logic.
package main import ( "fmt" "math" ) func main() { list := []float64{1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3} maxDiff := -1.0 var maxPairs [][2]float64 for i := 1; i < len(list); i++ { diff := math.Abs(list[i-1] - list[i]) if diff > maxDiff { maxDi...
def maxDeltas(ns): pairs = [ (abs(a - b), (a, b)) for a, b in zip(ns, ns[1:]) ] delta = max(pairs, key=lambda ab: ab[0])[0] return [ ab for ab in pairs if delta == ab[0] ] def main(): maxPairs = maxDeltas([ 1, 8, 2, -3, 0, 1, 1, -2.3, 0...
Convert this Go block to Python, preserving its control flow and logic.
package main import ( "fmt" "rcu" "strconv" "strings" ) func main() { count := 0 k := 11 * 11 var res []int for count < 20 { if k%3 == 0 || k%5 == 0 || k%7 == 0 { k += 2 continue } factors := rcu.PrimeFactors(k) if len(factors) > ...
from sympy import isprime, factorint def contains_its_prime_factors_all_over_7(n): if n < 10 or isprime(n): return False strn = str(n) pfacs = factorint(n).keys() return all(f > 9 and str(f) in strn for f in pfacs) found = 0 for n in range(1_000_000_000): if contains_its_prime_factors_all_...
Convert this Go snippet to Python and keep its semantics consistent.
package main import ( "fmt" "rcu" "strconv" "strings" ) func main() { count := 0 k := 11 * 11 var res []int for count < 20 { if k%3 == 0 || k%5 == 0 || k%7 == 0 { k += 2 continue } factors := rcu.PrimeFactors(k) if len(factors) > ...
from sympy import isprime, factorint def contains_its_prime_factors_all_over_7(n): if n < 10 or isprime(n): return False strn = str(n) pfacs = factorint(n).keys() return all(f > 9 and str(f) in strn for f in pfacs) found = 0 for n in range(1_000_000_000): if contains_its_prime_factors_all_...
Translate the given Go code snippet into Python without altering its behavior.
package main import "fmt" type FCNode struct { name string weight int coverage float64 children []*FCNode parent *FCNode } func newFCN(name string, weight int, coverage float64) *FCNode { return &FCNode{name, weight, coverage, nil, nil} } func (n *FCNode) addChildren(nodes []*FCNode)...
from itertools import zip_longest fc2 = NAME, WT, COV = 0, 1, 2 def right_type(txt): try: return float(txt) except ValueError: return txt def commas_to_list(the_list, lines, start_indent=0): for n, line in lines: indent = 0 while line.startswith(' ' * (4 * indent))...
Port the provided Go code into Python while preserving the original functionality.
package main import ( "fmt" "log" "math" "math/rand" "time" ) type Point struct{ x, y float64 } type Circle struct { c Point r float64 } func (p Point) String() string { return fmt.Sprintf("(%f, %f)", p.x, p.y) } func distSq(a, b Point) float64 { return (a.x-b.x)*(a.x-b.x) + (a.y-...
import numpy as np class ProjectorStack: def __init__(self, vec): self.vs = np.array(vec) def push(self, v): if len(self.vs) == 0: self.vs = np.array([v]) else: self.vs = np.append(self.vs, [v], axis=0) return self def pop(self): ...
Translate this program into Python but keep the logic exactly as in Go.
package main import ( "fmt" "strconv" "strings" "unicode/utf8" ) func sign(n int) int { switch { case n < 0: return -1 case n > 0: return 1 } return 0 } func abs(n int) int { if n < 0 { return -n } return n } func parseRange(r string) []string ...
from __future__ import annotations import itertools import re from abc import ABC from abc import abstractmethod from typing import Iterable from typing import Optional RE_SPEC = [ ( "INT_RANGE", r"\{(?P<int_start>[0-9]+)..(?P<int_stop>[0-9]+)(?:(?:..)?(?P<int_step>-?[0-9]+))?}", ), (...