Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Convert this PHP block to Python, preserving its control flow and logic. | <?php
function meaning_of_life() {
return 42;
}
function main($args) {
echo "Main: The meaning of life is " . meaning_of_life() . "\n";
}
if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) {
main($argv);
}
?>
|
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
|
Convert the following code from PHP to Python, ensuring the logic remains intact. | <?php
function meaning_of_life() {
return 42;
}
function main($args) {
echo "Main: The meaning of life is " . meaning_of_life() . "\n";
}
if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) {
main($argv);
}
?>
|
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
|
Please provide an equivalent version of this PHP code in Python. | <?php
foreach(scandir('.') as $fileName){
echo $fileName."\n";
}
| >>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
|
Please provide an equivalent version of this PHP code in Python. | <?php
foreach(scandir('.') as $fileName){
echo $fileName."\n";
}
| >>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
|
Convert this PHP block to Python, preserving its control flow and logic. | <?php
foreach(scandir('.') as $fileName){
echo $fileName."\n";
}
| >>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
|
Generate an equivalent Python version of this PHP code. | <?php
function symbolTable() {
$symbol = array();
for ($c = ord('a') ; $c <= ord('z') ; $c++) {
$symbol[$c - ord('a')] = chr($c);
}
return $symbol;
}
function mtfEncode($original, $symbol) {
$encoded = array();
for ($i = 0 ; $i < strlen($original) ; $i++) {
$char = $original[$i];
$position = array_search($char, $symbol);
$encoded[] = $position;
$mtf = $symbol[$position];
unset($symbol[$position]);
array_unshift($symbol, $mtf);
}
return $encoded;
}
function mtfDecode($encoded, $symbol) {
$decoded = '';
foreach ($encoded AS $position) {
$char = $symbol[$position];
$decoded .= $char;
unset($symbol[$position]);
array_unshift($symbol, $char);
}
return $decoded;
}
foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {
$encoded = mtfEncode($original, symbolTable());
$decoded = mtfDecode($encoded, symbolTable());
echo
$original,
' -> [', implode(',', $encoded), ']',
' -> ', $decoded,
' : ', ($original === $decoded ? 'OK' : 'Error'),
PHP_EOL;
}
| from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(chars)
if __name__ == '__main__':
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = move2front_encode(s, SYMBOLTABLE)
print('%14r encodes to %r' % (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
assert s == decode, 'Whoops!'
|
Rewrite this program in Python while keeping its functionality equivalent to the PHP version. | <?php
function symbolTable() {
$symbol = array();
for ($c = ord('a') ; $c <= ord('z') ; $c++) {
$symbol[$c - ord('a')] = chr($c);
}
return $symbol;
}
function mtfEncode($original, $symbol) {
$encoded = array();
for ($i = 0 ; $i < strlen($original) ; $i++) {
$char = $original[$i];
$position = array_search($char, $symbol);
$encoded[] = $position;
$mtf = $symbol[$position];
unset($symbol[$position]);
array_unshift($symbol, $mtf);
}
return $encoded;
}
function mtfDecode($encoded, $symbol) {
$decoded = '';
foreach ($encoded AS $position) {
$char = $symbol[$position];
$decoded .= $char;
unset($symbol[$position]);
array_unshift($symbol, $char);
}
return $decoded;
}
foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {
$encoded = mtfEncode($original, symbolTable());
$decoded = mtfDecode($encoded, symbolTable());
echo
$original,
' -> [', implode(',', $encoded), ']',
' -> ', $decoded,
' : ', ($original === $decoded ? 'OK' : 'Error'),
PHP_EOL;
}
| from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(chars)
if __name__ == '__main__':
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = move2front_encode(s, SYMBOLTABLE)
print('%14r encodes to %r' % (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
assert s == decode, 'Whoops!'
|
Can you help me rewrite this code in Python instead of PHP, keeping it the same logically? | <?php
function symbolTable() {
$symbol = array();
for ($c = ord('a') ; $c <= ord('z') ; $c++) {
$symbol[$c - ord('a')] = chr($c);
}
return $symbol;
}
function mtfEncode($original, $symbol) {
$encoded = array();
for ($i = 0 ; $i < strlen($original) ; $i++) {
$char = $original[$i];
$position = array_search($char, $symbol);
$encoded[] = $position;
$mtf = $symbol[$position];
unset($symbol[$position]);
array_unshift($symbol, $mtf);
}
return $encoded;
}
function mtfDecode($encoded, $symbol) {
$decoded = '';
foreach ($encoded AS $position) {
$char = $symbol[$position];
$decoded .= $char;
unset($symbol[$position]);
array_unshift($symbol, $char);
}
return $decoded;
}
foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {
$encoded = mtfEncode($original, symbolTable());
$decoded = mtfDecode($encoded, symbolTable());
echo
$original,
' -> [', implode(',', $encoded), ']',
' -> ', $decoded,
' : ', ($original === $decoded ? 'OK' : 'Error'),
PHP_EOL;
}
| from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(chars)
if __name__ == '__main__':
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = move2front_encode(s, SYMBOLTABLE)
print('%14r encodes to %r' % (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
assert s == decode, 'Whoops!'
|
Convert this PHP block to Python, preserving its control flow and logic. | <?php
$l = ldap_connect('ldap.example.com');
ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($l, LDAP_OPT_REFERRALS, false);
$bind = ldap_bind($l, 'me@example.com', 'password');
$base = 'dc=example, dc=com';
$criteria = '(&(objectClass=user)(sAMAccountName=username))';
$attributes = array('displayName', 'company');
$search = ldap_search($l, $base, $criteria, $attributes);
$entries = ldap_get_entries($l, $search);
var_dump($entries);
| Import-Module ActiveDirectory
$searchData = "user name"
$searchBase = "DC=example,DC=com"
get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
|
Write a version of this PHP function in Python with identical behavior. | <?php
$l = ldap_connect('ldap.example.com');
ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($l, LDAP_OPT_REFERRALS, false);
$bind = ldap_bind($l, 'me@example.com', 'password');
$base = 'dc=example, dc=com';
$criteria = '(&(objectClass=user)(sAMAccountName=username))';
$attributes = array('displayName', 'company');
$search = ldap_search($l, $base, $criteria, $attributes);
$entries = ldap_get_entries($l, $search);
var_dump($entries);
| Import-Module ActiveDirectory
$searchData = "user name"
$searchBase = "DC=example,DC=com"
get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
|
Generate an equivalent Python version of this PHP code. | <?php
$l = ldap_connect('ldap.example.com');
ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($l, LDAP_OPT_REFERRALS, false);
$bind = ldap_bind($l, 'me@example.com', 'password');
$base = 'dc=example, dc=com';
$criteria = '(&(objectClass=user)(sAMAccountName=username))';
$attributes = array('displayName', 'company');
$search = ldap_search($l, $base, $criteria, $attributes);
$entries = ldap_get_entries($l, $search);
var_dump($entries);
| Import-Module ActiveDirectory
$searchData = "user name"
$searchBase = "DC=example,DC=com"
get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
|
Write the same algorithm in Python as shown in this PHP implementation. | @exec($command,$output);
echo nl2br($output);
| import os
exit_code = os.system('ls')
output = os.popen('ls').read()
|
Keep all operations the same but rewrite the snippet in Python. | @exec($command,$output);
echo nl2br($output);
| import os
exit_code = os.system('ls')
output = os.popen('ls').read()
|
Produce a functionally identical Python code for the snippet given in PHP. | @exec($command,$output);
echo nl2br($output);
| import os
exit_code = os.system('ls')
output = os.popen('ls').read()
|
Rewrite the snippet below in Python so it works the same as the original PHP code. | libxml_use_internal_errors(true);
$xml = new DOMDocument();
$xml->load('shiporder.xml');
if (!$xml->schemaValidate('shiporder.xsd')) {
var_dump(libxml_get_errors()); exit;
} else {
echo 'success';
}
|
from __future__ import print_function
import lxml
from lxml import etree
if __name__=="__main__":
parser = etree.XMLParser(dtd_validation=True)
schema_root = etree.XML()
schema = etree.XMLSchema(schema_root)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5</a>", parser)
print ("Finished validating good xml")
except lxml.etree.XMLSyntaxError as err:
print (err)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5<b>foobar</b></a>", parser)
except lxml.etree.XMLSyntaxError as err:
print (err)
|
Translate this program into Python but keep the logic exactly as in PHP. | libxml_use_internal_errors(true);
$xml = new DOMDocument();
$xml->load('shiporder.xml');
if (!$xml->schemaValidate('shiporder.xsd')) {
var_dump(libxml_get_errors()); exit;
} else {
echo 'success';
}
|
from __future__ import print_function
import lxml
from lxml import etree
if __name__=="__main__":
parser = etree.XMLParser(dtd_validation=True)
schema_root = etree.XML()
schema = etree.XMLSchema(schema_root)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5</a>", parser)
print ("Finished validating good xml")
except lxml.etree.XMLSyntaxError as err:
print (err)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5<b>foobar</b></a>", parser)
except lxml.etree.XMLSyntaxError as err:
print (err)
|
Keep all operations the same but rewrite the snippet in Python. | libxml_use_internal_errors(true);
$xml = new DOMDocument();
$xml->load('shiporder.xml');
if (!$xml->schemaValidate('shiporder.xsd')) {
var_dump(libxml_get_errors()); exit;
} else {
echo 'success';
}
|
from __future__ import print_function
import lxml
from lxml import etree
if __name__=="__main__":
parser = etree.XMLParser(dtd_validation=True)
schema_root = etree.XML()
schema = etree.XMLSchema(schema_root)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5</a>", parser)
print ("Finished validating good xml")
except lxml.etree.XMLSyntaxError as err:
print (err)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5<b>foobar</b></a>", parser)
except lxml.etree.XMLSyntaxError as err:
print (err)
|
Transform the following PHP implementation into Python, maintaining the same output and logic. | <?php
class Node {
public $val;
public $back = NULL;
}
function lis($n) {
$pileTops = array();
foreach ($n as $x) {
$low = 0; $high = count($pileTops)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($pileTops[$mid]->val >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
$node = new Node();
$node->val = $x;
if ($i != 0)
$node->back = $pileTops[$i-1];
$pileTops[$i] = $node;
}
$result = array();
for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;
$node != NULL; $node = $node->back)
$result[] = $node->val;
return array_reverse($result);
}
print_r(lis(array(3, 2, 6, 4, 5, 1)));
print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));
?>
| def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if (newL > L):
L = newL
S = []
k = M[L]
for i in range(L-1, -1, -1):
S.append(X[k])
k = P[k]
return S[::-1]
if __name__ == '__main__':
for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
|
Produce a language-to-language conversion: from PHP to Python, same semantics. | <?php
class Node {
public $val;
public $back = NULL;
}
function lis($n) {
$pileTops = array();
foreach ($n as $x) {
$low = 0; $high = count($pileTops)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($pileTops[$mid]->val >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
$node = new Node();
$node->val = $x;
if ($i != 0)
$node->back = $pileTops[$i-1];
$pileTops[$i] = $node;
}
$result = array();
for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;
$node != NULL; $node = $node->back)
$result[] = $node->val;
return array_reverse($result);
}
print_r(lis(array(3, 2, 6, 4, 5, 1)));
print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));
?>
| def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if (newL > L):
L = newL
S = []
k = M[L]
for i in range(L-1, -1, -1):
S.append(X[k])
k = P[k]
return S[::-1]
if __name__ == '__main__':
for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
|
Can you help me rewrite this code in Python instead of PHP, keeping it the same logically? | <?php
class Node {
public $val;
public $back = NULL;
}
function lis($n) {
$pileTops = array();
foreach ($n as $x) {
$low = 0; $high = count($pileTops)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($pileTops[$mid]->val >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
$node = new Node();
$node->val = $x;
if ($i != 0)
$node->back = $pileTops[$i-1];
$pileTops[$i] = $node;
}
$result = array();
for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;
$node != NULL; $node = $node->back)
$result[] = $node->val;
return array_reverse($result);
}
print_r(lis(array(3, 2, 6, 4, 5, 1)));
print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));
?>
| def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if (newL > L):
L = newL
S = []
k = M[L]
for i in range(L-1, -1, -1):
S.append(X[k])
k = P[k]
return S[::-1]
if __name__ == '__main__':
for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
|
Change the following PHP code into Python without altering its purpose. | function getitem($s,$depth=0) {
$out = [''];
while ($s) {
$c = $s[0];
if ($depth && ($c == ',' || $c == '}')) {
return [$out, $s];
}
if ($c == '{') {
$x = getgroup(substr($s, 1), $depth + 1);
if($x) {
$tmp = [];
foreach($out as $a) {
foreach($x[0] as $b) {
$tmp[] = $a . $b;
}
}
$out = $tmp;
$s = $x[1];
continue;
}
}
if ($c == '\\' && strlen($s) > 1) {
list($s, $c) = [substr($s, 1), ($c . $s[1])];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = $a . $c;
}
$out = $tmp;
$s = substr($s, 1);
}
return [$out, $s];
}
function getgroup($s,$depth) {
list($out, $comma) = [[], false];
while ($s) {
list($g, $s) = getitem($s, $depth);
if (!$s) {
break;
}
$out = array_merge($out, $g);
if ($s[0] == '}') {
if ($comma) {
return [$out, substr($s, 1)];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = '{' . $a . '}';
}
return [$tmp, substr($s, 1)];
}
if ($s[0] == ',') {
list($comma, $s) = [true, substr($s, 1)];
}
}
return null;
}
$lines = <<< 'END'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
END;
foreach( explode("\n", $lines) as $line ) {
printf("\n%s\n", $line);
foreach( getitem($line)[0] as $expansion ) {
printf(" %s\n", $expansion);
}
}
| def getitem(s, depth=0):
out = [""]
while s:
c = s[0]
if depth and (c == ',' or c == '}'):
return out,s
if c == '{':
x = getgroup(s[1:], depth+1)
if x:
out,s = [a+b for a in out for b in x[0]], x[1]
continue
if c == '\\' and len(s) > 1:
s, c = s[1:], c + s[1]
out, s = [a+c for a in out], s[1:]
return out,s
def getgroup(s, depth):
out, comma = [], False
while s:
g,s = getitem(s, depth)
if not s: break
out += g
if s[0] == '}':
if comma: return out, s[1:]
return ['{' + a + '}' for a in out], s[1:]
if s[0] == ',':
comma,s = True, s[1:]
return None
for s in .split('\n'):
print "\n\t".join([s] + getitem(s)[0]) + "\n"
|
Maintain the same structure and functionality when rewriting this code in Python. | function getitem($s,$depth=0) {
$out = [''];
while ($s) {
$c = $s[0];
if ($depth && ($c == ',' || $c == '}')) {
return [$out, $s];
}
if ($c == '{') {
$x = getgroup(substr($s, 1), $depth + 1);
if($x) {
$tmp = [];
foreach($out as $a) {
foreach($x[0] as $b) {
$tmp[] = $a . $b;
}
}
$out = $tmp;
$s = $x[1];
continue;
}
}
if ($c == '\\' && strlen($s) > 1) {
list($s, $c) = [substr($s, 1), ($c . $s[1])];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = $a . $c;
}
$out = $tmp;
$s = substr($s, 1);
}
return [$out, $s];
}
function getgroup($s,$depth) {
list($out, $comma) = [[], false];
while ($s) {
list($g, $s) = getitem($s, $depth);
if (!$s) {
break;
}
$out = array_merge($out, $g);
if ($s[0] == '}') {
if ($comma) {
return [$out, substr($s, 1)];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = '{' . $a . '}';
}
return [$tmp, substr($s, 1)];
}
if ($s[0] == ',') {
list($comma, $s) = [true, substr($s, 1)];
}
}
return null;
}
$lines = <<< 'END'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
END;
foreach( explode("\n", $lines) as $line ) {
printf("\n%s\n", $line);
foreach( getitem($line)[0] as $expansion ) {
printf(" %s\n", $expansion);
}
}
| def getitem(s, depth=0):
out = [""]
while s:
c = s[0]
if depth and (c == ',' or c == '}'):
return out,s
if c == '{':
x = getgroup(s[1:], depth+1)
if x:
out,s = [a+b for a in out for b in x[0]], x[1]
continue
if c == '\\' and len(s) > 1:
s, c = s[1:], c + s[1]
out, s = [a+c for a in out], s[1:]
return out,s
def getgroup(s, depth):
out, comma = [], False
while s:
g,s = getitem(s, depth)
if not s: break
out += g
if s[0] == '}':
if comma: return out, s[1:]
return ['{' + a + '}' for a in out], s[1:]
if s[0] == ',':
comma,s = True, s[1:]
return None
for s in .split('\n'):
print "\n\t".join([s] + getitem(s)[0]) + "\n"
|
Preserve the algorithm and functionality while converting the code from PHP to Python. | function getitem($s,$depth=0) {
$out = [''];
while ($s) {
$c = $s[0];
if ($depth && ($c == ',' || $c == '}')) {
return [$out, $s];
}
if ($c == '{') {
$x = getgroup(substr($s, 1), $depth + 1);
if($x) {
$tmp = [];
foreach($out as $a) {
foreach($x[0] as $b) {
$tmp[] = $a . $b;
}
}
$out = $tmp;
$s = $x[1];
continue;
}
}
if ($c == '\\' && strlen($s) > 1) {
list($s, $c) = [substr($s, 1), ($c . $s[1])];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = $a . $c;
}
$out = $tmp;
$s = substr($s, 1);
}
return [$out, $s];
}
function getgroup($s,$depth) {
list($out, $comma) = [[], false];
while ($s) {
list($g, $s) = getitem($s, $depth);
if (!$s) {
break;
}
$out = array_merge($out, $g);
if ($s[0] == '}') {
if ($comma) {
return [$out, substr($s, 1)];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = '{' . $a . '}';
}
return [$tmp, substr($s, 1)];
}
if ($s[0] == ',') {
list($comma, $s) = [true, substr($s, 1)];
}
}
return null;
}
$lines = <<< 'END'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
END;
foreach( explode("\n", $lines) as $line ) {
printf("\n%s\n", $line);
foreach( getitem($line)[0] as $expansion ) {
printf(" %s\n", $expansion);
}
}
| def getitem(s, depth=0):
out = [""]
while s:
c = s[0]
if depth and (c == ',' or c == '}'):
return out,s
if c == '{':
x = getgroup(s[1:], depth+1)
if x:
out,s = [a+b for a in out for b in x[0]], x[1]
continue
if c == '\\' and len(s) > 1:
s, c = s[1:], c + s[1]
out, s = [a+c for a in out], s[1:]
return out,s
def getgroup(s, depth):
out, comma = [], False
while s:
g,s = getitem(s, depth)
if not s: break
out += g
if s[0] == '}':
if comma: return out, s[1:]
return ['{' + a + '}' for a in out], s[1:]
if s[0] == ',':
comma,s = True, s[1:]
return None
for s in .split('\n'):
print "\n\t".join([s] + getitem(s)[0]) + "\n"
|
Preserve the algorithm and functionality while converting the code from PHP to Python. | <?php
function is_describing($number) {
foreach (str_split((int) $number) as $place => $value) {
if (substr_count($number, $place) != $value) {
return false;
}
}
return true;
}
for ($i = 0; $i <= 50000000; $i += 10) {
if (is_describing($i)) {
echo $i . PHP_EOL;
}
}
?>
| >>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
|
Please provide an equivalent version of this PHP code in Python. | <?php
function is_describing($number) {
foreach (str_split((int) $number) as $place => $value) {
if (substr_count($number, $place) != $value) {
return false;
}
}
return true;
}
for ($i = 0; $i <= 50000000; $i += 10) {
if (is_describing($i)) {
echo $i . PHP_EOL;
}
}
?>
| >>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
|
Preserve the algorithm and functionality while converting the code from PHP to Python. | <?php
function is_describing($number) {
foreach (str_split((int) $number) as $place => $value) {
if (substr_count($number, $place) != $value) {
return false;
}
}
return true;
}
for ($i = 0; $i <= 50000000; $i += 10) {
if (is_describing($i)) {
echo $i . PHP_EOL;
}
}
?>
| >>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
|
Translate this program into Python but keep the logic exactly as in PHP. | <?php
function invmod($a,$n){
if ($n < 0) $n = -$n;
if ($a < 0) $a = $n - (-$a % $n);
$t = 0; $nt = 1; $r = $n; $nr = $a % $n;
while ($nr != 0) {
$quot= intval($r/$nr);
$tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp;
$tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp;
}
if ($r > 1) return -1;
if ($t < 0) $t += $n;
return $t;
}
printf("%d\n", invmod(42, 2017));
?>
| >>> def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
x, lastx = lastx - quotient*x, x
y, lasty = lasty - quotient*y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
>>> def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
raise ValueError
return x % m
>>> modinv(42, 2017)
1969
>>>
|
Port the following code from PHP to Python with equivalent syntax and logic. | <?php
function invmod($a,$n){
if ($n < 0) $n = -$n;
if ($a < 0) $a = $n - (-$a % $n);
$t = 0; $nt = 1; $r = $n; $nr = $a % $n;
while ($nr != 0) {
$quot= intval($r/$nr);
$tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp;
$tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp;
}
if ($r > 1) return -1;
if ($t < 0) $t += $n;
return $t;
}
printf("%d\n", invmod(42, 2017));
?>
| >>> def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
x, lastx = lastx - quotient*x, x
y, lasty = lasty - quotient*y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
>>> def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
raise ValueError
return x % m
>>> modinv(42, 2017)
1969
>>>
|
Translate the given PHP code snippet into Python without altering its behavior. | <?php
function invmod($a,$n){
if ($n < 0) $n = -$n;
if ($a < 0) $a = $n - (-$a % $n);
$t = 0; $nt = 1; $r = $n; $nr = $a % $n;
while ($nr != 0) {
$quot= intval($r/$nr);
$tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp;
$tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp;
}
if ($r > 1) return -1;
if ($t < 0) $t += $n;
return $t;
}
printf("%d\n", invmod(42, 2017));
?>
| >>> def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
x, lastx = lastx - quotient*x, x
y, lasty = lasty - quotient*y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
>>> def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
raise ValueError
return x % m
>>> modinv(42, 2017)
1969
>>>
|
Maintain the same structure and functionality when rewriting this code in Python. | <?php
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');
socket_bind($socket, 0, 8080);
socket_listen($socket);
$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';
for (;;) {
if ($client = @socket_accept($socket)) {
socket_write($client, "HTTP/1.1 200 OK\r\n" .
"Content-length: " . strlen($msg) . "\r\n" .
"Content-Type: text/html; charset=UTF-8\r\n\r\n" .
$msg);
}
else usleep(100000); // limits CPU usage by sleeping after doing every request
}
?>
| from wsgiref.simple_server import make_server
def app(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
yield b"<h1>Goodbye, World!</h1>"
server = make_server('127.0.0.1', 8080, app)
server.serve_forever()
|
Transform the following PHP implementation into Python, maintaining the same output and logic. | <?php
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');
socket_bind($socket, 0, 8080);
socket_listen($socket);
$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';
for (;;) {
if ($client = @socket_accept($socket)) {
socket_write($client, "HTTP/1.1 200 OK\r\n" .
"Content-length: " . strlen($msg) . "\r\n" .
"Content-Type: text/html; charset=UTF-8\r\n\r\n" .
$msg);
}
else usleep(100000); // limits CPU usage by sleeping after doing every request
}
?>
| from wsgiref.simple_server import make_server
def app(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
yield b"<h1>Goodbye, World!</h1>"
server = make_server('127.0.0.1', 8080, app)
server.serve_forever()
|
Write the same code in Python as shown below in PHP. | <?php
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');
socket_bind($socket, 0, 8080);
socket_listen($socket);
$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';
for (;;) {
if ($client = @socket_accept($socket)) {
socket_write($client, "HTTP/1.1 200 OK\r\n" .
"Content-length: " . strlen($msg) . "\r\n" .
"Content-Type: text/html; charset=UTF-8\r\n\r\n" .
$msg);
}
else usleep(100000); // limits CPU usage by sleeping after doing every request
}
?>
| from wsgiref.simple_server import make_server
def app(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
yield b"<h1>Goodbye, World!</h1>"
server = make_server('127.0.0.1', 8080, app)
server.serve_forever()
|
Change the programming language of this snippet from PHP to Python without modifying what it does. | <?
$image = imagecreate(200, 200);
imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 255, 0, 0);
cubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);
imagepng($image);
function cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {
$pts = array();
for($i = 0; $i <= $n; $i++) {
$t = $i / $n;
$t1 = 1 - $t;
$a = pow($t1, 3);
$b = 3 * $t * pow($t1, 2);
$c = 3 * pow($t, 2) * $t1;
$d = pow($t, 3);
$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);
$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);
$pts[$i] = array($x, $y);
}
for($i = 0; $i < $n; $i++) {
imageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);
}
}
| def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
pts = []
for i in range(n+1):
t = i / n
a = (1. - t)**3
b = 3. * t * (1. - t)**2
c = 3.0 * t**2 * (1.0 - t)
d = t**3
x = int(a * x0 + b * x1 + c * x2 + d * x3)
y = int(a * y0 + b * y1 + c * y2 + d * y3)
pts.append( (x, y) )
for i in range(n):
self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])
Bitmap.cubicbezier = cubicbezier
bitmap = Bitmap(17,17)
bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)
bitmap.chardisplay()
|
Maintain the same structure and functionality when rewriting this code in Python. | <?
$image = imagecreate(200, 200);
imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 255, 0, 0);
cubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);
imagepng($image);
function cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {
$pts = array();
for($i = 0; $i <= $n; $i++) {
$t = $i / $n;
$t1 = 1 - $t;
$a = pow($t1, 3);
$b = 3 * $t * pow($t1, 2);
$c = 3 * pow($t, 2) * $t1;
$d = pow($t, 3);
$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);
$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);
$pts[$i] = array($x, $y);
}
for($i = 0; $i < $n; $i++) {
imageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);
}
}
| def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
pts = []
for i in range(n+1):
t = i / n
a = (1. - t)**3
b = 3. * t * (1. - t)**2
c = 3.0 * t**2 * (1.0 - t)
d = t**3
x = int(a * x0 + b * x1 + c * x2 + d * x3)
y = int(a * y0 + b * y1 + c * y2 + d * y3)
pts.append( (x, y) )
for i in range(n):
self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])
Bitmap.cubicbezier = cubicbezier
bitmap = Bitmap(17,17)
bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)
bitmap.chardisplay()
|
Translate the given PHP code snippet into Python without altering its behavior. | <?
$image = imagecreate(200, 200);
imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 255, 0, 0);
cubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);
imagepng($image);
function cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {
$pts = array();
for($i = 0; $i <= $n; $i++) {
$t = $i / $n;
$t1 = 1 - $t;
$a = pow($t1, 3);
$b = 3 * $t * pow($t1, 2);
$c = 3 * pow($t, 2) * $t1;
$d = pow($t, 3);
$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);
$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);
$pts[$i] = array($x, $y);
}
for($i = 0; $i < $n; $i++) {
imageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);
}
}
| def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
pts = []
for i in range(n+1):
t = i / n
a = (1. - t)**3
b = 3. * t * (1. - t)**2
c = 3.0 * t**2 * (1.0 - t)
d = t**3
x = int(a * x0 + b * x1 + c * x2 + d * x3)
y = int(a * y0 + b * y1 + c * y2 + d * y3)
pts.append( (x, y) )
for i in range(n):
self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])
Bitmap.cubicbezier = cubicbezier
bitmap = Bitmap(17,17)
bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)
bitmap.chardisplay()
|
Generate a Python translation of this PHP snippet without changing its computational steps. | <?php
$ldap = ldap_connect($hostname, $port);
$success = ldap_bind($ldap, $username, $password);
| import ldap
l = ldap.initialize("ldap://ldap.example.com")
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s("me@example.com", "password")
finally:
l.unbind()
|
Convert the following code from PHP to Python, ensuring the logic remains intact. | <?php
$ldap = ldap_connect($hostname, $port);
$success = ldap_bind($ldap, $username, $password);
| import ldap
l = ldap.initialize("ldap://ldap.example.com")
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s("me@example.com", "password")
finally:
l.unbind()
|
Convert this PHP block to Python, preserving its control flow and logic. | <?php
$ldap = ldap_connect($hostname, $port);
$success = ldap_bind($ldap, $username, $password);
| import ldap
l = ldap.initialize("ldap://ldap.example.com")
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s("me@example.com", "password")
finally:
l.unbind()
|
Translate the given PHP code snippet into Python without altering its behavior. | <?php
$conf = file_get_contents('update-conf-file.txt');
$conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf);
$conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf);
$conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf);
if (preg_match('/^;?\s*(numberofstrawberries)/mi', $conf, $matches)) {
$conf = preg_replace('/^(numberofstrawberries)(|\s*\S*)$/mi', '$1 62000', $conf);
} else {
$conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;
}
echo $conf;
|
import re
import string
DISABLED_PREFIX = ';'
class Option(object):
def __init__(self, name, value=None, disabled=False,
disabled_prefix=DISABLED_PREFIX):
self.name = str(name)
self.value = value
self.disabled = bool(disabled)
self.disabled_prefix = disabled_prefix
def __str__(self):
disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]
value = (' %s' % self.value, '')[self.value is None]
return ''.join((disabled, self.name, value))
def get(self):
enabled = not bool(self.disabled)
if self.value is None:
value = enabled
else:
value = enabled and self.value
return value
class Config(object):
reOPTION = r'^\s*(?P<disabled>%s*)\s*(?P<name>\w+)(?:\s+(?P<value>.+?))?\s*$'
def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):
self.disabled_prefix = disabled_prefix
self.contents = []
self.options = {}
self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)
if fname:
self.parse_file(fname)
def __str__(self):
return '\n'.join(map(str, self.contents))
def parse_file(self, fname):
with open(fname) as f:
self.parse_lines(f)
return self
def parse_lines(self, lines):
for line in lines:
self.parse_line(line)
return self
def parse_line(self, line):
s = ''.join(c for c in line.strip() if c in string.printable)
moOPTION = self.creOPTION.match(s)
if moOPTION:
name = moOPTION.group('name').upper()
if not name in self.options:
self.add_option(name, moOPTION.group('value'),
moOPTION.group('disabled'))
else:
if not s.startswith(self.disabled_prefix):
self.contents.append(line.rstrip())
return self
def add_option(self, name, value=None, disabled=False):
name = name.upper()
opt = Option(name, value, disabled)
self.options[name] = opt
self.contents.append(opt)
return opt
def set_option(self, name, value=None, disabled=False):
name = name.upper()
opt = self.options.get(name)
if opt:
opt.value = value
opt.disabled = disabled
else:
opt = self.add_option(name, value, disabled)
return opt
def enable_option(self, name, value=None):
return self.set_option(name, value, False)
def disable_option(self, name, value=None):
return self.set_option(name, value, True)
def get_option(self, name):
opt = self.options.get(name.upper())
value = opt.get() if opt else None
return value
if __name__ == '__main__':
import sys
cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)
cfg.disable_option('needspeeling')
cfg.enable_option('seedsremoved')
cfg.enable_option('numberofbananas', 1024)
cfg.enable_option('numberofstrawberries', 62000)
print cfg
|
Convert this PHP snippet to Python and keep its semantics consistent. | <?php
$conf = file_get_contents('update-conf-file.txt');
$conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf);
$conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf);
$conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf);
if (preg_match('/^;?\s*(numberofstrawberries)/mi', $conf, $matches)) {
$conf = preg_replace('/^(numberofstrawberries)(|\s*\S*)$/mi', '$1 62000', $conf);
} else {
$conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;
}
echo $conf;
|
import re
import string
DISABLED_PREFIX = ';'
class Option(object):
def __init__(self, name, value=None, disabled=False,
disabled_prefix=DISABLED_PREFIX):
self.name = str(name)
self.value = value
self.disabled = bool(disabled)
self.disabled_prefix = disabled_prefix
def __str__(self):
disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]
value = (' %s' % self.value, '')[self.value is None]
return ''.join((disabled, self.name, value))
def get(self):
enabled = not bool(self.disabled)
if self.value is None:
value = enabled
else:
value = enabled and self.value
return value
class Config(object):
reOPTION = r'^\s*(?P<disabled>%s*)\s*(?P<name>\w+)(?:\s+(?P<value>.+?))?\s*$'
def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):
self.disabled_prefix = disabled_prefix
self.contents = []
self.options = {}
self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)
if fname:
self.parse_file(fname)
def __str__(self):
return '\n'.join(map(str, self.contents))
def parse_file(self, fname):
with open(fname) as f:
self.parse_lines(f)
return self
def parse_lines(self, lines):
for line in lines:
self.parse_line(line)
return self
def parse_line(self, line):
s = ''.join(c for c in line.strip() if c in string.printable)
moOPTION = self.creOPTION.match(s)
if moOPTION:
name = moOPTION.group('name').upper()
if not name in self.options:
self.add_option(name, moOPTION.group('value'),
moOPTION.group('disabled'))
else:
if not s.startswith(self.disabled_prefix):
self.contents.append(line.rstrip())
return self
def add_option(self, name, value=None, disabled=False):
name = name.upper()
opt = Option(name, value, disabled)
self.options[name] = opt
self.contents.append(opt)
return opt
def set_option(self, name, value=None, disabled=False):
name = name.upper()
opt = self.options.get(name)
if opt:
opt.value = value
opt.disabled = disabled
else:
opt = self.add_option(name, value, disabled)
return opt
def enable_option(self, name, value=None):
return self.set_option(name, value, False)
def disable_option(self, name, value=None):
return self.set_option(name, value, True)
def get_option(self, name):
opt = self.options.get(name.upper())
value = opt.get() if opt else None
return value
if __name__ == '__main__':
import sys
cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)
cfg.disable_option('needspeeling')
cfg.enable_option('seedsremoved')
cfg.enable_option('numberofbananas', 1024)
cfg.enable_option('numberofstrawberries', 62000)
print cfg
|
Write the same algorithm in Python as shown in this PHP implementation. | <?php
$conf = file_get_contents('update-conf-file.txt');
$conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf);
$conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf);
$conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf);
if (preg_match('/^;?\s*(numberofstrawberries)/mi', $conf, $matches)) {
$conf = preg_replace('/^(numberofstrawberries)(|\s*\S*)$/mi', '$1 62000', $conf);
} else {
$conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;
}
echo $conf;
|
import re
import string
DISABLED_PREFIX = ';'
class Option(object):
def __init__(self, name, value=None, disabled=False,
disabled_prefix=DISABLED_PREFIX):
self.name = str(name)
self.value = value
self.disabled = bool(disabled)
self.disabled_prefix = disabled_prefix
def __str__(self):
disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]
value = (' %s' % self.value, '')[self.value is None]
return ''.join((disabled, self.name, value))
def get(self):
enabled = not bool(self.disabled)
if self.value is None:
value = enabled
else:
value = enabled and self.value
return value
class Config(object):
reOPTION = r'^\s*(?P<disabled>%s*)\s*(?P<name>\w+)(?:\s+(?P<value>.+?))?\s*$'
def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):
self.disabled_prefix = disabled_prefix
self.contents = []
self.options = {}
self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)
if fname:
self.parse_file(fname)
def __str__(self):
return '\n'.join(map(str, self.contents))
def parse_file(self, fname):
with open(fname) as f:
self.parse_lines(f)
return self
def parse_lines(self, lines):
for line in lines:
self.parse_line(line)
return self
def parse_line(self, line):
s = ''.join(c for c in line.strip() if c in string.printable)
moOPTION = self.creOPTION.match(s)
if moOPTION:
name = moOPTION.group('name').upper()
if not name in self.options:
self.add_option(name, moOPTION.group('value'),
moOPTION.group('disabled'))
else:
if not s.startswith(self.disabled_prefix):
self.contents.append(line.rstrip())
return self
def add_option(self, name, value=None, disabled=False):
name = name.upper()
opt = Option(name, value, disabled)
self.options[name] = opt
self.contents.append(opt)
return opt
def set_option(self, name, value=None, disabled=False):
name = name.upper()
opt = self.options.get(name)
if opt:
opt.value = value
opt.disabled = disabled
else:
opt = self.add_option(name, value, disabled)
return opt
def enable_option(self, name, value=None):
return self.set_option(name, value, False)
def disable_option(self, name, value=None):
return self.set_option(name, value, True)
def get_option(self, name):
opt = self.options.get(name.upper())
value = opt.get() if opt else None
return value
if __name__ == '__main__':
import sys
cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)
cfg.disable_option('needspeeling')
cfg.enable_option('seedsremoved')
cfg.enable_option('numberofbananas', 1024)
cfg.enable_option('numberofstrawberries', 62000)
print cfg
|
Preserve the algorithm and functionality while converting the code from PHP to Python. | .12
0.1234
1.2e3
7E-10
| 2.3
.3
.3e4
.3e+34
.3e-34
2.e34
|
Keep all operations the same but rewrite the snippet in Python. | .12
0.1234
1.2e3
7E-10
| 2.3
.3
.3e4
.3e+34
.3e-34
2.e34
|
Preserve the algorithm and functionality while converting the code from PHP to Python. | .12
0.1234
1.2e3
7E-10
| 2.3
.3
.3e4
.3e+34
.3e-34
2.e34
|
Port the following code from PHP to Python with equivalent syntax and logic. | <?php
$zero = function($f) { return function ($x) { return $x; }; };
$succ = function($n) {
return function($f) use (&$n) {
return function($x) use (&$n, &$f) {
return $f( ($n($f))($x) );
};
};
};
$add = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($f))(($n($f))($x));
};
};
};
$mult = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($n($f)))($x);
};
};
};
$power = function($b,$e) {
return $e($b);
};
$to_int = function($f) {
$count_up = function($i) { return $i+1; };
return ($f($count_up))(0);
};
$from_int = function($x) {
$countdown = function($i) use (&$countdown) {
global $zero, $succ;
if ( $i == 0 ) {
return $zero;
} else {
return $succ($countdown($i-1));
};
};
return $countdown($x);
};
$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
$power($three,$four), $power($four,$three)) as $ch) {
print($to_int($ch));
print("\n");
}
?>
|
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
def churchExp(m):
return lambda n: n(m)
def churchFromInt(n):
return lambda f: (
foldl
(compose)
(identity)
(replicate(n)(f))
)
def churchFromInt_(n):
if 0 == n:
return churchZero()
else:
return churchSucc(churchFromInt(n - 1))
def intFromChurch(cn):
return cn(succ)(0)
def main():
'Tests'
cThree = churchFromInt(3)
cFour = churchFromInt(4)
print(list(map(intFromChurch, [
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
])))
def compose(f):
return lambda g: lambda x: g(f(x))
def foldl(f):
def go(acc, xs):
return reduce(lambda a, x: f(a)(x), xs, acc)
return lambda acc: lambda xs: go(acc, xs)
def identity(x):
return x
def replicate(n):
return lambda x: repeat(x, n)
def succ(x):
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
if __name__ == '__main__':
main()
|
Maintain the same structure and functionality when rewriting this code in Python. | <?php
$zero = function($f) { return function ($x) { return $x; }; };
$succ = function($n) {
return function($f) use (&$n) {
return function($x) use (&$n, &$f) {
return $f( ($n($f))($x) );
};
};
};
$add = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($f))(($n($f))($x));
};
};
};
$mult = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($n($f)))($x);
};
};
};
$power = function($b,$e) {
return $e($b);
};
$to_int = function($f) {
$count_up = function($i) { return $i+1; };
return ($f($count_up))(0);
};
$from_int = function($x) {
$countdown = function($i) use (&$countdown) {
global $zero, $succ;
if ( $i == 0 ) {
return $zero;
} else {
return $succ($countdown($i-1));
};
};
return $countdown($x);
};
$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
$power($three,$four), $power($four,$three)) as $ch) {
print($to_int($ch));
print("\n");
}
?>
|
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
def churchExp(m):
return lambda n: n(m)
def churchFromInt(n):
return lambda f: (
foldl
(compose)
(identity)
(replicate(n)(f))
)
def churchFromInt_(n):
if 0 == n:
return churchZero()
else:
return churchSucc(churchFromInt(n - 1))
def intFromChurch(cn):
return cn(succ)(0)
def main():
'Tests'
cThree = churchFromInt(3)
cFour = churchFromInt(4)
print(list(map(intFromChurch, [
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
])))
def compose(f):
return lambda g: lambda x: g(f(x))
def foldl(f):
def go(acc, xs):
return reduce(lambda a, x: f(a)(x), xs, acc)
return lambda acc: lambda xs: go(acc, xs)
def identity(x):
return x
def replicate(n):
return lambda x: repeat(x, n)
def succ(x):
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
if __name__ == '__main__':
main()
|
Translate this program into Python but keep the logic exactly as in PHP. | <?php
$zero = function($f) { return function ($x) { return $x; }; };
$succ = function($n) {
return function($f) use (&$n) {
return function($x) use (&$n, &$f) {
return $f( ($n($f))($x) );
};
};
};
$add = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($f))(($n($f))($x));
};
};
};
$mult = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($n($f)))($x);
};
};
};
$power = function($b,$e) {
return $e($b);
};
$to_int = function($f) {
$count_up = function($i) { return $i+1; };
return ($f($count_up))(0);
};
$from_int = function($x) {
$countdown = function($i) use (&$countdown) {
global $zero, $succ;
if ( $i == 0 ) {
return $zero;
} else {
return $succ($countdown($i-1));
};
};
return $countdown($x);
};
$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
$power($three,$four), $power($four,$three)) as $ch) {
print($to_int($ch));
print("\n");
}
?>
|
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
def churchExp(m):
return lambda n: n(m)
def churchFromInt(n):
return lambda f: (
foldl
(compose)
(identity)
(replicate(n)(f))
)
def churchFromInt_(n):
if 0 == n:
return churchZero()
else:
return churchSucc(churchFromInt(n - 1))
def intFromChurch(cn):
return cn(succ)(0)
def main():
'Tests'
cThree = churchFromInt(3)
cFour = churchFromInt(4)
print(list(map(intFromChurch, [
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
])))
def compose(f):
return lambda g: lambda x: g(f(x))
def foldl(f):
def go(acc, xs):
return reduce(lambda a, x: f(a)(x), xs, acc)
return lambda acc: lambda xs: go(acc, xs)
def identity(x):
return x
def replicate(n):
return lambda x: repeat(x, n)
def succ(x):
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
if __name__ == '__main__':
main()
|
Convert this PHP block to Python, preserving its control flow and logic. | <?php
$zero = function($f) { return function ($x) { return $x; }; };
$succ = function($n) {
return function($f) use (&$n) {
return function($x) use (&$n, &$f) {
return $f( ($n($f))($x) );
};
};
};
$add = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($f))(($n($f))($x));
};
};
};
$mult = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($n($f)))($x);
};
};
};
$power = function($b,$e) {
return $e($b);
};
$to_int = function($f) {
$count_up = function($i) { return $i+1; };
return ($f($count_up))(0);
};
$from_int = function($x) {
$countdown = function($i) use (&$countdown) {
global $zero, $succ;
if ( $i == 0 ) {
return $zero;
} else {
return $succ($countdown($i-1));
};
};
return $countdown($x);
};
$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
$power($three,$four), $power($four,$three)) as $ch) {
print($to_int($ch));
print("\n");
}
?>
|
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
def churchExp(m):
return lambda n: n(m)
def churchFromInt(n):
return lambda f: (
foldl
(compose)
(identity)
(replicate(n)(f))
)
def churchFromInt_(n):
if 0 == n:
return churchZero()
else:
return churchSucc(churchFromInt(n - 1))
def intFromChurch(cn):
return cn(succ)(0)
def main():
'Tests'
cThree = churchFromInt(3)
cFour = churchFromInt(4)
print(list(map(intFromChurch, [
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
])))
def compose(f):
return lambda g: lambda x: g(f(x))
def foldl(f):
def go(acc, xs):
return reduce(lambda a, x: f(a)(x), xs, acc)
return lambda acc: lambda xs: go(acc, xs)
def identity(x):
return x
def replicate(n):
return lambda x: repeat(x, n)
def succ(x):
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
if __name__ == '__main__':
main()
|
Translate this program into Python but keep the logic exactly as in PHP. | <?php
$zero = function($f) { return function ($x) { return $x; }; };
$succ = function($n) {
return function($f) use (&$n) {
return function($x) use (&$n, &$f) {
return $f( ($n($f))($x) );
};
};
};
$add = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($f))(($n($f))($x));
};
};
};
$mult = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($n($f)))($x);
};
};
};
$power = function($b,$e) {
return $e($b);
};
$to_int = function($f) {
$count_up = function($i) { return $i+1; };
return ($f($count_up))(0);
};
$from_int = function($x) {
$countdown = function($i) use (&$countdown) {
global $zero, $succ;
if ( $i == 0 ) {
return $zero;
} else {
return $succ($countdown($i-1));
};
};
return $countdown($x);
};
$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
$power($three,$four), $power($four,$three)) as $ch) {
print($to_int($ch));
print("\n");
}
?>
|
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
def churchExp(m):
return lambda n: n(m)
def churchFromInt(n):
return lambda f: (
foldl
(compose)
(identity)
(replicate(n)(f))
)
def churchFromInt_(n):
if 0 == n:
return churchZero()
else:
return churchSucc(churchFromInt(n - 1))
def intFromChurch(cn):
return cn(succ)(0)
def main():
'Tests'
cThree = churchFromInt(3)
cFour = churchFromInt(4)
print(list(map(intFromChurch, [
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
])))
def compose(f):
return lambda g: lambda x: g(f(x))
def foldl(f):
def go(acc, xs):
return reduce(lambda a, x: f(a)(x), xs, acc)
return lambda acc: lambda xs: go(acc, xs)
def identity(x):
return x
def replicate(n):
return lambda x: repeat(x, n)
def succ(x):
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
if __name__ == '__main__':
main()
|
Change the programming language of this snippet from PHP to Python without modifying what it does. | <?php
$zero = function($f) { return function ($x) { return $x; }; };
$succ = function($n) {
return function($f) use (&$n) {
return function($x) use (&$n, &$f) {
return $f( ($n($f))($x) );
};
};
};
$add = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($f))(($n($f))($x));
};
};
};
$mult = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($n($f)))($x);
};
};
};
$power = function($b,$e) {
return $e($b);
};
$to_int = function($f) {
$count_up = function($i) { return $i+1; };
return ($f($count_up))(0);
};
$from_int = function($x) {
$countdown = function($i) use (&$countdown) {
global $zero, $succ;
if ( $i == 0 ) {
return $zero;
} else {
return $succ($countdown($i-1));
};
};
return $countdown($x);
};
$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
$power($three,$four), $power($four,$three)) as $ch) {
print($to_int($ch));
print("\n");
}
?>
|
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
def churchExp(m):
return lambda n: n(m)
def churchFromInt(n):
return lambda f: (
foldl
(compose)
(identity)
(replicate(n)(f))
)
def churchFromInt_(n):
if 0 == n:
return churchZero()
else:
return churchSucc(churchFromInt(n - 1))
def intFromChurch(cn):
return cn(succ)(0)
def main():
'Tests'
cThree = churchFromInt(3)
cFour = churchFromInt(4)
print(list(map(intFromChurch, [
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
])))
def compose(f):
return lambda g: lambda x: g(f(x))
def foldl(f):
def go(acc, xs):
return reduce(lambda a, x: f(a)(x), xs, acc)
return lambda acc: lambda xs: go(acc, xs)
def identity(x):
return x
def replicate(n):
return lambda x: repeat(x, n)
def succ(x):
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
if __name__ == '__main__':
main()
|
Convert this PHP snippet to Python and keep its semantics consistent. | <?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
}
$class = new SimpleClass;
ob_start();
var_export($class);
$class_content = ob_get_clean();
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);
$new_class = eval($class_content);
echo $new_class['answer'];
| >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
|
Change the programming language of this snippet from PHP to Python without modifying what it does. | <?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
}
$class = new SimpleClass;
ob_start();
var_export($class);
$class_content = ob_get_clean();
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);
$new_class = eval($class_content);
echo $new_class['answer'];
| >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
|
Preserve the algorithm and functionality while converting the code from PHP to Python. | <?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
}
$class = new SimpleClass;
ob_start();
var_export($class);
$class_content = ob_get_clean();
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);
$new_class = eval($class_content);
echo $new_class['answer'];
| >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
|
Preserve the algorithm and functionality while converting the code from PHP to Python. | <?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
}
$class = new SimpleClass;
ob_start();
var_export($class);
$class_content = ob_get_clean();
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);
$new_class = eval($class_content);
echo $new_class['answer'];
| >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
|
Port the following code from PHP to Python with equivalent syntax and logic. | <?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
}
$class = new SimpleClass;
ob_start();
var_export($class);
$class_content = ob_get_clean();
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);
$new_class = eval($class_content);
echo $new_class['answer'];
| >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
|
Translate the given PHP code snippet into Python without altering its behavior. | <?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
}
$class = new SimpleClass;
ob_start();
var_export($class);
$class_content = ob_get_clean();
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);
$new_class = eval($class_content);
echo $new_class['answer'];
| >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
|
Convert the following code from PHP to Python, ensuring the logic remains intact. | $myObj = new Object();
$serializedObj = serialize($myObj);
|
import pickle
class Entity:
def __init__(self):
self.name = "Entity"
def printName(self):
print self.name
class Person(Entity):
def __init__(self):
self.name = "Cletus"
instance1 = Person()
instance1.printName()
instance2 = Entity()
instance2.printName()
target = file("objects.dat", "w")
pickle.dump((instance1, instance2), target)
target.close()
print "Serialized..."
target = file("objects.dat")
i1, i2 = pickle.load(target)
print "Unserialized..."
i1.printName()
i2.printName()
|
Rewrite the snippet below in Python so it works the same as the original PHP code. | $myObj = new Object();
$serializedObj = serialize($myObj);
|
import pickle
class Entity:
def __init__(self):
self.name = "Entity"
def printName(self):
print self.name
class Person(Entity):
def __init__(self):
self.name = "Cletus"
instance1 = Person()
instance1.printName()
instance2 = Entity()
instance2.printName()
target = file("objects.dat", "w")
pickle.dump((instance1, instance2), target)
target.close()
print "Serialized..."
target = file("objects.dat")
i1, i2 = pickle.load(target)
print "Unserialized..."
i1.printName()
i2.printName()
|
Convert this PHP snippet to Python and keep its semantics consistent. | $myObj = new Object();
$serializedObj = serialize($myObj);
|
import pickle
class Entity:
def __init__(self):
self.name = "Entity"
def printName(self):
print self.name
class Person(Entity):
def __init__(self):
self.name = "Cletus"
instance1 = Person()
instance1.printName()
instance2 = Entity()
instance2.printName()
target = file("objects.dat", "w")
pickle.dump((instance1, instance2), target)
target.close()
print "Serialized..."
target = file("objects.dat")
i1, i2 = pickle.load(target)
print "Unserialized..."
i1.printName()
i2.printName()
|
Convert this PHP snippet to Python and keep its semantics consistent. | function isLongYear($year) {
return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));
}
for ($y=1995; $y<=2045; ++$y) {
if (isLongYear($y)) {
printf("%s\n", $y);
}
}
|
from datetime import date
def longYear(y):
return 52 < date(y, 12, 28).isocalendar()[1]
def main():
for year in [
x for x in range(2000, 1 + 2100)
if longYear(x)
]:
print(year)
if __name__ == '__main__':
main()
|
Ensure the translated Python code behaves exactly like the original PHP snippet. | function isLongYear($year) {
return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));
}
for ($y=1995; $y<=2045; ++$y) {
if (isLongYear($y)) {
printf("%s\n", $y);
}
}
|
from datetime import date
def longYear(y):
return 52 < date(y, 12, 28).isocalendar()[1]
def main():
for year in [
x for x in range(2000, 1 + 2100)
if longYear(x)
]:
print(year)
if __name__ == '__main__':
main()
|
Ensure the translated Python code behaves exactly like the original PHP snippet. | function isLongYear($year) {
return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));
}
for ($y=1995; $y<=2045; ++$y) {
if (isLongYear($y)) {
printf("%s\n", $y);
}
}
|
from datetime import date
def longYear(y):
return 52 < date(y, 12, 28).isocalendar()[1]
def main():
for year in [
x for x in range(2000, 1 + 2100)
if longYear(x)
]:
print(year)
if __name__ == '__main__':
main()
|
Port the provided PHP code into Python while preserving the original functionality. | <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
| base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
|
Rewrite this program in Python while keeping its functionality equivalent to the PHP version. | <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
| base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
|
Port the provided PHP code into Python while preserving the original functionality. | <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
| base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
|
Transform the following PHP implementation into Python, maintaining the same output and logic. | <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
| base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
|
Convert this PHP snippet to Python and keep its semantics consistent. | <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
| base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
|
Write the same algorithm in Python as shown in this PHP implementation. | <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
| base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
|
Convert the following code from PHP to Python, ensuring the logic remains intact. | <?php
function markovChainTextGenerator($text, $keySize, $maxWords) {
$token = array();
$position = 0;
$maxPosition = strlen($text);
while ($position < $maxPosition) {
if (preg_match('/^(\S+)/', substr($text, $position, 25), $matches)) {
$token[] = $matches[1];
$position += strlen($matches[1]);
}
elseif (preg_match('/^(\s+)/', substr($text, $position, 25), $matches)) {
$position += strlen($matches[1]);
}
else {
die(
'Unknown token found at position ' . $position . ' : ' .
substr($text, $position, 25) . '...' . PHP_EOL
);
}
}
$dictionary = array();
for ($i = 0 ; $i < count($token) - $keySize ; $i++) {
$prefix = '';
$separator = '';
for ($c = 0 ; $c < $keySize ; $c++) {
$prefix .= $separator . $token[$i + $c];
$separator = '.';
}
$dictionary[$prefix][] = $token[$i + $keySize];
}
$rand = rand(0, count($token) - $keySize);
$startToken = array();
for ($c = 0 ; $c < $keySize ; $c++) {
array_push($startToken, $token[$rand + $c]);
}
$text = implode(' ', $startToken);
$words = $keySize;
do {
$tokenKey = implode('.', $startToken);
$rand = rand(0, count($dictionary[$tokenKey]) - 1);
$newToken = $dictionary[$tokenKey][$rand];
$text .= ' ' . $newToken;
$words++;
array_shift($startToken);
array_push($startToken, $newToken);
} while($words < $maxWords);
return $text;
}
srand(5678);
$text = markovChainTextGenerator(
file_get_contents(__DIR__ . '/inc/alice_oz.txt'),
3,
308
);
echo wordwrap($text, 100, PHP_EOL) . PHP_EOL;
| import random, sys
def makerule(data, context):
rule = {}
words = data.split(' ')
index = context
for word in words[index:]:
key = ' '.join(words[index-context:index])
if key in rule:
rule[key].append(word)
else:
rule[key] = [word]
index += 1
return rule
def makestring(rule, length):
oldwords = random.choice(list(rule.keys())).split(' ')
string = ' '.join(oldwords) + ' '
for i in range(length):
try:
key = ' '.join(oldwords)
newword = random.choice(rule[key])
string += newword + ' '
for word in range(len(oldwords)):
oldwords[word] = oldwords[(word + 1) % len(oldwords)]
oldwords[-1] = newword
except KeyError:
return string
return string
if __name__ == '__main__':
with open(sys.argv[1], encoding='utf8') as f:
data = f.read()
rule = makerule(data, int(sys.argv[2]))
string = makestring(rule, int(sys.argv[3]))
print(string)
|
Write a version of this PHP function in Python with identical behavior. | <?php
function markovChainTextGenerator($text, $keySize, $maxWords) {
$token = array();
$position = 0;
$maxPosition = strlen($text);
while ($position < $maxPosition) {
if (preg_match('/^(\S+)/', substr($text, $position, 25), $matches)) {
$token[] = $matches[1];
$position += strlen($matches[1]);
}
elseif (preg_match('/^(\s+)/', substr($text, $position, 25), $matches)) {
$position += strlen($matches[1]);
}
else {
die(
'Unknown token found at position ' . $position . ' : ' .
substr($text, $position, 25) . '...' . PHP_EOL
);
}
}
$dictionary = array();
for ($i = 0 ; $i < count($token) - $keySize ; $i++) {
$prefix = '';
$separator = '';
for ($c = 0 ; $c < $keySize ; $c++) {
$prefix .= $separator . $token[$i + $c];
$separator = '.';
}
$dictionary[$prefix][] = $token[$i + $keySize];
}
$rand = rand(0, count($token) - $keySize);
$startToken = array();
for ($c = 0 ; $c < $keySize ; $c++) {
array_push($startToken, $token[$rand + $c]);
}
$text = implode(' ', $startToken);
$words = $keySize;
do {
$tokenKey = implode('.', $startToken);
$rand = rand(0, count($dictionary[$tokenKey]) - 1);
$newToken = $dictionary[$tokenKey][$rand];
$text .= ' ' . $newToken;
$words++;
array_shift($startToken);
array_push($startToken, $newToken);
} while($words < $maxWords);
return $text;
}
srand(5678);
$text = markovChainTextGenerator(
file_get_contents(__DIR__ . '/inc/alice_oz.txt'),
3,
308
);
echo wordwrap($text, 100, PHP_EOL) . PHP_EOL;
| import random, sys
def makerule(data, context):
rule = {}
words = data.split(' ')
index = context
for word in words[index:]:
key = ' '.join(words[index-context:index])
if key in rule:
rule[key].append(word)
else:
rule[key] = [word]
index += 1
return rule
def makestring(rule, length):
oldwords = random.choice(list(rule.keys())).split(' ')
string = ' '.join(oldwords) + ' '
for i in range(length):
try:
key = ' '.join(oldwords)
newword = random.choice(rule[key])
string += newword + ' '
for word in range(len(oldwords)):
oldwords[word] = oldwords[(word + 1) % len(oldwords)]
oldwords[-1] = newword
except KeyError:
return string
return string
if __name__ == '__main__':
with open(sys.argv[1], encoding='utf8') as f:
data = f.read()
rule = makerule(data, int(sys.argv[2]))
string = makestring(rule, int(sys.argv[3]))
print(string)
|
Change the programming language of this snippet from PHP to Python without modifying what it does. | <?php
function markovChainTextGenerator($text, $keySize, $maxWords) {
$token = array();
$position = 0;
$maxPosition = strlen($text);
while ($position < $maxPosition) {
if (preg_match('/^(\S+)/', substr($text, $position, 25), $matches)) {
$token[] = $matches[1];
$position += strlen($matches[1]);
}
elseif (preg_match('/^(\s+)/', substr($text, $position, 25), $matches)) {
$position += strlen($matches[1]);
}
else {
die(
'Unknown token found at position ' . $position . ' : ' .
substr($text, $position, 25) . '...' . PHP_EOL
);
}
}
$dictionary = array();
for ($i = 0 ; $i < count($token) - $keySize ; $i++) {
$prefix = '';
$separator = '';
for ($c = 0 ; $c < $keySize ; $c++) {
$prefix .= $separator . $token[$i + $c];
$separator = '.';
}
$dictionary[$prefix][] = $token[$i + $keySize];
}
$rand = rand(0, count($token) - $keySize);
$startToken = array();
for ($c = 0 ; $c < $keySize ; $c++) {
array_push($startToken, $token[$rand + $c]);
}
$text = implode(' ', $startToken);
$words = $keySize;
do {
$tokenKey = implode('.', $startToken);
$rand = rand(0, count($dictionary[$tokenKey]) - 1);
$newToken = $dictionary[$tokenKey][$rand];
$text .= ' ' . $newToken;
$words++;
array_shift($startToken);
array_push($startToken, $newToken);
} while($words < $maxWords);
return $text;
}
srand(5678);
$text = markovChainTextGenerator(
file_get_contents(__DIR__ . '/inc/alice_oz.txt'),
3,
308
);
echo wordwrap($text, 100, PHP_EOL) . PHP_EOL;
| import random, sys
def makerule(data, context):
rule = {}
words = data.split(' ')
index = context
for word in words[index:]:
key = ' '.join(words[index-context:index])
if key in rule:
rule[key].append(word)
else:
rule[key] = [word]
index += 1
return rule
def makestring(rule, length):
oldwords = random.choice(list(rule.keys())).split(' ')
string = ' '.join(oldwords) + ' '
for i in range(length):
try:
key = ' '.join(oldwords)
newword = random.choice(rule[key])
string += newword + ' '
for word in range(len(oldwords)):
oldwords[word] = oldwords[(word + 1) % len(oldwords)]
oldwords[-1] = newword
except KeyError:
return string
return string
if __name__ == '__main__':
with open(sys.argv[1], encoding='utf8') as f:
data = f.read()
rule = makerule(data, int(sys.argv[2]))
string = makestring(rule, int(sys.argv[3]))
print(string)
|
Transform the following PHP implementation into Python, maintaining the same output and logic. | <?php
function dijkstra($graph_array, $source, $target) {
$vertices = array();
$neighbours = array();
foreach ($graph_array as $edge) {
array_push($vertices, $edge[0], $edge[1]);
$neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]);
$neighbours[$edge[1]][] = array("end" => $edge[0], "cost" => $edge[2]);
}
$vertices = array_unique($vertices);
foreach ($vertices as $vertex) {
$dist[$vertex] = INF;
$previous[$vertex] = NULL;
}
$dist[$source] = 0;
$Q = $vertices;
while (count($Q) > 0) {
$min = INF;
foreach ($Q as $vertex){
if ($dist[$vertex] < $min) {
$min = $dist[$vertex];
$u = $vertex;
}
}
$Q = array_diff($Q, array($u));
if ($dist[$u] == INF or $u == $target) {
break;
}
if (isset($neighbours[$u])) {
foreach ($neighbours[$u] as $arr) {
$alt = $dist[$u] + $arr["cost"];
if ($alt < $dist[$arr["end"]]) {
$dist[$arr["end"]] = $alt;
$previous[$arr["end"]] = $u;
}
}
}
}
$path = array();
$u = $target;
while (isset($previous[$u])) {
array_unshift($path, $u);
$u = $previous[$u];
}
array_unshift($path, $u);
return $path;
}
$graph_array = array(
array("a", "b", 7),
array("a", "c", 9),
array("a", "f", 14),
array("b", "c", 10),
array("b", "d", 15),
array("c", "d", 11),
array("c", "f", 2),
array("d", "e", 6),
array("e", "f", 9)
);
$path = dijkstra($graph_array, "a", "e");
echo "path is: ".implode(", ", $path)."\n";
| from collections import namedtuple, deque
from pprint import pprint as pp
inf = float('inf')
Edge = namedtuple('Edge', ['start', 'end', 'cost'])
class Graph():
def __init__(self, edges):
self.edges = [Edge(*edge) for edge in edges]
self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}
def dijkstra(self, source, dest):
assert source in self.vertices
dist = {vertex: inf for vertex in self.vertices}
previous = {vertex: None for vertex in self.vertices}
dist[source] = 0
q = self.vertices.copy()
neighbours = {vertex: set() for vertex in self.vertices}
for start, end, cost in self.edges:
neighbours[start].add((end, cost))
neighbours[end].add((start, cost))
while q:
u = min(q, key=lambda vertex: dist[vertex])
q.remove(u)
if dist[u] == inf or u == dest:
break
for v, cost in neighbours[u]:
alt = dist[u] + cost
if alt < dist[v]:
dist[v] = alt
previous[v] = u
s, u = deque(), dest
while previous[u]:
s.appendleft(u)
u = previous[u]
s.appendleft(u)
return s
graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10),
("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6),
("e", "f", 9)])
pp(graph.dijkstra("a", "e"))
|
Change the following PHP code into Python without altering its purpose. | <?php
function dijkstra($graph_array, $source, $target) {
$vertices = array();
$neighbours = array();
foreach ($graph_array as $edge) {
array_push($vertices, $edge[0], $edge[1]);
$neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]);
$neighbours[$edge[1]][] = array("end" => $edge[0], "cost" => $edge[2]);
}
$vertices = array_unique($vertices);
foreach ($vertices as $vertex) {
$dist[$vertex] = INF;
$previous[$vertex] = NULL;
}
$dist[$source] = 0;
$Q = $vertices;
while (count($Q) > 0) {
$min = INF;
foreach ($Q as $vertex){
if ($dist[$vertex] < $min) {
$min = $dist[$vertex];
$u = $vertex;
}
}
$Q = array_diff($Q, array($u));
if ($dist[$u] == INF or $u == $target) {
break;
}
if (isset($neighbours[$u])) {
foreach ($neighbours[$u] as $arr) {
$alt = $dist[$u] + $arr["cost"];
if ($alt < $dist[$arr["end"]]) {
$dist[$arr["end"]] = $alt;
$previous[$arr["end"]] = $u;
}
}
}
}
$path = array();
$u = $target;
while (isset($previous[$u])) {
array_unshift($path, $u);
$u = $previous[$u];
}
array_unshift($path, $u);
return $path;
}
$graph_array = array(
array("a", "b", 7),
array("a", "c", 9),
array("a", "f", 14),
array("b", "c", 10),
array("b", "d", 15),
array("c", "d", 11),
array("c", "f", 2),
array("d", "e", 6),
array("e", "f", 9)
);
$path = dijkstra($graph_array, "a", "e");
echo "path is: ".implode(", ", $path)."\n";
| from collections import namedtuple, deque
from pprint import pprint as pp
inf = float('inf')
Edge = namedtuple('Edge', ['start', 'end', 'cost'])
class Graph():
def __init__(self, edges):
self.edges = [Edge(*edge) for edge in edges]
self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}
def dijkstra(self, source, dest):
assert source in self.vertices
dist = {vertex: inf for vertex in self.vertices}
previous = {vertex: None for vertex in self.vertices}
dist[source] = 0
q = self.vertices.copy()
neighbours = {vertex: set() for vertex in self.vertices}
for start, end, cost in self.edges:
neighbours[start].add((end, cost))
neighbours[end].add((start, cost))
while q:
u = min(q, key=lambda vertex: dist[vertex])
q.remove(u)
if dist[u] == inf or u == dest:
break
for v, cost in neighbours[u]:
alt = dist[u] + cost
if alt < dist[v]:
dist[v] = alt
previous[v] = u
s, u = deque(), dest
while previous[u]:
s.appendleft(u)
u = previous[u]
s.appendleft(u)
return s
graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10),
("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6),
("e", "f", 9)])
pp(graph.dijkstra("a", "e"))
|
Ensure the translated Python code behaves exactly like the original PHP snippet. | <?php
function dijkstra($graph_array, $source, $target) {
$vertices = array();
$neighbours = array();
foreach ($graph_array as $edge) {
array_push($vertices, $edge[0], $edge[1]);
$neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]);
$neighbours[$edge[1]][] = array("end" => $edge[0], "cost" => $edge[2]);
}
$vertices = array_unique($vertices);
foreach ($vertices as $vertex) {
$dist[$vertex] = INF;
$previous[$vertex] = NULL;
}
$dist[$source] = 0;
$Q = $vertices;
while (count($Q) > 0) {
$min = INF;
foreach ($Q as $vertex){
if ($dist[$vertex] < $min) {
$min = $dist[$vertex];
$u = $vertex;
}
}
$Q = array_diff($Q, array($u));
if ($dist[$u] == INF or $u == $target) {
break;
}
if (isset($neighbours[$u])) {
foreach ($neighbours[$u] as $arr) {
$alt = $dist[$u] + $arr["cost"];
if ($alt < $dist[$arr["end"]]) {
$dist[$arr["end"]] = $alt;
$previous[$arr["end"]] = $u;
}
}
}
}
$path = array();
$u = $target;
while (isset($previous[$u])) {
array_unshift($path, $u);
$u = $previous[$u];
}
array_unshift($path, $u);
return $path;
}
$graph_array = array(
array("a", "b", 7),
array("a", "c", 9),
array("a", "f", 14),
array("b", "c", 10),
array("b", "d", 15),
array("c", "d", 11),
array("c", "f", 2),
array("d", "e", 6),
array("e", "f", 9)
);
$path = dijkstra($graph_array, "a", "e");
echo "path is: ".implode(", ", $path)."\n";
| from collections import namedtuple, deque
from pprint import pprint as pp
inf = float('inf')
Edge = namedtuple('Edge', ['start', 'end', 'cost'])
class Graph():
def __init__(self, edges):
self.edges = [Edge(*edge) for edge in edges]
self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}
def dijkstra(self, source, dest):
assert source in self.vertices
dist = {vertex: inf for vertex in self.vertices}
previous = {vertex: None for vertex in self.vertices}
dist[source] = 0
q = self.vertices.copy()
neighbours = {vertex: set() for vertex in self.vertices}
for start, end, cost in self.edges:
neighbours[start].add((end, cost))
neighbours[end].add((start, cost))
while q:
u = min(q, key=lambda vertex: dist[vertex])
q.remove(u)
if dist[u] == inf or u == dest:
break
for v, cost in neighbours[u]:
alt = dist[u] + cost
if alt < dist[v]:
dist[v] = alt
previous[v] = u
s, u = deque(), dest
while previous[u]:
s.appendleft(u)
u = previous[u]
s.appendleft(u)
return s
graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10),
("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6),
("e", "f", 9)])
pp(graph.dijkstra("a", "e"))
|
Transform the following PHP implementation into Python, maintaining the same output and logic. | <?php
$pairs = array( "hello" => 1,
"world" => 2,
"!" => 3 );
foreach($pairs as $k => $v) {
echo "(k,v) = ($k, $v)\n";
}
foreach(array_keys($pairs) as $key) {
echo "key = $key, value = $pairs[$key]\n";
}
foreach($pairs as $value) {
echo "values = $value\n";
}
?>
| myDict = { "hello": 13,
"world": 31,
"!" : 71 }
for key, value in myDict.items():
print ("key = %s, value = %s" % (key, value))
for key in myDict:
print ("key = %s" % key)
for key in myDict.keys():
print ("key = %s" % key)
for value in myDict.values():
print ("value = %s" % value)
|
Please provide an equivalent version of this PHP code in Python. | <?php
$pairs = array( "hello" => 1,
"world" => 2,
"!" => 3 );
foreach($pairs as $k => $v) {
echo "(k,v) = ($k, $v)\n";
}
foreach(array_keys($pairs) as $key) {
echo "key = $key, value = $pairs[$key]\n";
}
foreach($pairs as $value) {
echo "values = $value\n";
}
?>
| myDict = { "hello": 13,
"world": 31,
"!" : 71 }
for key, value in myDict.items():
print ("key = %s, value = %s" % (key, value))
for key in myDict:
print ("key = %s" % key)
for key in myDict.keys():
print ("key = %s" % key)
for value in myDict.values():
print ("value = %s" % value)
|
Translate this program into Python but keep the logic exactly as in PHP. | <?php
$pairs = array( "hello" => 1,
"world" => 2,
"!" => 3 );
foreach($pairs as $k => $v) {
echo "(k,v) = ($k, $v)\n";
}
foreach(array_keys($pairs) as $key) {
echo "key = $key, value = $pairs[$key]\n";
}
foreach($pairs as $value) {
echo "values = $value\n";
}
?>
| myDict = { "hello": 13,
"world": 31,
"!" : 71 }
for key, value in myDict.items():
print ("key = %s, value = %s" % (key, value))
for key in myDict:
print ("key = %s" % key)
for key in myDict.keys():
print ("key = %s" % key)
for value in myDict.values():
print ("value = %s" % value)
|
Change the programming language of this snippet from PHP to Python without modifying what it does. | $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
| print()
|
Please provide an equivalent version of this PHP code in Python. | $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
| print()
|
Convert this PHP snippet to Python and keep its semantics consistent. | $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
| print()
|
Ensure the translated Python code behaves exactly like the original PHP snippet. | $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
| print()
|
Generate a Python translation of this PHP snippet without changing its computational steps. | $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
| print()
|
Keep all operations the same but rewrite the snippet in Python. | $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
| print()
|
Port the following code from PHP to Python with equivalent syntax and logic. | <?php
function hashJoin($table1, $index1, $table2, $index2) {
foreach ($table1 as $s)
$h[$s[$index1]][] = $s;
foreach ($table2 as $r)
foreach ($h[$r[$index2]] as $s)
$result[] = array($s, $r);
return $result;
}
$table1 = array(array(27, "Jonah"),
array(18, "Alan"),
array(28, "Glory"),
array(18, "Popeye"),
array(28, "Alan"));
$table2 = array(array("Jonah", "Whales"),
array("Jonah", "Spiders"),
array("Alan", "Ghosts"),
array("Alan", "Zombies"),
array("Glory", "Buffy"),
array("Bob", "foo"));
foreach (hashJoin($table1, 1, $table2, 0) as $row)
print_r($row);
?>
| from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
for s in table1:
h[s[index1]].append(s)
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "Popeye"),
(28, "Alan")]
table2 = [("Jonah", "Whales"),
("Jonah", "Spiders"),
("Alan", "Ghosts"),
("Alan", "Zombies"),
("Glory", "Buffy")]
for row in hashJoin(table1, 1, table2, 0):
print(row)
|
Can you help me rewrite this code in Python instead of PHP, keeping it the same logically? | <?php
function hashJoin($table1, $index1, $table2, $index2) {
foreach ($table1 as $s)
$h[$s[$index1]][] = $s;
foreach ($table2 as $r)
foreach ($h[$r[$index2]] as $s)
$result[] = array($s, $r);
return $result;
}
$table1 = array(array(27, "Jonah"),
array(18, "Alan"),
array(28, "Glory"),
array(18, "Popeye"),
array(28, "Alan"));
$table2 = array(array("Jonah", "Whales"),
array("Jonah", "Spiders"),
array("Alan", "Ghosts"),
array("Alan", "Zombies"),
array("Glory", "Buffy"),
array("Bob", "foo"));
foreach (hashJoin($table1, 1, $table2, 0) as $row)
print_r($row);
?>
| from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
for s in table1:
h[s[index1]].append(s)
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "Popeye"),
(28, "Alan")]
table2 = [("Jonah", "Whales"),
("Jonah", "Spiders"),
("Alan", "Ghosts"),
("Alan", "Zombies"),
("Glory", "Buffy")]
for row in hashJoin(table1, 1, table2, 0):
print(row)
|
Port the provided PHP code into Python while preserving the original functionality. | <?php
function hashJoin($table1, $index1, $table2, $index2) {
foreach ($table1 as $s)
$h[$s[$index1]][] = $s;
foreach ($table2 as $r)
foreach ($h[$r[$index2]] as $s)
$result[] = array($s, $r);
return $result;
}
$table1 = array(array(27, "Jonah"),
array(18, "Alan"),
array(28, "Glory"),
array(18, "Popeye"),
array(28, "Alan"));
$table2 = array(array("Jonah", "Whales"),
array("Jonah", "Spiders"),
array("Alan", "Ghosts"),
array("Alan", "Zombies"),
array("Glory", "Buffy"),
array("Bob", "foo"));
foreach (hashJoin($table1, 1, $table2, 0) as $row)
print_r($row);
?>
| from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
for s in table1:
h[s[index1]].append(s)
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "Popeye"),
(28, "Alan")]
table2 = [("Jonah", "Whales"),
("Jonah", "Spiders"),
("Alan", "Ghosts"),
("Alan", "Zombies"),
("Glory", "Buffy")]
for row in hashJoin(table1, 1, table2, 0):
print(row)
|
Generate a Python translation of this PHP snippet without changing its computational steps. | <?php
class Example {
function foo() {
echo "this is foo\n";
}
function bar() {
echo "this is bar\n";
}
function __call($name, $args) {
echo "tried to handle unknown method $name\n";
if ($args)
echo "it had arguments: ", implode(', ', $args), "\n";
}
}
$example = new Example();
$example->foo(); // prints "this is foo"
$example->bar(); // prints "this is bar"
$example->grill(); // prints "tried to handle unknown method grill"
$example->ding("dong"); // prints "tried to handle unknown method ding"
?>
| class Example(object):
def foo(self):
print("this is foo")
def bar(self):
print("this is bar")
def __getattr__(self, name):
def method(*args):
print("tried to handle unknown method " + name)
if args:
print("it had arguments: " + str(args))
return method
example = Example()
example.foo()
example.bar()
example.grill()
example.ding("dong")
|
Ensure the translated Python code behaves exactly like the original PHP snippet. | <?php
class Example {
function foo() {
echo "this is foo\n";
}
function bar() {
echo "this is bar\n";
}
function __call($name, $args) {
echo "tried to handle unknown method $name\n";
if ($args)
echo "it had arguments: ", implode(', ', $args), "\n";
}
}
$example = new Example();
$example->foo(); // prints "this is foo"
$example->bar(); // prints "this is bar"
$example->grill(); // prints "tried to handle unknown method grill"
$example->ding("dong"); // prints "tried to handle unknown method ding"
?>
| class Example(object):
def foo(self):
print("this is foo")
def bar(self):
print("this is bar")
def __getattr__(self, name):
def method(*args):
print("tried to handle unknown method " + name)
if args:
print("it had arguments: " + str(args))
return method
example = Example()
example.foo()
example.bar()
example.grill()
example.ding("dong")
|
Please provide an equivalent version of this PHP code in Python. | <?php
class Example {
function foo() {
echo "this is foo\n";
}
function bar() {
echo "this is bar\n";
}
function __call($name, $args) {
echo "tried to handle unknown method $name\n";
if ($args)
echo "it had arguments: ", implode(', ', $args), "\n";
}
}
$example = new Example();
$example->foo(); // prints "this is foo"
$example->bar(); // prints "this is bar"
$example->grill(); // prints "tried to handle unknown method grill"
$example->ding("dong"); // prints "tried to handle unknown method ding"
?>
| class Example(object):
def foo(self):
print("this is foo")
def bar(self):
print("this is bar")
def __getattr__(self, name):
def method(*args):
print("tried to handle unknown method " + name)
if args:
print("it had arguments: " + str(args))
return method
example = Example()
example.foo()
example.bar()
example.grill()
example.ding("dong")
|
Produce a language-to-language conversion: from PHP to Python, same semantics. | class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
class Lab extends Dog {
}
class Collie extends Dog {
}
| class Animal:
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
class Lab(Dog):
pass
class Collie(Dog):
pass
|
Write the same algorithm in Python as shown in this PHP implementation. | class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
class Lab extends Dog {
}
class Collie extends Dog {
}
| class Animal:
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
class Lab(Dog):
pass
class Collie(Dog):
pass
|
Rewrite the snippet below in Python so it works the same as the original PHP code. | class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
class Lab extends Dog {
}
class Collie extends Dog {
}
| class Animal:
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
class Lab(Dog):
pass
class Collie(Dog):
pass
|
Rewrite the snippet below in Python so it works the same as the original PHP code. | $array = array();
$array = []; // Simpler form of array initialization
$array['foo'] = 'bar';
$array['bar'] = 'foo';
echo($array['foo']); // bar
echo($array['moo']); // Undefined index
$array2 = array('fruit' => 'apple',
'price' => 12.96,
'colour' => 'green');
$array2 = ['fruit' => 'apple',
'price' => 12.96,
'colour' => 'green'];
echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
| hash = dict()
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = { 'key1':1, 'key2':2, }
value = hash[key]
|
Transform the following PHP implementation into Python, maintaining the same output and logic. | $array = array();
$array = []; // Simpler form of array initialization
$array['foo'] = 'bar';
$array['bar'] = 'foo';
echo($array['foo']); // bar
echo($array['moo']); // Undefined index
$array2 = array('fruit' => 'apple',
'price' => 12.96,
'colour' => 'green');
$array2 = ['fruit' => 'apple',
'price' => 12.96,
'colour' => 'green'];
echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
| hash = dict()
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = { 'key1':1, 'key2':2, }
value = hash[key]
|
Can you help me rewrite this code in Python instead of PHP, keeping it the same logically? | $array = array();
$array = []; // Simpler form of array initialization
$array['foo'] = 'bar';
$array['bar'] = 'foo';
echo($array['foo']); // bar
echo($array['moo']); // Undefined index
$array2 = array('fruit' => 'apple',
'price' => 12.96,
'colour' => 'green');
$array2 = ['fruit' => 'apple',
'price' => 12.96,
'colour' => 'green'];
echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
| hash = dict()
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = { 'key1':1, 'key2':2, }
value = hash[key]
|
Change the programming language of this snippet from PHP to Python without modifying what it does. | class Point
{
protected $_x;
protected $_y;
public function __construct()
{
switch( func_num_args() )
{
case 1:
$point = func_get_arg( 0 );
$this->setFromPoint( $point );
break;
case 2:
$x = func_get_arg( 0 );
$y = func_get_arg( 1 );
$this->setX( $x );
$this->setY( $y );
break;
default:
throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );
}
}
public function setFromPoint( Point $point )
{
$this->setX( $point->getX() );
$this->setY( $point->getY() );
}
public function getX()
{
return $this->_x;
}
public function setX( $x )
{
if( !is_numeric( $x ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_x = (float) $x;
}
public function getY()
{
return $this->_y;
}
public function setY( $y )
{
if( !is_numeric( $y ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_y = (float) $y;
}
public function output()
{
echo $this->__toString();
}
public function __toString()
{
return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';
}
}
| class Point(object):
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __repr__(self):
return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)
class Circle(object):
def __init__(self, center=None, radius=1.0):
self.center = center or Point()
self.radius = radius
def __repr__(self):
return '<Circle 0x%x x: %f y: %f radius: %f>' % (
id(self), self.center.x, self.center.y, self.radius)
|
Rewrite this program in Python while keeping its functionality equivalent to the PHP version. | class Point
{
protected $_x;
protected $_y;
public function __construct()
{
switch( func_num_args() )
{
case 1:
$point = func_get_arg( 0 );
$this->setFromPoint( $point );
break;
case 2:
$x = func_get_arg( 0 );
$y = func_get_arg( 1 );
$this->setX( $x );
$this->setY( $y );
break;
default:
throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );
}
}
public function setFromPoint( Point $point )
{
$this->setX( $point->getX() );
$this->setY( $point->getY() );
}
public function getX()
{
return $this->_x;
}
public function setX( $x )
{
if( !is_numeric( $x ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_x = (float) $x;
}
public function getY()
{
return $this->_y;
}
public function setY( $y )
{
if( !is_numeric( $y ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_y = (float) $y;
}
public function output()
{
echo $this->__toString();
}
public function __toString()
{
return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';
}
}
| class Point(object):
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __repr__(self):
return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)
class Circle(object):
def __init__(self, center=None, radius=1.0):
self.center = center or Point()
self.radius = radius
def __repr__(self):
return '<Circle 0x%x x: %f y: %f radius: %f>' % (
id(self), self.center.x, self.center.y, self.radius)
|
Keep all operations the same but rewrite the snippet in Python. | class Point
{
protected $_x;
protected $_y;
public function __construct()
{
switch( func_num_args() )
{
case 1:
$point = func_get_arg( 0 );
$this->setFromPoint( $point );
break;
case 2:
$x = func_get_arg( 0 );
$y = func_get_arg( 1 );
$this->setX( $x );
$this->setY( $y );
break;
default:
throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );
}
}
public function setFromPoint( Point $point )
{
$this->setX( $point->getX() );
$this->setY( $point->getY() );
}
public function getX()
{
return $this->_x;
}
public function setX( $x )
{
if( !is_numeric( $x ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_x = (float) $x;
}
public function getY()
{
return $this->_y;
}
public function setY( $y )
{
if( !is_numeric( $y ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_y = (float) $y;
}
public function output()
{
echo $this->__toString();
}
public function __toString()
{
return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';
}
}
| class Point(object):
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __repr__(self):
return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)
class Circle(object):
def __init__(self, center=None, radius=1.0):
self.center = center or Point()
self.radius = radius
def __repr__(self):
return '<Circle 0x%x x: %f y: %f radius: %f>' % (
id(self), self.center.x, self.center.y, self.radius)
|
Write the same algorithm in Python as shown in this PHP implementation. | <?php
define('MINEGRID_WIDTH', 6);
define('MINEGRID_HEIGHT', 4);
define('MINESWEEPER_NOT_EXPLORED', -1);
define('MINESWEEPER_MINE', -2);
define('MINESWEEPER_FLAGGED', -3);
define('MINESWEEPER_FLAGGED_MINE', -4);
define('ACTIVATED_MINE', -5);
function check_field($field) {
if ($field === MINESWEEPER_MINE || $field === MINESWEEPER_FLAGGED_MINE) {
return true;
}
else {
return false;
}
}
function explore_field($field) {
if (!isset($_SESSION['minesweeper'][$field])
|| !in_array($_SESSION['minesweeper'][$field],
array(MINESWEEPER_NOT_EXPLORED, MINESWEEPER_FLAGGED))) {
return;
}
$mines = 0;
$fields = &$_SESSION['minesweeper'];
if ($field % MINEGRID_WIDTH !== 1) {
$mines += check_field(@$fields[$field - MINEGRID_WIDTH - 1]);
$mines += check_field(@$fields[$field - 1]);
$mines += check_field(@$fields[$field + MINEGRID_WIDTH - 1]);
}
$mines += check_field(@$fields[$field - MINEGRID_WIDTH]);
$mines += check_field(@$fields[$field + MINEGRID_WIDTH]);
if ($field % MINEGRID_WIDTH !== 0) {
$mines += check_field(@$fields[$field - MINEGRID_WIDTH + 1]);
$mines += check_field(@$fields[$field + 1]);
$mines += check_field(@$fields[$field + MINEGRID_WIDTH + 1]);
}
$fields[$field] = $mines;
if ($mines === 0) {
if ($field % MINEGRID_WIDTH !== 1) {
explore_field($field - MINEGRID_WIDTH - 1);
explore_field($field - 1);
explore_field($field + MINEGRID_WIDTH - 1);
}
explore_field($field - MINEGRID_WIDTH);
explore_field($field + MINEGRID_WIDTH);
if ($field % MINEGRID_WIDTH !== 0) {
explore_field($field - MINEGRID_WIDTH + 1);
explore_field($field + 1);
explore_field($field + MINEGRID_WIDTH + 1);
}
}
}
session_start(); // will start session storage
if (!isset($_SESSION['minesweeper'])) {
$_SESSION['minesweeper'] = array_fill(1,
MINEGRID_WIDTH * MINEGRID_HEIGHT,
MINESWEEPER_NOT_EXPLORED);
$number_of_mines = (int) mt_rand(0.1 * MINEGRID_WIDTH * MINEGRID_HEIGHT,
0.2 * MINEGRID_WIDTH * MINEGRID_HEIGHT);
$random_keys = array_rand($_SESSION['minesweeper'], $number_of_mines);
foreach ($random_keys as $key) {
$_SESSION['minesweeper'][$key] = MINESWEEPER_MINE;
}
$_SESSION['numberofmines'] = $number_of_mines;
}
if (isset($_GET['explore'])) {
if(isset($_SESSION['minesweeper'][$_GET['explore']])) {
switch ($_SESSION['minesweeper'][$_GET['explore']]) {
case MINESWEEPER_NOT_EXPLORED:
explore_field($_GET['explore']);
break;
case MINESWEEPER_MINE:
$lost = 1;
$_SESSION['minesweeper'][$_GET['explore']] = ACTIVATED_MINE;
break;
default:
break;
}
}
else {
die('Tile doesn\'t exist.');
}
}
elseif (isset($_GET['flag'])) {
if(isset($_SESSION['minesweeper'][$_GET['flag']])) {
$tile = &$_SESSION['minesweeper'][$_GET['flag']];
switch ($tile) {
case MINESWEEPER_NOT_EXPLORED:
$tile = MINESWEEPER_FLAGGED;
break;
case MINESWEEPER_MINE:
$tile = MINESWEEPER_FLAGGED_MINE;
break;
case MINESWEEPER_FLAGGED:
$tile = MINESWEEPER_NOT_EXPLORED;
break;
case MINESWEEPER_FLAGGED_MINE:
$tile = MINESWEEPER_MINE;
break;
default:
break;
}
}
else {
die('Tile doesn\'t exist.');
}
}
if (!in_array(MINESWEEPER_NOT_EXPLORED, $_SESSION['minesweeper'])
&& !in_array(MINESWEEPER_FLAGGED, $_SESSION['minesweeper'])) {
$won = true;
}
?>
<!DOCTYPE html>
<title>Minesweeper</title>
<style>
table {
border-collapse: collapse;
}
td, a {
text-align: center;
width: 1em;
height: 1em;
}
a {
display: block;
color: black;
text-decoration: none;
font-size: 2em;
}
</style>
<script>
function flag(number, e) {
if (e.which === 2 || e.which === 3) {
location = '?flag=' + number;
return false;
}
}
</script>
<?php
echo "<p>This field contains $_SESSION[numberofmines] mines.";
?>
<table border="1">
<?php
$mine_copy = $_SESSION['minesweeper'];
for ($x = 1; $x <= MINEGRID_HEIGHT; $x++) {
echo '<tr>';
for ($y = 1; $y <= MINEGRID_WIDTH; $y++) {
echo '<td>';
$number = array_shift($mine_copy);
switch ($number) {
case MINESWEEPER_FLAGGED:
case MINESWEEPER_FLAGGED_MINE:
if (!empty($lost) || !empty($won)) {
if ($number === MINESWEEPER_FLAGGED_MINE) {
echo '<a>*</a>';
}
else {
echo '<a>.</a>';
}
}
else {
echo '<a href=# onmousedown="return flag(',
($x - 1) * MINEGRID_WIDTH + $y,
',event)" oncontextmenu="return false">?</a>';
}
break;
case ACTIVATED_MINE:
echo '<a>:(</a>';
break;
case MINESWEEPER_MINE:
case MINESWEEPER_NOT_EXPLORED:
if (!empty($lost)) {
if ($number === MINESWEEPER_MINE) {
echo '<a>*</a>';
}
else {
echo '<a>.</a>';
}
}
elseif (!empty($won)) {
echo '<a>*</a>';
}
else {
echo '<a href="?explore=',
($x - 1) * MINEGRID_WIDTH + $y,
'" onmousedown="return flag(',
($x - 1) * MINEGRID_WIDTH + $y,
',event)" oncontextmenu="return false">.</a>';
}
break;
case 0:
echo '<a></a>';
break;
default:
echo '<a>', $number, '</a>';
break;
}
}
}
?>
</table>
<?php
if (!empty($lost)) {
unset($_SESSION['minesweeper']);
echo '<p>You lost :(. <a href="?">Reboot?</a>';
}
elseif (!empty($won)) {
unset($_SESSION['minesweeper']);
echo '<p>Congratulations. You won :).';
}
|
gridsize = (6, 4)
minerange = (0.2, 0.6)
try:
raw_input
except:
raw_input = input
import random
from itertools import product
from pprint import pprint as pp
def gridandmines(gridsize=gridsize, minerange=minerange):
xgrid, ygrid = gridsize
minmines, maxmines = minerange
minecount = xgrid * ygrid
minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))
grid = set(product(range(xgrid), range(ygrid)))
mines = set(random.sample(grid, minecount))
show = {xy:'.' for xy in grid}
return grid, mines, show
def printgrid(show, gridsize=gridsize):
xgrid, ygrid = gridsize
grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid))
for y in range(ygrid))
print( grid )
def resign(showgrid, mines, markedmines):
for m in mines:
showgrid[m] = 'Y' if m in markedmines else 'N'
def clear(x,y, showgrid, grid, mines, markedmines):
if showgrid[(x, y)] == '.':
xychar = str(sum(1
for xx in (x-1, x, x+1)
for yy in (y-1, y, y+1)
if (xx, yy) in mines ))
if xychar == '0': xychar = '.'
showgrid[(x,y)] = xychar
for xx in (x-1, x, x+1):
for yy in (y-1, y, y+1):
xxyy = (xx, yy)
if ( xxyy != (x, y)
and xxyy in grid
and xxyy not in mines | markedmines ):
clear(xx, yy, showgrid, grid, mines, markedmines)
if __name__ == '__main__':
grid, mines, showgrid = gridandmines()
markedmines = set([])
print( __doc__ )
print( '\nThere are %i true mines of fixed position in the grid\n' % len(mines) )
printgrid(showgrid)
while markedmines != mines:
inp = raw_input('m x y/c x y/p/r: ').strip().split()
if inp:
if inp[0] == 'm':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in markedmines:
markedmines.remove((x,y))
showgrid[(x,y)] = '.'
else:
markedmines.add((x,y))
showgrid[(x,y)] = '?'
elif inp[0] == 'p':
printgrid(showgrid)
elif inp[0] == 'c':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in mines | markedmines:
print( '\nKLABOOM!! You hit a mine.\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
clear(x,y, showgrid, grid, mines, markedmines)
printgrid(showgrid)
elif inp[0] == 'r':
print( '\nResigning!\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
print( '\nYou got %i and missed %i of the %i mines'
% (len(mines.intersection(markedmines)),
len(markedmines.difference(mines)),
len(mines)) )
|
Change the programming language of this snippet from PHP to Python without modifying what it does. | <?php
define('MINEGRID_WIDTH', 6);
define('MINEGRID_HEIGHT', 4);
define('MINESWEEPER_NOT_EXPLORED', -1);
define('MINESWEEPER_MINE', -2);
define('MINESWEEPER_FLAGGED', -3);
define('MINESWEEPER_FLAGGED_MINE', -4);
define('ACTIVATED_MINE', -5);
function check_field($field) {
if ($field === MINESWEEPER_MINE || $field === MINESWEEPER_FLAGGED_MINE) {
return true;
}
else {
return false;
}
}
function explore_field($field) {
if (!isset($_SESSION['minesweeper'][$field])
|| !in_array($_SESSION['minesweeper'][$field],
array(MINESWEEPER_NOT_EXPLORED, MINESWEEPER_FLAGGED))) {
return;
}
$mines = 0;
$fields = &$_SESSION['minesweeper'];
if ($field % MINEGRID_WIDTH !== 1) {
$mines += check_field(@$fields[$field - MINEGRID_WIDTH - 1]);
$mines += check_field(@$fields[$field - 1]);
$mines += check_field(@$fields[$field + MINEGRID_WIDTH - 1]);
}
$mines += check_field(@$fields[$field - MINEGRID_WIDTH]);
$mines += check_field(@$fields[$field + MINEGRID_WIDTH]);
if ($field % MINEGRID_WIDTH !== 0) {
$mines += check_field(@$fields[$field - MINEGRID_WIDTH + 1]);
$mines += check_field(@$fields[$field + 1]);
$mines += check_field(@$fields[$field + MINEGRID_WIDTH + 1]);
}
$fields[$field] = $mines;
if ($mines === 0) {
if ($field % MINEGRID_WIDTH !== 1) {
explore_field($field - MINEGRID_WIDTH - 1);
explore_field($field - 1);
explore_field($field + MINEGRID_WIDTH - 1);
}
explore_field($field - MINEGRID_WIDTH);
explore_field($field + MINEGRID_WIDTH);
if ($field % MINEGRID_WIDTH !== 0) {
explore_field($field - MINEGRID_WIDTH + 1);
explore_field($field + 1);
explore_field($field + MINEGRID_WIDTH + 1);
}
}
}
session_start(); // will start session storage
if (!isset($_SESSION['minesweeper'])) {
$_SESSION['minesweeper'] = array_fill(1,
MINEGRID_WIDTH * MINEGRID_HEIGHT,
MINESWEEPER_NOT_EXPLORED);
$number_of_mines = (int) mt_rand(0.1 * MINEGRID_WIDTH * MINEGRID_HEIGHT,
0.2 * MINEGRID_WIDTH * MINEGRID_HEIGHT);
$random_keys = array_rand($_SESSION['minesweeper'], $number_of_mines);
foreach ($random_keys as $key) {
$_SESSION['minesweeper'][$key] = MINESWEEPER_MINE;
}
$_SESSION['numberofmines'] = $number_of_mines;
}
if (isset($_GET['explore'])) {
if(isset($_SESSION['minesweeper'][$_GET['explore']])) {
switch ($_SESSION['minesweeper'][$_GET['explore']]) {
case MINESWEEPER_NOT_EXPLORED:
explore_field($_GET['explore']);
break;
case MINESWEEPER_MINE:
$lost = 1;
$_SESSION['minesweeper'][$_GET['explore']] = ACTIVATED_MINE;
break;
default:
break;
}
}
else {
die('Tile doesn\'t exist.');
}
}
elseif (isset($_GET['flag'])) {
if(isset($_SESSION['minesweeper'][$_GET['flag']])) {
$tile = &$_SESSION['minesweeper'][$_GET['flag']];
switch ($tile) {
case MINESWEEPER_NOT_EXPLORED:
$tile = MINESWEEPER_FLAGGED;
break;
case MINESWEEPER_MINE:
$tile = MINESWEEPER_FLAGGED_MINE;
break;
case MINESWEEPER_FLAGGED:
$tile = MINESWEEPER_NOT_EXPLORED;
break;
case MINESWEEPER_FLAGGED_MINE:
$tile = MINESWEEPER_MINE;
break;
default:
break;
}
}
else {
die('Tile doesn\'t exist.');
}
}
if (!in_array(MINESWEEPER_NOT_EXPLORED, $_SESSION['minesweeper'])
&& !in_array(MINESWEEPER_FLAGGED, $_SESSION['minesweeper'])) {
$won = true;
}
?>
<!DOCTYPE html>
<title>Minesweeper</title>
<style>
table {
border-collapse: collapse;
}
td, a {
text-align: center;
width: 1em;
height: 1em;
}
a {
display: block;
color: black;
text-decoration: none;
font-size: 2em;
}
</style>
<script>
function flag(number, e) {
if (e.which === 2 || e.which === 3) {
location = '?flag=' + number;
return false;
}
}
</script>
<?php
echo "<p>This field contains $_SESSION[numberofmines] mines.";
?>
<table border="1">
<?php
$mine_copy = $_SESSION['minesweeper'];
for ($x = 1; $x <= MINEGRID_HEIGHT; $x++) {
echo '<tr>';
for ($y = 1; $y <= MINEGRID_WIDTH; $y++) {
echo '<td>';
$number = array_shift($mine_copy);
switch ($number) {
case MINESWEEPER_FLAGGED:
case MINESWEEPER_FLAGGED_MINE:
if (!empty($lost) || !empty($won)) {
if ($number === MINESWEEPER_FLAGGED_MINE) {
echo '<a>*</a>';
}
else {
echo '<a>.</a>';
}
}
else {
echo '<a href=# onmousedown="return flag(',
($x - 1) * MINEGRID_WIDTH + $y,
',event)" oncontextmenu="return false">?</a>';
}
break;
case ACTIVATED_MINE:
echo '<a>:(</a>';
break;
case MINESWEEPER_MINE:
case MINESWEEPER_NOT_EXPLORED:
if (!empty($lost)) {
if ($number === MINESWEEPER_MINE) {
echo '<a>*</a>';
}
else {
echo '<a>.</a>';
}
}
elseif (!empty($won)) {
echo '<a>*</a>';
}
else {
echo '<a href="?explore=',
($x - 1) * MINEGRID_WIDTH + $y,
'" onmousedown="return flag(',
($x - 1) * MINEGRID_WIDTH + $y,
',event)" oncontextmenu="return false">.</a>';
}
break;
case 0:
echo '<a></a>';
break;
default:
echo '<a>', $number, '</a>';
break;
}
}
}
?>
</table>
<?php
if (!empty($lost)) {
unset($_SESSION['minesweeper']);
echo '<p>You lost :(. <a href="?">Reboot?</a>';
}
elseif (!empty($won)) {
unset($_SESSION['minesweeper']);
echo '<p>Congratulations. You won :).';
}
|
gridsize = (6, 4)
minerange = (0.2, 0.6)
try:
raw_input
except:
raw_input = input
import random
from itertools import product
from pprint import pprint as pp
def gridandmines(gridsize=gridsize, minerange=minerange):
xgrid, ygrid = gridsize
minmines, maxmines = minerange
minecount = xgrid * ygrid
minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))
grid = set(product(range(xgrid), range(ygrid)))
mines = set(random.sample(grid, minecount))
show = {xy:'.' for xy in grid}
return grid, mines, show
def printgrid(show, gridsize=gridsize):
xgrid, ygrid = gridsize
grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid))
for y in range(ygrid))
print( grid )
def resign(showgrid, mines, markedmines):
for m in mines:
showgrid[m] = 'Y' if m in markedmines else 'N'
def clear(x,y, showgrid, grid, mines, markedmines):
if showgrid[(x, y)] == '.':
xychar = str(sum(1
for xx in (x-1, x, x+1)
for yy in (y-1, y, y+1)
if (xx, yy) in mines ))
if xychar == '0': xychar = '.'
showgrid[(x,y)] = xychar
for xx in (x-1, x, x+1):
for yy in (y-1, y, y+1):
xxyy = (xx, yy)
if ( xxyy != (x, y)
and xxyy in grid
and xxyy not in mines | markedmines ):
clear(xx, yy, showgrid, grid, mines, markedmines)
if __name__ == '__main__':
grid, mines, showgrid = gridandmines()
markedmines = set([])
print( __doc__ )
print( '\nThere are %i true mines of fixed position in the grid\n' % len(mines) )
printgrid(showgrid)
while markedmines != mines:
inp = raw_input('m x y/c x y/p/r: ').strip().split()
if inp:
if inp[0] == 'm':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in markedmines:
markedmines.remove((x,y))
showgrid[(x,y)] = '.'
else:
markedmines.add((x,y))
showgrid[(x,y)] = '?'
elif inp[0] == 'p':
printgrid(showgrid)
elif inp[0] == 'c':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in mines | markedmines:
print( '\nKLABOOM!! You hit a mine.\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
clear(x,y, showgrid, grid, mines, markedmines)
printgrid(showgrid)
elif inp[0] == 'r':
print( '\nResigning!\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
print( '\nYou got %i and missed %i of the %i mines'
% (len(mines.intersection(markedmines)),
len(markedmines.difference(mines)),
len(mines)) )
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.