Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into PHP but keep the logic exactly as in Go.
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
<? $base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"); $update = array("price" => 15.25, "color" => "red", "year" => 1974); $result = $update + $base; // Notice that the order is reversed print_r($result); ?>
Convert this Go snippet to PHP and keep its semantics consistent.
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
<? $base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"); $update = array("price" => 15.25, "color" => "red", "year" => 1974); $result = $update + $base; // Notice that the order is reversed print_r($result); ?>
Convert the following code from Go to PHP, ensuring the logic remains intact.
package main import ( "bufio" "flag" "fmt" "io" "log" "math/rand" "os" "strings" "time" "unicode" "unicode/utf8" ) func main() { log.SetFlags(0) log.SetPrefix("markov: ") input := flag.String("in", "alice_oz.txt", "input file") n := flag.Int("n", 2, "number of words to use as prefix") runs := flag.Int("runs", 1, "number of runs to generate") wordsPerRun := flag.Int("words", 300, "number of words per run") startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix") stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMarkovFromFile(*input, *n) if err != nil { log.Fatal(err) } for i := 0; i < *runs; i++ { err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence) if err != nil { log.Fatal(err) } fmt.Println() } } type Markov struct { n int capitalized int suffix map[string][]string } func NewMarkovFromFile(filename string, n int) (*Markov, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() return NewMarkov(f, n) } func NewMarkov(r io.Reader, n int) (*Markov, error) { m := &Markov{ n: n, suffix: make(map[string][]string), } sc := bufio.NewScanner(r) sc.Split(bufio.ScanWords) window := make([]string, 0, n) for sc.Scan() { word := sc.Text() if len(window) > 0 { prefix := strings.Join(window, " ") m.suffix[prefix] = append(m.suffix[prefix], word) if isCapitalized(prefix) { m.capitalized++ } } window = appendMax(n, window, word) } if err := sc.Err(); err != nil { return nil, err } return m, nil } func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error { bw := bufio.NewWriter(w) var i int if startCapital { i = rand.Intn(m.capitalized) } else { i = rand.Intn(len(m.suffix)) } var prefix string for prefix = range m.suffix { if startCapital && !isCapitalized(prefix) { continue } if i == 0 { break } i-- } bw.WriteString(prefix) prefixWords := strings.Fields(prefix) n -= len(prefixWords) for { suffixChoices := m.suffix[prefix] if len(suffixChoices) == 0 { break } i = rand.Intn(len(suffixChoices)) suffix := suffixChoices[i] bw.WriteByte(' ') if _, err := bw.WriteString(suffix); err != nil { break } n-- if n < 0 && (!stopSentence || isSentenceEnd(suffix)) { break } prefixWords = appendMax(m.n, prefixWords, suffix) prefix = strings.Join(prefixWords, " ") } return bw.Flush() } func isCapitalized(s string) bool { r, _ := utf8.DecodeRuneInString(s) return unicode.IsUpper(r) } func isSentenceEnd(s string) bool { r, _ := utf8.DecodeLastRuneInString(s) return r == '.' || r == '?' || r == '!' } func appendMax(max int, slice []string, value string) []string { if len(slice)+1 > max { n := copy(slice, slice[1:]) slice = slice[:n] } return append(slice, value) }
<?php function markovChainTextGenerator($text, $keySize, $maxWords) { $token = array(); $position = 0; $maxPosition = strlen($text); while ($position < $maxPosition) { if (preg_match('/^(\S+)/', substr($text, $position, 25), $matches)) { $token[] = $matches[1]; $position += strlen($matches[1]); } elseif (preg_match('/^(\s+)/', substr($text, $position, 25), $matches)) { $position += strlen($matches[1]); } else { die( 'Unknown token found at position ' . $position . ' : ' . substr($text, $position, 25) . '...' . PHP_EOL ); } } $dictionary = array(); for ($i = 0 ; $i < count($token) - $keySize ; $i++) { $prefix = ''; $separator = ''; for ($c = 0 ; $c < $keySize ; $c++) { $prefix .= $separator . $token[$i + $c]; $separator = '.'; } $dictionary[$prefix][] = $token[$i + $keySize]; } $rand = rand(0, count($token) - $keySize); $startToken = array(); for ($c = 0 ; $c < $keySize ; $c++) { array_push($startToken, $token[$rand + $c]); } $text = implode(' ', $startToken); $words = $keySize; do { $tokenKey = implode('.', $startToken); $rand = rand(0, count($dictionary[$tokenKey]) - 1); $newToken = $dictionary[$tokenKey][$rand]; $text .= ' ' . $newToken; $words++; array_shift($startToken); array_push($startToken, $newToken); } while($words < $maxWords); return $text; } srand(5678); $text = markovChainTextGenerator( file_get_contents(__DIR__ . '/inc/alice_oz.txt'), 3, 308 ); echo wordwrap($text, 100, PHP_EOL) . PHP_EOL;
Rewrite the snippet below in PHP so it works the same as the original Go code.
package main import ( "bufio" "flag" "fmt" "io" "log" "math/rand" "os" "strings" "time" "unicode" "unicode/utf8" ) func main() { log.SetFlags(0) log.SetPrefix("markov: ") input := flag.String("in", "alice_oz.txt", "input file") n := flag.Int("n", 2, "number of words to use as prefix") runs := flag.Int("runs", 1, "number of runs to generate") wordsPerRun := flag.Int("words", 300, "number of words per run") startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix") stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMarkovFromFile(*input, *n) if err != nil { log.Fatal(err) } for i := 0; i < *runs; i++ { err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence) if err != nil { log.Fatal(err) } fmt.Println() } } type Markov struct { n int capitalized int suffix map[string][]string } func NewMarkovFromFile(filename string, n int) (*Markov, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() return NewMarkov(f, n) } func NewMarkov(r io.Reader, n int) (*Markov, error) { m := &Markov{ n: n, suffix: make(map[string][]string), } sc := bufio.NewScanner(r) sc.Split(bufio.ScanWords) window := make([]string, 0, n) for sc.Scan() { word := sc.Text() if len(window) > 0 { prefix := strings.Join(window, " ") m.suffix[prefix] = append(m.suffix[prefix], word) if isCapitalized(prefix) { m.capitalized++ } } window = appendMax(n, window, word) } if err := sc.Err(); err != nil { return nil, err } return m, nil } func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error { bw := bufio.NewWriter(w) var i int if startCapital { i = rand.Intn(m.capitalized) } else { i = rand.Intn(len(m.suffix)) } var prefix string for prefix = range m.suffix { if startCapital && !isCapitalized(prefix) { continue } if i == 0 { break } i-- } bw.WriteString(prefix) prefixWords := strings.Fields(prefix) n -= len(prefixWords) for { suffixChoices := m.suffix[prefix] if len(suffixChoices) == 0 { break } i = rand.Intn(len(suffixChoices)) suffix := suffixChoices[i] bw.WriteByte(' ') if _, err := bw.WriteString(suffix); err != nil { break } n-- if n < 0 && (!stopSentence || isSentenceEnd(suffix)) { break } prefixWords = appendMax(m.n, prefixWords, suffix) prefix = strings.Join(prefixWords, " ") } return bw.Flush() } func isCapitalized(s string) bool { r, _ := utf8.DecodeRuneInString(s) return unicode.IsUpper(r) } func isSentenceEnd(s string) bool { r, _ := utf8.DecodeLastRuneInString(s) return r == '.' || r == '?' || r == '!' } func appendMax(max int, slice []string, value string) []string { if len(slice)+1 > max { n := copy(slice, slice[1:]) slice = slice[:n] } return append(slice, value) }
<?php function markovChainTextGenerator($text, $keySize, $maxWords) { $token = array(); $position = 0; $maxPosition = strlen($text); while ($position < $maxPosition) { if (preg_match('/^(\S+)/', substr($text, $position, 25), $matches)) { $token[] = $matches[1]; $position += strlen($matches[1]); } elseif (preg_match('/^(\s+)/', substr($text, $position, 25), $matches)) { $position += strlen($matches[1]); } else { die( 'Unknown token found at position ' . $position . ' : ' . substr($text, $position, 25) . '...' . PHP_EOL ); } } $dictionary = array(); for ($i = 0 ; $i < count($token) - $keySize ; $i++) { $prefix = ''; $separator = ''; for ($c = 0 ; $c < $keySize ; $c++) { $prefix .= $separator . $token[$i + $c]; $separator = '.'; } $dictionary[$prefix][] = $token[$i + $keySize]; } $rand = rand(0, count($token) - $keySize); $startToken = array(); for ($c = 0 ; $c < $keySize ; $c++) { array_push($startToken, $token[$rand + $c]); } $text = implode(' ', $startToken); $words = $keySize; do { $tokenKey = implode('.', $startToken); $rand = rand(0, count($dictionary[$tokenKey]) - 1); $newToken = $dictionary[$tokenKey][$rand]; $text .= ' ' . $newToken; $words++; array_shift($startToken); array_push($startToken, $newToken); } while($words < $maxWords); return $text; } srand(5678); $text = markovChainTextGenerator( file_get_contents(__DIR__ . '/inc/alice_oz.txt'), 3, 308 ); echo wordwrap($text, 100, PHP_EOL) . PHP_EOL;
Maintain the same structure and functionality when rewriting this code in PHP.
package main import ( "container/heap" "fmt" ) type PriorityQueue struct { items []Vertex m map[Vertex]int pr map[Vertex]int } func (pq *PriorityQueue) Len() int { return len(pq.items) } func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] } func (pq *PriorityQueue) Swap(i, j int) { pq.items[i], pq.items[j] = pq.items[j], pq.items[i] pq.m[pq.items[i]] = i pq.m[pq.items[j]] = j } func (pq *PriorityQueue) Push(x interface{}) { n := len(pq.items) item := x.(Vertex) pq.m[item] = n pq.items = append(pq.items, item) } func (pq *PriorityQueue) Pop() interface{} { old := pq.items n := len(old) item := old[n-1] pq.m[item] = -1 pq.items = old[0 : n-1] return item } func (pq *PriorityQueue) update(item Vertex, priority int) { pq.pr[item] = priority heap.Fix(pq, pq.m[item]) } func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) { heap.Push(pq, item) pq.update(item, priority) } const ( Infinity = int(^uint(0) >> 1) Uninitialized = -1 ) func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) { vs := g.Vertices() dist = make(map[Vertex]int, len(vs)) prev = make(map[Vertex]Vertex, len(vs)) sid := source dist[sid] = 0 q := &PriorityQueue{ items: make([]Vertex, 0, len(vs)), m: make(map[Vertex]int, len(vs)), pr: make(map[Vertex]int, len(vs)), } for _, v := range vs { if v != sid { dist[v] = Infinity } prev[v] = Uninitialized q.addWithPriority(v, dist[v]) } for len(q.items) != 0 { u := heap.Pop(q).(Vertex) for _, v := range g.Neighbors(u) { alt := dist[u] + g.Weight(u, v) if alt < dist[v] { dist[v] = alt prev[v] = u q.update(v, alt) } } } return dist, prev } type Graph interface { Vertices() []Vertex Neighbors(v Vertex) []Vertex Weight(u, v Vertex) int } type Vertex int type sg struct { ids map[string]Vertex names map[Vertex]string edges map[Vertex]map[Vertex]int } func newsg(ids map[string]Vertex) sg { g := sg{ids: ids} g.names = make(map[Vertex]string, len(ids)) for k, v := range ids { g.names[v] = k } g.edges = make(map[Vertex]map[Vertex]int) return g } func (g sg) edge(u, v string, w int) { if _, ok := g.edges[g.ids[u]]; !ok { g.edges[g.ids[u]] = make(map[Vertex]int) } g.edges[g.ids[u]][g.ids[v]] = w } func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) { s = g.names[v] for prev[v] >= 0 { v = prev[v] s = g.names[v] + s } return s } func (g sg) Vertices() []Vertex { vs := make([]Vertex, 0, len(g.ids)) for _, v := range g.ids { vs = append(vs, v) } return vs } func (g sg) Neighbors(u Vertex) []Vertex { vs := make([]Vertex, 0, len(g.edges[u])) for v := range g.edges[u] { vs = append(vs, v) } return vs } func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] } func main() { g := newsg(map[string]Vertex{ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, }) g.edge("a", "b", 7) g.edge("a", "c", 9) g.edge("a", "f", 14) g.edge("b", "c", 10) g.edge("b", "d", 15) g.edge("c", "d", 11) g.edge("c", "f", 2) g.edge("d", "e", 6) g.edge("e", "f", 9) dist, prev := Dijkstra(g, g.ids["a"]) fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev)) fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev)) }
<?php function dijkstra($graph_array, $source, $target) { $vertices = array(); $neighbours = array(); foreach ($graph_array as $edge) { array_push($vertices, $edge[0], $edge[1]); $neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]); $neighbours[$edge[1]][] = array("end" => $edge[0], "cost" => $edge[2]); } $vertices = array_unique($vertices); foreach ($vertices as $vertex) { $dist[$vertex] = INF; $previous[$vertex] = NULL; } $dist[$source] = 0; $Q = $vertices; while (count($Q) > 0) { $min = INF; foreach ($Q as $vertex){ if ($dist[$vertex] < $min) { $min = $dist[$vertex]; $u = $vertex; } } $Q = array_diff($Q, array($u)); if ($dist[$u] == INF or $u == $target) { break; } if (isset($neighbours[$u])) { foreach ($neighbours[$u] as $arr) { $alt = $dist[$u] + $arr["cost"]; if ($alt < $dist[$arr["end"]]) { $dist[$arr["end"]] = $alt; $previous[$arr["end"]] = $u; } } } } $path = array(); $u = $target; while (isset($previous[$u])) { array_unshift($path, $u); $u = $previous[$u]; } array_unshift($path, $u); return $path; } $graph_array = array( array("a", "b", 7), array("a", "c", 9), array("a", "f", 14), array("b", "c", 10), array("b", "d", 15), array("c", "d", 11), array("c", "f", 2), array("d", "e", 6), array("e", "f", 9) ); $path = dijkstra($graph_array, "a", "e"); echo "path is: ".implode(", ", $path)."\n";
Convert the following code from Go to PHP, ensuring the logic remains intact.
package main import ( "container/heap" "fmt" ) type PriorityQueue struct { items []Vertex m map[Vertex]int pr map[Vertex]int } func (pq *PriorityQueue) Len() int { return len(pq.items) } func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] } func (pq *PriorityQueue) Swap(i, j int) { pq.items[i], pq.items[j] = pq.items[j], pq.items[i] pq.m[pq.items[i]] = i pq.m[pq.items[j]] = j } func (pq *PriorityQueue) Push(x interface{}) { n := len(pq.items) item := x.(Vertex) pq.m[item] = n pq.items = append(pq.items, item) } func (pq *PriorityQueue) Pop() interface{} { old := pq.items n := len(old) item := old[n-1] pq.m[item] = -1 pq.items = old[0 : n-1] return item } func (pq *PriorityQueue) update(item Vertex, priority int) { pq.pr[item] = priority heap.Fix(pq, pq.m[item]) } func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) { heap.Push(pq, item) pq.update(item, priority) } const ( Infinity = int(^uint(0) >> 1) Uninitialized = -1 ) func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) { vs := g.Vertices() dist = make(map[Vertex]int, len(vs)) prev = make(map[Vertex]Vertex, len(vs)) sid := source dist[sid] = 0 q := &PriorityQueue{ items: make([]Vertex, 0, len(vs)), m: make(map[Vertex]int, len(vs)), pr: make(map[Vertex]int, len(vs)), } for _, v := range vs { if v != sid { dist[v] = Infinity } prev[v] = Uninitialized q.addWithPriority(v, dist[v]) } for len(q.items) != 0 { u := heap.Pop(q).(Vertex) for _, v := range g.Neighbors(u) { alt := dist[u] + g.Weight(u, v) if alt < dist[v] { dist[v] = alt prev[v] = u q.update(v, alt) } } } return dist, prev } type Graph interface { Vertices() []Vertex Neighbors(v Vertex) []Vertex Weight(u, v Vertex) int } type Vertex int type sg struct { ids map[string]Vertex names map[Vertex]string edges map[Vertex]map[Vertex]int } func newsg(ids map[string]Vertex) sg { g := sg{ids: ids} g.names = make(map[Vertex]string, len(ids)) for k, v := range ids { g.names[v] = k } g.edges = make(map[Vertex]map[Vertex]int) return g } func (g sg) edge(u, v string, w int) { if _, ok := g.edges[g.ids[u]]; !ok { g.edges[g.ids[u]] = make(map[Vertex]int) } g.edges[g.ids[u]][g.ids[v]] = w } func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) { s = g.names[v] for prev[v] >= 0 { v = prev[v] s = g.names[v] + s } return s } func (g sg) Vertices() []Vertex { vs := make([]Vertex, 0, len(g.ids)) for _, v := range g.ids { vs = append(vs, v) } return vs } func (g sg) Neighbors(u Vertex) []Vertex { vs := make([]Vertex, 0, len(g.edges[u])) for v := range g.edges[u] { vs = append(vs, v) } return vs } func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] } func main() { g := newsg(map[string]Vertex{ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, }) g.edge("a", "b", 7) g.edge("a", "c", 9) g.edge("a", "f", 14) g.edge("b", "c", 10) g.edge("b", "d", 15) g.edge("c", "d", 11) g.edge("c", "f", 2) g.edge("d", "e", 6) g.edge("e", "f", 9) dist, prev := Dijkstra(g, g.ids["a"]) fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev)) fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev)) }
<?php function dijkstra($graph_array, $source, $target) { $vertices = array(); $neighbours = array(); foreach ($graph_array as $edge) { array_push($vertices, $edge[0], $edge[1]); $neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]); $neighbours[$edge[1]][] = array("end" => $edge[0], "cost" => $edge[2]); } $vertices = array_unique($vertices); foreach ($vertices as $vertex) { $dist[$vertex] = INF; $previous[$vertex] = NULL; } $dist[$source] = 0; $Q = $vertices; while (count($Q) > 0) { $min = INF; foreach ($Q as $vertex){ if ($dist[$vertex] < $min) { $min = $dist[$vertex]; $u = $vertex; } } $Q = array_diff($Q, array($u)); if ($dist[$u] == INF or $u == $target) { break; } if (isset($neighbours[$u])) { foreach ($neighbours[$u] as $arr) { $alt = $dist[$u] + $arr["cost"]; if ($alt < $dist[$arr["end"]]) { $dist[$arr["end"]] = $alt; $previous[$arr["end"]] = $u; } } } } $path = array(); $u = $target; while (isset($previous[$u])) { array_unshift($path, $u); $u = $previous[$u]; } array_unshift($path, $u); return $path; } $graph_array = array( array("a", "b", 7), array("a", "c", 9), array("a", "f", 14), array("b", "c", 10), array("b", "d", 15), array("c", "d", 11), array("c", "f", 2), array("d", "e", 6), array("e", "f", 9) ); $path = dijkstra($graph_array, "a", "e"); echo "path is: ".implode(", ", $path)."\n";
Please provide an equivalent version of this Go code in PHP.
myMap := map[string]int { "hello": 13, "world": 31, "!" : 71 } for key, value := range myMap { fmt.Printf("key = %s, value = %d\n", key, value) } for key := range myMap { fmt.Printf("key = %s\n", key) } for _, value := range myMap { fmt.Printf("value = %d\n", value) }
<?php $pairs = array( "hello" => 1, "world" => 2, "!" => 3 ); foreach($pairs as $k => $v) { echo "(k,v) = ($k, $v)\n"; } foreach(array_keys($pairs) as $key) { echo "key = $key, value = $pairs[$key]\n"; } foreach($pairs as $value) { echo "values = $value\n"; } ?>
Convert the following code from Go to PHP, ensuring the logic remains intact.
myMap := map[string]int { "hello": 13, "world": 31, "!" : 71 } for key, value := range myMap { fmt.Printf("key = %s, value = %d\n", key, value) } for key := range myMap { fmt.Printf("key = %s\n", key) } for _, value := range myMap { fmt.Printf("value = %d\n", value) }
<?php $pairs = array( "hello" => 1, "world" => 2, "!" => 3 ); foreach($pairs as $k => $v) { echo "(k,v) = ($k, $v)\n"; } foreach(array_keys($pairs) as $key) { echo "key = $key, value = $pairs[$key]\n"; } foreach($pairs as $value) { echo "values = $value\n"; } ?>
Convert this Go snippet to PHP and keep its semantics consistent.
var m = ` leading spaces and blank lines`
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
Write the same code in PHP as shown below in Go.
var m = ` leading spaces and blank lines`
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
Translate this program into PHP but keep the logic exactly as in Go.
var m = ` leading spaces and blank lines`
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
Please provide an equivalent version of this Go code in PHP.
var m = ` leading spaces and blank lines`
$address = <<<END 1, High Street, $town_name, West Midlands. WM4 5HD. END;
Generate an equivalent PHP version of this Go code.
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, } h := map[string][]int{} for i, r := range tableA { h[r.key] = append(h[r.key], i) } for _, x := range tableB { for _, a := range h[x.key] { fmt.Println(tableA[a], x) } } }
<?php function hashJoin($table1, $index1, $table2, $index2) { foreach ($table1 as $s) $h[$s[$index1]][] = $s; foreach ($table2 as $r) foreach ($h[$r[$index2]] as $s) $result[] = array($s, $r); return $result; } $table1 = array(array(27, "Jonah"), array(18, "Alan"), array(28, "Glory"), array(18, "Popeye"), array(28, "Alan")); $table2 = array(array("Jonah", "Whales"), array("Jonah", "Spiders"), array("Alan", "Ghosts"), array("Alan", "Zombies"), array("Glory", "Buffy"), array("Bob", "foo")); foreach (hashJoin($table1, 1, $table2, 0) as $row) print_r($row); ?>
Write the same code in PHP as shown below in Go.
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, } h := map[string][]int{} for i, r := range tableA { h[r.key] = append(h[r.key], i) } for _, x := range tableB { for _, a := range h[x.key] { fmt.Println(tableA[a], x) } } }
<?php function hashJoin($table1, $index1, $table2, $index2) { foreach ($table1 as $s) $h[$s[$index1]][] = $s; foreach ($table2 as $r) foreach ($h[$r[$index2]] as $s) $result[] = array($s, $r); return $result; } $table1 = array(array(27, "Jonah"), array(18, "Alan"), array(28, "Glory"), array(18, "Popeye"), array(28, "Alan")); $table2 = array(array("Jonah", "Whales"), array("Jonah", "Spiders"), array("Alan", "Ghosts"), array("Alan", "Zombies"), array("Glory", "Buffy"), array("Bob", "foo")); foreach (hashJoin($table1, 1, $table2, 0) as $row) print_r($row); ?>
Keep all operations the same but rewrite the snippet in PHP.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func (e example) CallMethod(n string) int { if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() { return int(m.Call(nil)[0].Int()) } fmt.Println("Unknown method:", n) return 0 } func main() { var e example fmt.Println(e.CallMethod("Foo")) fmt.Println(e.CallMethod("Bar")) }
<?php class Example { function foo() { echo "this is foo\n"; } function bar() { echo "this is bar\n"; } function __call($name, $args) { echo "tried to handle unknown method $name\n"; if ($args) echo "it had arguments: ", implode(', ', $args), "\n"; } } $example = new Example(); $example->foo(); // prints "this is foo" $example->bar(); // prints "this is bar" $example->grill(); // prints "tried to handle unknown method grill" $example->ding("dong"); // prints "tried to handle unknown method ding" ?>
Transform the following Go implementation into PHP, maintaining the same output and logic.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func (e example) CallMethod(n string) int { if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() { return int(m.Call(nil)[0].Int()) } fmt.Println("Unknown method:", n) return 0 } func main() { var e example fmt.Println(e.CallMethod("Foo")) fmt.Println(e.CallMethod("Bar")) }
<?php class Example { function foo() { echo "this is foo\n"; } function bar() { echo "this is bar\n"; } function __call($name, $args) { echo "tried to handle unknown method $name\n"; if ($args) echo "it had arguments: ", implode(', ', $args), "\n"; } } $example = new Example(); $example->foo(); // prints "this is foo" $example->bar(); // prints "this is bar" $example->grill(); // prints "tried to handle unknown method grill" $example->ding("dong"); // prints "tried to handle unknown method ding" ?>
Rewrite the snippet below in PHP so it works the same as the original Go code.
package main type animal struct { alive bool } type dog struct { animal obedienceTrained bool } type cat struct { animal litterBoxTrained bool } type lab struct { dog color string } type collie struct { dog catchesFrisbee bool } func main() { var pet lab pet.alive = true pet.obedienceTrained = false pet.color = "yellow" }
class Animal { } class Dog extends Animal { } class Cat extends Animal { } class Lab extends Dog { } class Collie extends Dog { }
Generate an equivalent PHP version of this Go code.
package main type animal struct { alive bool } type dog struct { animal obedienceTrained bool } type cat struct { animal litterBoxTrained bool } type lab struct { dog color string } type collie struct { dog catchesFrisbee bool } func main() { var pet lab pet.alive = true pet.obedienceTrained = false pet.color = "yellow" }
class Animal { } class Dog extends Animal { } class Cat extends Animal { } class Lab extends Dog { } class Collie extends Dog { }
Rewrite this program in PHP while keeping its functionality equivalent to the Go version.
var x map[string]int x = make(map[string]int) x = make(map[string]int, 42) x["foo"] = 3 y1 := x["bar"] y2, ok := x["bar"] delete(x, "foo") x = map[string]int{ "foo": 2, "bar": 42, "baz": -1, }
$array = array(); $array = []; // Simpler form of array initialization $array['foo'] = 'bar'; $array['bar'] = 'foo'; echo($array['foo']); // bar echo($array['moo']); // Undefined index $array2 = array('fruit' => 'apple', 'price' => 12.96, 'colour' => 'green'); $array2 = ['fruit' => 'apple', 'price' => 12.96, 'colour' => 'green']; echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
Generate an equivalent PHP version of this Go code.
var x map[string]int x = make(map[string]int) x = make(map[string]int, 42) x["foo"] = 3 y1 := x["bar"] y2, ok := x["bar"] delete(x, "foo") x = map[string]int{ "foo": 2, "bar": 42, "baz": -1, }
$array = array(); $array = []; // Simpler form of array initialization $array['foo'] = 'bar'; $array['bar'] = 'foo'; echo($array['foo']); // bar echo($array['moo']); // Undefined index $array2 = array('fruit' => 'apple', 'price' => 12.96, 'colour' => 'green'); $array2 = ['fruit' => 'apple', 'price' => 12.96, 'colour' => 'green']; echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
Port the following code from Go to PHP with equivalent syntax and logic.
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = newPoint(3, 4) i.print() i = newCircle(5, 12, 13) i.print() } func (p *point) getX() float64 { return p.x } func (p *point) getY() float64 { return p.y } func (p *point) setX(v float64) { p.x = v } func (p *point) setY(v float64) { p.y = v } func (c *circle) getX() float64 { return c.x } func (c *circle) getY() float64 { return c.y } func (c *circle) getR() float64 { return c.r } func (c *circle) setX(v float64) { c.x = v } func (c *circle) setY(v float64) { c.y = v } func (c *circle) setR(v float64) { c.r = v } func (p *point) clone() *point { r := *p; return &r } func (c *circle) clone() *circle { r := *c; return &r } func (p *point) set(q *point) { *p = *q } func (c *circle) set(d *circle) { *c = *d } func newPoint(x, y float64) *point { return &point{x, y} } func newCircle(x, y, r float64) *circle { return &circle{x, y, r} }
class Point { protected $_x; protected $_y; public function __construct() { switch( func_num_args() ) { case 1: $point = func_get_arg( 0 ); $this->setFromPoint( $point ); break; case 2: $x = func_get_arg( 0 ); $y = func_get_arg( 1 ); $this->setX( $x ); $this->setY( $y ); break; default: throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' ); } } public function setFromPoint( Point $point ) { $this->setX( $point->getX() ); $this->setY( $point->getY() ); } public function getX() { return $this->_x; } public function setX( $x ) { if( !is_numeric( $x ) ) { throw new InvalidArgumentException( 'expecting numeric value' ); } $this->_x = (float) $x; } public function getY() { return $this->_y; } public function setY( $y ) { if( !is_numeric( $y ) ) { throw new InvalidArgumentException( 'expecting numeric value' ); } $this->_y = (float) $y; } public function output() { echo $this->__toString(); } public function __toString() { return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']'; } }
Write a version of this Go function in PHP with identical behavior.
package main import "fmt" type point struct { x, y float64 } type circle struct { x, y, r float64 } type printer interface { print() } func (p *point) print() { fmt.Println(p.x, p.y) } func (c *circle) print() { fmt.Println(c.x, c.y, c.r) } func main() { var i printer i = newPoint(3, 4) i.print() i = newCircle(5, 12, 13) i.print() } func (p *point) getX() float64 { return p.x } func (p *point) getY() float64 { return p.y } func (p *point) setX(v float64) { p.x = v } func (p *point) setY(v float64) { p.y = v } func (c *circle) getX() float64 { return c.x } func (c *circle) getY() float64 { return c.y } func (c *circle) getR() float64 { return c.r } func (c *circle) setX(v float64) { c.x = v } func (c *circle) setY(v float64) { c.y = v } func (c *circle) setR(v float64) { c.r = v } func (p *point) clone() *point { r := *p; return &r } func (c *circle) clone() *circle { r := *c; return &r } func (p *point) set(q *point) { *p = *q } func (c *circle) set(d *circle) { *c = *d } func newPoint(x, y float64) *point { return &point{x, y} } func newCircle(x, y, r float64) *circle { return &circle{x, y, r} }
class Point { protected $_x; protected $_y; public function __construct() { switch( func_num_args() ) { case 1: $point = func_get_arg( 0 ); $this->setFromPoint( $point ); break; case 2: $x = func_get_arg( 0 ); $y = func_get_arg( 1 ); $this->setX( $x ); $this->setY( $y ); break; default: throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' ); } } public function setFromPoint( Point $point ) { $this->setX( $point->getX() ); $this->setY( $point->getY() ); } public function getX() { return $this->_x; } public function setX( $x ) { if( !is_numeric( $x ) ) { throw new InvalidArgumentException( 'expecting numeric value' ); } $this->_x = (float) $x; } public function getY() { return $this->_y; } public function setY( $y ) { if( !is_numeric( $y ) ) { throw new InvalidArgumentException( 'expecting numeric value' ); } $this->_y = (float) $y; } public function output() { echo $this->__toString(); } public function __toString() { return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']'; } }
Port the following code from Go to PHP with equivalent syntax and logic.
package main import ( "fmt" "image" "reflect" ) type t struct { X int next *t } func main() { report(t{}) report(image.Point{}) } func report(x interface{}) { t := reflect.TypeOf(x) n := t.NumField() fmt.Printf("Type %v has %d fields:\n", t, n) fmt.Println("Name Type Exported") for i := 0; i < n; i++ { f := t.Field(i) fmt.Printf("%-8s %-8v %-8t\n", f.Name, f.Type, f.PkgPath == "", ) } fmt.Println() }
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true; var_dump(get_object_vars($obj)); ?>
Rewrite this program in PHP while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "image" "reflect" ) type t struct { X int next *t } func main() { report(t{}) report(image.Point{}) } func report(x interface{}) { t := reflect.TypeOf(x) n := t.NumField() fmt.Printf("Type %v has %d fields:\n", t, n) fmt.Println("Name Type Exported") for i := 0; i < n; i++ { f := t.Field(i) fmt.Printf("%-8s %-8v %-8t\n", f.Name, f.Type, f.PkgPath == "", ) } fmt.Println() }
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true; var_dump(get_object_vars($obj)); ?>
Generate a PHP translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "strings" ) const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.` type formatter struct { text [][]string width []int } func newFormatter(text string) *formatter { var f formatter for _, line := range strings.Split(text, "\n") { words := strings.Split(line, "$") for words[len(words)-1] == "" { words = words[:len(words)-1] } f.text = append(f.text, words) for i, word := range words { if i == len(f.width) { f.width = append(f.width, len(word)) } else if len(word) > f.width[i] { f.width[i] = len(word) } } } return &f } const ( left = iota middle right ) func (f formatter) print(j int) { for _, line := range f.text { for i, word := range line { fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s", len(word)+(f.width[i]-len(word))*j/2, word)) } fmt.Println("") } fmt.Println("") } func main() { f := newFormatter(text) f.print(left) f.print(middle) f.print(right) }
<?php $j2justtype = array('L' => STR_PAD_RIGHT, 'R' => STR_PAD_LEFT, 'C' => STR_PAD_BOTH); function aligner($str, $justification = 'L') { global $j2justtype; assert(array_key_exists($justification, $j2justtype)); $justtype = $j2justtype[$justification]; $fieldsbyrow = array(); foreach (explode("\n", $str) as $line) $fieldsbyrow[] = explode('$', $line); $maxfields = max(array_map('count', $fieldsbyrow)); foreach (range(0, $maxfields - 1) as $col) { $maxwidth = 0; foreach ($fieldsbyrow as $fields) $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0)); foreach ($fieldsbyrow as &$fields) $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype); unset($fields); // see http://bugs.php.net/29992 } $result = ''; foreach ($fieldsbyrow as $fields) $result .= implode(' ', $fields) . "\n"; return $result; } $textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$\'dollar\'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.'; foreach (array('L', 'R', 'C') as $j) echo aligner($textinfile, $j); ?>
Generate an equivalent PHP version of this Go code.
package main import ( "fmt" "strings" ) const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.` type formatter struct { text [][]string width []int } func newFormatter(text string) *formatter { var f formatter for _, line := range strings.Split(text, "\n") { words := strings.Split(line, "$") for words[len(words)-1] == "" { words = words[:len(words)-1] } f.text = append(f.text, words) for i, word := range words { if i == len(f.width) { f.width = append(f.width, len(word)) } else if len(word) > f.width[i] { f.width[i] = len(word) } } } return &f } const ( left = iota middle right ) func (f formatter) print(j int) { for _, line := range f.text { for i, word := range line { fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s", len(word)+(f.width[i]-len(word))*j/2, word)) } fmt.Println("") } fmt.Println("") } func main() { f := newFormatter(text) f.print(left) f.print(middle) f.print(right) }
<?php $j2justtype = array('L' => STR_PAD_RIGHT, 'R' => STR_PAD_LEFT, 'C' => STR_PAD_BOTH); function aligner($str, $justification = 'L') { global $j2justtype; assert(array_key_exists($justification, $j2justtype)); $justtype = $j2justtype[$justification]; $fieldsbyrow = array(); foreach (explode("\n", $str) as $line) $fieldsbyrow[] = explode('$', $line); $maxfields = max(array_map('count', $fieldsbyrow)); foreach (range(0, $maxfields - 1) as $col) { $maxwidth = 0; foreach ($fieldsbyrow as $fields) $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0)); foreach ($fieldsbyrow as &$fields) $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype); unset($fields); // see http://bugs.php.net/29992 } $result = ''; foreach ($fieldsbyrow as $fields) $result .= implode(' ', $fields) . "\n"; return $result; } $textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$\'dollar\'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.'; foreach (array('L', 'R', 'C') as $j) echo aligner($textinfile, $j); ?>
Generate a PHP translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
<?php $urls = array( 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2', ); foreach ($urls AS $url) { $p = parse_url($url); echo $url, PHP_EOL; print_r($p); echo PHP_EOL; }
Maintain the same structure and functionality when rewriting this code in PHP.
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
<?php $urls = array( 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2', ); foreach ($urls AS $url) { $p = parse_url($url); echo $url, PHP_EOL; print_r($p); echo PHP_EOL; }
Ensure the translated PHP code behaves exactly like the original Go snippet.
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
<?php $urls = array( 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2', ); foreach ($urls AS $url) { $p = parse_url($url); echo $url, PHP_EOL; print_r($p); echo PHP_EOL; }
Change the programming language of this snippet from Go to PHP without modifying what it does.
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
<?php $urls = array( 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2', ); foreach ($urls AS $url) { $p = parse_url($url); echo $url, PHP_EOL; print_r($p); echo PHP_EOL; }
Convert the following code from Go to PHP, ensuring the logic remains intact.
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) n := 0 for n < 1 || n > 5 { fmt.Print("How many integer variables do you want to create (max 5) : ") scanner.Scan() n, _ = strconv.Atoi(scanner.Text()) check(scanner.Err()) } vars := make(map[string]int) fmt.Println("OK, enter the variable names and their values, below") for i := 1; i <= n; { fmt.Println("\n Variable", i) fmt.Print(" Name  : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if _, ok := vars[name]; ok { fmt.Println(" Sorry, you've already created a variable of that name, try again") continue } var value int var err error for { fmt.Print(" Value : ") scanner.Scan() value, err = strconv.Atoi(scanner.Text()) check(scanner.Err()) if err != nil { fmt.Println(" Not a valid integer, try again") } else { break } } vars[name] = value i++ } fmt.Println("\nEnter q to quit") for { fmt.Print("\nWhich variable do you want to inspect : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if s := strings.ToLower(name); s == "q" { return } v, ok := vars[name] if !ok { fmt.Println("Sorry there's no variable of that name, try again") } else { fmt.Println("It's value is", v) } } }
<?php $varname = rtrim(fgets(STDIN)); # type in "foo" on standard input $$varname = 42; echo "$foo\n"; # prints "42" ?>
Produce a functionally identical PHP code for the snippet given in Go.
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) n := 0 for n < 1 || n > 5 { fmt.Print("How many integer variables do you want to create (max 5) : ") scanner.Scan() n, _ = strconv.Atoi(scanner.Text()) check(scanner.Err()) } vars := make(map[string]int) fmt.Println("OK, enter the variable names and their values, below") for i := 1; i <= n; { fmt.Println("\n Variable", i) fmt.Print(" Name  : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if _, ok := vars[name]; ok { fmt.Println(" Sorry, you've already created a variable of that name, try again") continue } var value int var err error for { fmt.Print(" Value : ") scanner.Scan() value, err = strconv.Atoi(scanner.Text()) check(scanner.Err()) if err != nil { fmt.Println(" Not a valid integer, try again") } else { break } } vars[name] = value i++ } fmt.Println("\nEnter q to quit") for { fmt.Print("\nWhich variable do you want to inspect : ") scanner.Scan() name := scanner.Text() check(scanner.Err()) if s := strings.ToLower(name); s == "q" { return } v, ok := vars[name] if !ok { fmt.Println("Sorry there's no variable of that name, try again") } else { fmt.Println("It's value is", v) } } }
<?php $varname = rtrim(fgets(STDIN)); # type in "foo" on standard input $$varname = 42; echo "$foo\n"; # prints "42" ?>
Please provide an equivalent version of this Go code in PHP.
package main import ( "fmt" "image" "reflect" ) type t int func (r t) Twice() t { return r * 2 } func (r t) Half() t { return r / 2 } func (r t) Less(r2 t) bool { return r < r2 } func (r t) privateMethod() {} func main() { report(t(0)) report(image.Point{}) } func report(x interface{}) { v := reflect.ValueOf(x) t := reflect.TypeOf(x) n := t.NumMethod() fmt.Printf("Type %v has %d exported methods:\n", t, n) const format = "%-6s %-46s %s\n" fmt.Printf(format, "Name", "Method expression", "Method value") for i := 0; i < n; i++ { fmt.Printf(format, t.Method(i).Name, t.Method(i).Func.Type(), v.Method(i).Type(), ) } fmt.Println() }
<? class Foo { function bar(int $x) { } } $method_names = get_class_methods('Foo'); foreach ($method_names as $name) { echo "$name\n"; $method_info = new ReflectionMethod('Foo', $name); echo $method_info; } ?>
Translate the given Go code snippet into PHP without altering its behavior.
package main import ( "fmt" "image" "reflect" ) type t int func (r t) Twice() t { return r * 2 } func (r t) Half() t { return r / 2 } func (r t) Less(r2 t) bool { return r < r2 } func (r t) privateMethod() {} func main() { report(t(0)) report(image.Point{}) } func report(x interface{}) { v := reflect.ValueOf(x) t := reflect.TypeOf(x) n := t.NumMethod() fmt.Printf("Type %v has %d exported methods:\n", t, n) const format = "%-6s %-46s %s\n" fmt.Printf(format, "Name", "Method expression", "Method value") for i := 0; i < n; i++ { fmt.Printf(format, t.Method(i).Name, t.Method(i).Func.Type(), v.Method(i).Type(), ) } fmt.Println() }
<? class Foo { function bar(int $x) { } } $method_names = get_class_methods('Foo'); foreach ($method_names as $name) { echo "$name\n"; $method_info = new ReflectionMethod('Foo', $name); echo $method_info; } ?>
Write the same algorithm in PHP as shown in this Go implementation.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func main() { var e example m := reflect.ValueOf(e).MethodByName("Foo") r := m.Call(nil) fmt.Println(r[0].Int()) }
<?php class Example { function foo($x) { return 42 + $x; } } $example = new Example(); $name = 'foo'; echo $example->$name(5), "\n"; // prints "47" echo call_user_func(array($example, $name), 5), "\n"; ?>
Transform the following Go implementation into PHP, maintaining the same output and logic.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func main() { var e example m := reflect.ValueOf(e).MethodByName("Foo") r := m.Call(nil) fmt.Println(r[0].Int()) }
<?php class Example { function foo($x) { return 42 + $x; } } $example = new Example(); $name = 'foo'; echo $example->$name(5), "\n"; // prints "47" echo call_user_func(array($example, $name), 5), "\n"; ?>
Port the provided Go code into PHP while preserving the original functionality.
x := 3
<?php # NULL typed variable $null = NULL; var_dump($null); // output: null # defining a boolean $boolean = true; var_dump($boolean); // output: boolean true $boolean = false; var_dump($boolean); // output: boolean false # bool and boolean is the same $boolean = (bool)1; var_dump($boolean); // output: boolean true $boolean = (boolean)1; var_dump($boolean); // output: boolean true $boolean = (bool)0; var_dump($boolean); // output: boolean false $boolean = (boolean)0; var_dump($boolean); // output: boolean false # defining an integer $int = 0; var_dump($int); // output: int 0 # defining a float, $float = 0.01; var_dump($float); // output: float 0.01 # which is also identical to "real" and "double" var_dump((double)$float); // output: float 0.01 var_dump((real)$float); // output: float 0.01 # casting back to int (auto flooring the value) var_dump((int)$float); // output: int 0 var_dump((int)($float+1)); // output: int 1 var_dump((int)($float+1.9)); // output: int 1 # defining a string $string = 'string'; var_dump($string); // output: string 'string' (length=6) # referencing a variable (there are no pointers in PHP). $another_string = &$string; var_dump($another_string); $string = "I'm the same string!"; var_dump($another_string); # "deleting" a variable from memory unset($another_string); $string = 'string'; $parsed_string = "This is a $string"; var_dump($parsed_string); $parsed_string .= " with another {$string}"; var_dump($parsed_string); # with string parsing $heredoc = <<<HEREDOC This is the content of \$string: {$string} HEREDOC; var_dump($heredoc); # without string parsing (notice the single quotes surrounding NOWDOC) $nowdoc = <<<'NOWDOC' This is the content of \$string: {$string} NOWDOC; var_dump($nowdoc); # as of PHP5, defining an object typed stdClass => standard class $stdObject = new stdClass(); var_dump($stdObject); # defining an object typed Foo class Foo {} $foo = new Foo(); var_dump($foo); # defining an empty array $array = array(); var_dump($array); $assoc = array( 0 => $int, 'integer' => $int, 1 => $float, 'float' => $float, 2 => $string, 'string' => $string, 3 => NULL, // <=== key 3 is NULL 3, // <=== this is a value, not a key (key is 4) 5 => $stdObject, 'Foo' => $foo, ); var_dump($assoc); function a_function() { # not reachable var_dump(isset($foo)); // output: boolean false global $foo; # "global" (reachable) inside a_function()'s scope var_dump(isset($foo)); // output: boolean true } a_function();
Write the same algorithm in PHP as shown in this Go implementation.
x := 3
<?php # NULL typed variable $null = NULL; var_dump($null); // output: null # defining a boolean $boolean = true; var_dump($boolean); // output: boolean true $boolean = false; var_dump($boolean); // output: boolean false # bool and boolean is the same $boolean = (bool)1; var_dump($boolean); // output: boolean true $boolean = (boolean)1; var_dump($boolean); // output: boolean true $boolean = (bool)0; var_dump($boolean); // output: boolean false $boolean = (boolean)0; var_dump($boolean); // output: boolean false # defining an integer $int = 0; var_dump($int); // output: int 0 # defining a float, $float = 0.01; var_dump($float); // output: float 0.01 # which is also identical to "real" and "double" var_dump((double)$float); // output: float 0.01 var_dump((real)$float); // output: float 0.01 # casting back to int (auto flooring the value) var_dump((int)$float); // output: int 0 var_dump((int)($float+1)); // output: int 1 var_dump((int)($float+1.9)); // output: int 1 # defining a string $string = 'string'; var_dump($string); // output: string 'string' (length=6) # referencing a variable (there are no pointers in PHP). $another_string = &$string; var_dump($another_string); $string = "I'm the same string!"; var_dump($another_string); # "deleting" a variable from memory unset($another_string); $string = 'string'; $parsed_string = "This is a $string"; var_dump($parsed_string); $parsed_string .= " with another {$string}"; var_dump($parsed_string); # with string parsing $heredoc = <<<HEREDOC This is the content of \$string: {$string} HEREDOC; var_dump($heredoc); # without string parsing (notice the single quotes surrounding NOWDOC) $nowdoc = <<<'NOWDOC' This is the content of \$string: {$string} NOWDOC; var_dump($nowdoc); # as of PHP5, defining an object typed stdClass => standard class $stdObject = new stdClass(); var_dump($stdObject); # defining an object typed Foo class Foo {} $foo = new Foo(); var_dump($foo); # defining an empty array $array = array(); var_dump($array); $assoc = array( 0 => $int, 'integer' => $int, 1 => $float, 'float' => $float, 2 => $string, 'string' => $string, 3 => NULL, // <=== key 3 is NULL 3, // <=== this is a value, not a key (key is 4) 5 => $stdObject, 'Foo' => $foo, ); var_dump($assoc); function a_function() { # not reachable var_dump(isset($foo)); // output: boolean false global $foo; # "global" (reachable) inside a_function()'s scope var_dump(isset($foo)); // output: boolean true } a_function();
Rewrite this program in PHP while keeping its functionality equivalent to the Go version.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
Translate the given Go code snippet into PHP without altering its behavior.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
Keep all operations the same but rewrite the snippet in PHP.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
Convert the following code from Go to PHP, ensuring the logic remains intact.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w := eval.NewWorld() wVar := new(intV) err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } *wVar = 5 r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } *wVar-- r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) } type intV int64 func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
Port the provided Go code into PHP while preserving the original functionality.
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time error"); return; } fmt.Println("Return value:", val) }
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
Produce a language-to-language conversion: from Go to PHP, same semantics.
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time error"); return; } fmt.Println("Return value:", val) }
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
Preserve the algorithm and functionality while converting the code from Go to PHP.
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time error"); return; } fmt.Println("Return value:", val) }
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
Convert this Go block to PHP, preserving its control flow and logic.
package main import ( "fmt" "bitbucket.org/binet/go-eval/pkg/eval" "go/token" ) func main() { w := eval.NewWorld(); fset := token.NewFileSet(); code, err := w.Compile(fset, "1 + 2") if err != nil { fmt.Println("Compile error"); return } val, err := code.Run(); if err != nil { fmt.Println("Run time error"); return; } fmt.Println("Return value:", val) }
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
Convert this Go snippet to PHP and keep its semantics consistent.
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { p[i] = values[x] } fmt.Println(p) if decide(p) { return } for i := 0; ; { pn[i]++ if pn[i] < k { break } pn[i] = 0 i++ if i == n { return } } } }
<?php function permutate($values, $size, $offset) { $count = count($values); $array = array(); for ($i = 0; $i < $size; $i++) { $selector = ($offset / pow($count,$i)) % $count; $array[$i] = $values[$selector]; } return $array; } function permutations($values, $size) { $a = array(); $c = pow(count($values), $size); for ($i = 0; $i<$c; $i++) { $a[$i] = permutate($values, $size, $i); } return $a; } $permutations = permutations(['bat','fox','cow'], 2); foreach ($permutations as $permutation) { echo join(',', $permutation)."\n"; }
Rewrite the snippet below in PHP so it works the same as the original Go code.
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { p[i] = values[x] } fmt.Println(p) if decide(p) { return } for i := 0; ; { pn[i]++ if pn[i] < k { break } pn[i] = 0 i++ if i == n { return } } } }
<?php function permutate($values, $size, $offset) { $count = count($values); $array = array(); for ($i = 0; $i < $size; $i++) { $selector = ($offset / pow($count,$i)) % $count; $array[$i] = $values[$selector]; } return $array; } function permutations($values, $size) { $a = array(); $c = pow(count($values), $size); for ($i = 0; $i<$c; $i++) { $a[$i] = permutate($values, $size, $i); } return $a; } $permutations = permutations(['bat','fox','cow'], 2); foreach ($permutations as $permutation) { echo join(',', $permutation)."\n"; }
Generate a PHP translation of this Go snippet without changing its computational steps.
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { p[i] = values[x] } fmt.Println(p) if decide(p) { return } for i := 0; ; { pn[i]++ if pn[i] < k { break } pn[i] = 0 i++ if i == n { return } } } }
<?php function permutate($values, $size, $offset) { $count = count($values); $array = array(); for ($i = 0; $i < $size; $i++) { $selector = ($offset / pow($count,$i)) % $count; $array[$i] = $values[$selector]; } return $array; } function permutations($values, $size) { $a = array(); $c = pow(count($values), $size); for ($i = 0; $i<$c; $i++) { $a[$i] = permutate($values, $size, $i); } return $a; } $permutations = permutations(['bat','fox','cow'], 2); foreach ($permutations as $permutation) { echo join(',', $permutation)."\n"; }
Rewrite the snippet below in PHP so it works the same as the original Go code.
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { p[i] = values[x] } fmt.Println(p) if decide(p) { return } for i := 0; ; { pn[i]++ if pn[i] < k { break } pn[i] = 0 i++ if i == n { return } } } }
<?php function permutate($values, $size, $offset) { $count = count($values); $array = array(); for ($i = 0; $i < $size; $i++) { $selector = ($offset / pow($count,$i)) % $count; $array[$i] = $values[$selector]; } return $array; } function permutations($values, $size) { $a = array(); $c = pow(count($values), $size); for ($i = 0; $i<$c; $i++) { $a[$i] = permutate($values, $size, $i); } return $a; } $permutations = permutations(['bat','fox','cow'], 2); foreach ($permutations as $permutation) { echo join(',', $permutation)."\n"; }
Change the programming language of this snippet from Go to PHP without modifying what it does.
package main import ( "fmt" "strconv" ) func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd } start = false } switch c { case '1': num1 = (num2 & 0xFFFFFF80) >> 7 num2 = num2 << 25 case '2': num1 = (num2 & 0xFFFFFFF0) >> 4 num2 = num2 << 28 case '3': num1 = (num2 & 0xFFFFFFF8) >> 3 num2 = num2 << 29 case '4': num1 = num2 << 1 num2 = num2 >> 31 case '5': num1 = num2 << 5 num2 = num2 >> 27 case '6': num1 = num2 << 12 num2 = num2 >> 20 case '7': num3 := num2 & 0x0000FF00 num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16) num1 = num3 | num4 num2 = (num2 & 0xFF000000) >> 8 case '8': num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24) num2 = (num2 & 0x00FF0000) >> 8 case '9': num1 = ^num2 default: num1 = num2 } num1 &= 0xFFFFFFFF num2 &= 0xFFFFFFFF if c != '0' && c != '9' { num1 |= num2 } num2 = num1 } return num1 } func testPasswordCalc(password, nonce string, expected uint32) { res := ownCalcPass(password, nonce) m := fmt.Sprintf("%s %s  %-10d  %-10d", password, nonce, res, expected) if res == expected { fmt.Println("PASS", m) } else { fmt.Println("FAIL", m) } } func main() { testPasswordCalc("12345", "603356072", 25280520) testPasswordCalc("12345", "410501656", 119537670) testPasswordCalc("12345", "630292165", 4269684735) }
function ownCalcPass($password, $nonce) { $msr = 0x7FFFFFFF; $m_1 = (int)0xFFFFFFFF; $m_8 = (int)0xFFFFFFF8; $m_16 = (int)0xFFFFFFF0; $m_128 = (int)0xFFFFFF80; $m_16777216 = (int)0xFF000000; $flag = True; $num1 = 0; $num2 = 0; foreach (str_split($nonce) as $c) { $num1 = $num1 & $m_1; $num2 = $num2 & $m_1; if ($c == '1') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_128; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 6; $num2 = $num2 << 25; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '2') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_16; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 3; $num2 = $num2 << 28; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '3') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_8; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 2; $num2 = $num2 << 29; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '4') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 1; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 30; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '5') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 5; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 26; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '6') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 12; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 19; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '7') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & 0xFF00; $num1 = $num1 + (( $num2 & 0xFF ) << 24 ); $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 ); $num2 = $num2 & $m_16777216; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 7; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '8') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & 0xFFFF; $num1 = $num1 << 16; $numx = $num2 >> 1; $numx = $numx & $msr; $numx = $numx >> 23; $num1 = $num1 + $numx; $num2 = $num2 & 0xFF0000; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 7; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '9') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = ~(int)$num2; $flag = False; } else { $num1 = $num2; } $num2 = $num1; } return sprintf('%u', $num1 & $m_1); }
Produce a language-to-language conversion: from Go to PHP, same semantics.
package main import ( "fmt" "strconv" ) func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd } start = false } switch c { case '1': num1 = (num2 & 0xFFFFFF80) >> 7 num2 = num2 << 25 case '2': num1 = (num2 & 0xFFFFFFF0) >> 4 num2 = num2 << 28 case '3': num1 = (num2 & 0xFFFFFFF8) >> 3 num2 = num2 << 29 case '4': num1 = num2 << 1 num2 = num2 >> 31 case '5': num1 = num2 << 5 num2 = num2 >> 27 case '6': num1 = num2 << 12 num2 = num2 >> 20 case '7': num3 := num2 & 0x0000FF00 num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16) num1 = num3 | num4 num2 = (num2 & 0xFF000000) >> 8 case '8': num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24) num2 = (num2 & 0x00FF0000) >> 8 case '9': num1 = ^num2 default: num1 = num2 } num1 &= 0xFFFFFFFF num2 &= 0xFFFFFFFF if c != '0' && c != '9' { num1 |= num2 } num2 = num1 } return num1 } func testPasswordCalc(password, nonce string, expected uint32) { res := ownCalcPass(password, nonce) m := fmt.Sprintf("%s %s  %-10d  %-10d", password, nonce, res, expected) if res == expected { fmt.Println("PASS", m) } else { fmt.Println("FAIL", m) } } func main() { testPasswordCalc("12345", "603356072", 25280520) testPasswordCalc("12345", "410501656", 119537670) testPasswordCalc("12345", "630292165", 4269684735) }
function ownCalcPass($password, $nonce) { $msr = 0x7FFFFFFF; $m_1 = (int)0xFFFFFFFF; $m_8 = (int)0xFFFFFFF8; $m_16 = (int)0xFFFFFFF0; $m_128 = (int)0xFFFFFF80; $m_16777216 = (int)0xFF000000; $flag = True; $num1 = 0; $num2 = 0; foreach (str_split($nonce) as $c) { $num1 = $num1 & $m_1; $num2 = $num2 & $m_1; if ($c == '1') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_128; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 6; $num2 = $num2 << 25; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '2') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_16; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 3; $num2 = $num2 << 28; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '3') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & $m_8; $num1 = $num1 >> 1; $num1 = $num1 & $msr; $num1 = $num1 >> 2; $num2 = $num2 << 29; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '4') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 1; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 30; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '5') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 5; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 26; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '6') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 << 12; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 19; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '7') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & 0xFF00; $num1 = $num1 + (( $num2 & 0xFF ) << 24 ); $num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 ); $num2 = $num2 & $m_16777216; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 7; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '8') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = $num2 & 0xFFFF; $num1 = $num1 << 16; $numx = $num2 >> 1; $numx = $numx & $msr; $numx = $numx >> 23; $num1 = $num1 + $numx; $num2 = $num2 & 0xFF0000; $num2 = $num2 >> 1; $num2 = $num2 & $msr; $num2 = $num2 >> 7; $num1 = $num1 + $num2; $flag = False; } elseif ($c == '9') { $length = !$flag; if (!$length) { $num2 = $password; } $num1 = ~(int)$num2; $flag = False; } else { $num1 = $num2; } $num2 = $num1; } return sprintf('%u', $num1 & $m_1); }
Convert the following code from Go to PHP, ensuring the logic remains intact.
package main import ( "fmt" "math" ) type mwriter struct { value float64 log string } func (m mwriter) bind(f func(v float64) mwriter) mwriter { n := f(m.value) n.log = m.log + n.log return n } func unit(v float64, s string) mwriter { return mwriter{v, fmt.Sprintf("  %-17s: %g\n", s, v)} } func root(v float64) mwriter { return unit(math.Sqrt(v), "Took square root") } func addOne(v float64) mwriter { return unit(v+1, "Added one") } func half(v float64) mwriter { return unit(v/2, "Divided by two") } func main() { mw1 := unit(5, "Initial value") mw2 := mw1.bind(root).bind(addOne).bind(half) fmt.Println("The Golden Ratio is", mw2.value) fmt.Println("\nThis was derived as follows:-") fmt.Println(mw2.log) }
class WriterMonad { private $value; private $logs; private function __construct($value, array $logs = []) { $this->value = $value; $this->logs = $logs; } public static function unit($value, string $log): WriterMonad { return new WriterMonad($value, ["{$log}: {$value}"]); } public function bind(callable $mapper): WriterMonad { $mapped = $mapper($this->value); assert($mapped instanceof WriterMonad); return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]); } public function value() { return $this->value; } public function logs(): array { return $this->logs; } } $root = fn(float $i): float => sqrt($i); $addOne = fn(float $i): float => $i + 1; $half = fn(float $i): float => $i / 2; $m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log); $result = WriterMonad::unit(5, "Initial value") ->bind($m($root, "square root")) ->bind($m($addOne, "add one")) ->bind($m($half, "half")); print "The Golden Ratio is: {$result->value()}\n"; print join("\n", $result->logs());
Write a version of this Go function in PHP with identical behavior.
package main import ( "fmt" "math" ) type mwriter struct { value float64 log string } func (m mwriter) bind(f func(v float64) mwriter) mwriter { n := f(m.value) n.log = m.log + n.log return n } func unit(v float64, s string) mwriter { return mwriter{v, fmt.Sprintf("  %-17s: %g\n", s, v)} } func root(v float64) mwriter { return unit(math.Sqrt(v), "Took square root") } func addOne(v float64) mwriter { return unit(v+1, "Added one") } func half(v float64) mwriter { return unit(v/2, "Divided by two") } func main() { mw1 := unit(5, "Initial value") mw2 := mw1.bind(root).bind(addOne).bind(half) fmt.Println("The Golden Ratio is", mw2.value) fmt.Println("\nThis was derived as follows:-") fmt.Println(mw2.log) }
class WriterMonad { private $value; private $logs; private function __construct($value, array $logs = []) { $this->value = $value; $this->logs = $logs; } public static function unit($value, string $log): WriterMonad { return new WriterMonad($value, ["{$log}: {$value}"]); } public function bind(callable $mapper): WriterMonad { $mapped = $mapper($this->value); assert($mapped instanceof WriterMonad); return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]); } public function value() { return $this->value; } public function logs(): array { return $this->logs; } } $root = fn(float $i): float => sqrt($i); $addOne = fn(float $i): float => $i + 1; $half = fn(float $i): float => $i / 2; $m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log); $result = WriterMonad::unit(5, "Initial value") ->bind($m($root, "square root")) ->bind($m($addOne, "add one")) ->bind($m($half, "half")); print "The Golden Ratio is: {$result->value()}\n"; print join("\n", $result->logs());
Generate an equivalent PHP version of this Go code.
package main import ( ed "github.com/Ernyoke/Imger/edgedetection" "github.com/Ernyoke/Imger/imgio" "log" ) func main() { img, err := imgio.ImreadRGBA("Valve_original_(1).png") if err != nil { log.Fatal("Could not read image", err) } cny, err := ed.CannyRGBA(img, 15, 45, 5) if err != nil { log.Fatal("Could not perform Canny Edge detection") } err = imgio.Imwrite(cny, "Valve_canny_(1).png") if err != nil { log.Fatal("Could not write Canny image to disk") } }
function RGBtoHSV($r, $g, $b) { $r = $r/255.; // convert to range 0..1 $g = $g/255.; $b = $b/255.; $cols = array("r" => $r, "g" => $g, "b" => $b); asort($cols, SORT_NUMERIC); $min = key(array_slice($cols, 1)); // "r", "g" or "b" $max = key(array_slice($cols, -1)); // "r", "g" or "b" if($cols[$min] == $cols[$max]) { $h = 0; } else { if($max == "r") { $h = 60. * ( 0 + ( ($cols["g"]-$cols["b"]) / ($cols[$max]-$cols[$min]) ) ); } elseif ($max == "g") { $h = 60. * ( 2 + ( ($cols["b"]-$cols["r"]) / ($cols[$max]-$cols[$min]) ) ); } elseif ($max == "b") { $h = 60. * ( 4 + ( ($cols["r"]-$cols["g"]) / ($cols[$max]-$cols[$min]) ) ); } if($h < 0) { $h += 360; } } if($cols[$max] == 0) { $s = 0; } else { $s = ( ($cols[$max]-$cols[$min])/$cols[$max] ); $s = $s * 255; } $v = $cols[$max]; $v = $v * 255; return(array($h, $s, $v)); } $filename = "image.png"; $dimensions = getimagesize($filename); $w = $dimensions[0]; // width $h = $dimensions[1]; // height $im = imagecreatefrompng($filename); for($hi=0; $hi < $h; $hi++) { for($wi=0; $wi < $w; $wi++) { $rgb = imagecolorat($im, $wi, $hi); $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; $hsv = RGBtoHSV($r, $g, $b); $brgb = imagecolorat($im, $wi, $hi+1); $br = ($brgb >> 16) & 0xFF; $bg = ($brgb >> 8) & 0xFF; $bb = $brgb & 0xFF; $bhsv = RGBtoHSV($br, $bg, $bb); if($hsv[2]-$bhsv[2] > 20) { imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0)); } else { imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0)); } } } header('Content-Type: image/jpeg'); imagepng($im); imagedestroy($im);
Port the following code from Go to PHP with equivalent syntax and logic.
package main import ( ed "github.com/Ernyoke/Imger/edgedetection" "github.com/Ernyoke/Imger/imgio" "log" ) func main() { img, err := imgio.ImreadRGBA("Valve_original_(1).png") if err != nil { log.Fatal("Could not read image", err) } cny, err := ed.CannyRGBA(img, 15, 45, 5) if err != nil { log.Fatal("Could not perform Canny Edge detection") } err = imgio.Imwrite(cny, "Valve_canny_(1).png") if err != nil { log.Fatal("Could not write Canny image to disk") } }
function RGBtoHSV($r, $g, $b) { $r = $r/255.; // convert to range 0..1 $g = $g/255.; $b = $b/255.; $cols = array("r" => $r, "g" => $g, "b" => $b); asort($cols, SORT_NUMERIC); $min = key(array_slice($cols, 1)); // "r", "g" or "b" $max = key(array_slice($cols, -1)); // "r", "g" or "b" if($cols[$min] == $cols[$max]) { $h = 0; } else { if($max == "r") { $h = 60. * ( 0 + ( ($cols["g"]-$cols["b"]) / ($cols[$max]-$cols[$min]) ) ); } elseif ($max == "g") { $h = 60. * ( 2 + ( ($cols["b"]-$cols["r"]) / ($cols[$max]-$cols[$min]) ) ); } elseif ($max == "b") { $h = 60. * ( 4 + ( ($cols["r"]-$cols["g"]) / ($cols[$max]-$cols[$min]) ) ); } if($h < 0) { $h += 360; } } if($cols[$max] == 0) { $s = 0; } else { $s = ( ($cols[$max]-$cols[$min])/$cols[$max] ); $s = $s * 255; } $v = $cols[$max]; $v = $v * 255; return(array($h, $s, $v)); } $filename = "image.png"; $dimensions = getimagesize($filename); $w = $dimensions[0]; // width $h = $dimensions[1]; // height $im = imagecreatefrompng($filename); for($hi=0; $hi < $h; $hi++) { for($wi=0; $wi < $w; $wi++) { $rgb = imagecolorat($im, $wi, $hi); $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; $hsv = RGBtoHSV($r, $g, $b); $brgb = imagecolorat($im, $wi, $hi+1); $br = ($brgb >> 16) & 0xFF; $bg = ($brgb >> 8) & 0xFF; $bb = $brgb & 0xFF; $bhsv = RGBtoHSV($br, $bg, $bb); if($hsv[2]-$bhsv[2] > 20) { imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0)); } else { imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0)); } } } header('Content-Type: image/jpeg'); imagepng($im); imagedestroy($im);
Rewrite the snippet below in PHP so it works the same as the original Go code.
package main import ( "bufio" "fmt" "log" "os" ) type SomeStruct struct { runtimeFields map[string]string } func check(err error) { if err != nil { log.Fatal(err) } } func main() { ss := SomeStruct{make(map[string]string)} scanner := bufio.NewScanner(os.Stdin) fmt.Println("Create two fields at runtime: ") for i := 1; i <= 2; i++ { fmt.Printf(" Field #%d:\n", i) fmt.Print(" Enter name  : ") scanner.Scan() name := scanner.Text() fmt.Print(" Enter value : ") scanner.Scan() value := scanner.Text() check(scanner.Err()) ss.runtimeFields[name] = value fmt.Println() } for { fmt.Print("Which field do you want to inspect ? ") scanner.Scan() name := scanner.Text() check(scanner.Err()) value, ok := ss.runtimeFields[name] if !ok { fmt.Println("There is no field of that name, try again") } else { fmt.Printf("Its value is '%s'\n", value) return } } }
class E {}; $e=new E(); $e->foo=1; $e->{"foo"} = 1; // using a runtime name $x = "foo"; $e->$x = 1; // using a runtime name in a variable
Transform the following Go implementation into PHP, maintaining the same output and logic.
package main import ( "bufio" "fmt" "log" "os" ) type SomeStruct struct { runtimeFields map[string]string } func check(err error) { if err != nil { log.Fatal(err) } } func main() { ss := SomeStruct{make(map[string]string)} scanner := bufio.NewScanner(os.Stdin) fmt.Println("Create two fields at runtime: ") for i := 1; i <= 2; i++ { fmt.Printf(" Field #%d:\n", i) fmt.Print(" Enter name  : ") scanner.Scan() name := scanner.Text() fmt.Print(" Enter value : ") scanner.Scan() value := scanner.Text() check(scanner.Err()) ss.runtimeFields[name] = value fmt.Println() } for { fmt.Print("Which field do you want to inspect ? ") scanner.Scan() name := scanner.Text() check(scanner.Err()) value, ok := ss.runtimeFields[name] if !ok { fmt.Println("There is no field of that name, try again") } else { fmt.Printf("Its value is '%s'\n", value) return } } }
class E {}; $e=new E(); $e->foo=1; $e->{"foo"} = 1; // using a runtime name $x = "foo"; $e->$x = 1; // using a runtime name in a variable
Maintain the same structure and functionality when rewriting this code in PHP.
package main import ( "fmt" "github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre" ) var pattern = "(*UTF)(*UCP)" + "[a-z][-a-z0-9+.]*:" + "(?=[/\\w])" + "(?: "[-\\w.~/%!$&'()*+,;=]*" + "(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" + "(?:\\#[-\\w.~%!$&'()*+,;=/?]*)?" func main() { text := ` this URI contains an illegal character, parentheses and a misplaced full stop: http: and another one just to confuse the parser: http: ")" is handled the wrong way by the mediawiki parser. ftp: ftp: ftp: leading junk ftp: leading junk ftp: if you have other interesting URIs for testing, please add them here: http: http: ` descs := []string{"URIs:-", "IRIs:-"} patterns := []string{pattern[12:], pattern} for i := 0; i <= 1; i++ { fmt.Println(descs[i]) re := pcre.MustCompile(patterns[i], 0) t := text for { se := re.FindIndex([]byte(t), 0) if se == nil { break } fmt.Println(t[se[0]:se[1]]) t = t[se[1]:] } fmt.Println() } }
$tests = array( 'this URI contains an illegal character, parentheses and a misplaced full stop:', 'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).', 'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)', '")" is handled the wrong way by the mediawiki parser.', 'ftp://domain.name/path(balanced_brackets)/foo.html', 'ftp://domain.name/path(balanced_brackets)/ending.in.dot.', 'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.', 'leading junk ftp://domain.name/path/embedded?punct/uation.', 'leading junk ftp://domain.name/dangling_close_paren)', 'if you have other interesting URIs for testing, please add them here:', 'http://www.example.org/foo.html#includes_fragment', 'http://www.example.org/foo.html#enthält_Unicode-Fragment', ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true', 'blah (foo://domain.hld/))))', 'https://haxor.ur:4592/~mama/####&?foo' ); foreach ( $tests as $test ) { foreach( explode( ' ', $test ) as $uri ) { if ( filter_var( $uri, FILTER_VALIDATE_URL ) ) echo $uri, PHP_EOL; } }
Can you help me rewrite this code in PHP instead of Go, keeping it the same logically?
package main import ( "fmt" "github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre" ) var pattern = "(*UTF)(*UCP)" + "[a-z][-a-z0-9+.]*:" + "(?=[/\\w])" + "(?: "[-\\w.~/%!$&'()*+,;=]*" + "(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" + "(?:\\#[-\\w.~%!$&'()*+,;=/?]*)?" func main() { text := ` this URI contains an illegal character, parentheses and a misplaced full stop: http: and another one just to confuse the parser: http: ")" is handled the wrong way by the mediawiki parser. ftp: ftp: ftp: leading junk ftp: leading junk ftp: if you have other interesting URIs for testing, please add them here: http: http: ` descs := []string{"URIs:-", "IRIs:-"} patterns := []string{pattern[12:], pattern} for i := 0; i <= 1; i++ { fmt.Println(descs[i]) re := pcre.MustCompile(patterns[i], 0) t := text for { se := re.FindIndex([]byte(t), 0) if se == nil { break } fmt.Println(t[se[0]:se[1]]) t = t[se[1]:] } fmt.Println() } }
$tests = array( 'this URI contains an illegal character, parentheses and a misplaced full stop:', 'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).', 'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)', '")" is handled the wrong way by the mediawiki parser.', 'ftp://domain.name/path(balanced_brackets)/foo.html', 'ftp://domain.name/path(balanced_brackets)/ending.in.dot.', 'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.', 'leading junk ftp://domain.name/path/embedded?punct/uation.', 'leading junk ftp://domain.name/dangling_close_paren)', 'if you have other interesting URIs for testing, please add them here:', 'http://www.example.org/foo.html#includes_fragment', 'http://www.example.org/foo.html#enthält_Unicode-Fragment', ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true', 'blah (foo://domain.hld/))))', 'https://haxor.ur:4592/~mama/####&?foo' ); foreach ( $tests as $test ) { foreach( explode( ' ', $test ) as $uri ) { if ( filter_var( $uri, FILTER_VALIDATE_URL ) ) echo $uri, PHP_EOL; } }
Convert the following code from Go to PHP, ensuring the logic remains intact.
package main import ( "fmt" "github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre" ) var pattern = "(*UTF)(*UCP)" + "[a-z][-a-z0-9+.]*:" + "(?=[/\\w])" + "(?: "[-\\w.~/%!$&'()*+,;=]*" + "(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" + "(?:\\#[-\\w.~%!$&'()*+,;=/?]*)?" func main() { text := ` this URI contains an illegal character, parentheses and a misplaced full stop: http: and another one just to confuse the parser: http: ")" is handled the wrong way by the mediawiki parser. ftp: ftp: ftp: leading junk ftp: leading junk ftp: if you have other interesting URIs for testing, please add them here: http: http: ` descs := []string{"URIs:-", "IRIs:-"} patterns := []string{pattern[12:], pattern} for i := 0; i <= 1; i++ { fmt.Println(descs[i]) re := pcre.MustCompile(patterns[i], 0) t := text for { se := re.FindIndex([]byte(t), 0) if se == nil { break } fmt.Println(t[se[0]:se[1]]) t = t[se[1]:] } fmt.Println() } }
$tests = array( 'this URI contains an illegal character, parentheses and a misplaced full stop:', 'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).', 'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)', '")" is handled the wrong way by the mediawiki parser.', 'ftp://domain.name/path(balanced_brackets)/foo.html', 'ftp://domain.name/path(balanced_brackets)/ending.in.dot.', 'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.', 'leading junk ftp://domain.name/path/embedded?punct/uation.', 'leading junk ftp://domain.name/dangling_close_paren)', 'if you have other interesting URIs for testing, please add them here:', 'http://www.example.org/foo.html#includes_fragment', 'http://www.example.org/foo.html#enthält_Unicode-Fragment', ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true', 'blah (foo://domain.hld/))))', 'https://haxor.ur:4592/~mama/####&?foo' ); foreach ( $tests as $test ) { foreach( explode( ' ', $test ) as $uri ) { if ( filter_var( $uri, FILTER_VALIDATE_URL ) ) echo $uri, PHP_EOL; } }
Produce a functionally identical PHP code for the snippet given in Go.
package main import ( "fmt" "github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre" ) var pattern = "(*UTF)(*UCP)" + "[a-z][-a-z0-9+.]*:" + "(?=[/\\w])" + "(?: "[-\\w.~/%!$&'()*+,;=]*" + "(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" + "(?:\\#[-\\w.~%!$&'()*+,;=/?]*)?" func main() { text := ` this URI contains an illegal character, parentheses and a misplaced full stop: http: and another one just to confuse the parser: http: ")" is handled the wrong way by the mediawiki parser. ftp: ftp: ftp: leading junk ftp: leading junk ftp: if you have other interesting URIs for testing, please add them here: http: http: ` descs := []string{"URIs:-", "IRIs:-"} patterns := []string{pattern[12:], pattern} for i := 0; i <= 1; i++ { fmt.Println(descs[i]) re := pcre.MustCompile(patterns[i], 0) t := text for { se := re.FindIndex([]byte(t), 0) if se == nil { break } fmt.Println(t[se[0]:se[1]]) t = t[se[1]:] } fmt.Println() } }
$tests = array( 'this URI contains an illegal character, parentheses and a misplaced full stop:', 'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).', 'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)', '")" is handled the wrong way by the mediawiki parser.', 'ftp://domain.name/path(balanced_brackets)/foo.html', 'ftp://domain.name/path(balanced_brackets)/ending.in.dot.', 'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.', 'leading junk ftp://domain.name/path/embedded?punct/uation.', 'leading junk ftp://domain.name/dangling_close_paren)', 'if you have other interesting URIs for testing, please add them here:', 'http://www.example.org/foo.html#includes_fragment', 'http://www.example.org/foo.html#enthält_Unicode-Fragment', ' http://192.168.0.1/admin/?hackme=%%%%%%%%%true', 'blah (foo://domain.hld/))))', 'https://haxor.ur:4592/~mama/####&?foo' ); foreach ( $tests as $test ) { foreach( explode( ' ', $test ) as $uri ) { if ( filter_var( $uri, FILTER_VALIDATE_URL ) ) echo $uri, PHP_EOL; } }
Change the programming language of this snippet from VB to Python without modifying what it does.
Option Explicit sub verifydistribution(calledfunction, samples, delta) Dim i, n, maxdiff Dim d : Set d = CreateObject("Scripting.Dictionary") wscript.echo "Running """ & calledfunction & """ " & samples & " times..." for i = 1 to samples Execute "n = " & calledfunction d(n) = d(n) + 1 next n = d.Count maxdiff = 0 wscript.echo "Expected average count is " & Int(samples/n) & " across " & n & " buckets." for each i in d.Keys dim diff : diff = abs(1 - d(i) / (samples/n)) if diff > maxdiff then maxdiff = diff wscript.echo "Bucket " & i & " had " & d(i) & " occurences" _ & vbTab & " difference from expected=" & FormatPercent(diff, 2) next wscript.echo "Maximum found variation is " & FormatPercent(maxdiff, 2) _ & ", desired limit is " & FormatPercent(delta, 2) & "." if maxdiff > delta then wscript.echo "Skewed!" else wscript.echo "Smooth!" end sub
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))
Ensure the translated Python code behaves exactly like the original VB snippet.
Imports System.Numerics Module Module1 Class Sterling Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger) Private Shared Function CacheKey(n As Integer, k As Integer) As String Return String.Format("{0}:{1}", n, k) End Function Private Shared Function Impl(n As Integer, k As Integer) As BigInteger If n = 0 AndAlso k = 0 Then Return 1 End If If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then Return 0 End If If n = k Then Return 1 End If If k > n Then Return 0 End If Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1) End Function Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger Dim key = CacheKey(n, k) If COMPUTED.ContainsKey(key) Then Return COMPUTED(key) End If Dim result = Impl(n, k) COMPUTED.Add(key, result) Return result End Function End Class Sub Main() Console.WriteLine("Stirling numbers of the second kind:") Dim max = 12 Console.Write("n/k") For n = 0 To max Console.Write("{0,10}", n) Next Console.WriteLine() For n = 0 To max Console.Write("{0,3}", n) For k = 0 To n Console.Write("{0,10}", Sterling.Sterling2(n, k)) Next Console.WriteLine() Next Console.WriteLine("The maximum value of S2(100, k) = ") Dim previous = BigInteger.Zero For k = 1 To 100 Dim current = Sterling.Sterling2(100, k) If current > previous Then previous = current Else Console.WriteLine(previous) Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1) Exit For End If Next End Sub End Module
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
Produce a functionally identical Python code for the snippet given in VB.
Imports System.Numerics Module Module1 Class Sterling Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger) Private Shared Function CacheKey(n As Integer, k As Integer) As String Return String.Format("{0}:{1}", n, k) End Function Private Shared Function Impl(n As Integer, k As Integer) As BigInteger If n = 0 AndAlso k = 0 Then Return 1 End If If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then Return 0 End If If n = k Then Return 1 End If If k > n Then Return 0 End If Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1) End Function Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger Dim key = CacheKey(n, k) If COMPUTED.ContainsKey(key) Then Return COMPUTED(key) End If Dim result = Impl(n, k) COMPUTED.Add(key, result) Return result End Function End Class Sub Main() Console.WriteLine("Stirling numbers of the second kind:") Dim max = 12 Console.Write("n/k") For n = 0 To max Console.Write("{0,10}", n) Next Console.WriteLine() For n = 0 To max Console.Write("{0,3}", n) For k = 0 To n Console.Write("{0,10}", Sterling.Sterling2(n, k)) Next Console.WriteLine() Next Console.WriteLine("The maximum value of S2(100, k) = ") Dim previous = BigInteger.Zero For k = 1 To 100 Dim current = Sterling.Sterling2(100, k) If current > previous Then previous = current Else Console.WriteLine(previous) Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1) Exit For End If Next End Sub End Module
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
Port the provided VB code into Python while preserving the original functionality.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
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
Port the following code from VB to Python with equivalent syntax and logic.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
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
Generate a Python translation of this VB snippet without changing its computational steps.
Option Explicit Private Lines(1 To 3, 1 To 3) As String Private Nb As Byte, player As Byte Private GameWin As Boolean, GameOver As Boolean Sub Main_TicTacToe() Dim p As String InitLines printLines Nb Do p = WhoPlay Debug.Print p & " play" If p = "Human" Then Call HumanPlay GameWin = IsWinner("X") Else Call ComputerPlay GameWin = IsWinner("O") End If If Not GameWin Then GameOver = IsEnd Loop Until GameWin Or GameOver If Not GameOver Then Debug.Print p & " Win !" Else Debug.Print "Game Over!" End If End Sub Sub InitLines(Optional S As String) Dim i As Byte, j As Byte Nb = 0: player = 0 For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) Lines(i, j) = "#" Next j Next i End Sub Sub printLines(Nb As Byte) Dim i As Byte, j As Byte, strT As String Debug.Print "Loop " & Nb For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) strT = strT & Lines(i, j) Next j Debug.Print strT strT = vbNullString Next i End Sub Function WhoPlay(Optional S As String) As String If player = 0 Then player = 1 WhoPlay = "Human" Else player = 0 WhoPlay = "Computer" End If End Function Sub HumanPlay(Optional S As String) Dim L As Byte, C As Byte, GoodPlay As Boolean Do L = Application.InputBox("Choose the row", "Numeric only", Type:=1) If L > 0 And L < 4 Then C = Application.InputBox("Choose the column", "Numeric only", Type:=1) If C > 0 And C < 4 Then If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then Lines(L, C) = "X" Nb = Nb + 1 printLines Nb GoodPlay = True End If End If End If Loop Until GoodPlay End Sub Sub ComputerPlay(Optional S As String) Dim L As Byte, C As Byte, GoodPlay As Boolean Randomize Timer Do L = Int((Rnd * 3) + 1) C = Int((Rnd * 3) + 1) If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then Lines(L, C) = "O" Nb = Nb + 1 printLines Nb GoodPlay = True End If Loop Until GoodPlay End Sub Function IsWinner(S As String) As Boolean Dim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String Ch = String(UBound(Lines, 1), S) For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) strTL = strTL & Lines(i, j) strTC = strTC & Lines(j, i) Next j If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For strTL = vbNullString: strTC = vbNullString Next i strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3) strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1) If strTL = Ch Or strTC = Ch Then IsWinner = True End Function Function IsEnd() As Boolean Dim i As Byte, j As Byte For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) If Lines(i, j) = "#" Then Exit Function Next j Next i IsEnd = True End Function
import random board = list('123456789') wins = ((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)) def printboard(): print('\n'.join(' '.join(board[x:x+3]) for x in(0,3,6))) def score(): for w in wins: b = board[w[0]] if b in 'XO' and all (board[i] == b for i in w): return b, [i+1 for i in w] return None, None def finished(): return all (b in 'XO' for b in board) def space(): return [ b for b in board if b not in 'XO'] def my_turn(xo): options = space() choice = random.choice(options) board[int(choice)-1] = xo return choice def your_turn(xo): options = space() while True: choice = input(" Put your %s in any of these positions: %s " % (xo, ''.join(options))).strip() if choice in options: break print( "Whoops I don't understand the input" ) board[int(choice)-1] = xo return choice def me(xo='X'): printboard() print('I go at', my_turn(xo)) return score() assert not s[0], "\n%s wins across %s" % s def you(xo='O'): printboard() print('You went at', your_turn(xo)) return score() assert not s[0], "\n%s wins across %s" % s print(__doc__) while not finished(): s = me('X') if s[0]: printboard() print("\n%s wins across %s" % s) break if not finished(): s = you('O') if s[0]: printboard() print("\n%s wins across %s" % s) break else: print('\nA draw')
Translate the given VB code snippet into Python without altering its behavior.
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
i=1 while i: print(i) i += 1
Ensure the translated Python code behaves exactly like the original VB snippet.
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
i=1 while i: print(i) i += 1
Rewrite the snippet below in Python so it works the same as the original VB code.
Function dns_query(url,ver) Set r = New RegExp r.Pattern = "Pinging.+?\[(.+?)\].+" Set objshell = CreateObject("WScript.Shell") Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url) WScript.StdOut.WriteLine "URL: " & url Do Until objexec.StdOut.AtEndOfStream line = objexec.StdOut.ReadLine If r.Test(line) Then WScript.StdOut.WriteLine "IP Version " &_ ver & ": " & r.Replace(line,"$1") End If Loop End Function Call dns_query(WScript.Arguments(0),WScript.Arguments(1))
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
Maintain the same structure and functionality when rewriting this code in Python.
Const WIDTH = 243 Dim n As Long Dim points() As Single Dim flag As Boolean Private Sub lineto(x As Integer, y As Integer) If flag Then points(n, 1) = x points(n, 2) = y End If n = n + 1 End Sub Private Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _ ByVal i1 As Integer, ByVal i2 As Integer) If (lg = 1) Then Call lineto(x * 3, y * 3) Exit Sub End If lg = lg / 3 Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2) Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2) Call Peano(x + lg, y + lg, lg, i1, 1 - i2) Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2) Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2) Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2) Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2) Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2) Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2) End Sub Sub main() n = 1: flag = False Call Peano(0, 0, WIDTH, 0, 0) ReDim points(1 To n - 1, 1 To 2) n = 1: flag = True Call Peano(0, 0, WIDTH, 0, 0) ActiveSheet.Shapes.AddPolyline points End Sub
import turtle as tt import inspect stack = [] def peano(iterations=1): global stack ivan = tt.Turtle(shape = "classic", visible = True) screen = tt.Screen() screen.title("Desenhin do Peano") screen.bgcolor(" screen.delay(0) screen.setup(width=0.95, height=0.9) walk = 1 def screenlength(k): if k != 0: length = screenlength(k-1) return 2*length + 1 else: return 0 kkkj = screenlength(iterations) screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1) ivan.color(" def step1(k): global stack stack.append(len(inspect.stack())) if k != 0: ivan.left(90) step2(k - 1) ivan.forward(walk) ivan.right(90) step1(k - 1) ivan.forward(walk) step1(k - 1) ivan.right(90) ivan.forward(walk) step2(k - 1) ivan.left(90) def step2(k): global stack stack.append(len(inspect.stack())) if k != 0: ivan.right(90) step1(k - 1) ivan.forward(walk) ivan.left(90) step2(k - 1) ivan.forward(walk) step2(k - 1) ivan.left(90) ivan.forward(walk) step1(k - 1) ivan.right(90) ivan.left(90) step2(iterations) tt.done() if __name__ == "__main__": peano(4) import pylab as P P.plot(stack) P.show()
Generate a Python translation of this VB snippet without changing its computational steps.
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double Debug.Print "[1] ""Data set:"" "; For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) Total = Total + ObservationFrequencies(i) Debug.Print ObservationFrequencies(i); " "; Next i DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies) Ei = Total / (DegreesOfFreedom + 1) For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei Next i p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True) Debug.Print Debug.Print "Chi-squared test for given frequencies" Debug.Print "X-squared ="; Format(ChiSquared, "0.0000"); ", "; Debug.Print "df ="; DegreesOfFreedom; ", "; Debug.Print "p-value = "; Format(p_value, "0.0000") Test4DiscreteUniformDistribution = p_value > Significance End Function Private Function Dice5() As Integer Dice5 = Int(5 * Rnd + 1) End Function Private Function Dice7() As Integer Dim i As Integer Do i = 5 * (Dice5 - 1) + Dice5 Loop While i > 21 Dice7 = i Mod 7 + 1 End Function Sub TestDice7() Dim i As Long, roll As Integer Dim Bins(1 To 7) As Variant For i = 1 To 1000000 roll = Dice7 Bins(roll) = Bins(roll) + 1 Next i Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """" End Sub
from random import randint def dice5(): return randint(1, 5) def dice7(): r = dice5() + dice5() * 5 - 6 return (r % 7) + 1 if r < 21 else dice7()
Please provide an equivalent version of this VB code in Python.
Option Explicit Sub Main() Dim Primes() As Long, n As Long, temp$ Dim t As Single t = Timer n = 133218295 Primes = ListPrimes(n) Debug.Print "For N = " & Format(n, "#,##0") & ", execution time : " & _ Format(Timer - t, "0.000 s") & ", " & _ Format(UBound(Primes) + 1, "#,##0") & " primes numbers." For n = 0 To 19 temp = temp & ", " & Primes(n) Next Debug.Print "First twenty primes : "; Mid(temp, 3) n = 0: temp = vbNullString Do While Primes(n) < 100 n = n + 1 Loop Do While Primes(n) < 150 temp = temp & ", " & Primes(n) n = n + 1 Loop Debug.Print "Primes between 100 and 150 : " & Mid(temp, 3) Dim ccount As Long n = 0 Do While Primes(n) < 7700 n = n + 1 Loop Do While Primes(n) < 8000 ccount = ccount + 1 n = n + 1 Loop Debug.Print "Number of primes between 7,700 and 8,000 : " & ccount n = 1 Do While n <= 100000 n = n * 10 Debug.Print "The " & n & "th prime: "; Format(Primes(n - 1), "#,##0") Loop Debug.Print "VBA has a limit in array Debug.Print "With my computer, the limit for an array of Long is : 133 218 295" Debug.Print "The last prime I could find is the : " & _ Format(UBound(Primes), "#,##0") & "th, Value : " & _ Format(Primes(UBound(Primes)), "#,##0") End Sub Function ListPrimes(MAX As Long) As Long() Dim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long ReDim t(2 To MAX) ReDim L(MAX \ 2) s = Sqr(MAX) For i = 3 To s Step 2 If t(i) = False Then For j = i * i To MAX Step i t(j) = True Next End If Next i L(0) = 2 For i = 3 To MAX Step 2 If t(i) = False Then c = c + 1 L(c) = i End If Next i ReDim Preserve L(c) ListPrimes = L End Function
islice(count(7), 0, None, 2)
Maintain the same structure and functionality when rewriting this code in Python.
Module Program Sub Main() Console.WriteLine("Enter two space-delimited integers:") Dim input = Console.ReadLine().Split() Dim rows = Integer.Parse(input(0)) Dim cols = Integer.Parse(input(1)) Dim arr(rows - 1, cols - 1) As Integer arr(0, 0) = 2 Console.WriteLine(arr(0, 0)) End Sub End Module
width = int(raw_input("Width of myarray: ")) height = int(raw_input("Height of Array: ")) myarray = [[0] * width for i in range(height)] myarray[0][0] = 3.5 print (myarray[0][0])
Keep all operations the same but rewrite the snippet in Python.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Ensure the translated Python code behaves exactly like the original VB snippet.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Preserve the algorithm and functionality while converting the code from VB to Python.
Option Explicit Sub Main() Const VECSIZE As Long = 3350 Const BUFSIZE As Long = 201 Dim buffer(1 To BUFSIZE) As Long Dim vect(1 To VECSIZE) As Long Dim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long For n = 1 To VECSIZE vect(n) = 2 Next n For n = 1 To BUFSIZE karray = 0 For l = VECSIZE To 1 Step -1 num = 100000 * vect(l) + karray * l karray = num \ (2 * l - 1) vect(l) = num - karray * (2 * l - 1) Next l k = karray \ 100000 buffer(n) = more + k more = karray - k * 100000 Next n Debug.Print CStr(buffer(1)); Debug.Print "." l = 0 For n = 2 To BUFSIZE Debug.Print Format$(buffer(n), "00000"); l = l + 1 If l = 10 Then l = 0 Debug.Print End If Next n End Sub
def calcPi(): q, r, t, k, n, l = 1, 0, 1, 1, 3, 3 while True: if 4*q+r-t < n*t: yield n nr = 10*(r-n*t) n = ((10*(3*q+r))//t)-10*n q *= 10 r = nr else: nr = (2*q+r)*l nn = (q*(7*k)+2+(r*l))//(t*l) q *= k t *= l l += 2 k += 1 n = nn r = nr import sys pi_digits = calcPi() i = 0 for d in pi_digits: sys.stdout.write(str(d)) i += 1 if i == 40: print(""); i = 0
Preserve the algorithm and functionality while converting the code from VB to Python.
Public Q(100000) As Long Public Sub HofstadterQ() Dim n As Long, smaller As Long Q(1) = 1 Q(2) = 1 For n = 3 To 100000 Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2)) If Q(n) < Q(n - 1) Then smaller = smaller + 1 Next n Debug.Print "First ten terms:" For i = 1 To 10 Debug.Print Q(i); Next i Debug.print Debug.Print "The 1000th term is:"; Q(1000) Debug.Print "Number of times smaller:"; smaller End Sub
def q(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return q.seq[n] except IndexError: ans = q(n - q(n - 1)) + q(n - q(n - 2)) q.seq.append(ans) return ans q.seq = [None, 1, 1] if __name__ == '__main__': first10 = [q(i) for i in range(1,11)] assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], "Q() value error(s)" print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10)) assert q(1000) == 502, "Q(1000) value error" print("Q(1000) =", q(1000))
Convert this VB block to Python, preserving its control flow and logic.
Public Q(100000) As Long Public Sub HofstadterQ() Dim n As Long, smaller As Long Q(1) = 1 Q(2) = 1 For n = 3 To 100000 Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2)) If Q(n) < Q(n - 1) Then smaller = smaller + 1 Next n Debug.Print "First ten terms:" For i = 1 To 10 Debug.Print Q(i); Next i Debug.print Debug.Print "The 1000th term is:"; Q(1000) Debug.Print "Number of times smaller:"; smaller End Sub
def q(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return q.seq[n] except IndexError: ans = q(n - q(n - 1)) + q(n - q(n - 2)) q.seq.append(ans) return ans q.seq = [None, 1, 1] if __name__ == '__main__': first10 = [q(i) for i in range(1,11)] assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], "Q() value error(s)" print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10)) assert q(1000) == 502, "Q(1000) value error" print("Q(1000) =", q(1000))
Change the programming language of this snippet from VB to Python without modifying what it does.
Private Function call_fn(f As String, n As Long) As Long call_fn = Application.Run(f, f, n) End Function Private Function Y(f As String) As String Y = f End Function Private Function fac(self As String, n As Long) As Long If n > 1 Then fac = n * call_fn(self, n - 1) Else fac = 1 End If End Function Private Function fib(self As String, n As Long) As Long If n > 1 Then fib = call_fn(self, n - 1) + call_fn(self, n - 2) Else fib = n End If End Function Private Sub test(name As String) Dim f As String: f = Y(name) Dim i As Long Debug.Print name For i = 1 To 10 Debug.Print call_fn(f, i); Next i Debug.Print End Sub Public Sub main() test "fac" test "fib" End Sub
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1)) >>> [ Y(fac)(i) for i in range(10) ] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] >>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)) >>> [ Y(fib)(i) for i in range(10) ] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Write the same code in Python as shown below in VB.
Type Contact Name As String firstname As String Age As Byte End Type Function SetContact(N As String, Fn As String, A As Byte) As Contact SetContact.Name = N SetContact.firstname = Fn SetContact.Age = A End Function Sub Test_SetContact() Dim Cont As Contact Cont = SetContact("SMITH", "John", 23) Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old." End Sub
def addsub(x, y): return x + y, x - y
Rewrite this program in Python while keeping its functionality equivalent to the VB version.
Imports System.Linq Module Module1 Dim h() As Integer Sub sho(i As Integer) Console.WriteLine(String.Join(" ", h.Skip(i).Take(10))) End Sub Sub Main() Dim a, b, c, d, f, g As Integer : g = 1000 h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g f = h(b) : For d = a To 0 Step -1 If f = h(d) Then h(c) = b - d: Exit For Next : a = b : b = c : Next : sho(0) : sho(990) End Sub End Module
def van_eck(): n, seen, val = 0, {}, 0 while True: yield val last = {val: n} val = n - seen.get(val, n) seen.update(last) n += 1 if __name__ == '__main__': print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10))) print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
Produce a language-to-language conversion: from VB to Python, same semantics.
Imports System.Linq Module Module1 Dim h() As Integer Sub sho(i As Integer) Console.WriteLine(String.Join(" ", h.Skip(i).Take(10))) End Sub Sub Main() Dim a, b, c, d, f, g As Integer : g = 1000 h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g f = h(b) : For d = a To 0 Step -1 If f = h(d) Then h(c) = b - d: Exit For Next : a = b : b = c : Next : sho(0) : sho(990) End Sub End Module
def van_eck(): n, seen, val = 0, {}, 0 while True: yield val last = {val: n} val = n - seen.get(val, n) seen.update(last) n += 1 if __name__ == '__main__': print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10))) print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
Preserve the algorithm and functionality while converting the code from VB to Python.
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant GenerateNewDigits: For i = 1 To 4 Digit(i) = [randbetween(1,9)] Next i GetUserExpression: bValidExpression = True stFailMessage = "" stFailDigits = "" stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _ Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game") bValidDigits = True stFailDigits = "" For i = 1 To 4 If InStr(stUserExpression, Digit(i)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Digit(i) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 1 To Len(stUserExpression) If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" iDigitCount = 0 For i = 1 To Len(stUserExpression) If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then iDigitCount = iDigitCount + 1 If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If End If Next i If iDigitCount > 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr End If If iDigitCount < 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr End If If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 11 To 99 If Not InStr(stUserExpression, i) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & i End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr End If On Error GoTo EvalFail vResult = Evaluate(stUserExpression) If Not vResult = 24 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult End If If bValidExpression = False Then vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED") If vTryAgain = vbRetry Then vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY") If vSameDigits = vbYes Then GoTo GetUserExpression Else GoTo GenerateNewDigits End If End If Else vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _ vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS") If vTryAgain = vbRetry Then GoTo GenerateNewDigits End If End If Exit Sub EvalFail: bValidExpression = False vResult = Err.Description Resume End Sub
from __future__ import division, print_function import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer.lower() == 'q': break if answer == '!': digits = choose4() print ("New digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") if __name__ == '__main__': main()
Generate a Python translation of this VB snippet without changing its computational steps.
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant GenerateNewDigits: For i = 1 To 4 Digit(i) = [randbetween(1,9)] Next i GetUserExpression: bValidExpression = True stFailMessage = "" stFailDigits = "" stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _ Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game") bValidDigits = True stFailDigits = "" For i = 1 To 4 If InStr(stUserExpression, Digit(i)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Digit(i) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 1 To Len(stUserExpression) If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" iDigitCount = 0 For i = 1 To Len(stUserExpression) If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then iDigitCount = iDigitCount + 1 If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If End If Next i If iDigitCount > 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr End If If iDigitCount < 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr End If If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 11 To 99 If Not InStr(stUserExpression, i) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & i End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr End If On Error GoTo EvalFail vResult = Evaluate(stUserExpression) If Not vResult = 24 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult End If If bValidExpression = False Then vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED") If vTryAgain = vbRetry Then vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY") If vSameDigits = vbYes Then GoTo GetUserExpression Else GoTo GenerateNewDigits End If End If Else vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _ vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS") If vTryAgain = vbRetry Then GoTo GenerateNewDigits End If End If Exit Sub EvalFail: bValidExpression = False vResult = Err.Description Resume End Sub
from __future__ import division, print_function import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer.lower() == 'q': break if answer == '!': digits = choose4() print ("New digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") if __name__ == '__main__': main()
Rewrite the snippet below in Python so it works the same as the original VB code.
For i = 1 To 10 Console.Write(i) If i Mod 5 = 0 Then Console.WriteLine() Else Console.Write(", ") End If Next
for i in range(1, 11): if i % 5 == 0: print(i) continue print(i, end=', ')
Generate a Python translation of this VB snippet without changing its computational steps.
Option Base 1 Private Function pivotize(m As Variant) As Variant Dim n As Integer: n = UBound(m) Dim im() As Double ReDim im(n, n) For i = 1 To n For j = 1 To n im(i, j) = 0 Next j im(i, i) = 1 Next i For i = 1 To n mx = Abs(m(i, i)) row_ = i For j = i To n If Abs(m(j, i)) > mx Then mx = Abs(m(j, i)) row_ = j End If Next j If i <> Row Then For j = 1 To n tmp = im(i, j) im(i, j) = im(row_, j) im(row_, j) = tmp Next j End If Next i pivotize = im End Function Private Function lu(a As Variant) As Variant Dim n As Integer: n = UBound(a) Dim l() As Double ReDim l(n, n) For i = 1 To n For j = 1 To n l(i, j) = 0 Next j Next i u = l p = pivotize(a) a2 = WorksheetFunction.MMult(p, a) For j = 1 To n l(j, j) = 1# For i = 1 To j sum1 = 0# For k = 1 To i sum1 = sum1 + u(k, j) * l(i, k) Next k u(i, j) = a2(i, j) - sum1 Next i For i = j + 1 To n sum2 = 0# For k = 1 To j sum2 = sum2 + u(k, j) * l(i, k) Next k l(i, j) = (a2(i, j) - sum2) / u(j, j) Next i Next j Dim res(4) As Variant res(1) = a res(2) = l res(3) = u res(4) = p lu = res End Function Public Sub main() a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}] Debug.Print "== a,l,u,p: ==" result = lu(a) For i = 1 To 4 For j = 1 To UBound(result(1)) For k = 1 To UBound(result(1), 2) Debug.Print result(i)(j, k), Next k Debug.Print Next j Debug.Print Next i a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}] Debug.Print "== a,l,u,p: ==" result = lu(a) For i = 1 To 4 For j = 1 To UBound(result(1)) For k = 1 To UBound(result(1), 2) Debug.Print Format(result(i)(j, k), "0.#####"), Next k Debug.Print Next j Debug.Print Next i End Sub
from pprint import pprint def matrixMul(A, B): TB = zip(*B) return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A] def pivotize(m): n = len(m) ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)] for j in xrange(n): row = max(xrange(j, n), key=lambda i: abs(m[i][j])) if j != row: ID[j], ID[row] = ID[row], ID[j] return ID def lu(A): n = len(A) L = [[0.0] * n for i in xrange(n)] U = [[0.0] * n for i in xrange(n)] P = pivotize(A) A2 = matrixMul(P, A) for j in xrange(n): L[j][j] = 1.0 for i in xrange(j+1): s1 = sum(U[k][j] * L[i][k] for k in xrange(i)) U[i][j] = A2[i][j] - s1 for i in xrange(j, n): s2 = sum(U[k][j] * L[i][k] for k in xrange(j)) L[i][j] = (A2[i][j] - s2) / U[j][j] return (L, U, P) a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]] for part in lu(a): pprint(part, width=19) print print b = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]] for part in lu(b): pprint(part) print
Convert the following code from VB to Python, ensuring the logic remains intact.
Option Explicit Private Type Choice Number As Integer Name As String End Type Private MaxNumber As Integer Sub Main() Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$ MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1) For i = 1 To 3 U(i) = UserChoice Next For i = 1 To MaxNumber t = vbNullString For j = 1 To 3 If i Mod U(j).Number = 0 Then t = t & U(j).Name Next Debug.Print IIf(t = vbNullString, i, t) Next i End Sub Private Function UserChoice() As Choice Dim ok As Boolean Do While Not ok UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1) UserChoice.Name = InputBox("Enter the corresponding word : ") If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True Loop End Function
def genfizzbuzz(factorwords, numbers): factorwords.sort(key=lambda factor_and_word: factor_and_word[0]) lines = [] for num in numbers: words = ''.join(word for factor, word in factorwords if (num % factor) == 0) lines.append(words if words else str(num)) return '\n'.join(lines) if __name__ == '__main__': print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
Translate this program into Python but keep the logic exactly as in VB.
Option Explicit Private Type Choice Number As Integer Name As String End Type Private MaxNumber As Integer Sub Main() Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$ MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1) For i = 1 To 3 U(i) = UserChoice Next For i = 1 To MaxNumber t = vbNullString For j = 1 To 3 If i Mod U(j).Number = 0 Then t = t & U(j).Name Next Debug.Print IIf(t = vbNullString, i, t) Next i End Sub Private Function UserChoice() As Choice Dim ok As Boolean Do While Not ok UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1) UserChoice.Name = InputBox("Enter the corresponding word : ") If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True Loop End Function
def genfizzbuzz(factorwords, numbers): factorwords.sort(key=lambda factor_and_word: factor_and_word[0]) lines = [] for num in numbers: words = ''.join(word for factor, word in factorwords if (num % factor) == 0) lines.append(words if words else str(num)) return '\n'.join(lines) if __name__ == '__main__': print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
Translate the given VB code snippet into Python without altering its behavior.
Function read_line(filepath,n) Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filepath,1) arrLines = Split(objFile.ReadAll,vbCrLf) If UBound(arrLines) >= n-1 Then If arrLines(n-1) <> "" Then read_line = arrLines(n-1) Else read_line = "Line " & n & " is null." End If Else read_line = "Line " & n & " does not exist." End If objFile.Close Set objFSO = Nothing End Function WScript.Echo read_line("c:\temp\input.txt",7)
with open('xxx.txt') as f: for i, line in enumerate(f): if i == 6: break else: print('Not 7 lines in file') line = None
Port the provided VB code into Python while preserving the original functionality.
Function read_line(filepath,n) Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filepath,1) arrLines = Split(objFile.ReadAll,vbCrLf) If UBound(arrLines) >= n-1 Then If arrLines(n-1) <> "" Then read_line = arrLines(n-1) Else read_line = "Line " & n & " is null." End If Else read_line = "Line " & n & " does not exist." End If objFile.Close Set objFSO = Nothing End Function WScript.Echo read_line("c:\temp\input.txt",7)
with open('xxx.txt') as f: for i, line in enumerate(f): if i == 6: break else: print('Not 7 lines in file') line = None
Convert this VB snippet to Python and keep its semantics consistent.
Module Module1 Function ToVlq(v As ULong) As ULong Dim array(8) As Byte Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray buffer.CopyTo(array, 0) Return BitConverter.ToUInt64(array, 0) End Function Function FromVlq(v As ULong) As ULong Dim collection = BitConverter.GetBytes(v).Reverse() Return FromVlqCollection(collection) End Function Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte) If v > Math.Pow(2, 56) Then Throw New OverflowException("Integer exceeds max value.") End If Dim index = 7 Dim significantBitReached = False Dim mask = &H7FUL << (index * 7) While index >= 0 Dim buffer = mask And v If buffer > 0 OrElse significantBitReached Then significantBitReached = True buffer >>= index * 7 If index > 0 Then buffer = buffer Or &H80 End If Yield buffer End If mask >>= 7 index -= 1 End While End Function Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong Dim v = 0UL Dim significantBitReached = False Using enumerator = vlq.GetEnumerator Dim index = 0 While enumerator.MoveNext Dim buffer = enumerator.Current If buffer > 0 OrElse significantBitReached Then significantBitReached = True v <<= 7 v = v Or (buffer And &H7FUL) End If index += 1 If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then Exit While End If End While End Using Return v End Function Sub Main() Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF} For Each original In values Console.WriteLine("Original: 0x{0:X}", original) REM collection Dim seq = ToVlqCollection(original) Console.WriteLine("Sequence: 0x{0}", seq.Select(Function(b) b.ToString("X2")).Aggregate(Function(a, b) String.Concat(a, b))) Dim decoded = FromVlqCollection(seq) Console.WriteLine("Decoded: 0x{0:X}", decoded) REM ints Dim encoded = ToVlq(original) Console.WriteLine("Encoded: 0x{0:X}", encoded) decoded = FromVlq(encoded) Console.WriteLine("Decoded: 0x{0:X}", decoded) Console.WriteLine() Next End Sub End Module
def tobits(n, _group=8, _sep='_', _pad=False): 'Express n as binary bits with separator' bits = '{0:b}'.format(n)[::-1] if _pad: bits = '{0:0{1}b}'.format(n, ((_group+len(bits)-1)//_group)*_group)[::-1] answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] answer = '0'*(len(_sep)-1) + answer else: answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] return answer def tovlq(n): return tobits(n, _group=7, _sep='1_', _pad=True) def toint(vlq): return int(''.join(vlq.split('_1')), 2) def vlqsend(vlq): for i, byte in enumerate(vlq.split('_')[::-1]): print('Sent byte {0:3}: {1:
Can you help me rewrite this code in Python instead of VB, keeping it the same logically?
Sub Main() Const TESTSTRING As String = "alphaBETA" Debug.Print "initial = " _ & TESTSTRING Debug.Print "uppercase = " _ & UCase(TESTSTRING) Debug.Print "lowercase = " _ & LCase(TESTSTRING) Debug.Print "first letter capitalized = " _ & StrConv(TESTSTRING, vbProperCase) Debug.Print "length (in characters) = " _ & CStr(Len(TESTSTRING)) Debug.Print "length (in bytes) = " _ & CStr(LenB(TESTSTRING)) Debug.Print "reversed = " _ & StrReverse(TESTSTRING) Debug.Print "first position of letter A (case-sensitive) = " _ & InStr(1, TESTSTRING, "A", vbBinaryCompare) Debug.Print "first position of letter A (case-insensitive) = " _ & InStr(1, TESTSTRING, "A", vbTextCompare) Debug.Print "concatenated with & TESTSTRING & "123" End Sub
s = "alphaBETA" print s.upper() print s.lower() print s.swapcase() print "fOo bAR".capitalize() print "fOo bAR".title() import string print string.capwords("fOo bAR")
Generate a Python translation of this VB snippet without changing its computational steps.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\data.txt",1) bad_readings_total = 0 good_readings_total = 0 data_gap = 0 start_date = "" end_date = "" tmp_datax_gap = 0 tmp_start_date = "" Do Until objFile.AtEndOfStream bad_readings = 0 good_readings = 0 line_total = 0 line = objFile.ReadLine token = Split(line,vbTab) n = 1 Do While n <= UBound(token) If n + 1 <= UBound(token) Then If CInt(token(n+1)) < 1 Then bad_readings = bad_readings + 1 bad_readings_total = bad_readings_total + 1 If tmp_start_date = "" Then tmp_start_date = token(0) End If tmp_data_gap = tmp_data_gap + 1 Else good_readings = good_readings + 1 line_total = line_total + CInt(token(n)) good_readings_total = good_readings_total + 1 If (tmp_start_date <> "") And (tmp_data_gap > data_gap) Then start_date = tmp_start_date end_date = token(0) data_gap = tmp_data_gap tmp_start_date = "" tmp_data_gap = 0 Else tmp_start_date = "" tmp_data_gap = 0 End If End If End If n = n + 2 Loop line_avg = line_total/good_readings WScript.StdOut.Write "Date: " & token(0) & vbTab &_ "Bad Reads: " & bad_readings & vbTab &_ "Good Reads: " & good_readings & vbTab &_ "Line Total: " & FormatNumber(line_total,3) & vbTab &_ "Line Avg: " & FormatNumber(line_avg,3) WScript.StdOut.WriteLine Loop WScript.StdOut.WriteLine WScript.StdOut.Write "Maximum run of " & data_gap &_ " consecutive bad readings from " & start_date & " to " &_ end_date & "." WScript.StdOut.WriteLine objFile.Close Set objFSO = Nothing
import fileinput import sys nodata = 0; nodata_max=-1; nodata_maxline=[]; tot_file = 0 num_file = 0 infiles = sys.argv[1:] for line in fileinput.input(): tot_line=0; num_line=0; field = line.split() date = field[0] data = [float(f) for f in field[1::2]] flags = [int(f) for f in field[2::2]] for datum, flag in zip(data, flags): if flag<1: nodata += 1 else: if nodata_max==nodata and nodata>0: nodata_maxline.append(date) if nodata_max<nodata and nodata>0: nodata_max=nodata nodata_maxline=[date] nodata=0; tot_line += datum num_line += 1 tot_file += tot_line num_file += num_line print "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f" % ( date, len(data) -num_line, num_line, tot_line, tot_line/num_line if (num_line>0) else 0) print "" print "File(s) = %s" % (", ".join(infiles),) print "Total = %10.3f" % (tot_file,) print "Readings = %6i" % (num_file,) print "Average = %10.3f" % (tot_file / num_file,) print "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s" % ( nodata_max, ", ".join(nodata_maxline))
Convert this VB snippet to Python and keep its semantics consistent.
Imports System.Security.Cryptography Imports System.Text Module MD5hash Sub Main(args As String()) Console.WriteLine(GetMD5("Visual Basic .Net")) End Sub Private Function GetMD5(plainText As String) As String Dim hash As String = "" Using hashObject As MD5 = MD5.Create() Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText)) Dim hashBuilder As New StringBuilder For i As Integer = 0 To ptBytes.Length - 1 hashBuilder.Append(ptBytes(i).ToString("X2")) Next hash = hashBuilder.ToString End Using Return hash End Function End Module
>>> import hashlib >>> >>> tests = ( (b"", 'd41d8cd98f00b204e9800998ecf8427e'), (b"a", '0cc175b9c0f1b6a831c399e269772661'), (b"abc", '900150983cd24fb0d6963f7d28e17f72'), (b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'), (b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'), (b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'), (b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') ) >>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden >>>
Convert this VB snippet to Python and keep its semantics consistent.
Option Explicit Private Type Aliquot Sequence() As Double Classification As String End Type Sub Main() Dim result As Aliquot, i As Long, j As Double, temp As String For j = 1 To 10 result = Aliq(j) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next j Dim a a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488) For j = LBound(a) To UBound(a) result = Aliq(CDbl(a(j))) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next End Sub Private Function Aliq(Nb As Double) As Aliquot Dim s() As Double, i As Long, temp, j As Long, cpt As Long temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic") ReDim s(0) s(0) = Nb For i = 1 To 15 cpt = cpt + 1 ReDim Preserve s(cpt) s(i) = SumPDiv(s(i - 1)) If s(i) > 140737488355328# Then Exit For If s(i) = 0 Then j = 1 If s(1) = s(0) Then j = 2 If s(i) = s(0) And i > 1 And i <> 2 Then j = 4 If s(i) = s(i - 1) And i > 1 Then j = 5 If i >= 2 Then If s(2) = s(0) Then j = 3 If s(i) = s(i - 2) And i <> 2 Then j = 6 End If If j > 0 Then Exit For Next Aliq.Classification = temp(j) Aliq.Sequence = s End Function Private Function SumPDiv(n As Double) As Double Dim j As Long, t As Long If n > 1 Then For j = 1 To n \ 2 If n Mod j = 0 Then t = t + j Next End If SumPDiv = t End Function
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pdsum(s[-1]) if new in s: if s[0] == new: if slen == 1: return 'perfect', s elif slen == 2: return 'amicable', s else: return 'sociable of length %i' % slen, s elif s[-1] == new: return 'aspiring', s else: return 'cyclic back to %i' % new, s elif new == 0: return 'terminating', s + [0] else: s.append(new) slen += 1 else: return 'non-terminating', s if __name__ == '__main__': for n in range(1, 11): print('%s: %r' % aliquot(n)) print() for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: print('%s: %r' % aliquot(n))
Generate an equivalent Python version of this VB code.
Option Explicit Private Type Aliquot Sequence() As Double Classification As String End Type Sub Main() Dim result As Aliquot, i As Long, j As Double, temp As String For j = 1 To 10 result = Aliq(j) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next j Dim a a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488) For j = LBound(a) To UBound(a) result = Aliq(CDbl(a(j))) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next End Sub Private Function Aliq(Nb As Double) As Aliquot Dim s() As Double, i As Long, temp, j As Long, cpt As Long temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic") ReDim s(0) s(0) = Nb For i = 1 To 15 cpt = cpt + 1 ReDim Preserve s(cpt) s(i) = SumPDiv(s(i - 1)) If s(i) > 140737488355328# Then Exit For If s(i) = 0 Then j = 1 If s(1) = s(0) Then j = 2 If s(i) = s(0) And i > 1 And i <> 2 Then j = 4 If s(i) = s(i - 1) And i > 1 Then j = 5 If i >= 2 Then If s(2) = s(0) Then j = 3 If s(i) = s(i - 2) And i <> 2 Then j = 6 End If If j > 0 Then Exit For Next Aliq.Classification = temp(j) Aliq.Sequence = s End Function Private Function SumPDiv(n As Double) As Double Dim j As Long, t As Long If n > 1 Then For j = 1 To n \ 2 If n Mod j = 0 Then t = t + j Next End If SumPDiv = t End Function
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pdsum(s[-1]) if new in s: if s[0] == new: if slen == 1: return 'perfect', s elif slen == 2: return 'amicable', s else: return 'sociable of length %i' % slen, s elif s[-1] == new: return 'aspiring', s else: return 'cyclic back to %i' % new, s elif new == 0: return 'terminating', s + [0] else: s.append(new) slen += 1 else: return 'non-terminating', s if __name__ == '__main__': for n in range(1, 11): print('%s: %r' % aliquot(n)) print() for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: print('%s: %r' % aliquot(n))
Translate this program into Python but keep the logic exactly as in VB.
Imports System.Threading Module Module1 Sub SleepSort(items As IEnumerable(Of Integer)) For Each item In items Task.Factory.StartNew(Sub() Thread.Sleep(1000 * item) Console.WriteLine(item) End Sub) Next End Sub Sub Main() SleepSort({1, 5, 2, 1, 8, 10, 3}) Console.ReadKey() End Sub End Module
from time import sleep from threading import Timer def sleepsort(values): sleepsort.result = [] def add1(x): sleepsort.result.append(x) mx = values[0] for v in values: if mx < v: mx = v Timer(v, add1, [v]).start() sleep(mx+1) return sleepsort.result if __name__ == '__main__': x = [3,2,4,7,3,6,9,1] if sleepsort(x) == sorted(x): print('sleep sort worked for:',x) else: print('sleep sort FAILED for:',x)
Translate this program into Python but keep the logic exactly as in VB.
Public Sub LoopsNested() Dim a(1 To 10, 1 To 10) As Integer Randomize For i = 1 To 10 For j = 1 To 10 a(i, j) = Int(20 * Rnd) + 1 Next j Next i For i = 1 To 10 For j = 1 To 10 If a(i, j) <> 20 Then Debug.Print a(i, j), Else i = 10 Exit For End If Next j Debug.Print Next i End Sub
from random import randint def do_scan(mat): for row in mat: for item in row: print item, if item == 20: print return print print mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)] do_scan(mat)