Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate a PHP translation of this Python snippet without changing its computational steps. | 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")
| $str = "alphaBETA";
echo strtoupper($str), "\n"; // ALPHABETA
echo strtolower($str), "\n"; // alphabeta
echo ucfirst($str), "\n"; // AlphaBETA
echo lcfirst("FOObar"), "\n"; // fOObar
echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ
echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
|
Port the following code from Python to PHP with equivalent syntax and logic. | 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")
| $str = "alphaBETA";
echo strtoupper($str), "\n"; // ALPHABETA
echo strtolower($str), "\n"; // alphabeta
echo ucfirst($str), "\n"; // AlphaBETA
echo lcfirst("FOObar"), "\n"; // fOObar
echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ
echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
|
Port the following code from Python to PHP with equivalent syntax and logic. | 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")
| $str = "alphaBETA";
echo strtoupper($str), "\n"; // ALPHABETA
echo strtolower($str), "\n"; // alphabeta
echo ucfirst($str), "\n"; // AlphaBETA
echo lcfirst("FOObar"), "\n"; // fOObar
echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ
echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
|
Keep all operations the same but rewrite the snippet in PHP. | >>> 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
>>>
| $string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $string );
|
Generate an equivalent PHP version of this Python code. | >>> 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
>>>
| $string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $string );
|
Please provide an equivalent version of this Python code in PHP. | >>> 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
>>>
| $string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $string );
|
Maintain the same structure and functionality when rewriting this code in PHP. | import datetime
def mt():
datime1="March 7 2009 7:30pm EST"
formatting = "%B %d %Y %I:%M%p "
datime2 = datime1[:-3]
tdelta = datetime.timedelta(hours=12)
s3 = datetime.datetime.strptime(datime2, formatting)
datime2 = s3+tdelta
print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]
mt()
| <?php
$time = new DateTime('March 7 2009 7:30pm EST');
$time->modify('+12 hours');
echo $time->format('c');
?>
|
Rewrite the snippet below in PHP so it works the same as the original Python code. | import datetime
def mt():
datime1="March 7 2009 7:30pm EST"
formatting = "%B %d %Y %I:%M%p "
datime2 = datime1[:-3]
tdelta = datetime.timedelta(hours=12)
s3 = datetime.datetime.strptime(datime2, formatting)
datime2 = s3+tdelta
print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]
mt()
| <?php
$time = new DateTime('March 7 2009 7:30pm EST');
$time->modify('+12 hours');
echo $time->format('c');
?>
|
Produce a language-to-language conversion: from Python to PHP, same semantics. | import datetime
def mt():
datime1="March 7 2009 7:30pm EST"
formatting = "%B %d %Y %I:%M%p "
datime2 = datime1[:-3]
tdelta = datetime.timedelta(hours=12)
s3 = datetime.datetime.strptime(datime2, formatting)
datime2 = s3+tdelta
print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]
mt()
| <?php
$time = new DateTime('March 7 2009 7:30pm EST');
$time->modify('+12 hours');
echo $time->format('c');
?>
|
Translate this program into PHP but keep the logic exactly as in Python. | 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)
| <?php
$buffer = 1;
$pids = [];
for ($i = 1; $i < $argc; $i++) {
$pid = pcntl_fork();
if ($pid < 0) {
die("failed to start child process");
}
if ($pid === 0) {
sleep($argv[$i] + $buffer);
echo $argv[$i] . "\n";
exit();
}
$pids[] = $pid;
}
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
|
Generate a PHP translation of this Python snippet without changing its computational steps. | 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)
| <?php
$buffer = 1;
$pids = [];
for ($i = 1; $i < $argc; $i++) {
$pid = pcntl_fork();
if ($pid < 0) {
die("failed to start child process");
}
if ($pid === 0) {
sleep($argv[$i] + $buffer);
echo $argv[$i] . "\n";
exit();
}
$pids[] = $pid;
}
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
|
Transform the following Python implementation into PHP, maintaining the same output and logic. | 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)
| <?php
$buffer = 1;
$pids = [];
for ($i = 1; $i < $argc; $i++) {
$pid = pcntl_fork();
if ($pid < 0) {
die("failed to start child process");
}
if ($pid === 0) {
sleep($argv[$i] + $buffer);
echo $argv[$i] . "\n";
exit();
}
$pids[] = $pid;
}
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
|
Can you help me rewrite this code in PHP instead of Python, keeping it the same logically? | 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)
| <?php
for ($i = 0; $i < 10; $i++)
for ($j = 0; $j < 10; $j++)
$a[$i][$j] = rand(1, 20);
foreach ($a as $row) {
foreach ($row as $element) {
echo " $element";
if ($element == 20)
break 2; // 2 is the number of loops we want to break out of
}
echo "\n";
}
echo "\n";
?>
|
Convert this Python block to PHP, preserving its control flow and logic. | 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)
| <?php
for ($i = 0; $i < 10; $i++)
for ($j = 0; $j < 10; $j++)
$a[$i][$j] = rand(1, 20);
foreach ($a as $row) {
foreach ($row as $element) {
echo " $element";
if ($element == 20)
break 2; // 2 is the number of loops we want to break out of
}
echo "\n";
}
echo "\n";
?>
|
Can you help me rewrite this code in PHP instead of Python, keeping it the same logically? | 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)
| <?php
for ($i = 0; $i < 10; $i++)
for ($j = 0; $j < 10; $j++)
$a[$i][$j] = rand(1, 20);
foreach ($a as $row) {
foreach ($row as $element) {
echo " $element";
if ($element == 20)
break 2; // 2 is the number of loops we want to break out of
}
echo "\n";
}
echo "\n";
?>
|
Maintain the same structure and functionality when rewriting this code in PHP. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| <?php
function gcd($a, $b)
{
if ($a == 0)
return $b;
if ($b == 0)
return $a;
if($a == $b)
return $a;
if($a > $b)
return gcd($a-$b, $b);
return gcd($a, $b-$a);
}
$pytha = 0;
$prim = 0;
$max_p = 100;
for ($a = 1; $a <= $max_p / 3; $a++) {
$aa = $a**2;
for ($b = $a + 1; $b < $max_p/2; $b++) {
$bb = $b**2;
for ($c = $b + 1; $c < $max_p/2; $c++) {
$cc = $c**2;
if ($aa + $bb < $cc) break;
if ($a + $b + $c > $max_p) break;
if ($aa + $bb == $cc) {
$pytha++;
if (gcd($a, $b) == 1) $prim++;
}
}
}
}
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
|
Produce a functionally identical PHP code for the snippet given in Python. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| <?php
function gcd($a, $b)
{
if ($a == 0)
return $b;
if ($b == 0)
return $a;
if($a == $b)
return $a;
if($a > $b)
return gcd($a-$b, $b);
return gcd($a, $b-$a);
}
$pytha = 0;
$prim = 0;
$max_p = 100;
for ($a = 1; $a <= $max_p / 3; $a++) {
$aa = $a**2;
for ($b = $a + 1; $b < $max_p/2; $b++) {
$bb = $b**2;
for ($c = $b + 1; $c < $max_p/2; $c++) {
$cc = $c**2;
if ($aa + $bb < $cc) break;
if ($a + $b + $c > $max_p) break;
if ($aa + $bb == $cc) {
$pytha++;
if (gcd($a, $b) == 1) $prim++;
}
}
}
}
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
|
Convert this Python snippet to PHP and keep its semantics consistent. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| <?php
function gcd($a, $b)
{
if ($a == 0)
return $b;
if ($b == 0)
return $a;
if($a == $b)
return $a;
if($a > $b)
return gcd($a-$b, $b);
return gcd($a, $b-$a);
}
$pytha = 0;
$prim = 0;
$max_p = 100;
for ($a = 1; $a <= $max_p / 3; $a++) {
$aa = $a**2;
for ($b = $a + 1; $b < $max_p/2; $b++) {
$bb = $b**2;
for ($c = $b + 1; $c < $max_p/2; $c++) {
$cc = $c**2;
if ($aa + $bb < $cc) break;
if ($a + $b + $c > $max_p) break;
if ($aa + $bb == $cc) {
$pytha++;
if (gcd($a, $b) == 1) $prim++;
}
}
}
}
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
|
Produce a functionally identical PHP code for the snippet given in Python. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| <?php
function gcd($a, $b)
{
if ($a == 0)
return $b;
if ($b == 0)
return $a;
if($a == $b)
return $a;
if($a > $b)
return gcd($a-$b, $b);
return gcd($a, $b-$a);
}
$pytha = 0;
$prim = 0;
$max_p = 100;
for ($a = 1; $a <= $max_p / 3; $a++) {
$aa = $a**2;
for ($b = $a + 1; $b < $max_p/2; $b++) {
$bb = $b**2;
for ($c = $b + 1; $c < $max_p/2; $c++) {
$cc = $c**2;
if ($aa + $bb < $cc) break;
if ($a + $b + $c > $max_p) break;
if ($aa + $bb == $cc) {
$pytha++;
if (gcd($a, $b) == 1) $prim++;
}
}
}
}
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
|
Translate the given Python code snippet into PHP without altering its behavior. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| <?php
function gcd($a, $b)
{
if ($a == 0)
return $b;
if ($b == 0)
return $a;
if($a == $b)
return $a;
if($a > $b)
return gcd($a-$b, $b);
return gcd($a, $b-$a);
}
$pytha = 0;
$prim = 0;
$max_p = 100;
for ($a = 1; $a <= $max_p / 3; $a++) {
$aa = $a**2;
for ($b = $a + 1; $b < $max_p/2; $b++) {
$bb = $b**2;
for ($c = $b + 1; $c < $max_p/2; $c++) {
$cc = $c**2;
if ($aa + $bb < $cc) break;
if ($a + $b + $c > $max_p) break;
if ($aa + $bb == $cc) {
$pytha++;
if (gcd($a, $b) == 1) $prim++;
}
}
}
}
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
|
Produce a language-to-language conversion: from Python to PHP, same semantics. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| <?php
function gcd($a, $b)
{
if ($a == 0)
return $b;
if ($b == 0)
return $a;
if($a == $b)
return $a;
if($a > $b)
return gcd($a-$b, $b);
return gcd($a, $b-$a);
}
$pytha = 0;
$prim = 0;
$max_p = 100;
for ($a = 1; $a <= $max_p / 3; $a++) {
$aa = $a**2;
for ($b = $a + 1; $b < $max_p/2; $b++) {
$bb = $b**2;
for ($c = $b + 1; $c < $max_p/2; $c++) {
$cc = $c**2;
if ($aa + $bb < $cc) break;
if ($a + $b + $c > $max_p) break;
if ($aa + $bb == $cc) {
$pytha++;
if (gcd($a, $b) == 1) $prim++;
}
}
}
}
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
|
Transform the following Python implementation into PHP, maintaining the same output and logic. | items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
| $list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');
$unique_list = array_unique($list);
|
Ensure the translated PHP code behaves exactly like the original Python snippet. | items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
| $list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');
$unique_list = array_unique($list);
|
Preserve the algorithm and functionality while converting the code from Python to PHP. | items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
| $list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');
$unique_list = array_unique($list);
|
Convert this Python snippet to PHP and keep its semantics consistent. | def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
| <?php
function lookAndSay($str) {
return preg_replace_callback('#(.)\1*#', function($matches) {
return strlen($matches[0]).$matches[1];
}, $str);
}
$num = "1";
foreach(range(1,10) as $i) {
echo $num."<br/>";
$num = lookAndSay($num);
}
?>
|
Rewrite this program in PHP while keeping its functionality equivalent to the Python version. | def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
| <?php
function lookAndSay($str) {
return preg_replace_callback('#(.)\1*#', function($matches) {
return strlen($matches[0]).$matches[1];
}, $str);
}
$num = "1";
foreach(range(1,10) as $i) {
echo $num."<br/>";
$num = lookAndSay($num);
}
?>
|
Generate an equivalent PHP version of this Python code. | def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
| <?php
function lookAndSay($str) {
return preg_replace_callback('#(.)\1*#', function($matches) {
return strlen($matches[0]).$matches[1];
}, $str);
}
$num = "1";
foreach(range(1,10) as $i) {
echo $num."<br/>";
$num = lookAndSay($num);
}
?>
|
Convert this Python block to PHP, preserving its control flow and logic. | from collections import deque
stack = deque()
stack.append(value)
value = stack.pop()
not stack
| $stack = array();
empty( $stack ); // true
array_push( $stack, 1 ); // or $stack[] = 1;
array_push( $stack, 2 ); // or $stack[] = 2;
empty( $stack ); // false
echo array_pop( $stack ); // outputs "2"
echo array_pop( $stack ); // outputs "1"
|
Write the same code in PHP as shown below in Python. | from collections import deque
stack = deque()
stack.append(value)
value = stack.pop()
not stack
| $stack = array();
empty( $stack ); // true
array_push( $stack, 1 ); // or $stack[] = 1;
array_push( $stack, 2 ); // or $stack[] = 2;
empty( $stack ); // false
echo array_pop( $stack ); // outputs "2"
echo array_pop( $stack ); // outputs "1"
|
Change the following Python code into PHP without altering its purpose. | from collections import deque
stack = deque()
stack.append(value)
value = stack.pop()
not stack
| $stack = array();
empty( $stack ); // true
array_push( $stack, 1 ); // or $stack[] = 1;
array_push( $stack, 2 ); // or $stack[] = 2;
empty( $stack ); // false
echo array_pop( $stack ); // outputs "2"
echo array_pop( $stack ); // outputs "1"
|
Ensure the translated PHP code behaves exactly like the original Python snippet. | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
| <?php
$foo = 3;
if ($foo == 2)
if ($foo == 3)
else
if ($foo != 0)
{
}
else
{
}
?>
|
Convert this Python snippet to PHP and keep its semantics consistent. | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
| <?php
$foo = 3;
if ($foo == 2)
if ($foo == 3)
else
if ($foo != 0)
{
}
else
{
}
?>
|
Please provide an equivalent version of this Python code in PHP. | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
| <?php
$foo = 3;
if ($foo == 2)
if ($foo == 3)
else
if ($foo != 0)
{
}
else
{
}
?>
|
Write the same algorithm in PHP as shown in this Python implementation. | >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
if j is None:
j = len(L) - 1
if L[j] < L[i]:
L[i], L[j] = L[j], L[i]
if j - i > 1:
t = (j - i + 1) // 3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
| function stoogeSort(&$arr, $i, $j)
{
if($arr[$j] < $arr[$i])
{
list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);
}
if(($j - $i) > 1)
{
$t = ($j - $i + 1) / 3;
stoogesort($arr, $i, $j - $t);
stoogesort($arr, $i + $t, $j);
stoogesort($arr, $i, $j - $t);
}
}
|
Translate the given Python code snippet into PHP without altering its behavior. | >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
if j is None:
j = len(L) - 1
if L[j] < L[i]:
L[i], L[j] = L[j], L[i]
if j - i > 1:
t = (j - i + 1) // 3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
| function stoogeSort(&$arr, $i, $j)
{
if($arr[$j] < $arr[$i])
{
list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);
}
if(($j - $i) > 1)
{
$t = ($j - $i + 1) / 3;
stoogesort($arr, $i, $j - $t);
stoogesort($arr, $i + $t, $j);
stoogesort($arr, $i, $j - $t);
}
}
|
Convert this Python block to PHP, preserving its control flow and logic. | >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
if j is None:
j = len(L) - 1
if L[j] < L[i]:
L[i], L[j] = L[j], L[i]
if j - i > 1:
t = (j - i + 1) // 3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
| function stoogeSort(&$arr, $i, $j)
{
if($arr[$j] < $arr[$i])
{
list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);
}
if(($j - $i) > 1)
{
$t = ($j - $i + 1) / 3;
stoogesort($arr, $i, $j - $t);
stoogesort($arr, $i + $t, $j);
stoogesort($arr, $i, $j - $t);
}
}
|
Preserve the algorithm and functionality while converting the code from Python to PHP. | def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
line = line.strip()
if not line or line.startswith('
boolval = True
if line.startswith(';'):
line = line.lstrip(';')
if len(line.split()) != 1: continue
boolval = False
bits = line.split(None, 1)
if len(bits) == 1:
k = bits[0]
v = boolval
else:
k, v = bits
ret[k.lower()] = v
return ret
if __name__ == '__main__':
import sys
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v
| <?php
$conf = file_get_contents('parse-conf-file.txt');
$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);
$conf = preg_replace_callback(
'/^([a-z]+)\s*=((?=.*\,.*).*)$/mi',
function ($matches) {
$r = '';
foreach (explode(',', $matches[2]) AS $val) {
$r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;
}
return $r;
},
$conf
);
$conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf);
$ini = parse_ini_string($conf);
echo 'Full name = ', $ini['FULLNAME'], PHP_EOL;
echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;
echo 'Need spelling = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;
echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;
echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;
|
Can you help me rewrite this code in PHP instead of Python, keeping it the same logically? | def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
line = line.strip()
if not line or line.startswith('
boolval = True
if line.startswith(';'):
line = line.lstrip(';')
if len(line.split()) != 1: continue
boolval = False
bits = line.split(None, 1)
if len(bits) == 1:
k = bits[0]
v = boolval
else:
k, v = bits
ret[k.lower()] = v
return ret
if __name__ == '__main__':
import sys
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v
| <?php
$conf = file_get_contents('parse-conf-file.txt');
$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);
$conf = preg_replace_callback(
'/^([a-z]+)\s*=((?=.*\,.*).*)$/mi',
function ($matches) {
$r = '';
foreach (explode(',', $matches[2]) AS $val) {
$r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;
}
return $r;
},
$conf
);
$conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf);
$ini = parse_ini_string($conf);
echo 'Full name = ', $ini['FULLNAME'], PHP_EOL;
echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;
echo 'Need spelling = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;
echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;
echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;
|
Convert the following code from Python to PHP, ensuring the logic remains intact. | def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
line = line.strip()
if not line or line.startswith('
boolval = True
if line.startswith(';'):
line = line.lstrip(';')
if len(line.split()) != 1: continue
boolval = False
bits = line.split(None, 1)
if len(bits) == 1:
k = bits[0]
v = boolval
else:
k, v = bits
ret[k.lower()] = v
return ret
if __name__ == '__main__':
import sys
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v
| <?php
$conf = file_get_contents('parse-conf-file.txt');
$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);
$conf = preg_replace_callback(
'/^([a-z]+)\s*=((?=.*\,.*).*)$/mi',
function ($matches) {
$r = '';
foreach (explode(',', $matches[2]) AS $val) {
$r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;
}
return $r;
},
$conf
);
$conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf);
$ini = parse_ini_string($conf);
echo 'Full name = ', $ini['FULLNAME'], PHP_EOL;
echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;
echo 'Need spelling = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;
echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;
echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;
|
Rewrite the snippet below in PHP so it works the same as the original Python code. | strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
| <?php
function mycmp($s1, $s2)
{
if ($d = strlen($s2) - strlen($s1))
return $d;
return strcasecmp($s1, $s2);
}
$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
usort($strings, "mycmp");
?>
|
Please provide an equivalent version of this Python code in PHP. | strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
| <?php
function mycmp($s1, $s2)
{
if ($d = strlen($s2) - strlen($s1))
return $d;
return strcasecmp($s1, $s2);
}
$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
usort($strings, "mycmp");
?>
|
Keep all operations the same but rewrite the snippet in PHP. | strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
| <?php
function mycmp($s1, $s2)
{
if ($d = strlen($s2) - strlen($s1))
return $d;
return strcasecmp($s1, $s2);
}
$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
usort($strings, "mycmp");
?>
|
Convert this Python snippet to PHP and keep its semantics consistent. | def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
| function selection_sort(&$arr) {
$n = count($arr);
for($i = 0; $i < count($arr); $i++) {
$min = $i;
for($j = $i + 1; $j < $n; $j++){
if($arr[$j] < $arr[$min]){
$min = $j;
}
}
list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
}
}
|
Maintain the same structure and functionality when rewriting this code in PHP. | def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
| function selection_sort(&$arr) {
$n = count($arr);
for($i = 0; $i < count($arr); $i++) {
$min = $i;
for($j = $i + 1; $j < $n; $j++){
if($arr[$j] < $arr[$min]){
$min = $j;
}
}
list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
}
}
|
Keep all operations the same but rewrite the snippet in PHP. | def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
| function selection_sort(&$arr) {
$n = count($arr);
for($i = 0; $i < count($arr); $i++) {
$min = $i;
for($j = $i + 1; $j < $n; $j++){
if($arr[$j] < $arr[$min]){
$min = $j;
}
}
list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
}
}
|
Translate the given Python code snippet into PHP without altering its behavior. | 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)
| function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
|
Generate a PHP translation of this Python snippet without changing its computational steps. | 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)
| function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
|
Write a version of this Python function in PHP with identical behavior. | 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)
| function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
|
Port the provided Python code into PHP while preserving the original functionality. | >>> 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
>>>
| 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
|
Rewrite the snippet below in PHP so it works the same as the original Python code. | >>> 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
>>>
| 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
|
Produce a functionally identical PHP code for the snippet given in Python. | >>> 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
>>>
| 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
|
Maintain the same structure and functionality when rewriting this code in PHP. | >>> 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
>>>
| <?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";
|
Maintain the same structure and functionality when rewriting this code in PHP. | >>> 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
>>>
| <?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";
|
Change the following Python code into PHP without altering its purpose. | >>> 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
>>>
| <?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";
|
Convert this Python snippet to PHP and keep its semantics consistent. | for i in xrange(10, -1, -1):
print i
| for ($i = 10; $i >= 0; $i--)
echo "$i\n";
|
Translate the given Python code snippet into PHP without altering its behavior. | for i in xrange(10, -1, -1):
print i
| for ($i = 10; $i >= 0; $i--)
echo "$i\n";
|
Change the programming language of this snippet from Python to PHP without modifying what it does. | for i in xrange(10, -1, -1):
print i
| for ($i = 10; $i >= 0; $i--)
echo "$i\n";
|
Port the provided Python code into PHP while preserving the original functionality. | for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
| for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo '*';
}
echo "\n";
}
|
Rewrite this program in PHP while keeping its functionality equivalent to the Python version. | for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
| for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo '*';
}
echo "\n";
}
|
Convert the following code from Python to PHP, ensuring the logic remains intact. | for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
| for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo '*';
}
echo "\n";
}
|
Port the provided Python code into PHP while preserving the original functionality. |
print 2**64*2**64
| <?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
|
Translate the given Python code snippet into PHP without altering its behavior. |
print 2**64*2**64
| <?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
|
Convert this Python snippet to PHP and keep its semantics consistent. |
print 2**64*2**64
| <?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
|
Generate an equivalent PHP version of this Python code. |
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)
| <?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);
}
?>
|
Convert this Python snippet to PHP and keep its semantics consistent. |
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)
| <?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);
}
?>
|
Produce a language-to-language conversion: from Python to PHP, same semantics. |
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)
| <?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);
}
?>
|
Can you help me rewrite this code in PHP instead of Python, keeping it the same logically? | 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
| 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;
}
|
Transform the following Python implementation into PHP, maintaining the same output and logic. | 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
| 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;
}
|
Write a version of this Python function in PHP with identical behavior. | 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
| 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;
}
|
Convert this Python snippet to PHP and keep its semantics consistent. | import shutil
shutil.copyfile('input.txt', 'output.txt')
| <?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);
?>
|
Rewrite the snippet below in PHP so it works the same as the original Python code. | import shutil
shutil.copyfile('input.txt', 'output.txt')
| <?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);
?>
|
Can you help me rewrite this code in PHP instead of Python, keeping it the same logically? | import shutil
shutil.copyfile('input.txt', 'output.txt')
| <?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);
?>
|
Write the same code in PHP as shown below in Python. | 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( )
| <?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
?>
|
Translate the given Python code snippet into PHP without altering its behavior. | 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( )
| <?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
?>
|
Please provide an equivalent version of this Python code in PHP. | 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( )
| <?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
?>
|
Port the following code from Python to PHP with equivalent syntax and logic. | m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625))
print(zip(*m))
| 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);
}
|
Ensure the translated PHP code behaves exactly like the original Python snippet. | m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625))
print(zip(*m))
| 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);
}
|
Change the following Python code into PHP without altering its purpose. | m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625))
print(zip(*m))
| 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);
}
|
Generate a PHP translation of this Python snippet without changing its computational steps. |
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)))
| <?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";
?>
|
Translate the given Python code snippet into PHP without altering its behavior. |
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)))
| <?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";
?>
|
Port the following code from Python to PHP with equivalent syntax and logic. |
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)))
| <?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";
?>
|
Rewrite this program in PHP while keeping its functionality equivalent to the Python version. | import sys
print(sys.getrecursionlimit())
| <?php
function a() {
static $i = 0;
print ++$i . "\n";
a();
}
a();
|
Convert the following code from Python to PHP, ensuring the logic remains intact. | import sys
print(sys.getrecursionlimit())
| <?php
function a() {
static $i = 0;
print ++$i . "\n";
a();
}
a();
|
Convert this Python block to PHP, preserving its control flow and logic. | import sys
print(sys.getrecursionlimit())
| <?php
function a() {
static $i = 0;
print ++$i . "\n";
a();
}
a();
|
Translate this program into PHP but keep the logic exactly as in Python. | import sys
print(sys.getrecursionlimit())
| <?php
function a() {
static $i = 0;
print ++$i . "\n";
a();
}
a();
|
Convert the following code from Python to PHP, ensuring the logic remains intact. | import sys
print(sys.getrecursionlimit())
| <?php
function a() {
static $i = 0;
print ++$i . "\n";
a();
}
a();
|
Rewrite the snippet below in PHP so it works the same as the original Python code. | import sys
print(sys.getrecursionlimit())
| <?php
function a() {
static $i = 0;
print ++$i . "\n";
a();
}
a();
|
Port the following code from Python to PHP with equivalent syntax and logic. | def perf1(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n
| 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;
}
|
Change the programming language of this snippet from Python to PHP without modifying what it does. | def perf1(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n
| 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;
}
|
Translate the given Python code snippet into PHP without altering its behavior. | def perf1(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n
| 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;
}
|
Translate the given Python code snippet into PHP without altering its behavior. |
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]))
| <?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)));
?>
|
Rewrite the snippet below in PHP so it works the same as the original Python code. |
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]))
| <?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)));
?>
|
Convert this Python block to PHP, preserving its control flow and logic. |
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]))
| <?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)));
?>
|
Write a version of this Python function in PHP with identical behavior. | >>> 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
| <?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));
?>
|
Generate an equivalent PHP version of this Python code. | >>> 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
| <?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));
?>
|
Write a version of this Python function in PHP with identical behavior. | >>> 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
| <?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));
?>
|
Translate this program into PHP but keep the logic exactly as in Python. |
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)))
| <?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";
}
}
|
Convert this Python block to PHP, preserving its control flow and logic. |
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)))
| <?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";
}
}
|
Convert the following code from Python to PHP, ensuring the logic remains intact. |
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)))
| <?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";
}
}
|
Ensure the translated PHP code behaves exactly like the original Python snippet. | >>> 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
>>>
| 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;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.