Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write a version of this PHP function in Python with identical behavior.
function cube($n) { return($n * $n * $n); } $a = array(1, 2, 3, 4, 5); $b = array_map("cube", $a); print_r($b);
def square(n): return n * n numbers = [1, 3, 5, 7] squares1 = [square(n) for n in numbers] squares2a = map(square, numbers) squares2b = map(lambda x: x*x, numbers) squares3 = [n * n for n in numbers] isquares1 = (n * n for n in numbers) import itertools isquares2 = itertools.imap(square, numbers)
Write a version of this PHP function in Python with identical behavior.
function cube($n) { return($n * $n * $n); } $a = array(1, 2, 3, 4, 5); $b = array_map("cube", $a); print_r($b);
def square(n): return n * n numbers = [1, 3, 5, 7] squares1 = [square(n) for n in numbers] squares2a = map(square, numbers) squares2b = map(lambda x: x*x, numbers) squares3 = [n * n for n in numbers] isquares1 = (n * n for n in numbers) import itertools isquares2 = itertools.imap(square, numbers)
Produce a language-to-language conversion: from PHP to Python, same semantics.
function cube($n) { return($n * $n * $n); } $a = array(1, 2, 3, 4, 5); $b = array_map("cube", $a); print_r($b);
def square(n): return n * n numbers = [1, 3, 5, 7] squares1 = [square(n) for n in numbers] squares2a = map(square, numbers) squares2b = map(lambda x: x*x, numbers) squares3 = [n * n for n in numbers] isquares1 = (n * n for n in numbers) import itertools isquares2 = itertools.imap(square, numbers)
Translate the given PHP code snippet into Python without altering its behavior.
class Singleton { protected static $instance = null; public $test_var; private function __construct(){ } public static function getInstance(){ if (is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } } $foo = Singleton::getInstance(); $foo->test_var = 'One'; $bar = Singleton::getInstance(); echo $bar->test_var; //Prints 'One' $fail = new Singleton(); //Fatal error
>>> class Borg(object): __state = {} def __init__(self): self.__dict__ = self.__state >>> b1 = Borg() >>> b2 = Borg() >>> b1 is b2 False >>> b1.datum = range(5) >>> b1.datum [0, 1, 2, 3, 4] >>> b2.datum [0, 1, 2, 3, 4] >>> b1.datum is b2.datum True >>>
Change the programming language of this snippet from PHP to Python without modifying what it does.
class Singleton { protected static $instance = null; public $test_var; private function __construct(){ } public static function getInstance(){ if (is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } } $foo = Singleton::getInstance(); $foo->test_var = 'One'; $bar = Singleton::getInstance(); echo $bar->test_var; //Prints 'One' $fail = new Singleton(); //Fatal error
>>> class Borg(object): __state = {} def __init__(self): self.__dict__ = self.__state >>> b1 = Borg() >>> b2 = Borg() >>> b1 is b2 False >>> b1.datum = range(5) >>> b1.datum [0, 1, 2, 3, 4] >>> b2.datum [0, 1, 2, 3, 4] >>> b1.datum is b2.datum True >>>
Convert the following code from PHP to Python, ensuring the logic remains intact.
class Singleton { protected static $instance = null; public $test_var; private function __construct(){ } public static function getInstance(){ if (is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } } $foo = Singleton::getInstance(); $foo->test_var = 'One'; $bar = Singleton::getInstance(); echo $bar->test_var; //Prints 'One' $fail = new Singleton(); //Fatal error
>>> class Borg(object): __state = {} def __init__(self): self.__dict__ = self.__state >>> b1 = Borg() >>> b2 = Borg() >>> b1 is b2 False >>> b1.datum = range(5) >>> b1.datum [0, 1, 2, 3, 4] >>> b2.datum [0, 1, 2, 3, 4] >>> b1.datum is b2.datum True >>>
Translate the given PHP code snippet into Python without altering its behavior.
<?php $dog = 'Benjamin'; $Dog = 'Samba'; $DOG = 'Bernie'; echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n"; function DOG() { return 'Bernie'; } echo 'There is only 1 dog named ' . dog() . "\n";
>>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie' >>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG) The three dogs are named Benjamin , Samba , and Bernie >>>
Generate an equivalent Python version of this PHP code.
<?php $dog = 'Benjamin'; $Dog = 'Samba'; $DOG = 'Bernie'; echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n"; function DOG() { return 'Bernie'; } echo 'There is only 1 dog named ' . dog() . "\n";
>>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie' >>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG) The three dogs are named Benjamin , Samba , and Bernie >>>
Write a version of this PHP function in Python with identical behavior.
<?php $dog = 'Benjamin'; $Dog = 'Samba'; $DOG = 'Bernie'; echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n"; function DOG() { return 'Bernie'; } echo 'There is only 1 dog named ' . dog() . "\n";
>>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie' >>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG) The three dogs are named Benjamin , Samba , and Bernie >>>
Produce a functionally identical Python code for the snippet given in PHP.
for ($i = 10; $i >= 0; $i--) echo "$i\n";
for i in xrange(10, -1, -1): print i
Rewrite the snippet below in Python so it works the same as the original PHP code.
for ($i = 10; $i >= 0; $i--) echo "$i\n";
for i in xrange(10, -1, -1): print i
Write a version of this PHP function in Python with identical behavior.
for ($i = 10; $i >= 0; $i--) echo "$i\n";
for i in xrange(10, -1, -1): print i
Port the following code from PHP to Python with equivalent syntax and logic.
for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo '*'; } echo "\n"; }
for i in 1..5: for j in 1..i: stdout.write("*") echo("")
Generate a Python translation of this PHP snippet without changing its computational steps.
for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo '*'; } echo "\n"; }
for i in 1..5: for j in 1..i: stdout.write("*") echo("")
Write the same algorithm in Python as shown in this PHP implementation.
for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo '*'; } echo "\n"; }
for i in 1..5: for j in 1..i: stdout.write("*") echo("")
Convert the following code from PHP to Python, ensuring the logic remains intact.
<?php function longMult($a, $b) { $as = (string) $a; $bs = (string) $b; for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--) { for($p = 0; $p < $pi; $p++) { $regi[$ai][] = 0; } for($bi = strlen($bs) - 1; $bi >= 0; $bi--) { $regi[$ai][] = $as[$ai] * $bs[$bi]; } } return $regi; } function longAdd($arr) { $outer = count($arr); $inner = count($arr[$outer-1]) + $outer; for($i = 0; $i <= $inner; $i++) { for($o = 0; $o < $outer; $o++) { $val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0; @$sum[$i] += $val; } } return $sum; } function carry($arr) { for($i = 0; $i < count($arr); $i++) { $s = (string) $arr[$i]; switch(strlen($s)) { case 2: $arr[$i] = $s{1}; @$arr[$i+1] += $s{0}; break; case 3: $arr[$i] = $s{2}; @$arr[$i+1] += $s{0}.$s{1}; break; } } return ltrim(implode('',array_reverse($arr)),'0'); } function lm($a,$b) { return carry(longAdd(longMult($a,$b))); } if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456') { echo 'pass!'; }; // 2^64 * 2^64
print 2**64*2**64
Port the following code from PHP to Python with equivalent syntax and logic.
<?php function longMult($a, $b) { $as = (string) $a; $bs = (string) $b; for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--) { for($p = 0; $p < $pi; $p++) { $regi[$ai][] = 0; } for($bi = strlen($bs) - 1; $bi >= 0; $bi--) { $regi[$ai][] = $as[$ai] * $bs[$bi]; } } return $regi; } function longAdd($arr) { $outer = count($arr); $inner = count($arr[$outer-1]) + $outer; for($i = 0; $i <= $inner; $i++) { for($o = 0; $o < $outer; $o++) { $val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0; @$sum[$i] += $val; } } return $sum; } function carry($arr) { for($i = 0; $i < count($arr); $i++) { $s = (string) $arr[$i]; switch(strlen($s)) { case 2: $arr[$i] = $s{1}; @$arr[$i+1] += $s{0}; break; case 3: $arr[$i] = $s{2}; @$arr[$i+1] += $s{0}.$s{1}; break; } } return ltrim(implode('',array_reverse($arr)),'0'); } function lm($a,$b) { return carry(longAdd(longMult($a,$b))); } if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456') { echo 'pass!'; }; // 2^64 * 2^64
print 2**64*2**64
Rewrite this program in Python while keeping its functionality equivalent to the PHP version.
<?php function longMult($a, $b) { $as = (string) $a; $bs = (string) $b; for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--) { for($p = 0; $p < $pi; $p++) { $regi[$ai][] = 0; } for($bi = strlen($bs) - 1; $bi >= 0; $bi--) { $regi[$ai][] = $as[$ai] * $bs[$bi]; } } return $regi; } function longAdd($arr) { $outer = count($arr); $inner = count($arr[$outer-1]) + $outer; for($i = 0; $i <= $inner; $i++) { for($o = 0; $o < $outer; $o++) { $val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0; @$sum[$i] += $val; } } return $sum; } function carry($arr) { for($i = 0; $i < count($arr); $i++) { $s = (string) $arr[$i]; switch(strlen($s)) { case 2: $arr[$i] = $s{1}; @$arr[$i+1] += $s{0}; break; case 3: $arr[$i] = $s{2}; @$arr[$i+1] += $s{0}.$s{1}; break; } } return ltrim(implode('',array_reverse($arr)),'0'); } function lm($a,$b) { return carry(longAdd(longMult($a,$b))); } if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456') { echo 'pass!'; }; // 2^64 * 2^64
print 2**64*2**64
Keep all operations the same but rewrite the snippet in Python.
<?php $size = 4; $chosen = implode(array_rand(array_flip(range(1,9)), $size)); echo "I've chosen a number from $size unique digits from 1 to 9; you need to input $size unique digits to guess my number\n"; for ($guesses = 1; ; $guesses++) { while (true) { echo "\nNext guess [$guesses]: "; $guess = rtrim(fgets(STDIN)); if (!checkguess($guess)) echo "$size digits, no repetition, no 0... retry\n"; else break; } if ($guess == $chosen) { echo "You did it in $guesses attempts!\n"; break; } else { $bulls = 0; $cows = 0; foreach (range(0, $size-1) as $i) { if ($guess[$i] == $chosen[$i]) $bulls++; else if (strpos($chosen, $guess[$i]) !== FALSE) $cows++; } echo "$cows cows, $bulls bulls\n"; } } function checkguess($g) { global $size; return count(array_unique(str_split($g))) == $size && preg_match("/^[1-9]{{$size}}$/", $g); } ?>
import random digits = '123456789' size = 4 chosen = ''.join(random.sample(digits,size)) print % (size, size) guesses = 0 while True: guesses += 1 while True: guess = raw_input('\nNext guess [%i]: ' % guesses).strip() if len(guess) == size and \ all(char in digits for char in guess) \ and len(set(guess)) == size: break print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size if guess == chosen: print '\nCongratulations you guessed correctly in',guesses,'attempts' break bulls = cows = 0 for i in range(size): if guess[i] == chosen[i]: bulls += 1 elif guess[i] in chosen: cows += 1 print ' %i Bulls\n %i Cows' % (bulls, cows)
Generate a Python translation of this PHP snippet without changing its computational steps.
<?php $size = 4; $chosen = implode(array_rand(array_flip(range(1,9)), $size)); echo "I've chosen a number from $size unique digits from 1 to 9; you need to input $size unique digits to guess my number\n"; for ($guesses = 1; ; $guesses++) { while (true) { echo "\nNext guess [$guesses]: "; $guess = rtrim(fgets(STDIN)); if (!checkguess($guess)) echo "$size digits, no repetition, no 0... retry\n"; else break; } if ($guess == $chosen) { echo "You did it in $guesses attempts!\n"; break; } else { $bulls = 0; $cows = 0; foreach (range(0, $size-1) as $i) { if ($guess[$i] == $chosen[$i]) $bulls++; else if (strpos($chosen, $guess[$i]) !== FALSE) $cows++; } echo "$cows cows, $bulls bulls\n"; } } function checkguess($g) { global $size; return count(array_unique(str_split($g))) == $size && preg_match("/^[1-9]{{$size}}$/", $g); } ?>
import random digits = '123456789' size = 4 chosen = ''.join(random.sample(digits,size)) print % (size, size) guesses = 0 while True: guesses += 1 while True: guess = raw_input('\nNext guess [%i]: ' % guesses).strip() if len(guess) == size and \ all(char in digits for char in guess) \ and len(set(guess)) == size: break print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size if guess == chosen: print '\nCongratulations you guessed correctly in',guesses,'attempts' break bulls = cows = 0 for i in range(size): if guess[i] == chosen[i]: bulls += 1 elif guess[i] in chosen: cows += 1 print ' %i Bulls\n %i Cows' % (bulls, cows)
Produce a functionally identical Python code for the snippet given in PHP.
<?php $size = 4; $chosen = implode(array_rand(array_flip(range(1,9)), $size)); echo "I've chosen a number from $size unique digits from 1 to 9; you need to input $size unique digits to guess my number\n"; for ($guesses = 1; ; $guesses++) { while (true) { echo "\nNext guess [$guesses]: "; $guess = rtrim(fgets(STDIN)); if (!checkguess($guess)) echo "$size digits, no repetition, no 0... retry\n"; else break; } if ($guess == $chosen) { echo "You did it in $guesses attempts!\n"; break; } else { $bulls = 0; $cows = 0; foreach (range(0, $size-1) as $i) { if ($guess[$i] == $chosen[$i]) $bulls++; else if (strpos($chosen, $guess[$i]) !== FALSE) $cows++; } echo "$cows cows, $bulls bulls\n"; } } function checkguess($g) { global $size; return count(array_unique(str_split($g))) == $size && preg_match("/^[1-9]{{$size}}$/", $g); } ?>
import random digits = '123456789' size = 4 chosen = ''.join(random.sample(digits,size)) print % (size, size) guesses = 0 while True: guesses += 1 while True: guess = raw_input('\nNext guess [%i]: ' % guesses).strip() if len(guess) == size and \ all(char in digits for char in guess) \ and len(set(guess)) == size: break print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size if guess == chosen: print '\nCongratulations you guessed correctly in',guesses,'attempts' break bulls = cows = 0 for i in range(size): if guess[i] == chosen[i]: bulls += 1 elif guess[i] in chosen: cows += 1 print ' %i Bulls\n %i Cows' % (bulls, cows)
Generate an equivalent Python version of this PHP code.
function bubbleSort(array $array){ foreach($array as $i => &$val){ foreach($array as $k => &$val2){ if($k <= $i) continue; if($val > $val2) { list($val, $val2) = [$val2, $val]; break; } } } return $array; }
def bubble_sort(seq): changed = True while changed: changed = False for i in range(len(seq) - 1): if seq[i] > seq[i+1]: seq[i], seq[i+1] = seq[i+1], seq[i] changed = True return seq if __name__ == "__main__": from random import shuffle testset = [_ for _ in range(100)] testcase = testset.copy() shuffle(testcase) assert testcase != testset bubble_sort(testcase) assert testcase == testset
Write the same algorithm in Python as shown in this PHP implementation.
function bubbleSort(array $array){ foreach($array as $i => &$val){ foreach($array as $k => &$val2){ if($k <= $i) continue; if($val > $val2) { list($val, $val2) = [$val2, $val]; break; } } } return $array; }
def bubble_sort(seq): changed = True while changed: changed = False for i in range(len(seq) - 1): if seq[i] > seq[i+1]: seq[i], seq[i+1] = seq[i+1], seq[i] changed = True return seq if __name__ == "__main__": from random import shuffle testset = [_ for _ in range(100)] testcase = testset.copy() shuffle(testcase) assert testcase != testset bubble_sort(testcase) assert testcase == testset
Convert this PHP snippet to Python and keep its semantics consistent.
function bubbleSort(array $array){ foreach($array as $i => &$val){ foreach($array as $k => &$val2){ if($k <= $i) continue; if($val > $val2) { list($val, $val2) = [$val2, $val]; break; } } } return $array; }
def bubble_sort(seq): changed = True while changed: changed = False for i in range(len(seq) - 1): if seq[i] > seq[i+1]: seq[i], seq[i+1] = seq[i+1], seq[i] changed = True return seq if __name__ == "__main__": from random import shuffle testset = [_ for _ in range(100)] testcase = testset.copy() shuffle(testcase) assert testcase != testset bubble_sort(testcase) assert testcase == testset
Can you help me rewrite this code in Python instead of PHP, keeping it the same logically?
<?php if (!$in = fopen('input.txt', 'r')) { die('Could not open input file.'); } if (!$out = fopen('output.txt', 'w')) { die('Could not open output file.'); } while (!feof($in)) { $data = fread($in, 512); fwrite($out, $data); } fclose($out); fclose($in); ?>
import shutil shutil.copyfile('input.txt', 'output.txt')
Change the programming language of this snippet from PHP to Python without modifying what it does.
<?php if (!$in = fopen('input.txt', 'r')) { die('Could not open input file.'); } if (!$out = fopen('output.txt', 'w')) { die('Could not open output file.'); } while (!feof($in)) { $data = fread($in, 512); fwrite($out, $data); } fclose($out); fclose($in); ?>
import shutil shutil.copyfile('input.txt', 'output.txt')
Ensure the translated Python code behaves exactly like the original PHP snippet.
<?php if (!$in = fopen('input.txt', 'r')) { die('Could not open input file.'); } if (!$out = fopen('output.txt', 'w')) { die('Could not open output file.'); } while (!feof($in)) { $data = fread($in, 512); fwrite($out, $data); } fclose($out); fclose($in); ?>
import shutil shutil.copyfile('input.txt', 'output.txt')
Rewrite the snippet below in Python so it works the same as the original PHP code.
<?php $a = fgets(STDIN); $b = fgets(STDIN); echo "sum: ", $a + $b, "\n", "difference: ", $a - $b, "\n", "product: ", $a * $b, "\n", "truncating quotient: ", (int)($a / $b), "\n", "flooring quotient: ", floor($a / $b), "\n", "remainder: ", $a % $b, "\n", "power: ", $a ** $b, "\n"; // PHP 5.6+ only ?>
x = int(raw_input("Number 1: ")) y = int(raw_input("Number 2: ")) print "Sum: %d" % (x + y) print "Difference: %d" % (x - y) print "Product: %d" % (x * y) print "Quotient: %d" % (x / y) print "Remainder: %d" % (x % y) print "Quotient: %d with Remainder: %d" % divmod(x, y) print "Power: %d" % x**y raw_input( )
Produce a functionally identical Python code for the snippet given in PHP.
<?php $a = fgets(STDIN); $b = fgets(STDIN); echo "sum: ", $a + $b, "\n", "difference: ", $a - $b, "\n", "product: ", $a * $b, "\n", "truncating quotient: ", (int)($a / $b), "\n", "flooring quotient: ", floor($a / $b), "\n", "remainder: ", $a % $b, "\n", "power: ", $a ** $b, "\n"; // PHP 5.6+ only ?>
x = int(raw_input("Number 1: ")) y = int(raw_input("Number 2: ")) print "Sum: %d" % (x + y) print "Difference: %d" % (x - y) print "Product: %d" % (x * y) print "Quotient: %d" % (x / y) print "Remainder: %d" % (x % y) print "Quotient: %d with Remainder: %d" % divmod(x, y) print "Power: %d" % x**y raw_input( )
Convert this PHP snippet to Python and keep its semantics consistent.
<?php $a = fgets(STDIN); $b = fgets(STDIN); echo "sum: ", $a + $b, "\n", "difference: ", $a - $b, "\n", "product: ", $a * $b, "\n", "truncating quotient: ", (int)($a / $b), "\n", "flooring quotient: ", floor($a / $b), "\n", "remainder: ", $a % $b, "\n", "power: ", $a ** $b, "\n"; // PHP 5.6+ only ?>
x = int(raw_input("Number 1: ")) y = int(raw_input("Number 2: ")) print "Sum: %d" % (x + y) print "Difference: %d" % (x - y) print "Product: %d" % (x * y) print "Quotient: %d" % (x / y) print "Remainder: %d" % (x % y) print "Quotient: %d with Remainder: %d" % divmod(x, y) print "Power: %d" % x**y raw_input( )
Please provide an equivalent version of this PHP code in Python.
function transpose($m) { if (count($m) == 0) // special case: empty matrix return array(); else if (count($m) == 1) // special case: row matrix return array_chunk($m[0], 1); array_unshift($m, NULL); // the original matrix is not modified because it was passed by value return call_user_func_array('array_map', $m); }
m=((1, 1, 1, 1), (2, 4, 8, 16), (3, 9, 27, 81), (4, 16, 64, 256), (5, 25,125, 625)) print(zip(*m))
Rewrite this program in Python while keeping its functionality equivalent to the PHP version.
function transpose($m) { if (count($m) == 0) // special case: empty matrix return array(); else if (count($m) == 1) // special case: row matrix return array_chunk($m[0], 1); array_unshift($m, NULL); // the original matrix is not modified because it was passed by value return call_user_func_array('array_map', $m); }
m=((1, 1, 1, 1), (2, 4, 8, 16), (3, 9, 27, 81), (4, 16, 64, 256), (5, 25,125, 625)) print(zip(*m))
Write the same algorithm in Python as shown in this PHP implementation.
function transpose($m) { if (count($m) == 0) // special case: empty matrix return array(); else if (count($m) == 1) // special case: row matrix return array_chunk($m[0], 1); array_unshift($m, NULL); // the original matrix is not modified because it was passed by value return call_user_func_array('array_map', $m); }
m=((1, 1, 1, 1), (2, 4, 8, 16), (3, 9, 27, 81), (4, 16, 64, 256), (5, 25,125, 625)) print(zip(*m))
Translate this program into Python but keep the logic exactly as in PHP.
<?php function A($k,$x1,$x2,$x3,$x4,$x5) { $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) { return A(--$k,$b,$x1,$x2,$x3,$x4); }; return $k <= 0 ? $x4() + $x5() : $b(); } echo A(10, function () { return 1; }, function () { return -1; }, function () { return -1; }, function () { return 1; }, function () { return 0; }) . "\n"; ?>
import sys sys.setrecursionlimit(1025) def a(in_k, x1, x2, x3, x4, x5): k = [in_k] def b(): k[0] -= 1 return a(k[0], b, x1, x2, x3, x4) return x4() + x5() if k[0] <= 0 else b() x = lambda i: lambda: i print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
Write the same algorithm in Python as shown in this PHP implementation.
<?php function A($k,$x1,$x2,$x3,$x4,$x5) { $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) { return A(--$k,$b,$x1,$x2,$x3,$x4); }; return $k <= 0 ? $x4() + $x5() : $b(); } echo A(10, function () { return 1; }, function () { return -1; }, function () { return -1; }, function () { return 1; }, function () { return 0; }) . "\n"; ?>
import sys sys.setrecursionlimit(1025) def a(in_k, x1, x2, x3, x4, x5): k = [in_k] def b(): k[0] -= 1 return a(k[0], b, x1, x2, x3, x4) return x4() + x5() if k[0] <= 0 else b() x = lambda i: lambda: i print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
Rewrite this program in Python while keeping its functionality equivalent to the PHP version.
<?php function A($k,$x1,$x2,$x3,$x4,$x5) { $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) { return A(--$k,$b,$x1,$x2,$x3,$x4); }; return $k <= 0 ? $x4() + $x5() : $b(); } echo A(10, function () { return 1; }, function () { return -1; }, function () { return -1; }, function () { return 1; }, function () { return 0; }) . "\n"; ?>
import sys sys.setrecursionlimit(1025) def a(in_k, x1, x2, x3, x4, x5): k = [in_k] def b(): k[0] -= 1 return a(k[0], b, x1, x2, x3, x4) return x4() + x5() if k[0] <= 0 else b() x = lambda i: lambda: i print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
Produce a language-to-language conversion: from PHP to Python, same semantics.
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
import sys print(sys.getrecursionlimit())
Port the following code from PHP to Python with equivalent syntax and logic.
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
import sys print(sys.getrecursionlimit())
Port the provided PHP code into Python while preserving the original functionality.
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
import sys print(sys.getrecursionlimit())
Generate an equivalent Python version of this PHP code.
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
import sys print(sys.getrecursionlimit())
Convert the following code from PHP to Python, ensuring the logic remains intact.
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
import sys print(sys.getrecursionlimit())
Convert the following code from PHP to Python, ensuring the logic remains intact.
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
import sys print(sys.getrecursionlimit())
Rewrite the snippet below in Python so it works the same as the original PHP code.
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
Rewrite the snippet below in Python so it works the same as the original PHP code.
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
Generate an equivalent Python version of this PHP code.
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
Rewrite this program in Python while keeping its functionality equivalent to the PHP version.
<?php function columns($arr) { if (count($arr) == 0) return array(); else if (count($arr) == 1) return array_chunk($arr[0], 1); array_unshift($arr, NULL); $transpose = call_user_func_array('array_map', $arr); return array_map('array_filter', $transpose); } function beadsort($arr) { foreach ($arr as $e) $poles []= array_fill(0, $e, 1); return array_map('count', columns(columns($poles))); } print_r(beadsort(array(5,3,1,7,4,1,1))); ?>
from itertools import zip_longest def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0))) print(beadsort([5,3,1,7,4,1,1]))
Transform the following PHP implementation into Python, maintaining the same output and logic.
<?php function columns($arr) { if (count($arr) == 0) return array(); else if (count($arr) == 1) return array_chunk($arr[0], 1); array_unshift($arr, NULL); $transpose = call_user_func_array('array_map', $arr); return array_map('array_filter', $transpose); } function beadsort($arr) { foreach ($arr as $e) $poles []= array_fill(0, $e, 1); return array_map('count', columns(columns($poles))); } print_r(beadsort(array(5,3,1,7,4,1,1))); ?>
from itertools import zip_longest def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0))) print(beadsort([5,3,1,7,4,1,1]))
Change the following PHP code into Python without altering its purpose.
<?php function columns($arr) { if (count($arr) == 0) return array(); else if (count($arr) == 1) return array_chunk($arr[0], 1); array_unshift($arr, NULL); $transpose = call_user_func_array('array_map', $arr); return array_map('array_filter', $transpose); } function beadsort($arr) { foreach ($arr as $e) $poles []= array_fill(0, $e, 1); return array_map('count', columns(columns($poles))); } print_r(beadsort(array(5,3,1,7,4,1,1))); ?>
from itertools import zip_longest def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0))) print(beadsort([5,3,1,7,4,1,1]))
Keep all operations the same but rewrite the snippet in Python.
<?php $y = bcpow('5', bcpow('4', bcpow('3', '2'))); printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y)); ?>
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Translate the given PHP code snippet into Python without altering its behavior.
<?php $y = bcpow('5', bcpow('4', bcpow('3', '2'))); printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y)); ?>
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Maintain the same structure and functionality when rewriting this code in Python.
<?php $y = bcpow('5', bcpow('4', bcpow('3', '2'))); printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y)); ?>
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Generate a Python translation of this PHP snippet without changing its computational steps.
<?php function buildInvertedIndex($filenames) { $invertedIndex = []; foreach($filenames as $filename) { $data = file_get_contents($filename); if($data === false) die('Unable to read file: ' . $filename); preg_match_all('/(\w+)/', $data, $matches, PREG_SET_ORDER); foreach($matches as $match) { $word = strtolower($match[0]); if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = []; if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename; } } return $invertedIndex; } function lookupWord($invertedIndex, $word) { return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false; } $invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']); foreach(['cat', 'is', 'banana', 'it'] as $word) { $matches = lookupWord($invertedIndex, $word); if($matches !== false) { echo "Found the word \"$word\" in the following files: " . implode(', ', $matches) . "\n"; } else { echo "Unable to find the word \"$word\" in the index\n"; } }
from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for txtfile in glob(fileglob): with open(txtfile, 'r') as f: txt = f.read().split() words |= set(txt) texts[txtfile.split('\\')[-1]] = txt return texts, words def termsearch(terms): return reduce(set.intersection, (invindex[term] for term in terms), set(texts.keys())) texts, words = parsetexts() print('\nTexts') pp(texts) print('\nWords') pp(sorted(words)) invindex = {word:set(txt for txt, wrds in texts.items() if word in wrds) for word in words} print('\nInverted Index') pp({k:sorted(v) for k,v in invindex.items()}) terms = ["what", "is", "it"] print('\nTerm Search for: ' + repr(terms)) pp(sorted(termsearch(terms)))
Convert this PHP snippet to Python and keep its semantics consistent.
<?php function buildInvertedIndex($filenames) { $invertedIndex = []; foreach($filenames as $filename) { $data = file_get_contents($filename); if($data === false) die('Unable to read file: ' . $filename); preg_match_all('/(\w+)/', $data, $matches, PREG_SET_ORDER); foreach($matches as $match) { $word = strtolower($match[0]); if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = []; if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename; } } return $invertedIndex; } function lookupWord($invertedIndex, $word) { return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false; } $invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']); foreach(['cat', 'is', 'banana', 'it'] as $word) { $matches = lookupWord($invertedIndex, $word); if($matches !== false) { echo "Found the word \"$word\" in the following files: " . implode(', ', $matches) . "\n"; } else { echo "Unable to find the word \"$word\" in the index\n"; } }
from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for txtfile in glob(fileglob): with open(txtfile, 'r') as f: txt = f.read().split() words |= set(txt) texts[txtfile.split('\\')[-1]] = txt return texts, words def termsearch(terms): return reduce(set.intersection, (invindex[term] for term in terms), set(texts.keys())) texts, words = parsetexts() print('\nTexts') pp(texts) print('\nWords') pp(sorted(words)) invindex = {word:set(txt for txt, wrds in texts.items() if word in wrds) for word in words} print('\nInverted Index') pp({k:sorted(v) for k,v in invindex.items()}) terms = ["what", "is", "it"] print('\nTerm Search for: ' + repr(terms)) pp(sorted(termsearch(terms)))
Convert this PHP block to Python, preserving its control flow and logic.
<?php function buildInvertedIndex($filenames) { $invertedIndex = []; foreach($filenames as $filename) { $data = file_get_contents($filename); if($data === false) die('Unable to read file: ' . $filename); preg_match_all('/(\w+)/', $data, $matches, PREG_SET_ORDER); foreach($matches as $match) { $word = strtolower($match[0]); if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = []; if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename; } } return $invertedIndex; } function lookupWord($invertedIndex, $word) { return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false; } $invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']); foreach(['cat', 'is', 'banana', 'it'] as $word) { $matches = lookupWord($invertedIndex, $word); if($matches !== false) { echo "Found the word \"$word\" in the following files: " . implode(', ', $matches) . "\n"; } else { echo "Unable to find the word \"$word\" in the index\n"; } }
from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for txtfile in glob(fileglob): with open(txtfile, 'r') as f: txt = f.read().split() words |= set(txt) texts[txtfile.split('\\')[-1]] = txt return texts, words def termsearch(terms): return reduce(set.intersection, (invindex[term] for term in terms), set(texts.keys())) texts, words = parsetexts() print('\nTexts') pp(texts) print('\nWords') pp(sorted(words)) invindex = {word:set(txt for txt, wrds in texts.items() if word in wrds) for word in words} print('\nInverted Index') pp({k:sorted(v) for k,v in invindex.items()}) terms = ["what", "is", "it"] print('\nTerm Search for: ' + repr(terms)) pp(sorted(termsearch(terms)))
Preserve the algorithm and functionality while converting the code from PHP to Python.
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Ensure the translated Python code behaves exactly like the original PHP snippet.
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Generate a Python translation of this PHP snippet without changing its computational steps.
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Change the programming language of this snippet from PHP to Python without modifying what it does.
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Change the programming language of this snippet from PHP to Python without modifying what it does.
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Rewrite the snippet below in Python so it works the same as the original PHP code.
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Write the same algorithm in Python as shown in this PHP implementation.
while (true) { $a = rand(0,19); echo "$a\n"; if ($a == 10) break; $b = rand(0,19); echo "$b\n"; }
from random import randrange while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
Generate a Python translation of this PHP snippet without changing its computational steps.
while (true) { $a = rand(0,19); echo "$a\n"; if ($a == 10) break; $b = rand(0,19); echo "$b\n"; }
from random import randrange while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
Generate an equivalent Python version of this PHP code.
while (true) { $a = rand(0,19); echo "$a\n"; if ($a == 10) break; $b = rand(0,19); echo "$b\n"; }
from random import randrange while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
Maintain the same structure and functionality when rewriting this code in Python.
<?php file_put_contents('/dev/lp0', 'Hello world!'); ?>
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Ensure the translated Python code behaves exactly like the original PHP snippet.
<?php file_put_contents('/dev/lp0', 'Hello world!'); ?>
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Change the following PHP code into Python without altering its purpose.
<?php file_put_contents('/dev/lp0', 'Hello world!'); ?>
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Port the provided PHP code into Python while preserving the original functionality.
<?php file_put_contents('/dev/lp0', 'Hello world!'); ?>
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Produce a language-to-language conversion: from PHP to Python, same semantics.
<?php file_put_contents('/dev/lp0', 'Hello world!'); ?>
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Preserve the algorithm and functionality while converting the code from PHP to Python.
<?php file_put_contents('/dev/lp0', 'Hello world!'); ?>
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Please provide an equivalent version of this PHP code in Python.
<?php function f($n) { return sqrt(abs($n)) + 5 * $n * $n * $n; } $sArray = []; echo "Enter 11 numbers.\n"; for ($i = 0; $i <= 10; $i++) { echo $i + 1, " - Enter number: "; array_push($sArray, (float)fgets(STDIN)); } echo PHP_EOL; $sArray = array_reverse($sArray); foreach ($sArray as $s) { $r = f($s); echo "f(", $s, ") = "; if ($r > 400) echo "overflow\n"; else echo $r, PHP_EOL; } ?>
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def f(x): return abs(x) ** 0.5 + 5 * x**3 >>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!") for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1]))) 11 numbers: 1 2 3 4 5 6 7 8 9 10 11 11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0 >>>
Port the provided PHP code into Python while preserving the original functionality.
<?php function f($n) { return sqrt(abs($n)) + 5 * $n * $n * $n; } $sArray = []; echo "Enter 11 numbers.\n"; for ($i = 0; $i <= 10; $i++) { echo $i + 1, " - Enter number: "; array_push($sArray, (float)fgets(STDIN)); } echo PHP_EOL; $sArray = array_reverse($sArray); foreach ($sArray as $s) { $r = f($s); echo "f(", $s, ") = "; if ($r > 400) echo "overflow\n"; else echo $r, PHP_EOL; } ?>
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def f(x): return abs(x) ** 0.5 + 5 * x**3 >>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!") for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1]))) 11 numbers: 1 2 3 4 5 6 7 8 9 10 11 11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0 >>>
Preserve the algorithm and functionality while converting the code from PHP to Python.
<?php function f($n) { return sqrt(abs($n)) + 5 * $n * $n * $n; } $sArray = []; echo "Enter 11 numbers.\n"; for ($i = 0; $i <= 10; $i++) { echo $i + 1, " - Enter number: "; array_push($sArray, (float)fgets(STDIN)); } echo PHP_EOL; $sArray = array_reverse($sArray); foreach ($sArray as $s) { $r = f($s); echo "f(", $s, ") = "; if ($r > 400) echo "overflow\n"; else echo $r, PHP_EOL; } ?>
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def f(x): return abs(x) ** 0.5 + 5 * x**3 >>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!") for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1]))) 11 numbers: 1 2 3 4 5 6 7 8 9 10 11 11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0 >>>
Produce a functionally identical Python code for the snippet given in PHP.
function middlethree($integer) { $int = (int)str_replace('-','',$integer); $length = strlen($int); if(is_int($int)) { if($length >= 3) { if($length % 2 == 1) { $middle = floor($length / 2) - 1; return substr($int,$middle, 3); } else { return 'The value must contain an odd amount of digits...'; } } else { return 'The value must contain at least three digits...'; } } else { return 'The value does not appear to be an integer...'; } } $numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0); foreach($numbers as $nums) { echo $nums.' : '.middlethree($nums). '<br>'; }
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer)) middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
Rewrite the snippet below in Python so it works the same as the original PHP code.
function middlethree($integer) { $int = (int)str_replace('-','',$integer); $length = strlen($int); if(is_int($int)) { if($length >= 3) { if($length % 2 == 1) { $middle = floor($length / 2) - 1; return substr($int,$middle, 3); } else { return 'The value must contain an odd amount of digits...'; } } else { return 'The value must contain at least three digits...'; } } else { return 'The value does not appear to be an integer...'; } } $numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0); foreach($numbers as $nums) { echo $nums.' : '.middlethree($nums). '<br>'; }
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer)) middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
Translate the given PHP code snippet into Python without altering its behavior.
function middlethree($integer) { $int = (int)str_replace('-','',$integer); $length = strlen($int); if(is_int($int)) { if($length >= 3) { if($length % 2 == 1) { $middle = floor($length / 2) - 1; return substr($int,$middle, 3); } else { return 'The value must contain an odd amount of digits...'; } } else { return 'The value must contain at least three digits...'; } } else { return 'The value does not appear to be an integer...'; } } $numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0); foreach($numbers as $nums) { echo $nums.' : '.middlethree($nums). '<br>'; }
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer)) middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
Keep all operations the same but rewrite the snippet in Python.
$odd = function ($prev) use ( &$odd ) { $a = fgetc(STDIN); if (!ctype_alpha($a)) { $prev(); fwrite(STDOUT, $a); return $a != '.'; } $clos = function () use ($a , $prev) { fwrite(STDOUT, $a); $prev(); }; return $odd($clos); }; $even = function () { while (true) { $c = fgetc(STDIN); fwrite(STDOUT, $c); if (!ctype_alpha($c)) { return $c != "."; } } }; $prev = function(){}; $e = false; while ($e ? $odd($prev) : $even()) { $e = !$e; }
from sys import stdin, stdout def char_in(): return stdin.read(1) def char_out(c): stdout.write(c) def odd(prev = lambda: None): a = char_in() if not a.isalpha(): prev() char_out(a) return a != '.' def clos(): char_out(a) prev() return odd(clos) def even(): while True: c = char_in() char_out(c) if not c.isalpha(): return c != '.' e = False while odd() if e else even(): e = not e
Maintain the same structure and functionality when rewriting this code in Python.
$odd = function ($prev) use ( &$odd ) { $a = fgetc(STDIN); if (!ctype_alpha($a)) { $prev(); fwrite(STDOUT, $a); return $a != '.'; } $clos = function () use ($a , $prev) { fwrite(STDOUT, $a); $prev(); }; return $odd($clos); }; $even = function () { while (true) { $c = fgetc(STDIN); fwrite(STDOUT, $c); if (!ctype_alpha($c)) { return $c != "."; } } }; $prev = function(){}; $e = false; while ($e ? $odd($prev) : $even()) { $e = !$e; }
from sys import stdin, stdout def char_in(): return stdin.read(1) def char_out(c): stdout.write(c) def odd(prev = lambda: None): a = char_in() if not a.isalpha(): prev() char_out(a) return a != '.' def clos(): char_out(a) prev() return odd(clos) def even(): while True: c = char_in() char_out(c) if not c.isalpha(): return c != '.' e = False while odd() if e else even(): e = not e
Transform the following PHP implementation into Python, maintaining the same output and logic.
$odd = function ($prev) use ( &$odd ) { $a = fgetc(STDIN); if (!ctype_alpha($a)) { $prev(); fwrite(STDOUT, $a); return $a != '.'; } $clos = function () use ($a , $prev) { fwrite(STDOUT, $a); $prev(); }; return $odd($clos); }; $even = function () { while (true) { $c = fgetc(STDIN); fwrite(STDOUT, $c); if (!ctype_alpha($c)) { return $c != "."; } } }; $prev = function(){}; $e = false; while ($e ? $odd($prev) : $even()) { $e = !$e; }
from sys import stdin, stdout def char_in(): return stdin.read(1) def char_out(c): stdout.write(c) def odd(prev = lambda: None): a = char_in() if not a.isalpha(): prev() char_out(a) return a != '.' def clos(): char_out(a) prev() return odd(clos) def even(): while True: c = char_in() char_out(c) if not c.isalpha(): return c != '.' e = False while odd() if e else even(): e = not e
Convert this PHP snippet to Python and keep its semantics consistent.
<?php $db = new SQLite3(':memory:'); $db->exec(" CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL ) "); ?>
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> conn.execute() <sqlite3.Cursor object at 0x013265C0> >>>
Change the programming language of this snippet from PHP to Python without modifying what it does.
<?php $db = new SQLite3(':memory:'); $db->exec(" CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL ) "); ?>
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> conn.execute() <sqlite3.Cursor object at 0x013265C0> >>>
Change the following PHP code into Python without altering its purpose.
<?php $db = new SQLite3(':memory:'); $db->exec(" CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL ) "); ?>
>>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> conn.execute() <sqlite3.Cursor object at 0x013265C0> >>>
Port the provided PHP code into Python while preserving the original functionality.
<?php echo soundex("Soundex"), "\n"; // S532 echo soundex("Example"), "\n"; // E251 echo soundex("Sownteks"), "\n"; // S532 echo soundex("Ekzampul"), "\n"; // E251 ?>
from itertools import groupby def soundex(word): codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r") soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod) cmap2 = lambda kar: soundDict.get(kar, '9') sdx = ''.join(cmap2(kar) for kar in word.lower()) sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9') sdx3 = sdx2[0:4].ljust(4,'0') return sdx3
Write the same algorithm in Python as shown in this PHP implementation.
<?php echo soundex("Soundex"), "\n"; // S532 echo soundex("Example"), "\n"; // E251 echo soundex("Sownteks"), "\n"; // S532 echo soundex("Ekzampul"), "\n"; // E251 ?>
from itertools import groupby def soundex(word): codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r") soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod) cmap2 = lambda kar: soundDict.get(kar, '9') sdx = ''.join(cmap2(kar) for kar in word.lower()) sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9') sdx3 = sdx2[0:4].ljust(4,'0') return sdx3
Can you help me rewrite this code in Python instead of PHP, keeping it the same logically?
<?php echo soundex("Soundex"), "\n"; // S532 echo soundex("Example"), "\n"; // E251 echo soundex("Sownteks"), "\n"; // S532 echo soundex("Ekzampul"), "\n"; // E251 ?>
from itertools import groupby def soundex(word): codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r") soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod) cmap2 = lambda kar: soundDict.get(kar, '9') sdx = ''.join(cmap2(kar) for kar in word.lower()) sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9') sdx3 = sdx2[0:4].ljust(4,'0') return sdx3
Maintain the same structure and functionality when rewriting this code in Python.
define('src_name', 'input.jpg'); // source image define('dest_name', 'output.jpg'); // destination image $img = imagecreatefromjpeg(src_name); // read image if(empty($img)){ echo 'Image could not be loaded!'; exit; } $black = imagecolorallocate($img, 0, 0, 0); $white = imagecolorallocate($img, 255, 255, 255); $width = imagesx($img); $height = imagesy($img); $array_lum = array(); // for storage of luminosity of each pixel $sum_lum = 0; // total sum of luminosity $average_lum = 0; // average luminosity of whole image for($x = 0; $x < $width; $x++){ for($y = 0; $y < $height; $y++){ $color = imagecolorat($img, $x, $y); $r = ($color >> 16) & 0xFF; $g = ($color >> 8) & 0xFF; $b = $color & 0xFF; $array_lum[$x][$y] = ($r + $g + $b); $sum_lum += $array_lum[$x][$y]; } } $average_lum = $sum_lum / ($width * $height); for($x = 0; $x < $width; $x++){ for($y = 0; $y < $height; $y++){ if($array_lum[$x][$y] > $average_lum){ imagesetpixel($img, $x, $y, $white); } else{ imagesetpixel($img, $x, $y, $black); } } } imagejpeg($img, dest_name); if(!file_exists(dest_name)){ echo 'Image not saved! Check permission!'; }
from PIL import Image image = Image.open("lena.jpg") width, height = image.size amount = width * height total = 0 bw_image = Image.new('L', (width, height), 0) bm_image = Image.new('1', (width, height), 0) for h in range(0, height): for w in range(0, width): r, g, b = image.getpixel((w, h)) greyscale = int((r + g + b) / 3) total += greyscale bw_image.putpixel((w, h), gray_scale) avg = total / amount black = 0 white = 1 for h in range(0, height): for w in range(0, width): v = bw_image.getpixel((w, h)) if v >= avg: bm_image.putpixel((w, h), white) else: bm_image.putpixel((w, h), black) bw_image.show() bm_image.show()
Change the following PHP code into Python without altering its purpose.
define('src_name', 'input.jpg'); // source image define('dest_name', 'output.jpg'); // destination image $img = imagecreatefromjpeg(src_name); // read image if(empty($img)){ echo 'Image could not be loaded!'; exit; } $black = imagecolorallocate($img, 0, 0, 0); $white = imagecolorallocate($img, 255, 255, 255); $width = imagesx($img); $height = imagesy($img); $array_lum = array(); // for storage of luminosity of each pixel $sum_lum = 0; // total sum of luminosity $average_lum = 0; // average luminosity of whole image for($x = 0; $x < $width; $x++){ for($y = 0; $y < $height; $y++){ $color = imagecolorat($img, $x, $y); $r = ($color >> 16) & 0xFF; $g = ($color >> 8) & 0xFF; $b = $color & 0xFF; $array_lum[$x][$y] = ($r + $g + $b); $sum_lum += $array_lum[$x][$y]; } } $average_lum = $sum_lum / ($width * $height); for($x = 0; $x < $width; $x++){ for($y = 0; $y < $height; $y++){ if($array_lum[$x][$y] > $average_lum){ imagesetpixel($img, $x, $y, $white); } else{ imagesetpixel($img, $x, $y, $black); } } } imagejpeg($img, dest_name); if(!file_exists(dest_name)){ echo 'Image not saved! Check permission!'; }
from PIL import Image image = Image.open("lena.jpg") width, height = image.size amount = width * height total = 0 bw_image = Image.new('L', (width, height), 0) bm_image = Image.new('1', (width, height), 0) for h in range(0, height): for w in range(0, width): r, g, b = image.getpixel((w, h)) greyscale = int((r + g + b) / 3) total += greyscale bw_image.putpixel((w, h), gray_scale) avg = total / amount black = 0 white = 1 for h in range(0, height): for w in range(0, width): v = bw_image.getpixel((w, h)) if v >= avg: bm_image.putpixel((w, h), white) else: bm_image.putpixel((w, h), black) bw_image.show() bm_image.show()
Produce a language-to-language conversion: from PHP to Python, same semantics.
define('src_name', 'input.jpg'); // source image define('dest_name', 'output.jpg'); // destination image $img = imagecreatefromjpeg(src_name); // read image if(empty($img)){ echo 'Image could not be loaded!'; exit; } $black = imagecolorallocate($img, 0, 0, 0); $white = imagecolorallocate($img, 255, 255, 255); $width = imagesx($img); $height = imagesy($img); $array_lum = array(); // for storage of luminosity of each pixel $sum_lum = 0; // total sum of luminosity $average_lum = 0; // average luminosity of whole image for($x = 0; $x < $width; $x++){ for($y = 0; $y < $height; $y++){ $color = imagecolorat($img, $x, $y); $r = ($color >> 16) & 0xFF; $g = ($color >> 8) & 0xFF; $b = $color & 0xFF; $array_lum[$x][$y] = ($r + $g + $b); $sum_lum += $array_lum[$x][$y]; } } $average_lum = $sum_lum / ($width * $height); for($x = 0; $x < $width; $x++){ for($y = 0; $y < $height; $y++){ if($array_lum[$x][$y] > $average_lum){ imagesetpixel($img, $x, $y, $white); } else{ imagesetpixel($img, $x, $y, $black); } } } imagejpeg($img, dest_name); if(!file_exists(dest_name)){ echo 'Image not saved! Check permission!'; }
from PIL import Image image = Image.open("lena.jpg") width, height = image.size amount = width * height total = 0 bw_image = Image.new('L', (width, height), 0) bm_image = Image.new('1', (width, height), 0) for h in range(0, height): for w in range(0, width): r, g, b = image.getpixel((w, h)) greyscale = int((r + g + b) / 3) total += greyscale bw_image.putpixel((w, h), gray_scale) avg = total / amount black = 0 white = 1 for h in range(0, height): for w in range(0, width): v = bw_image.getpixel((w, h)) if v >= avg: bm_image.putpixel((w, h), white) else: bm_image.putpixel((w, h), black) bw_image.show() bm_image.show()
Rewrite this program in Python while keeping its functionality equivalent to the PHP version.
'c'; # character 'hello'; # these two strings are the same "hello"; 'Hi $name. How are you?'; # result: "Hi $name. How are you?" "Hi $name. How are you?"; # result: "Hi Bob. How are you?" '\n'; # 2-character string with a backslash and "n" "\n"; # newline character `ls`; # runs a command in the shell and returns the output as a string <<END # Here-Document Hi, whatever goes here gets put into the string, including newlines and $variables, until the label we put above END; <<'END' # Here-Document like single-quoted Same as above, but no interpolation of $variables. END;
'c' == "c" 'text' == "text" ' " ' " ' " '\x20' == ' ' u'unicode string' u'\u05d0'
Translate this program into Python but keep the logic exactly as in PHP.
'c'; # character 'hello'; # these two strings are the same "hello"; 'Hi $name. How are you?'; # result: "Hi $name. How are you?" "Hi $name. How are you?"; # result: "Hi Bob. How are you?" '\n'; # 2-character string with a backslash and "n" "\n"; # newline character `ls`; # runs a command in the shell and returns the output as a string <<END # Here-Document Hi, whatever goes here gets put into the string, including newlines and $variables, until the label we put above END; <<'END' # Here-Document like single-quoted Same as above, but no interpolation of $variables. END;
'c' == "c" 'text' == "text" ' " ' " ' " '\x20' == ' ' u'unicode string' u'\u05d0'
Port the provided PHP code into Python while preserving the original functionality.
'c'; # character 'hello'; # these two strings are the same "hello"; 'Hi $name. How are you?'; # result: "Hi $name. How are you?" "Hi $name. How are you?"; # result: "Hi Bob. How are you?" '\n'; # 2-character string with a backslash and "n" "\n"; # newline character `ls`; # runs a command in the shell and returns the output as a string <<END # Here-Document Hi, whatever goes here gets put into the string, including newlines and $variables, until the label we put above END; <<'END' # Here-Document like single-quoted Same as above, but no interpolation of $variables. END;
'c' == "c" 'text' == "text" ' " ' " ' " '\x20' == ' ' u'unicode string' u'\u05d0'
Keep all operations the same but rewrite the snippet in Python.
$fruits = array( "apple", "banana", "cherry" ); $fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 ); class Fruit { const APPLE = 0; const BANANA = 1; const CHERRY = 2; } $value = Fruit::APPLE; define("FRUIT_APPLE", 0); define("FRUIT_BANANA", 1); define("FRUIT_CHERRY", 2);
>>> from enum import Enum >>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE') >>> Contact.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)])) >>> >>> >>> class Contact2(Enum): FIRST_NAME = 1 LAST_NAME = 2 PHONE = 3 >>> Contact2.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)])) >>>
Translate this program into Python but keep the logic exactly as in PHP.
$fruits = array( "apple", "banana", "cherry" ); $fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 ); class Fruit { const APPLE = 0; const BANANA = 1; const CHERRY = 2; } $value = Fruit::APPLE; define("FRUIT_APPLE", 0); define("FRUIT_BANANA", 1); define("FRUIT_CHERRY", 2);
>>> from enum import Enum >>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE') >>> Contact.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)])) >>> >>> >>> class Contact2(Enum): FIRST_NAME = 1 LAST_NAME = 2 PHONE = 3 >>> Contact2.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)])) >>>
Port the following code from PHP to Python with equivalent syntax and logic.
$fruits = array( "apple", "banana", "cherry" ); $fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 ); class Fruit { const APPLE = 0; const BANANA = 1; const CHERRY = 2; } $value = Fruit::APPLE; define("FRUIT_APPLE", 0); define("FRUIT_BANANA", 1); define("FRUIT_CHERRY", 2);
>>> from enum import Enum >>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE') >>> Contact.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)])) >>> >>> >>> class Contact2(Enum): FIRST_NAME = 1 LAST_NAME = 2 PHONE = 3 >>> Contact2.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)])) >>>
Rewrite this program in Python while keeping its functionality equivalent to the PHP version.
<?php $client = new SoapClient("http://example.com/soap/definition.wsdl"); $result = $client->soapFunc("hello"); $result = $client->anotherSoapFunc(34234); $client = new SoapClient("http://example.com/soap/definition.wsdl"); print_r($client->__getTypes()); print_r($client->__getFunctions()); ?>
from SOAPpy import WSDL proxy = WSDL.Proxy("http://example.com/soap/wsdl") result = proxy.soapFunc("hello") result = proxy.anotherSoapFunc(34234)
Port the following code from PHP to Python with equivalent syntax and logic.
<?php $client = new SoapClient("http://example.com/soap/definition.wsdl"); $result = $client->soapFunc("hello"); $result = $client->anotherSoapFunc(34234); $client = new SoapClient("http://example.com/soap/definition.wsdl"); print_r($client->__getTypes()); print_r($client->__getFunctions()); ?>
from SOAPpy import WSDL proxy = WSDL.Proxy("http://example.com/soap/wsdl") result = proxy.soapFunc("hello") result = proxy.anotherSoapFunc(34234)
Produce a language-to-language conversion: from PHP to Python, same semantics.
<?php $client = new SoapClient("http://example.com/soap/definition.wsdl"); $result = $client->soapFunc("hello"); $result = $client->anotherSoapFunc(34234); $client = new SoapClient("http://example.com/soap/definition.wsdl"); print_r($client->__getTypes()); print_r($client->__getFunctions()); ?>
from SOAPpy import WSDL proxy = WSDL.Proxy("http://example.com/soap/wsdl") result = proxy.soapFunc("hello") result = proxy.anotherSoapFunc(34234)
Change the following PHP code into Python without altering its purpose.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
Ensure the translated Python code behaves exactly like the original PHP snippet.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
Change the programming language of this snippet from PHP to Python without modifying what it does.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
Convert this PHP snippet to Python and keep its semantics consistent.
<?php function meaning_of_life() { return 42; } function main($args) { echo "Main: The meaning of life is " . meaning_of_life() . "\n"; } if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) { main($argv); } ?>
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())