Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert the following code from Python to PHP, ensuring the logic remains intact.
>>> >>> from math import sin, cos, acos, asin >>> >>> cube = lambda x: x * x * x >>> croot = lambda x: x ** (1/3.0) >>> >>> >>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) ) >>> >>> funclist = [sin, cos, cube] >>> funclisti = [asin, acos, croot] >>> >>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)] [0.5, 0.4999999999999999, 0.5] >>>
$compose = function ($f, $g) { return function ($x) use ($f, $g) { return $f($g($x)); }; }; $fn = array('sin', 'cos', function ($x) { return pow($x, 3); }); $inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); }); for ($i = 0; $i < 3; $i++) { $f = $compose($inv[$i], $fn[$i]); echo $f(0.5), PHP_EOL; }
Ensure the translated PHP code behaves exactly like the original Python snippet.
>>> >>> from math import sin, cos, acos, asin >>> >>> cube = lambda x: x * x * x >>> croot = lambda x: x ** (1/3.0) >>> >>> >>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) ) >>> >>> funclist = [sin, cos, cube] >>> funclisti = [asin, acos, croot] >>> >>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)] [0.5, 0.4999999999999999, 0.5] >>>
$compose = function ($f, $g) { return function ($x) use ($f, $g) { return $f($g($x)); }; }; $fn = array('sin', 'cos', function ($x) { return pow($x, 3); }); $inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); }); for ($i = 0; $i < 3; $i++) { $f = $compose($inv[$i], $fn[$i]); echo $f(0.5), PHP_EOL; }
Generate a PHP translation of this Python snippet without changing its computational steps.
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x} ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
<?php function ProperDivisors($n) { yield 1; $large_divisors = []; for ($i = 2; $i <= sqrt($n); $i++) { if ($n % $i == 0) { yield $i; if ($i*$i != $n) { $large_divisors[] = $n / $i; } } } foreach (array_reverse($large_divisors) as $i) { yield $i; } } assert([1, 2, 4, 5, 10, 20, 25, 50] == iterator_to_array(ProperDivisors(100))); foreach (range(1, 10) as $n) { echo "$n =>"; foreach (ProperDivisors($n) as $divisor) { echo " $divisor"; } echo "\n"; } $divisorsCount = []; for ($i = 1; $i < 20000; $i++) { $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i; } ksort($divisorsCount); echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n"; echo "They have ", key($divisorsCount), " divisors.\n";
Write the same code in PHP as shown below in Python.
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x} ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
<?php function ProperDivisors($n) { yield 1; $large_divisors = []; for ($i = 2; $i <= sqrt($n); $i++) { if ($n % $i == 0) { yield $i; if ($i*$i != $n) { $large_divisors[] = $n / $i; } } } foreach (array_reverse($large_divisors) as $i) { yield $i; } } assert([1, 2, 4, 5, 10, 20, 25, 50] == iterator_to_array(ProperDivisors(100))); foreach (range(1, 10) as $n) { echo "$n =>"; foreach (ProperDivisors($n) as $divisor) { echo " $divisor"; } echo "\n"; } $divisorsCount = []; for ($i = 1; $i < 20000; $i++) { $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i; } ksort($divisorsCount); echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n"; echo "They have ", key($divisorsCount), " divisors.\n";
Keep all operations the same but rewrite the snippet in PHP.
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x} ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
<?php function ProperDivisors($n) { yield 1; $large_divisors = []; for ($i = 2; $i <= sqrt($n); $i++) { if ($n % $i == 0) { yield $i; if ($i*$i != $n) { $large_divisors[] = $n / $i; } } } foreach (array_reverse($large_divisors) as $i) { yield $i; } } assert([1, 2, 4, 5, 10, 20, 25, 50] == iterator_to_array(ProperDivisors(100))); foreach (range(1, 10) as $n) { echo "$n =>"; foreach (ProperDivisors($n) as $divisor) { echo " $divisor"; } echo "\n"; } $divisorsCount = []; for ($i = 1; $i < 20000; $i++) { $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i; } ksort($divisorsCount); echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n"; echo "They have ", key($divisorsCount), " divisors.\n";
Keep all operations the same but rewrite the snippet in PHP.
import re string = "This is a string" if re.search('string$', string): print("Ends with string.") string = re.sub(" a ", " another ", string) print(string)
$string = 'I am a string'; # Test if (preg_match('/string$/', $string)) { echo "Ends with 'string'\n"; } # Replace $string = preg_replace('/\ba\b/', 'another', $string); echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";
Preserve the algorithm and functionality while converting the code from Python to PHP.
import re string = "This is a string" if re.search('string$', string): print("Ends with string.") string = re.sub(" a ", " another ", string) print(string)
$string = 'I am a string'; # Test if (preg_match('/string$/', $string)) { echo "Ends with 'string'\n"; } # Replace $string = preg_replace('/\ba\b/', 'another', $string); echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";
Keep all operations the same but rewrite the snippet in PHP.
import re string = "This is a string" if re.search('string$', string): print("Ends with string.") string = re.sub(" a ", " another ", string) print(string)
$string = 'I am a string'; # Test if (preg_match('/string$/', $string)) { echo "Ends with 'string'\n"; } # Replace $string = preg_replace('/\ba\b/', 'another', $string); echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";
Convert this Python snippet to PHP and keep its semantics consistent.
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = {key: value for key, value in zip(keys, values)}
$keys = array('a', 'b', 'c'); $values = array(1, 2, 3); $hash = array_combine($keys, $values);
Write the same code in PHP as shown below in Python.
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = {key: value for key, value in zip(keys, values)}
$keys = array('a', 'b', 'c'); $values = array(1, 2, 3); $hash = array_combine($keys, $values);
Generate an equivalent PHP version of this Python code.
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = {key: value for key, value in zip(keys, values)}
$keys = array('a', 'b', 'c'); $values = array(1, 2, 3); $hash = array_combine($keys, $values);
Port the following code from Python to PHP with equivalent syntax and logic.
def setup(): size(600, 600) background(0) stroke(255) drawTree(300, 550, 9) def drawTree(x, y, depth): fork_ang = radians(20) base_len = 10 if depth > 0: pushMatrix() translate(x, y - baseLen * depth) line(0, baseLen * depth, 0, 0) rotate(fork_ang) drawTree(0, 0, depth - 1) rotate(2 * -fork_ang) drawTree(0, 0, depth - 1) popMatrix()
<?php header("Content-type: image/png"); $width = 512; $height = 512; $img = imagecreatetruecolor($width,$height); $bg = imagecolorallocate($img,255,255,255); imagefilledrectangle($img, 0, 0, $width, $width, $bg); $depth = 8; function drawTree($x1, $y1, $angle, $depth){ global $img; if ($depth != 0){ $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0); $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0); imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0)); drawTree($x2, $y2, $angle - 20, $depth - 1); drawTree($x2, $y2, $angle + 20, $depth - 1); } } drawTree($width/2, $height, -90, $depth); imagepng($img); imagedestroy($img); ?>
Transform the following Python implementation into PHP, maintaining the same output and logic.
def setup(): size(600, 600) background(0) stroke(255) drawTree(300, 550, 9) def drawTree(x, y, depth): fork_ang = radians(20) base_len = 10 if depth > 0: pushMatrix() translate(x, y - baseLen * depth) line(0, baseLen * depth, 0, 0) rotate(fork_ang) drawTree(0, 0, depth - 1) rotate(2 * -fork_ang) drawTree(0, 0, depth - 1) popMatrix()
<?php header("Content-type: image/png"); $width = 512; $height = 512; $img = imagecreatetruecolor($width,$height); $bg = imagecolorallocate($img,255,255,255); imagefilledrectangle($img, 0, 0, $width, $width, $bg); $depth = 8; function drawTree($x1, $y1, $angle, $depth){ global $img; if ($depth != 0){ $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0); $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0); imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0)); drawTree($x2, $y2, $angle - 20, $depth - 1); drawTree($x2, $y2, $angle + 20, $depth - 1); } } drawTree($width/2, $height, -90, $depth); imagepng($img); imagedestroy($img); ?>
Can you help me rewrite this code in PHP instead of Python, keeping it the same logically?
def setup(): size(600, 600) background(0) stroke(255) drawTree(300, 550, 9) def drawTree(x, y, depth): fork_ang = radians(20) base_len = 10 if depth > 0: pushMatrix() translate(x, y - baseLen * depth) line(0, baseLen * depth, 0, 0) rotate(fork_ang) drawTree(0, 0, depth - 1) rotate(2 * -fork_ang) drawTree(0, 0, depth - 1) popMatrix()
<?php header("Content-type: image/png"); $width = 512; $height = 512; $img = imagecreatetruecolor($width,$height); $bg = imagecolorallocate($img,255,255,255); imagefilledrectangle($img, 0, 0, $width, $width, $bg); $depth = 8; function drawTree($x1, $y1, $angle, $depth){ global $img; if ($depth != 0){ $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0); $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0); imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0)); drawTree($x2, $y2, $angle - 20, $depth - 1); drawTree($x2, $y2, $angle + 20, $depth - 1); } } drawTree($width/2, $height, -90, $depth); imagepng($img); imagedestroy($img); ?>
Write a version of this Python function in PHP with identical behavior.
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
<?php function gray_encode($binary){ return $binary ^ ($binary >> 1); } function gray_decode($gray){ $binary = $gray; while($gray >>= 1) $binary ^= $gray; return $binary; } for($i=0;$i<32;$i++){ $gray_encoded = gray_encode($i); printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); }
Rewrite this program in PHP while keeping its functionality equivalent to the Python version.
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
<?php function gray_encode($binary){ return $binary ^ ($binary >> 1); } function gray_decode($gray){ $binary = $gray; while($gray >>= 1) $binary ^= $gray; return $binary; } for($i=0;$i<32;$i++){ $gray_encoded = gray_encode($i); printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); }
Convert the following code from Python to PHP, ensuring the logic remains intact.
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
<?php function gray_encode($binary){ return $binary ^ ($binary >> 1); } function gray_decode($gray){ $binary = $gray; while($gray >>= 1) $binary ^= $gray; return $binary; } for($i=0;$i<32;$i++){ $gray_encoded = gray_encode($i); printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); }
Produce a functionally identical PHP code for the snippet given in Python.
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
<?php function gray_encode($binary){ return $binary ^ ($binary >> 1); } function gray_decode($gray){ $binary = $gray; while($gray >>= 1) $binary ^= $gray; return $binary; } for($i=0;$i<32;$i++){ $gray_encoded = gray_encode($i); printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); }
Rewrite this program in PHP while keeping its functionality equivalent to the Python version.
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
<?php function gray_encode($binary){ return $binary ^ ($binary >> 1); } function gray_decode($gray){ $binary = $gray; while($gray >>= 1) $binary ^= $gray; return $binary; } for($i=0;$i<32;$i++){ $gray_encoded = gray_encode($i); printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); }
Produce a language-to-language conversion: from Python to PHP, same semantics.
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
<?php function gray_encode($binary){ return $binary ^ ($binary >> 1); } function gray_decode($gray){ $binary = $gray; while($gray >>= 1) $binary ^= $gray; return $binary; } for($i=0;$i<32;$i++){ $gray_encoded = gray_encode($i); printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); }
Write the same algorithm in PHP as shown in this Python implementation.
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
class Card { protected static $suits = array( '♠', '♥', '♦', '♣' ); protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); protected $suit; protected $suitOrder; protected $pip; protected $pipOrder; protected $order; public function __construct( $suit, $pip ) { if( !in_array( $suit, self::$suits ) ) { throw new InvalidArgumentException( 'Invalid suit' ); } if( !in_array( $pip, self::$pips ) ) { throw new InvalidArgumentException( 'Invalid pip' ); } $this->suit = $suit; $this->pip = $pip; } public function getSuit() { return $this->suit; } public function getPip() { return $this->pip; } public function getSuitOrder() { if( !isset( $this->suitOrder ) ) { $this->suitOrder = array_search( $this->suit, self::$suits ); } return $this->suitOrder; } public function getPipOrder() { if( !isset( $this->pipOrder ) ) { $this->pipOrder = array_search( $this->pip, self::$pips ); } return $this->pipOrder; } public function getOrder() { if( !isset( $this->order ) ) { $suitOrder = $this->getSuitOrder(); $pipOrder = $this->getPipOrder(); $this->order = $pipOrder * count( self::$suits ) + $suitOrder; } return $this->order; } public function compareSuit( Card $other ) { return $this->getSuitOrder() - $other->getSuitOrder(); } public function comparePip( Card $other ) { return $this->getPipOrder() - $other->getPipOrder(); } public function compare( Card $other ) { return $this->getOrder() - $other->getOrder(); } public function __toString() { return $this->suit . $this->pip; } public static function getSuits() { return self::$suits; } public static function getPips() { return self::$pips; } } class CardCollection implements Countable, Iterator { protected $cards = array(); protected function __construct( array $cards = array() ) { foreach( $cards as $card ) { $this->addCard( $card ); } } public function count() { return count( $this->cards ); } public function key() { return key( $this->cards ); } public function valid() { return null !== $this->key(); } public function next() { next( $this->cards ); } public function current() { return current( $this->cards ); } public function rewind() { reset( $this->cards ); } public function sort( $comparer = null ) { $comparer = $comparer ?: function( $a, $b ) { return $a->compare( $b ); }; if( !is_callable( $comparer ) ) { throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' ); } usort( $this->cards, $comparer ); return $this; } public function toString() { return implode( ' ', $this->cards ); } public function __toString() { return $this->toString(); } protected function addCard( Card $card ) { if( in_array( $card, $this->cards ) ) { throw new DomainException( 'Card is already present in this collection' ); } $this->cards[] = $card; } } class Deck extends CardCollection { public function __construct( $shuffled = false ) { foreach( Card::getSuits() as $suit ) { foreach( Card::getPips() as $pip ) { $this->addCard( new Card( $suit, $pip ) ); } } if( $shuffled ) { $this->shuffle(); } } public function deal( $amount = 1, CardCollection $cardCollection = null ) { if( !is_int( $amount ) || $amount < 1 ) { throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' ); } if( $amount > count( $this->cards ) ) { throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' ); } $cards = array_splice( $this->cards, 0, $amount ); $cardCollection = $cardCollection ?: new CardCollection; foreach( $cards as $card ) { $cardCollection->addCard( $card ); } return $cardCollection; } public function shuffle() { shuffle( $this->cards ); } } class Hand extends CardCollection { public function __construct() {} public function play( $position ) { if( !isset( $this->cards[ $position ] ) ) { throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' ); } $result = array_splice( $this->cards, $position, 1 ); return $result[ 0 ]; } }
Generate an equivalent PHP version of this Python code.
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
class Card { protected static $suits = array( '♠', '♥', '♦', '♣' ); protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); protected $suit; protected $suitOrder; protected $pip; protected $pipOrder; protected $order; public function __construct( $suit, $pip ) { if( !in_array( $suit, self::$suits ) ) { throw new InvalidArgumentException( 'Invalid suit' ); } if( !in_array( $pip, self::$pips ) ) { throw new InvalidArgumentException( 'Invalid pip' ); } $this->suit = $suit; $this->pip = $pip; } public function getSuit() { return $this->suit; } public function getPip() { return $this->pip; } public function getSuitOrder() { if( !isset( $this->suitOrder ) ) { $this->suitOrder = array_search( $this->suit, self::$suits ); } return $this->suitOrder; } public function getPipOrder() { if( !isset( $this->pipOrder ) ) { $this->pipOrder = array_search( $this->pip, self::$pips ); } return $this->pipOrder; } public function getOrder() { if( !isset( $this->order ) ) { $suitOrder = $this->getSuitOrder(); $pipOrder = $this->getPipOrder(); $this->order = $pipOrder * count( self::$suits ) + $suitOrder; } return $this->order; } public function compareSuit( Card $other ) { return $this->getSuitOrder() - $other->getSuitOrder(); } public function comparePip( Card $other ) { return $this->getPipOrder() - $other->getPipOrder(); } public function compare( Card $other ) { return $this->getOrder() - $other->getOrder(); } public function __toString() { return $this->suit . $this->pip; } public static function getSuits() { return self::$suits; } public static function getPips() { return self::$pips; } } class CardCollection implements Countable, Iterator { protected $cards = array(); protected function __construct( array $cards = array() ) { foreach( $cards as $card ) { $this->addCard( $card ); } } public function count() { return count( $this->cards ); } public function key() { return key( $this->cards ); } public function valid() { return null !== $this->key(); } public function next() { next( $this->cards ); } public function current() { return current( $this->cards ); } public function rewind() { reset( $this->cards ); } public function sort( $comparer = null ) { $comparer = $comparer ?: function( $a, $b ) { return $a->compare( $b ); }; if( !is_callable( $comparer ) ) { throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' ); } usort( $this->cards, $comparer ); return $this; } public function toString() { return implode( ' ', $this->cards ); } public function __toString() { return $this->toString(); } protected function addCard( Card $card ) { if( in_array( $card, $this->cards ) ) { throw new DomainException( 'Card is already present in this collection' ); } $this->cards[] = $card; } } class Deck extends CardCollection { public function __construct( $shuffled = false ) { foreach( Card::getSuits() as $suit ) { foreach( Card::getPips() as $pip ) { $this->addCard( new Card( $suit, $pip ) ); } } if( $shuffled ) { $this->shuffle(); } } public function deal( $amount = 1, CardCollection $cardCollection = null ) { if( !is_int( $amount ) || $amount < 1 ) { throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' ); } if( $amount > count( $this->cards ) ) { throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' ); } $cards = array_splice( $this->cards, 0, $amount ); $cardCollection = $cardCollection ?: new CardCollection; foreach( $cards as $card ) { $cardCollection->addCard( $card ); } return $cardCollection; } public function shuffle() { shuffle( $this->cards ); } } class Hand extends CardCollection { public function __construct() {} public function play( $position ) { if( !isset( $this->cards[ $position ] ) ) { throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' ); } $result = array_splice( $this->cards, $position, 1 ); return $result[ 0 ]; } }
Produce a language-to-language conversion: from Python to PHP, same semantics.
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
class Card { protected static $suits = array( '♠', '♥', '♦', '♣' ); protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); protected $suit; protected $suitOrder; protected $pip; protected $pipOrder; protected $order; public function __construct( $suit, $pip ) { if( !in_array( $suit, self::$suits ) ) { throw new InvalidArgumentException( 'Invalid suit' ); } if( !in_array( $pip, self::$pips ) ) { throw new InvalidArgumentException( 'Invalid pip' ); } $this->suit = $suit; $this->pip = $pip; } public function getSuit() { return $this->suit; } public function getPip() { return $this->pip; } public function getSuitOrder() { if( !isset( $this->suitOrder ) ) { $this->suitOrder = array_search( $this->suit, self::$suits ); } return $this->suitOrder; } public function getPipOrder() { if( !isset( $this->pipOrder ) ) { $this->pipOrder = array_search( $this->pip, self::$pips ); } return $this->pipOrder; } public function getOrder() { if( !isset( $this->order ) ) { $suitOrder = $this->getSuitOrder(); $pipOrder = $this->getPipOrder(); $this->order = $pipOrder * count( self::$suits ) + $suitOrder; } return $this->order; } public function compareSuit( Card $other ) { return $this->getSuitOrder() - $other->getSuitOrder(); } public function comparePip( Card $other ) { return $this->getPipOrder() - $other->getPipOrder(); } public function compare( Card $other ) { return $this->getOrder() - $other->getOrder(); } public function __toString() { return $this->suit . $this->pip; } public static function getSuits() { return self::$suits; } public static function getPips() { return self::$pips; } } class CardCollection implements Countable, Iterator { protected $cards = array(); protected function __construct( array $cards = array() ) { foreach( $cards as $card ) { $this->addCard( $card ); } } public function count() { return count( $this->cards ); } public function key() { return key( $this->cards ); } public function valid() { return null !== $this->key(); } public function next() { next( $this->cards ); } public function current() { return current( $this->cards ); } public function rewind() { reset( $this->cards ); } public function sort( $comparer = null ) { $comparer = $comparer ?: function( $a, $b ) { return $a->compare( $b ); }; if( !is_callable( $comparer ) ) { throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' ); } usort( $this->cards, $comparer ); return $this; } public function toString() { return implode( ' ', $this->cards ); } public function __toString() { return $this->toString(); } protected function addCard( Card $card ) { if( in_array( $card, $this->cards ) ) { throw new DomainException( 'Card is already present in this collection' ); } $this->cards[] = $card; } } class Deck extends CardCollection { public function __construct( $shuffled = false ) { foreach( Card::getSuits() as $suit ) { foreach( Card::getPips() as $pip ) { $this->addCard( new Card( $suit, $pip ) ); } } if( $shuffled ) { $this->shuffle(); } } public function deal( $amount = 1, CardCollection $cardCollection = null ) { if( !is_int( $amount ) || $amount < 1 ) { throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' ); } if( $amount > count( $this->cards ) ) { throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' ); } $cards = array_splice( $this->cards, 0, $amount ); $cardCollection = $cardCollection ?: new CardCollection; foreach( $cards as $card ) { $cardCollection->addCard( $card ); } return $cardCollection; } public function shuffle() { shuffle( $this->cards ); } } class Hand extends CardCollection { public function __construct() {} public function play( $position ) { if( !isset( $this->cards[ $position ] ) ) { throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' ); } $result = array_splice( $this->cards, $position, 1 ); return $result[ 0 ]; } }
Ensure the translated PHP code behaves exactly like the original Python snippet.
array = [] array.append(1) array.append(3) array[0] = 2 print(array[0])
$NumberArray = array(0, 1, 2, 3, 4, 5, 6); $LetterArray = array("a", "b", "c", "d", "e", "f"); $simpleForm = ['apple', 'orange'];
Please provide an equivalent version of this Python code in PHP.
array = [] array.append(1) array.append(3) array[0] = 2 print(array[0])
$NumberArray = array(0, 1, 2, 3, 4, 5, 6); $LetterArray = array("a", "b", "c", "d", "e", "f"); $simpleForm = ['apple', 'orange'];
Keep all operations the same but rewrite the snippet in PHP.
array = [] array.append(1) array.append(3) array[0] = 2 print(array[0])
$NumberArray = array(0, 1, 2, 3, 4, 5, 6); $LetterArray = array("a", "b", "c", "d", "e", "f"); $simpleForm = ['apple', 'orange'];
Maintain the same structure and functionality when rewriting this code in PHP.
def setup(): size(729, 729) fill(0) background(255) noStroke() rect(width / 3, height / 3, width / 3, width / 3) rectangles(width / 3, height / 3, width / 3) def rectangles(x, y, s): if s < 1: return xc, yc = x - s, y - s for row in range(3): for col in range(3): if not (row == 1 and col == 1): xx, yy = xc + row * s, yc + col * s delta = s / 3 rect(xx + delta, yy + delta, delta, delta) rectangles(xx + s / 3, yy + s / 3, s / 3)
<?php function isSierpinskiCarpetPixelFilled($x, $y) { while (($x > 0) or ($y > 0)) { if (($x % 3 == 1) and ($y % 3 == 1)) { return false; } $x /= 3; $y /= 3; } return true; } function sierpinskiCarpet($order) { $size = pow(3, $order); for ($y = 0 ; $y < $size ; $y++) { for ($x = 0 ; $x < $size ; $x++) { echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' '; } echo PHP_EOL; } } for ($order = 0 ; $order <= 3 ; $order++) { echo 'N=', $order, PHP_EOL; sierpinskiCarpet($order); echo PHP_EOL; }
Write the same algorithm in PHP as shown in this Python implementation.
def setup(): size(729, 729) fill(0) background(255) noStroke() rect(width / 3, height / 3, width / 3, width / 3) rectangles(width / 3, height / 3, width / 3) def rectangles(x, y, s): if s < 1: return xc, yc = x - s, y - s for row in range(3): for col in range(3): if not (row == 1 and col == 1): xx, yy = xc + row * s, yc + col * s delta = s / 3 rect(xx + delta, yy + delta, delta, delta) rectangles(xx + s / 3, yy + s / 3, s / 3)
<?php function isSierpinskiCarpetPixelFilled($x, $y) { while (($x > 0) or ($y > 0)) { if (($x % 3 == 1) and ($y % 3 == 1)) { return false; } $x /= 3; $y /= 3; } return true; } function sierpinskiCarpet($order) { $size = pow(3, $order); for ($y = 0 ; $y < $size ; $y++) { for ($x = 0 ; $x < $size ; $x++) { echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' '; } echo PHP_EOL; } } for ($order = 0 ; $order <= 3 ; $order++) { echo 'N=', $order, PHP_EOL; sierpinskiCarpet($order); echo PHP_EOL; }
Please provide an equivalent version of this Python code in PHP.
def setup(): size(729, 729) fill(0) background(255) noStroke() rect(width / 3, height / 3, width / 3, width / 3) rectangles(width / 3, height / 3, width / 3) def rectangles(x, y, s): if s < 1: return xc, yc = x - s, y - s for row in range(3): for col in range(3): if not (row == 1 and col == 1): xx, yy = xc + row * s, yc + col * s delta = s / 3 rect(xx + delta, yy + delta, delta, delta) rectangles(xx + s / 3, yy + s / 3, s / 3)
<?php function isSierpinskiCarpetPixelFilled($x, $y) { while (($x > 0) or ($y > 0)) { if (($x % 3 == 1) and ($y % 3 == 1)) { return false; } $x /= 3; $y /= 3; } return true; } function sierpinskiCarpet($order) { $size = pow(3, $order); for ($y = 0 ; $y < $size ; $y++) { for ($x = 0 ; $x < $size ; $x++) { echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' '; } echo PHP_EOL; } } for ($order = 0 ; $order <= 3 ; $order++) { echo 'N=', $order, PHP_EOL; sierpinskiCarpet($order); echo PHP_EOL; }
Ensure the translated PHP code behaves exactly like the original Python snippet.
import random def bogosort(l): while not in_order(l): random.shuffle(l) return l def in_order(l): if not l: return True last = l[0] for x in l[1:]: if x < last: return False last = x return True
function bogosort($l) { while (!in_order($l)) shuffle($l); return $l; } function in_order($l) { for ($i = 1; $i < count($l); $i++) if ($l[$i] < $l[$i-1]) return FALSE; return TRUE; }
Preserve the algorithm and functionality while converting the code from Python to PHP.
import random def bogosort(l): while not in_order(l): random.shuffle(l) return l def in_order(l): if not l: return True last = l[0] for x in l[1:]: if x < last: return False last = x return True
function bogosort($l) { while (!in_order($l)) shuffle($l); return $l; } function in_order($l) { for ($i = 1; $i < count($l); $i++) if ($l[$i] < $l[$i-1]) return FALSE; return TRUE; }
Port the provided Python code into PHP while preserving the original functionality.
import random def bogosort(l): while not in_order(l): random.shuffle(l) return l def in_order(l): if not l: return True last = l[0] for x in l[1:]: if x < last: return False last = x return True
function bogosort($l) { while (!in_order($l)) shuffle($l); return $l; } function in_order($l) { for ($i = 1; $i < count($l); $i++) if ($l[$i] < $l[$i-1]) return FALSE; return TRUE; }
Preserve the algorithm and functionality while converting the code from Python to PHP.
>>> from math import floor, sqrt >>> def non_square(n): return n + floor(1/2 + sqrt(n)) >>> >>> print(*map(non_square, range(1, 23))) 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 >>> >>> def is_square(n): return sqrt(n).is_integer() >>> non_squares = map(non_square, range(1, 10 ** 6)) >>> next(filter(is_square, non_squares)) StopIteration Traceback (most recent call last) <ipython-input-45-f32645fc1c0a> in <module>() 1 non_squares = map(non_square, range(1, 10 ** 6)) ----> 2 next(filter(is_square, non_squares)) StopIteration:
<?php for($i=1;$i<=22;$i++){ echo($i + floor(1/2 + sqrt($i)) . "\n"); } $found_square=False; for($i=1;$i<=1000000;$i++){ $non_square=$i + floor(1/2 + sqrt($i)); if(sqrt($non_square)==intval(sqrt($non_square))){ $found_square=True; } } echo("\n"); if($found_square){ echo("Found a square number, so the formula does not always work."); } else { echo("Up to 1000000, found no square number in the sequence!"); } ?>
Translate this program into PHP but keep the logic exactly as in Python.
>>> from math import floor, sqrt >>> def non_square(n): return n + floor(1/2 + sqrt(n)) >>> >>> print(*map(non_square, range(1, 23))) 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 >>> >>> def is_square(n): return sqrt(n).is_integer() >>> non_squares = map(non_square, range(1, 10 ** 6)) >>> next(filter(is_square, non_squares)) StopIteration Traceback (most recent call last) <ipython-input-45-f32645fc1c0a> in <module>() 1 non_squares = map(non_square, range(1, 10 ** 6)) ----> 2 next(filter(is_square, non_squares)) StopIteration:
<?php for($i=1;$i<=22;$i++){ echo($i + floor(1/2 + sqrt($i)) . "\n"); } $found_square=False; for($i=1;$i<=1000000;$i++){ $non_square=$i + floor(1/2 + sqrt($i)); if(sqrt($non_square)==intval(sqrt($non_square))){ $found_square=True; } } echo("\n"); if($found_square){ echo("Found a square number, so the formula does not always work."); } else { echo("Up to 1000000, found no square number in the sequence!"); } ?>
Translate the given Python code snippet into PHP without altering its behavior.
>>> from math import floor, sqrt >>> def non_square(n): return n + floor(1/2 + sqrt(n)) >>> >>> print(*map(non_square, range(1, 23))) 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 >>> >>> def is_square(n): return sqrt(n).is_integer() >>> non_squares = map(non_square, range(1, 10 ** 6)) >>> next(filter(is_square, non_squares)) StopIteration Traceback (most recent call last) <ipython-input-45-f32645fc1c0a> in <module>() 1 non_squares = map(non_square, range(1, 10 ** 6)) ----> 2 next(filter(is_square, non_squares)) StopIteration:
<?php for($i=1;$i<=22;$i++){ echo($i + floor(1/2 + sqrt($i)) . "\n"); } $found_square=False; for($i=1;$i<=1000000;$i++){ $non_square=$i + floor(1/2 + sqrt($i)); if(sqrt($non_square)==intval(sqrt($non_square))){ $found_square=True; } } echo("\n"); if($found_square){ echo("Found a square number, so the formula does not always work."); } else { echo("Up to 1000000, found no square number in the sequence!"); } ?>
Can you help me rewrite this code in PHP instead of Python, keeping it the same logically?
>>> s = 'abcdefgh' >>> n, m, char, chars = 2, 3, 'd', 'cd' >>> >>> s[n-1:n+m-1] 'bcd' >>> >>> s[n-1:] 'bcdefgh' >>> >>> s[:-1] 'abcdefg' >>> >>> indx = s.index(char) >>> s[indx:indx+m] 'def' >>> >>> indx = s.index(chars) >>> s[indx:indx+m] 'cde' >>>
<?php $str = 'abcdefgh'; $n = 2; $m = 3; echo substr($str, $n, $m), "\n"; //cde echo substr($str, $n), "\n"; //cdefgh echo substr($str, 0, -1), "\n"; //abcdefg echo substr($str, strpos($str, 'd'), $m), "\n"; //def echo substr($str, strpos($str, 'de'), $m), "\n"; //def ?>
Generate an equivalent PHP version of this Python code.
>>> s = 'abcdefgh' >>> n, m, char, chars = 2, 3, 'd', 'cd' >>> >>> s[n-1:n+m-1] 'bcd' >>> >>> s[n-1:] 'bcdefgh' >>> >>> s[:-1] 'abcdefg' >>> >>> indx = s.index(char) >>> s[indx:indx+m] 'def' >>> >>> indx = s.index(chars) >>> s[indx:indx+m] 'cde' >>>
<?php $str = 'abcdefgh'; $n = 2; $m = 3; echo substr($str, $n, $m), "\n"; //cde echo substr($str, $n), "\n"; //cdefgh echo substr($str, 0, -1), "\n"; //abcdefg echo substr($str, strpos($str, 'd'), $m), "\n"; //def echo substr($str, strpos($str, 'de'), $m), "\n"; //def ?>
Please provide an equivalent version of this Python code in PHP.
>>> s = 'abcdefgh' >>> n, m, char, chars = 2, 3, 'd', 'cd' >>> >>> s[n-1:n+m-1] 'bcd' >>> >>> s[n-1:] 'bcdefgh' >>> >>> s[:-1] 'abcdefg' >>> >>> indx = s.index(char) >>> s[indx:indx+m] 'def' >>> >>> indx = s.index(chars) >>> s[indx:indx+m] 'cde' >>>
<?php $str = 'abcdefgh'; $n = 2; $m = 3; echo substr($str, $n, $m), "\n"; //cde echo substr($str, $n), "\n"; //cdefgh echo substr($str, 0, -1), "\n"; //abcdefg echo substr($str, strpos($str, 'd'), $m), "\n"; //def echo substr($str, strpos($str, 'de'), $m), "\n"; //def ?>
Preserve the algorithm and functionality while converting the code from Python to PHP.
import calendar calendar.isleap(year)
<?php function isLeapYear($year) { if ($year % 100 == 0) { return ($year % 400 == 0); } return ($year % 4 == 0); }
Change the following Python code into PHP without altering its purpose.
import calendar calendar.isleap(year)
<?php function isLeapYear($year) { if ($year % 100 == 0) { return ($year % 400 == 0); } return ($year % 4 == 0); }
Port the provided Python code into PHP while preserving the original functionality.
import calendar calendar.isleap(year)
<?php function isLeapYear($year) { if ($year % 100 == 0) { return ($year % 400 == 0); } return ($year % 4 == 0); }
Convert this Python snippet to PHP and keep its semantics consistent.
TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")] def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num) if __name__ == '__main__': for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): print('%+4i -> %s' % (n, spell_integer(n))) print('') n = 201021002001 while n: print('%-12i -> %s' % (n, spell_integer(n))) n //= -10 print('%-12i -> %s' % (n, spell_integer(n))) print('')
$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,'); $smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'); $decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'); function NumberToEnglish($num, $count = 0){ global $orderOfMag, $smallNumbers, $decades; $isLast = true; $str = ''; if ($num < 0){ $str = 'Negative '; $num = abs($num); } (int) $thisPart = substr((string) $num, -3); if (strlen((string) $num) > 3){ $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1); $isLast = false; } if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative ')) $and = ''; else $and = ' and '; if ($thisPart > 99){ $str .= ($isLast ? '' : ' ') . "{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}"; if(($thisPart %= 100) == 0){ $str .= " {$orderOfMag[$count]}"; return $str; } $and = ' and '; // Set up our and string to the word "and" since there is something in the hundreds place of this chunk } if ($thisPart >= 20){ $str .= "{$and}{$decades[$thisPart /10]}"; $and = ' '; // Make sure we don't have any extranious "and"s if(($thisPart %= 10) == 0) return $str . ($count != 0 ? " {$orderOfMag[$count]}" : ''); } if ($thisPart < 20 && $thisPart > 0) return $str . "{$and}{$smallNumbers[(int) $thisPart]} " . ($count != 0 ? $orderOfMag[$count] : ''); elseif ($thisPart == 0 && strlen($thisPart) == 1) return $str . "{$smallNumbers[(int)$thisPart]}"; }
Rewrite the snippet below in PHP so it works the same as the original Python code.
TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")] def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num) if __name__ == '__main__': for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): print('%+4i -> %s' % (n, spell_integer(n))) print('') n = 201021002001 while n: print('%-12i -> %s' % (n, spell_integer(n))) n //= -10 print('%-12i -> %s' % (n, spell_integer(n))) print('')
$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,'); $smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'); $decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'); function NumberToEnglish($num, $count = 0){ global $orderOfMag, $smallNumbers, $decades; $isLast = true; $str = ''; if ($num < 0){ $str = 'Negative '; $num = abs($num); } (int) $thisPart = substr((string) $num, -3); if (strlen((string) $num) > 3){ $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1); $isLast = false; } if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative ')) $and = ''; else $and = ' and '; if ($thisPart > 99){ $str .= ($isLast ? '' : ' ') . "{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}"; if(($thisPart %= 100) == 0){ $str .= " {$orderOfMag[$count]}"; return $str; } $and = ' and '; // Set up our and string to the word "and" since there is something in the hundreds place of this chunk } if ($thisPart >= 20){ $str .= "{$and}{$decades[$thisPart /10]}"; $and = ' '; // Make sure we don't have any extranious "and"s if(($thisPart %= 10) == 0) return $str . ($count != 0 ? " {$orderOfMag[$count]}" : ''); } if ($thisPart < 20 && $thisPart > 0) return $str . "{$and}{$smallNumbers[(int) $thisPart]} " . ($count != 0 ? $orderOfMag[$count] : ''); elseif ($thisPart == 0 && strlen($thisPart) == 1) return $str . "{$smallNumbers[(int)$thisPart]}"; }
Change the following Python code into PHP without altering its purpose.
TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")] def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num) if __name__ == '__main__': for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): print('%+4i -> %s' % (n, spell_integer(n))) print('') n = 201021002001 while n: print('%-12i -> %s' % (n, spell_integer(n))) n //= -10 print('%-12i -> %s' % (n, spell_integer(n))) print('')
$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,'); $smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'); $decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'); function NumberToEnglish($num, $count = 0){ global $orderOfMag, $smallNumbers, $decades; $isLast = true; $str = ''; if ($num < 0){ $str = 'Negative '; $num = abs($num); } (int) $thisPart = substr((string) $num, -3); if (strlen((string) $num) > 3){ $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1); $isLast = false; } if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative ')) $and = ''; else $and = ' and '; if ($thisPart > 99){ $str .= ($isLast ? '' : ' ') . "{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}"; if(($thisPart %= 100) == 0){ $str .= " {$orderOfMag[$count]}"; return $str; } $and = ' and '; // Set up our and string to the word "and" since there is something in the hundreds place of this chunk } if ($thisPart >= 20){ $str .= "{$and}{$decades[$thisPart /10]}"; $and = ' '; // Make sure we don't have any extranious "and"s if(($thisPart %= 10) == 0) return $str . ($count != 0 ? " {$orderOfMag[$count]}" : ''); } if ($thisPart < 20 && $thisPart > 0) return $str . "{$and}{$smallNumbers[(int) $thisPart]} " . ($count != 0 ? $orderOfMag[$count] : ''); elseif ($thisPart == 0 && strlen($thisPart) == 1) return $str . "{$smallNumbers[(int)$thisPart]}"; }
Convert the following code from Python to PHP, ensuring the logic remains intact.
A = 'I am string' B = 'I am string too' if len(A) > len(B): print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings') print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings') elif len(A) < len(B): print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings') print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings') else: print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string') print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
<?php function retrieveStrings() { if (isset($_POST['input'])) { $strings = explode("\n", $_POST['input']); } else { $strings = ['abcd', '123456789', 'abcdef', '1234567']; } return $strings; } function setInput() { echo join("\n", retrieveStrings()); } function setOutput() { $strings = retrieveStrings(); $strings = array_map('trim', $strings); $strings = array_filter($strings); if (!empty($strings)) { usort($strings, function ($a, $b) { return strlen($b) - strlen($a); }); $max_len = strlen($strings[0]); $min_len = strlen($strings[count($strings) - 1]); foreach ($strings as $s) { $length = strlen($s); if ($length == $max_len) { $predicate = "is the longest string"; } elseif ($length == $min_len) { $predicate = "is the shortest string"; } else { $predicate = "is neither the longest nor the shortest string"; } echo "$s has length $length and $predicate\n"; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <style> div { margin-top: 4ch; margin-bottom: 4ch; } label { display: block; margin-bottom: 1ch; } textarea { display: block; } input { display: block; margin-top: 4ch; margin-bottom: 4ch; } </style> </head> <body> <main> <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8"> <div> <label for="input">Input: </label> <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea> </label> </div> <input type="submit" value="press to compare strings"> </input> <div> <label for="Output">Output: </label> <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea> </div> </form> </main> </body> </html>
Translate the given Python code snippet into PHP without altering its behavior.
A = 'I am string' B = 'I am string too' if len(A) > len(B): print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings') print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings') elif len(A) < len(B): print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings') print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings') else: print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string') print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
<?php function retrieveStrings() { if (isset($_POST['input'])) { $strings = explode("\n", $_POST['input']); } else { $strings = ['abcd', '123456789', 'abcdef', '1234567']; } return $strings; } function setInput() { echo join("\n", retrieveStrings()); } function setOutput() { $strings = retrieveStrings(); $strings = array_map('trim', $strings); $strings = array_filter($strings); if (!empty($strings)) { usort($strings, function ($a, $b) { return strlen($b) - strlen($a); }); $max_len = strlen($strings[0]); $min_len = strlen($strings[count($strings) - 1]); foreach ($strings as $s) { $length = strlen($s); if ($length == $max_len) { $predicate = "is the longest string"; } elseif ($length == $min_len) { $predicate = "is the shortest string"; } else { $predicate = "is neither the longest nor the shortest string"; } echo "$s has length $length and $predicate\n"; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <style> div { margin-top: 4ch; margin-bottom: 4ch; } label { display: block; margin-bottom: 1ch; } textarea { display: block; } input { display: block; margin-top: 4ch; margin-bottom: 4ch; } </style> </head> <body> <main> <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8"> <div> <label for="input">Input: </label> <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea> </label> </div> <input type="submit" value="press to compare strings"> </input> <div> <label for="Output">Output: </label> <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea> </div> </form> </main> </body> </html>
Generate an equivalent PHP version of this Python code.
A = 'I am string' B = 'I am string too' if len(A) > len(B): print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings') print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings') elif len(A) < len(B): print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings') print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings') else: print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string') print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
<?php function retrieveStrings() { if (isset($_POST['input'])) { $strings = explode("\n", $_POST['input']); } else { $strings = ['abcd', '123456789', 'abcdef', '1234567']; } return $strings; } function setInput() { echo join("\n", retrieveStrings()); } function setOutput() { $strings = retrieveStrings(); $strings = array_map('trim', $strings); $strings = array_filter($strings); if (!empty($strings)) { usort($strings, function ($a, $b) { return strlen($b) - strlen($a); }); $max_len = strlen($strings[0]); $min_len = strlen($strings[count($strings) - 1]); foreach ($strings as $s) { $length = strlen($s); if ($length == $max_len) { $predicate = "is the longest string"; } elseif ($length == $min_len) { $predicate = "is the shortest string"; } else { $predicate = "is neither the longest nor the shortest string"; } echo "$s has length $length and $predicate\n"; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <style> div { margin-top: 4ch; margin-bottom: 4ch; } label { display: block; margin-bottom: 1ch; } textarea { display: block; } input { display: block; margin-top: 4ch; margin-bottom: 4ch; } </style> </head> <body> <main> <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8"> <div> <label for="input">Input: </label> <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea> </label> </div> <input type="submit" value="press to compare strings"> </input> <div> <label for="Output">Output: </label> <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea> </div> </form> </main> </body> </html>
Port the following code from Python to PHP with equivalent syntax and logic.
def shell(seq): inc = len(seq) // 2 while inc: for i, el in enumerate(seq[inc:], inc): while i >= inc and seq[i - inc] > el: seq[i] = seq[i - inc] i -= inc seq[i] = el inc = 1 if inc == 2 else inc * 5 // 11
function shellSort($arr) { $inc = round(count($arr)/2); while($inc > 0) { for($i = $inc; $i < count($arr);$i++){ $temp = $arr[$i]; $j = $i; while($j >= $inc && $arr[$j-$inc] > $temp) { $arr[$j] = $arr[$j - $inc]; $j -= $inc; } $arr[$j] = $temp; } $inc = round($inc/2.2); } return $arr; }
Write a version of this Python function in PHP with identical behavior.
def shell(seq): inc = len(seq) // 2 while inc: for i, el in enumerate(seq[inc:], inc): while i >= inc and seq[i - inc] > el: seq[i] = seq[i - inc] i -= inc seq[i] = el inc = 1 if inc == 2 else inc * 5 // 11
function shellSort($arr) { $inc = round(count($arr)/2); while($inc > 0) { for($i = $inc; $i < count($arr);$i++){ $temp = $arr[$i]; $j = $i; while($j >= $inc && $arr[$j-$inc] > $temp) { $arr[$j] = $arr[$j - $inc]; $j -= $inc; } $arr[$j] = $temp; } $inc = round($inc/2.2); } return $arr; }
Maintain the same structure and functionality when rewriting this code in PHP.
def shell(seq): inc = len(seq) // 2 while inc: for i, el in enumerate(seq[inc:], inc): while i >= inc and seq[i - inc] > el: seq[i] = seq[i - inc] i -= inc seq[i] = el inc = 1 if inc == 2 else inc * 5 // 11
function shellSort($arr) { $inc = round(count($arr)/2); while($inc > 0) { for($i = $inc; $i < count($arr);$i++){ $temp = $arr[$i]; $j = $i; while($j >= $inc && $arr[$j-$inc] > $temp) { $arr[$j] = $arr[$j - $inc]; $j -= $inc; } $arr[$j] = $temp; } $inc = round($inc/2.2); } return $arr; }
Keep all operations the same but rewrite the snippet in PHP.
import collections, sys def filecharcount(openfile): return sorted(collections.Counter(c for l in openfile for c in l).items()) f = open(sys.argv[1]) print(filecharcount(f))
<?php print_r(array_count_values(str_split(file_get_contents($argv[1])))); ?>
Translate this program into PHP but keep the logic exactly as in Python.
import collections, sys def filecharcount(openfile): return sorted(collections.Counter(c for l in openfile for c in l).items()) f = open(sys.argv[1]) print(filecharcount(f))
<?php print_r(array_count_values(str_split(file_get_contents($argv[1])))); ?>
Can you help me rewrite this code in PHP instead of Python, keeping it the same logically?
import collections, sys def filecharcount(openfile): return sorted(collections.Counter(c for l in openfile for c in l).items()) f = open(sys.argv[1]) print(filecharcount(f))
<?php print_r(array_count_values(str_split(file_get_contents($argv[1])))); ?>
Produce a functionally identical PHP code for the snippet given in Python.
>>> def stripchars(s, chars): ... return s.translate(None, chars) ... >>> stripchars("She was a soul stripper. She took my heart!", "aei") 'Sh ws soul strppr. Sh took my hrt!'
<?php function stripchars($s, $chars) { return str_replace(str_split($chars), "", $s); } echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n"; ?>
Generate a PHP translation of this Python snippet without changing its computational steps.
>>> def stripchars(s, chars): ... return s.translate(None, chars) ... >>> stripchars("She was a soul stripper. She took my heart!", "aei") 'Sh ws soul strppr. Sh took my hrt!'
<?php function stripchars($s, $chars) { return str_replace(str_split($chars), "", $s); } echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n"; ?>
Keep all operations the same but rewrite the snippet in PHP.
>>> def stripchars(s, chars): ... return s.translate(None, chars) ... >>> stripchars("She was a soul stripper. She took my heart!", "aei") 'Sh ws soul strppr. Sh took my hrt!'
<?php function stripchars($s, $chars) { return str_replace(str_split($chars), "", $s); } echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n"; ?>
Write the same code in PHP as shown below in Python.
from itertools import permutations in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1])) perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
function inOrder($arr){ for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ return false; } } } return true; } function permute($items, $perms = array( )) { if (empty($items)) { if(inOrder($perms)){ return $perms; } } else { for ($i = count($items) - 1; $i >= 0; --$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); $res = permute($newitems, $newperms); if($res){ return $res; } } } } $arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4); $arr = permute($arr); echo implode(',',$arr);
Produce a functionally identical PHP code for the snippet given in Python.
from itertools import permutations in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1])) perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
function inOrder($arr){ for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ return false; } } } return true; } function permute($items, $perms = array( )) { if (empty($items)) { if(inOrder($perms)){ return $perms; } } else { for ($i = count($items) - 1; $i >= 0; --$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); $res = permute($newitems, $newperms); if($res){ return $res; } } } } $arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4); $arr = permute($arr); echo implode(',',$arr);
Change the following Python code into PHP without altering its purpose.
from itertools import permutations in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1])) perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
function inOrder($arr){ for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ return false; } } } return true; } function permute($items, $perms = array( )) { if (empty($items)) { if(inOrder($perms)){ return $perms; } } else { for ($i = count($items) - 1; $i >= 0; --$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); $res = permute($newitems, $newperms); if($res){ return $res; } } } } $arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4); $arr = permute($arr); echo implode(',',$arr);
Keep all operations the same but rewrite the snippet in PHP.
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
Write the same code in PHP as shown below in Python.
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
Ensure the translated PHP code behaves exactly like the original Python snippet.
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
Keep all operations the same but rewrite the snippet in PHP.
from __future__ import division import math def hist(source): hist = {}; l = 0; for e in source: l += 1 if e not in hist: hist[e] = 0 hist[e] += 1 return (l,hist) def entropy(hist,l): elist = [] for v in hist.values(): c = v / l elist.append(-c * math.log(c ,2)) return sum(elist) def printHist(h): flip = lambda (k,v) : (v,k) h = sorted(h.iteritems(), key = flip) print 'Sym\thi\tfi\tInf' for (k,v) in h: print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) source = "1223334444" (l,h) = hist(source); print '.[Results].' print 'Length',l print 'Entropy:', entropy(h, l) printHist(h)
<?php function shannonEntropy($string) { $h = 0.0; $len = strlen($string); foreach (count_chars($string, 1) as $count) { $h -= (double) ($count / $len) * log((double) ($count / $len), 2); } return $h; } $strings = array( '1223334444', '1225554444', 'aaBBcccDDDD', '122333444455555', 'Rosetta Code', '1234567890abcdefghijklmnopqrstuvwxyz', ); foreach ($strings AS $string) { printf( '%36s : %s' . PHP_EOL, $string, number_format(shannonEntropy($string), 6) ); }
Can you help me rewrite this code in PHP instead of Python, keeping it the same logically?
from __future__ import division import math def hist(source): hist = {}; l = 0; for e in source: l += 1 if e not in hist: hist[e] = 0 hist[e] += 1 return (l,hist) def entropy(hist,l): elist = [] for v in hist.values(): c = v / l elist.append(-c * math.log(c ,2)) return sum(elist) def printHist(h): flip = lambda (k,v) : (v,k) h = sorted(h.iteritems(), key = flip) print 'Sym\thi\tfi\tInf' for (k,v) in h: print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) source = "1223334444" (l,h) = hist(source); print '.[Results].' print 'Length',l print 'Entropy:', entropy(h, l) printHist(h)
<?php function shannonEntropy($string) { $h = 0.0; $len = strlen($string); foreach (count_chars($string, 1) as $count) { $h -= (double) ($count / $len) * log((double) ($count / $len), 2); } return $h; } $strings = array( '1223334444', '1225554444', 'aaBBcccDDDD', '122333444455555', 'Rosetta Code', '1234567890abcdefghijklmnopqrstuvwxyz', ); foreach ($strings AS $string) { printf( '%36s : %s' . PHP_EOL, $string, number_format(shannonEntropy($string), 6) ); }
Change the following Python code into PHP without altering its purpose.
from __future__ import division import math def hist(source): hist = {}; l = 0; for e in source: l += 1 if e not in hist: hist[e] = 0 hist[e] += 1 return (l,hist) def entropy(hist,l): elist = [] for v in hist.values(): c = v / l elist.append(-c * math.log(c ,2)) return sum(elist) def printHist(h): flip = lambda (k,v) : (v,k) h = sorted(h.iteritems(), key = flip) print 'Sym\thi\tfi\tInf' for (k,v) in h: print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) source = "1223334444" (l,h) = hist(source); print '.[Results].' print 'Length',l print 'Entropy:', entropy(h, l) printHist(h)
<?php function shannonEntropy($string) { $h = 0.0; $len = strlen($string); foreach (count_chars($string, 1) as $count) { $h -= (double) ($count / $len) * log((double) ($count / $len), 2); } return $h; } $strings = array( '1223334444', '1225554444', 'aaBBcccDDDD', '122333444455555', 'Rosetta Code', '1234567890abcdefghijklmnopqrstuvwxyz', ); foreach ($strings AS $string) { printf( '%36s : %s' . PHP_EOL, $string, number_format(shannonEntropy($string), 6) ); }
Translate the given Python code snippet into PHP without altering its behavior.
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
<?php function forwardDiff($anArray, $times = 1) { if ($times <= 0) { return $anArray; } for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { $accumilation[] = $anArray[$i] - $anArray[$i - 1]; } if ($times === 1) { return $accumilation; } return forwardDiff($accumilation, $times - 1); } class ForwardDiffExample extends PweExample { function _should_run_empty_array_for_single_elem() { $expected = array($this->rand()->int()); $this->spec(forwardDiff($expected))->shouldEqual(array()); } function _should_give_diff_of_two_elem_as_single_elem() { $twoNums = array($this->rand()->int(), $this->rand()->int()); $expected = array($twoNums[1] - $twoNums[0]); $this->spec(forwardDiff($twoNums))->shouldEqual($expected); } function _should_compute_correct_forward_diff_for_longer_arrays() { $diffInput = array(10, 2, 9, 6, 5); $expected = array(-8, 7, -3, -1); $this->spec(forwardDiff($diffInput))->shouldEqual($expected); } function _should_apply_more_than_once_if_specified() { $diffInput = array(4, 6, 9, 3, 4); $expectedAfter1 = array(2, 3, -6, 1); $expectedAfter2 = array(1, -9, 7); $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1); $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2); } function _should_return_array_unaltered_if_no_times() { $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected); } }
Preserve the algorithm and functionality while converting the code from Python to PHP.
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
<?php function forwardDiff($anArray, $times = 1) { if ($times <= 0) { return $anArray; } for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { $accumilation[] = $anArray[$i] - $anArray[$i - 1]; } if ($times === 1) { return $accumilation; } return forwardDiff($accumilation, $times - 1); } class ForwardDiffExample extends PweExample { function _should_run_empty_array_for_single_elem() { $expected = array($this->rand()->int()); $this->spec(forwardDiff($expected))->shouldEqual(array()); } function _should_give_diff_of_two_elem_as_single_elem() { $twoNums = array($this->rand()->int(), $this->rand()->int()); $expected = array($twoNums[1] - $twoNums[0]); $this->spec(forwardDiff($twoNums))->shouldEqual($expected); } function _should_compute_correct_forward_diff_for_longer_arrays() { $diffInput = array(10, 2, 9, 6, 5); $expected = array(-8, 7, -3, -1); $this->spec(forwardDiff($diffInput))->shouldEqual($expected); } function _should_apply_more_than_once_if_specified() { $diffInput = array(4, 6, 9, 3, 4); $expectedAfter1 = array(2, 3, -6, 1); $expectedAfter2 = array(1, -9, 7); $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1); $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2); } function _should_return_array_unaltered_if_no_times() { $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected); } }
Produce a functionally identical PHP code for the snippet given in Python.
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
<?php function forwardDiff($anArray, $times = 1) { if ($times <= 0) { return $anArray; } for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { $accumilation[] = $anArray[$i] - $anArray[$i - 1]; } if ($times === 1) { return $accumilation; } return forwardDiff($accumilation, $times - 1); } class ForwardDiffExample extends PweExample { function _should_run_empty_array_for_single_elem() { $expected = array($this->rand()->int()); $this->spec(forwardDiff($expected))->shouldEqual(array()); } function _should_give_diff_of_two_elem_as_single_elem() { $twoNums = array($this->rand()->int(), $this->rand()->int()); $expected = array($twoNums[1] - $twoNums[0]); $this->spec(forwardDiff($twoNums))->shouldEqual($expected); } function _should_compute_correct_forward_diff_for_longer_arrays() { $diffInput = array(10, 2, 9, 6, 5); $expected = array(-8, 7, -3, -1); $this->spec(forwardDiff($diffInput))->shouldEqual($expected); } function _should_apply_more_than_once_if_specified() { $diffInput = array(4, 6, 9, 3, 4); $expectedAfter1 = array(2, 3, -6, 1); $expectedAfter2 = array(1, -9, 7); $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1); $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2); } function _should_return_array_unaltered_if_no_times() { $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected); } }
Ensure the translated PHP code behaves exactly like the original Python snippet.
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
<?php function prime($a) { if (($a % 2 == 0 && $a != 2) || $a < 2) return false; $limit = sqrt($a); for ($i = 2; $i <= $limit; $i++) if ($a % $i == 0) return false; return true; } foreach (range(1, 100) as $x) if (prime($x)) echo "$x\n"; ?>
Translate this program into PHP but keep the logic exactly as in Python.
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
<?php function prime($a) { if (($a % 2 == 0 && $a != 2) || $a < 2) return false; $limit = sqrt($a); for ($i = 2; $i <= $limit; $i++) if ($a % $i == 0) return false; return true; } foreach (range(1, 100) as $x) if (prime($x)) echo "$x\n"; ?>
Write the same algorithm in PHP as shown in this Python implementation.
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
<?php function prime($a) { if (($a % 2 == 0 && $a != 2) || $a < 2) return false; $limit = sqrt($a); for ($i = 2; $i <= $limit; $i++) if ($a % $i == 0) return false; return true; } foreach (range(1, 100) as $x) if (prime($x)) echo "$x\n"; ?>
Preserve the algorithm and functionality while converting the code from Python to PHP.
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
<?php $n=5; $k=3; function factorial($val){ for($f=2;$val-1>1;$f*=$val--); return $f; } $binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k)); echo $binomial_coefficient; ?>
Can you help me rewrite this code in PHP instead of Python, keeping it the same logically?
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
<?php $n=5; $k=3; function factorial($val){ for($f=2;$val-1>1;$f*=$val--); return $f; } $binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k)); echo $binomial_coefficient; ?>
Write the same code in PHP as shown below in Python.
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
<?php $n=5; $k=3; function factorial($val){ for($f=2;$val-1>1;$f*=$val--); return $f; } $binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k)); echo $binomial_coefficient; ?>
Change the following Python code into PHP without altering its purpose.
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection="some string" x = collection[::-1] collection[::2] == "some string"[::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: "zero", 1: "one"} collection['zero'] = 2 collection = set([0, '1'])
<?php $a = array(); # add elements "at the end" array_push($a, 55, 10, 20); print_r($a); # using an explicit key $a['one'] = 1; $a['two'] = 2; print_r($a); ?>
Rewrite the snippet below in PHP so it works the same as the original Python code.
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection="some string" x = collection[::-1] collection[::2] == "some string"[::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: "zero", 1: "one"} collection['zero'] = 2 collection = set([0, '1'])
<?php $a = array(); # add elements "at the end" array_push($a, 55, 10, 20); print_r($a); # using an explicit key $a['one'] = 1; $a['two'] = 2; print_r($a); ?>
Translate the given Python code snippet into PHP without altering its behavior.
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection="some string" x = collection[::-1] collection[::2] == "some string"[::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: "zero", 1: "one"} collection['zero'] = 2 collection = set([0, '1'])
<?php $a = array(); # add elements "at the end" array_push($a, 55, 10, 20); print_r($a); # using an explicit key $a['one'] = 1; $a['two'] = 2; print_r($a); ?>
Port the following code from Python to PHP with equivalent syntax and logic.
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){ if (is_null($w)) $w = $this->w; if (is_null($h)) $h = $this->h; $w += $x; $h += $y; for ($i = $y; $i < $h; $i++){ for ($j = $x; $j < $w; $j++){ $this->setPixel($j, $i, $color); } } } public function setPixel($x, $y, $color = array(0,0,0)){ if ($x >= $this->w) return false; if ($x < 0) return false; if ($y >= $this->h) return false; if ($y < 0) return false; $this->data[$y][$x] = $color; } public function getPixel($x, $y){ return $this->data[$y][$x]; } public function writeP6($filename){ $fh = fopen($filename, 'w'); if (!$fh) return false; fputs($fh, "P6 {$this->w} {$this->h} 255\n"); foreach ($this->data as $row){ foreach($row as $pixel){ fputs($fh, pack('C', $pixel[0])); fputs($fh, pack('C', $pixel[1])); fputs($fh, pack('C', $pixel[2])); } } fclose($fh); } } $b = new Bitmap(16,16); $b->fill(); $b->fill(2, 2, 18, 18, array(240,240,240)); $b->setPixel(0, 15, array(255,0,0)); $b->writeP6('p6.ppm');
Preserve the algorithm and functionality while converting the code from Python to PHP.
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){ if (is_null($w)) $w = $this->w; if (is_null($h)) $h = $this->h; $w += $x; $h += $y; for ($i = $y; $i < $h; $i++){ for ($j = $x; $j < $w; $j++){ $this->setPixel($j, $i, $color); } } } public function setPixel($x, $y, $color = array(0,0,0)){ if ($x >= $this->w) return false; if ($x < 0) return false; if ($y >= $this->h) return false; if ($y < 0) return false; $this->data[$y][$x] = $color; } public function getPixel($x, $y){ return $this->data[$y][$x]; } public function writeP6($filename){ $fh = fopen($filename, 'w'); if (!$fh) return false; fputs($fh, "P6 {$this->w} {$this->h} 255\n"); foreach ($this->data as $row){ foreach($row as $pixel){ fputs($fh, pack('C', $pixel[0])); fputs($fh, pack('C', $pixel[1])); fputs($fh, pack('C', $pixel[2])); } } fclose($fh); } } $b = new Bitmap(16,16); $b->fill(); $b->fill(2, 2, 18, 18, array(240,240,240)); $b->setPixel(0, 15, array(255,0,0)); $b->writeP6('p6.ppm');
Produce a language-to-language conversion: from Python to PHP, same semantics.
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){ if (is_null($w)) $w = $this->w; if (is_null($h)) $h = $this->h; $w += $x; $h += $y; for ($i = $y; $i < $h; $i++){ for ($j = $x; $j < $w; $j++){ $this->setPixel($j, $i, $color); } } } public function setPixel($x, $y, $color = array(0,0,0)){ if ($x >= $this->w) return false; if ($x < 0) return false; if ($y >= $this->h) return false; if ($y < 0) return false; $this->data[$y][$x] = $color; } public function getPixel($x, $y){ return $this->data[$y][$x]; } public function writeP6($filename){ $fh = fopen($filename, 'w'); if (!$fh) return false; fputs($fh, "P6 {$this->w} {$this->h} 255\n"); foreach ($this->data as $row){ foreach($row as $pixel){ fputs($fh, pack('C', $pixel[0])); fputs($fh, pack('C', $pixel[1])); fputs($fh, pack('C', $pixel[2])); } } fclose($fh); } } $b = new Bitmap(16,16); $b->fill(); $b->fill(2, 2, 18, 18, array(240,240,240)); $b->setPixel(0, 15, array(255,0,0)); $b->writeP6('p6.ppm');
Transform the following Python implementation into PHP, maintaining the same output and logic.
import os os.remove("output.txt") os.rmdir("docs") os.remove("/output.txt") os.rmdir("/docs")
<?php unlink('input.txt'); unlink('/input.txt'); rmdir('docs'); rmdir('/docs'); ?>
Please provide an equivalent version of this Python code in PHP.
import os os.remove("output.txt") os.rmdir("docs") os.remove("/output.txt") os.rmdir("/docs")
<?php unlink('input.txt'); unlink('/input.txt'); rmdir('docs'); rmdir('/docs'); ?>
Change the programming language of this snippet from Python to PHP without modifying what it does.
import os os.remove("output.txt") os.rmdir("docs") os.remove("/output.txt") os.rmdir("/docs")
<?php unlink('input.txt'); unlink('/input.txt'); rmdir('docs'); rmdir('/docs'); ?>
Convert this Python block to PHP, preserving its control flow and logic.
import datetime, calendar DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] def ddate(year, month, day): today = datetime.date(year, month, day) is_leap_year = calendar.isleap(year) if is_leap_year and month == 2 and day == 29: return "St. Tib's Day, YOLD " + (year + 1166) day_of_year = today.timetuple().tm_yday - 1 if is_leap_year and day_of_year >= 60: day_of_year -= 1 season, dday = divmod(day_of_year, 73) return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
<?php $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31); $MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath"); $DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle"); $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th'); $Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay"); $Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux"); $edate = explode(" ",date('Y m j L')); $usery = $edate[0]; $userm = $edate[1]; $userd = $edate[2]; $IsLeap = $edate[3]; if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) { $usery = $_GET['y']; $userm = $_GET['m']; $userd = $_GET['d']; $IsLeap = 0; if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1; if ($usery%400 == 0) $IsLeap = 1; } $userdays = 0; $i = 0; while ($i < ($userm-1)) { $userdays = $userdays + $Anerisia[$i]; $i = $i +1; } $userdays = $userdays + $userd; $IsHolyday = 0; $dyear = $usery + 1166; $dmonth = $MONTHS[$userdays/73.2]; $dday = $userdays%73; if (0 == $dday) $dday = 73; $Dname = $DAYS[$userdays%5]; $Holyday = "St. Tibs Day"; if ($dday == 5) { $Holyday = $Holy5[$userdays/73.2]; $IsHolyday =1; } if ($dday == 50) { $Holyday = $Holy50[$userdays/73.2]; $IsHolyday =1; } if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2; $suff = $Dsuff[$dday%10] ; if ((11 <= $dday) && (19 >= $dday)) $suff='th'; if ($IsHolyday ==2) echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear; if ($IsHolyday ==1) echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday; if ($IsHolyday == 0) echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear; ?>
Keep all operations the same but rewrite the snippet in PHP.
import datetime, calendar DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] def ddate(year, month, day): today = datetime.date(year, month, day) is_leap_year = calendar.isleap(year) if is_leap_year and month == 2 and day == 29: return "St. Tib's Day, YOLD " + (year + 1166) day_of_year = today.timetuple().tm_yday - 1 if is_leap_year and day_of_year >= 60: day_of_year -= 1 season, dday = divmod(day_of_year, 73) return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
<?php $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31); $MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath"); $DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle"); $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th'); $Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay"); $Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux"); $edate = explode(" ",date('Y m j L')); $usery = $edate[0]; $userm = $edate[1]; $userd = $edate[2]; $IsLeap = $edate[3]; if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) { $usery = $_GET['y']; $userm = $_GET['m']; $userd = $_GET['d']; $IsLeap = 0; if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1; if ($usery%400 == 0) $IsLeap = 1; } $userdays = 0; $i = 0; while ($i < ($userm-1)) { $userdays = $userdays + $Anerisia[$i]; $i = $i +1; } $userdays = $userdays + $userd; $IsHolyday = 0; $dyear = $usery + 1166; $dmonth = $MONTHS[$userdays/73.2]; $dday = $userdays%73; if (0 == $dday) $dday = 73; $Dname = $DAYS[$userdays%5]; $Holyday = "St. Tibs Day"; if ($dday == 5) { $Holyday = $Holy5[$userdays/73.2]; $IsHolyday =1; } if ($dday == 50) { $Holyday = $Holy50[$userdays/73.2]; $IsHolyday =1; } if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2; $suff = $Dsuff[$dday%10] ; if ((11 <= $dday) && (19 >= $dday)) $suff='th'; if ($IsHolyday ==2) echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear; if ($IsHolyday ==1) echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday; if ($IsHolyday == 0) echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear; ?>
Keep all operations the same but rewrite the snippet in PHP.
import datetime, calendar DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] def ddate(year, month, day): today = datetime.date(year, month, day) is_leap_year = calendar.isleap(year) if is_leap_year and month == 2 and day == 29: return "St. Tib's Day, YOLD " + (year + 1166) day_of_year = today.timetuple().tm_yday - 1 if is_leap_year and day_of_year >= 60: day_of_year -= 1 season, dday = divmod(day_of_year, 73) return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
<?php $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31); $MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath"); $DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle"); $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th'); $Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay"); $Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux"); $edate = explode(" ",date('Y m j L')); $usery = $edate[0]; $userm = $edate[1]; $userd = $edate[2]; $IsLeap = $edate[3]; if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) { $usery = $_GET['y']; $userm = $_GET['m']; $userd = $_GET['d']; $IsLeap = 0; if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1; if ($usery%400 == 0) $IsLeap = 1; } $userdays = 0; $i = 0; while ($i < ($userm-1)) { $userdays = $userdays + $Anerisia[$i]; $i = $i +1; } $userdays = $userdays + $userd; $IsHolyday = 0; $dyear = $usery + 1166; $dmonth = $MONTHS[$userdays/73.2]; $dday = $userdays%73; if (0 == $dday) $dday = 73; $Dname = $DAYS[$userdays%5]; $Holyday = "St. Tibs Day"; if ($dday == 5) { $Holyday = $Holy5[$userdays/73.2]; $IsHolyday =1; } if ($dday == 50) { $Holyday = $Holy50[$userdays/73.2]; $IsHolyday =1; } if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2; $suff = $Dsuff[$dday%10] ; if ((11 <= $dday) && (19 >= $dday)) $suff='th'; if ($IsHolyday ==2) echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear; if ($IsHolyday ==1) echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday; if ($IsHolyday == 0) echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear; ?>
Convert this Python snippet to PHP and keep its semantics consistent.
>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'
<?php $extra = 'little'; echo "Mary had a $extra lamb.\n"; printf("Mary had a %s lamb.\n", $extra); ?>
Transform the following Python implementation into PHP, maintaining the same output and logic.
>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'
<?php $extra = 'little'; echo "Mary had a $extra lamb.\n"; printf("Mary had a %s lamb.\n", $extra); ?>
Convert this Python snippet to PHP and keep its semantics consistent.
>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'
<?php $extra = 'little'; echo "Mary had a $extra lamb.\n"; printf("Mary had a %s lamb.\n", $extra); ?>
Preserve the algorithm and functionality while converting the code from Python to PHP.
from functools import total_ordering from bisect import bisect_left from heapq import merge @total_ordering class Pile(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(n): piles = [] for x in n: new_pile = Pile([x]) i = bisect_left(piles, new_pile) if i != len(piles): piles[i].append(x) else: piles.append(new_pile) n[:] = merge(*[reversed(pile) for pile in piles]) if __name__ == "__main__": a = [4, 65, 2, -31, 0, 99, 83, 782, 1] patience_sort(a) print a
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } } function patience_sort(&$n) { $piles = array(); foreach ($n as $x) { $low = 0; $high = count($piles)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($piles[$mid]->top() >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; if ($i == count($piles)) $piles[] = new SplStack(); $piles[$i]->push($x); } $heap = new PilesHeap(); foreach ($piles as $pile) $heap->insert($pile); for ($c = 0; $c < count($n); $c++) { $smallPile = $heap->extract(); $n[$c] = $smallPile->pop(); if (!$smallPile->isEmpty()) $heap->insert($smallPile); } assert($heap->isEmpty()); } $a = array(4, 65, 2, -31, 0, 99, 83, 782, 1); patience_sort($a); print_r($a); ?>
Generate a PHP translation of this Python snippet without changing its computational steps.
from functools import total_ordering from bisect import bisect_left from heapq import merge @total_ordering class Pile(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(n): piles = [] for x in n: new_pile = Pile([x]) i = bisect_left(piles, new_pile) if i != len(piles): piles[i].append(x) else: piles.append(new_pile) n[:] = merge(*[reversed(pile) for pile in piles]) if __name__ == "__main__": a = [4, 65, 2, -31, 0, 99, 83, 782, 1] patience_sort(a) print a
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } } function patience_sort(&$n) { $piles = array(); foreach ($n as $x) { $low = 0; $high = count($piles)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($piles[$mid]->top() >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; if ($i == count($piles)) $piles[] = new SplStack(); $piles[$i]->push($x); } $heap = new PilesHeap(); foreach ($piles as $pile) $heap->insert($pile); for ($c = 0; $c < count($n); $c++) { $smallPile = $heap->extract(); $n[$c] = $smallPile->pop(); if (!$smallPile->isEmpty()) $heap->insert($smallPile); } assert($heap->isEmpty()); } $a = array(4, 65, 2, -31, 0, 99, 83, 782, 1); patience_sort($a); print_r($a); ?>
Port the provided Python code into PHP while preserving the original functionality.
from functools import total_ordering from bisect import bisect_left from heapq import merge @total_ordering class Pile(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(n): piles = [] for x in n: new_pile = Pile([x]) i = bisect_left(piles, new_pile) if i != len(piles): piles[i].append(x) else: piles.append(new_pile) n[:] = merge(*[reversed(pile) for pile in piles]) if __name__ == "__main__": a = [4, 65, 2, -31, 0, 99, 83, 782, 1] patience_sort(a) print a
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } } function patience_sort(&$n) { $piles = array(); foreach ($n as $x) { $low = 0; $high = count($piles)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($piles[$mid]->top() >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; if ($i == count($piles)) $piles[] = new SplStack(); $piles[$i]->push($x); } $heap = new PilesHeap(); foreach ($piles as $pile) $heap->insert($pile); for ($c = 0; $c < count($n); $c++) { $smallPile = $heap->extract(); $n[$c] = $smallPile->pop(); if (!$smallPile->isEmpty()) $heap->insert($smallPile); } assert($heap->isEmpty()); } $a = array(4, 65, 2, -31, 0, 99, 83, 782, 1); patience_sort($a); print_r($a); ?>
Port the following code from Python to PHP with equivalent syntax and logic.
from io import StringIO from collections import namedtuple from pprint import pprint as pp import copy WW = namedtuple('WW', 'world, w, h') head, tail, conductor, empty = allstates = 'Ht. ' infile = StringIO() def readfile(f): world = [row.rstrip('\r\n') for row in f] height = len(world) width = max(len(row) for row in world) nonrow = [ " %*s " % (-width, "") ] world = nonrow + \ [ " %*s " % (-width, row) for row in world ] + \ nonrow world = [list(row) for row in world] return WW(world, width, height) def newcell(currentworld, x, y): istate = currentworld[y][x] assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate if istate == head: ostate = tail elif istate == tail: ostate = conductor elif istate == empty: ostate = empty else: n = sum( currentworld[y+dy][x+dx] == head for dx,dy in ( (-1,-1), (-1,+0), (-1,+1), (+0,-1), (+0,+1), (+1,-1), (+1,+0), (+1,+1) ) ) ostate = head if 1 <= n <= 2 else conductor return ostate def nextgen(ww): 'compute next generation of wireworld' world, width, height = ww newworld = copy.deepcopy(world) for x in range(1, width+1): for y in range(1, height+1): newworld[y][x] = newcell(world, x, y) return WW(newworld, width, height) def world2string(ww): return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] ) ww = readfile(infile) infile.close() for gen in range(10): print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' ) print ( world2string(ww) ) ww = nextgen(ww)
$desc = 'tH......... . . ........ . . Ht.. ...... .. tH.... ....... .. .. tH..... ...... ..'; $steps = 30; $world = array(array()); $row = 0; $col = 0; foreach(str_split($desc) as $i){ switch($i){ case "\n": $row++; $col = 0; $world[] = array(); break; case '.': $world[$row][$col] = 1;//conductor $col++; break; case 'H': $world[$row][$col] = 2;//head $col++; break; case 't': $world[$row][$col] = 3;//tail $col++; break; default: $world[$row][$col] = 0;//insulator/air $col++; break; }; }; function draw_world($world){ foreach($world as $rowc){ foreach($rowc as $cell){ switch($cell){ case 0: echo ' '; break; case 1: echo '.'; break; case 2: echo 'H'; break; case 3: echo 't'; }; }; echo "\n"; }; }; echo "Original world:\n"; draw_world($world); for($i = 0; $i < $steps; $i++){ $old_world = $world; //backup to look up where was an electron head foreach($world as $row => &$rowc){ foreach($rowc as $col => &$cell){ switch($cell){ case 2: $cell = 3; break; case 3: $cell = 1; break; case 1: $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col] == 2; if($neigh_heads == 1 || $neigh_heads == 2){ $cell = 2; }; }; }; unset($cell); //just to be safe }; unset($rowc); //just to be safe echo "\nStep " . ($i + 1) . ":\n"; draw_world($world); };
Rewrite the snippet below in PHP so it works the same as the original Python code.
from io import StringIO from collections import namedtuple from pprint import pprint as pp import copy WW = namedtuple('WW', 'world, w, h') head, tail, conductor, empty = allstates = 'Ht. ' infile = StringIO() def readfile(f): world = [row.rstrip('\r\n') for row in f] height = len(world) width = max(len(row) for row in world) nonrow = [ " %*s " % (-width, "") ] world = nonrow + \ [ " %*s " % (-width, row) for row in world ] + \ nonrow world = [list(row) for row in world] return WW(world, width, height) def newcell(currentworld, x, y): istate = currentworld[y][x] assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate if istate == head: ostate = tail elif istate == tail: ostate = conductor elif istate == empty: ostate = empty else: n = sum( currentworld[y+dy][x+dx] == head for dx,dy in ( (-1,-1), (-1,+0), (-1,+1), (+0,-1), (+0,+1), (+1,-1), (+1,+0), (+1,+1) ) ) ostate = head if 1 <= n <= 2 else conductor return ostate def nextgen(ww): 'compute next generation of wireworld' world, width, height = ww newworld = copy.deepcopy(world) for x in range(1, width+1): for y in range(1, height+1): newworld[y][x] = newcell(world, x, y) return WW(newworld, width, height) def world2string(ww): return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] ) ww = readfile(infile) infile.close() for gen in range(10): print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' ) print ( world2string(ww) ) ww = nextgen(ww)
$desc = 'tH......... . . ........ . . Ht.. ...... .. tH.... ....... .. .. tH..... ...... ..'; $steps = 30; $world = array(array()); $row = 0; $col = 0; foreach(str_split($desc) as $i){ switch($i){ case "\n": $row++; $col = 0; $world[] = array(); break; case '.': $world[$row][$col] = 1;//conductor $col++; break; case 'H': $world[$row][$col] = 2;//head $col++; break; case 't': $world[$row][$col] = 3;//tail $col++; break; default: $world[$row][$col] = 0;//insulator/air $col++; break; }; }; function draw_world($world){ foreach($world as $rowc){ foreach($rowc as $cell){ switch($cell){ case 0: echo ' '; break; case 1: echo '.'; break; case 2: echo 'H'; break; case 3: echo 't'; }; }; echo "\n"; }; }; echo "Original world:\n"; draw_world($world); for($i = 0; $i < $steps; $i++){ $old_world = $world; //backup to look up where was an electron head foreach($world as $row => &$rowc){ foreach($rowc as $col => &$cell){ switch($cell){ case 2: $cell = 3; break; case 3: $cell = 1; break; case 1: $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col] == 2; if($neigh_heads == 1 || $neigh_heads == 2){ $cell = 2; }; }; }; unset($cell); //just to be safe }; unset($rowc); //just to be safe echo "\nStep " . ($i + 1) . ":\n"; draw_world($world); };
Rewrite this program in PHP while keeping its functionality equivalent to the Python version.
from io import StringIO from collections import namedtuple from pprint import pprint as pp import copy WW = namedtuple('WW', 'world, w, h') head, tail, conductor, empty = allstates = 'Ht. ' infile = StringIO() def readfile(f): world = [row.rstrip('\r\n') for row in f] height = len(world) width = max(len(row) for row in world) nonrow = [ " %*s " % (-width, "") ] world = nonrow + \ [ " %*s " % (-width, row) for row in world ] + \ nonrow world = [list(row) for row in world] return WW(world, width, height) def newcell(currentworld, x, y): istate = currentworld[y][x] assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate if istate == head: ostate = tail elif istate == tail: ostate = conductor elif istate == empty: ostate = empty else: n = sum( currentworld[y+dy][x+dx] == head for dx,dy in ( (-1,-1), (-1,+0), (-1,+1), (+0,-1), (+0,+1), (+1,-1), (+1,+0), (+1,+1) ) ) ostate = head if 1 <= n <= 2 else conductor return ostate def nextgen(ww): 'compute next generation of wireworld' world, width, height = ww newworld = copy.deepcopy(world) for x in range(1, width+1): for y in range(1, height+1): newworld[y][x] = newcell(world, x, y) return WW(newworld, width, height) def world2string(ww): return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] ) ww = readfile(infile) infile.close() for gen in range(10): print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' ) print ( world2string(ww) ) ww = nextgen(ww)
$desc = 'tH......... . . ........ . . Ht.. ...... .. tH.... ....... .. .. tH..... ...... ..'; $steps = 30; $world = array(array()); $row = 0; $col = 0; foreach(str_split($desc) as $i){ switch($i){ case "\n": $row++; $col = 0; $world[] = array(); break; case '.': $world[$row][$col] = 1;//conductor $col++; break; case 'H': $world[$row][$col] = 2;//head $col++; break; case 't': $world[$row][$col] = 3;//tail $col++; break; default: $world[$row][$col] = 0;//insulator/air $col++; break; }; }; function draw_world($world){ foreach($world as $rowc){ foreach($rowc as $cell){ switch($cell){ case 0: echo ' '; break; case 1: echo '.'; break; case 2: echo 'H'; break; case 3: echo 't'; }; }; echo "\n"; }; }; echo "Original world:\n"; draw_world($world); for($i = 0; $i < $steps; $i++){ $old_world = $world; //backup to look up where was an electron head foreach($world as $row => &$rowc){ foreach($rowc as $col => &$cell){ switch($cell){ case 2: $cell = 3; break; case 3: $cell = 1; break; case 1: $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col] == 2; if($neigh_heads == 1 || $neigh_heads == 2){ $cell = 2; }; }; }; unset($cell); //just to be safe }; unset($rowc); //just to be safe echo "\nStep " . ($i + 1) . ":\n"; draw_world($world); };
Convert this Python block to PHP, preserving its control flow and logic.
from collections import namedtuple from pprint import pprint as pp import sys Pt = namedtuple('Pt', 'x, y') Edge = namedtuple('Edge', 'a, b') Poly = namedtuple('Poly', 'name, edges') _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_info.min def rayintersectseg(p, edge): a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect def _odd(x): return x%2 == 1 def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges )) def polypp(poly): print ("\n Polygon(name='%s', edges=(" % poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[6:]))
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return $count % 2; } function west($A, $B, $x, $y) { if ($A['y'] <= $B['y']) { if ($y <= $A['y'] || $y > $B['y'] || $x >= $A['x'] && $x >= $B['x']) { return false; } if ($x < $A['x'] && $x < $B['x']) { return true; } if ($x == $A['x']) { if ($y == $A['y']) { $result1 = NAN; } else { $result1 = INF; } } else { $result1 = ($y - $A['y']) / ($x - $A['x']); } if ($B['x'] == $A['x']) { if ($B['y'] == $A['y']) { $result2 = NAN; } else { $result2 = INF; } } else { $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']); } return $result1 > $result2; } return west($B, $A, $x, $y); } $square = [ 'name' => 'square', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]] ]; $squareHole = [ 'name' => 'squareHole', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]] ]; $strange = [ 'name' => 'strange', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]] ]; $hexagon = [ 'name' => 'hexagon', 'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]] ]; $shapes = [$square, $squareHole, $strange, $hexagon]; $testPoints = [ ['lng' => 10, 'lat' => 10], ['lng' => 10, 'lat' => 16], ['lng' => -20, 'lat' => 10], ['lng' => 0, 'lat' => 10], ['lng' => 20, 'lat' => 10], ['lng' => 16, 'lat' => 10], ['lng' => 20, 'lat' => 20] ]; for ($s = 0; $s < count($shapes); $s++) { $shape = $shapes[$s]; for ($tp = 0; $tp < count($testPoints); $tp++) { $testPoint = $testPoints[$tp]; echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL; } }
Keep all operations the same but rewrite the snippet in PHP.
from collections import namedtuple from pprint import pprint as pp import sys Pt = namedtuple('Pt', 'x, y') Edge = namedtuple('Edge', 'a, b') Poly = namedtuple('Poly', 'name, edges') _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_info.min def rayintersectseg(p, edge): a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect def _odd(x): return x%2 == 1 def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges )) def polypp(poly): print ("\n Polygon(name='%s', edges=(" % poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[6:]))
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return $count % 2; } function west($A, $B, $x, $y) { if ($A['y'] <= $B['y']) { if ($y <= $A['y'] || $y > $B['y'] || $x >= $A['x'] && $x >= $B['x']) { return false; } if ($x < $A['x'] && $x < $B['x']) { return true; } if ($x == $A['x']) { if ($y == $A['y']) { $result1 = NAN; } else { $result1 = INF; } } else { $result1 = ($y - $A['y']) / ($x - $A['x']); } if ($B['x'] == $A['x']) { if ($B['y'] == $A['y']) { $result2 = NAN; } else { $result2 = INF; } } else { $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']); } return $result1 > $result2; } return west($B, $A, $x, $y); } $square = [ 'name' => 'square', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]] ]; $squareHole = [ 'name' => 'squareHole', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]] ]; $strange = [ 'name' => 'strange', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]] ]; $hexagon = [ 'name' => 'hexagon', 'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]] ]; $shapes = [$square, $squareHole, $strange, $hexagon]; $testPoints = [ ['lng' => 10, 'lat' => 10], ['lng' => 10, 'lat' => 16], ['lng' => -20, 'lat' => 10], ['lng' => 0, 'lat' => 10], ['lng' => 20, 'lat' => 10], ['lng' => 16, 'lat' => 10], ['lng' => 20, 'lat' => 20] ]; for ($s = 0; $s < count($shapes); $s++) { $shape = $shapes[$s]; for ($tp = 0; $tp < count($testPoints); $tp++) { $testPoint = $testPoints[$tp]; echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL; } }
Rewrite this program in PHP while keeping its functionality equivalent to the Python version.
from collections import namedtuple from pprint import pprint as pp import sys Pt = namedtuple('Pt', 'x, y') Edge = namedtuple('Edge', 'a, b') Poly = namedtuple('Poly', 'name, edges') _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_info.min def rayintersectseg(p, edge): a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect def _odd(x): return x%2 == 1 def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges )) def polypp(poly): print ("\n Polygon(name='%s', edges=(" % poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[6:]))
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return $count % 2; } function west($A, $B, $x, $y) { if ($A['y'] <= $B['y']) { if ($y <= $A['y'] || $y > $B['y'] || $x >= $A['x'] && $x >= $B['x']) { return false; } if ($x < $A['x'] && $x < $B['x']) { return true; } if ($x == $A['x']) { if ($y == $A['y']) { $result1 = NAN; } else { $result1 = INF; } } else { $result1 = ($y - $A['y']) / ($x - $A['x']); } if ($B['x'] == $A['x']) { if ($B['y'] == $A['y']) { $result2 = NAN; } else { $result2 = INF; } } else { $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']); } return $result1 > $result2; } return west($B, $A, $x, $y); } $square = [ 'name' => 'square', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]] ]; $squareHole = [ 'name' => 'squareHole', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]] ]; $strange = [ 'name' => 'strange', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]] ]; $hexagon = [ 'name' => 'hexagon', 'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]] ]; $shapes = [$square, $squareHole, $strange, $hexagon]; $testPoints = [ ['lng' => 10, 'lat' => 10], ['lng' => 10, 'lat' => 16], ['lng' => -20, 'lat' => 10], ['lng' => 0, 'lat' => 10], ['lng' => 20, 'lat' => 10], ['lng' => 16, 'lat' => 10], ['lng' => 20, 'lat' => 20] ]; for ($s = 0; $s < count($shapes); $s++) { $shape = $shapes[$s]; for ($tp = 0; $tp < count($testPoints); $tp++) { $testPoint = $testPoints[$tp]; echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL; } }
Produce a language-to-language conversion: from Python to PHP, same semantics.
>>> "the three truths".count("th") 3 >>> "ababababab".count("abab") 2
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
Write a version of this Python function in PHP with identical behavior.
>>> "the three truths".count("th") 3 >>> "ababababab".count("abab") 2
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"