WeixiangYan/CodeTransOcean huggingface dataset:
Task: Sorting algorithms_Sleep sort






PHP: <?php

$buffer = 1;
$pids = [];

for ($i = 1; $i < $argc; $i++) {
    $pid = pcntl_fork();
    if ($pid < 0) {
        die("failed to start child process");
    }

    if ($pid === 0) {
        sleep($argv[$i] + $buffer);
        echo $argv[$i] . "\n";
        exit();
    }
    
    $pids[] = $pid;
}

foreach ($pids as $pid) {
    pcntl_waitpid($pid, $status);
}


Python: from time import sleep
from threading import Timer

def sleepsort(values):
    sleepsort.result = []
    def add1(x):
        sleepsort.result.append(x)
    mx = values[0]
    for v in values:
        if mx < v: mx = v
        Timer(v, add1, [v]).start()
    sleep(mx+1)
    return sleepsort.result

if __name__ == '__main__':
    x = [3,2,4,7,3,6,9,1]
    if sleepsort(x) == sorted(x):
        print('sleep sort worked for:',x)
    else:
        print('sleep sort FAILED for:',x)
Task: Loops_Nested






PHP: <?php
for ($i = 0; $i < 10; $i++)
    for ($j = 0; $j < 10; $j++)
        $a[$i][$j] = rand(1, 20);

foreach ($a as $row) {
    foreach ($row as $element) {
        echo " $element";
        if ($element == 20)
            break 2; // 2 is the number of loops we want to break out of
    }
    echo "\n";
}
echo "\n";
?>


Python: from random import randint

def do_scan(mat):
    for row in mat:
        for item in row:
            print item,
            if item == 20:
                print
                return
        print
    print

mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
do_scan(mat)
Task: Pythagorean triples






PHP: <?php
 
function gcd($a, $b)
{
    if ($a == 0)
       return $b;
    if ($b == 0)
       return $a;
    if($a == $b)
        return $a;
    if($a > $b)
        return gcd($a-$b, $b);
    return gcd($a, $b-$a);
}

$pytha = 0;
$prim = 0;
$max_p = 100;

for ($a = 1; $a <= $max_p / 3; $a++) {
    $aa = $a**2;
    for ($b = $a + 1; $b < $max_p/2; $b++) {
        $bb = $b**2;
        for ($c = $b + 1; $c < $max_p/2; $c++) {
            $cc = $c**2;
            if ($aa + $bb < $cc) break;
            if ($a + $b + $c > $max_p) break;

            if ($aa + $bb == $cc) {
                $pytha++;
                if (gcd($a, $b) == 1) $prim++;
            }
        }
    }
}

echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';


Python: from fractions import gcd


def pt1(maxperimeter=100):
    
    trips = []
    for a in range(1, maxperimeter):
        aa = a*a
        for b in range(a, maxperimeter-a+1):
            bb = b*b
            for c in range(b, maxperimeter-b-a+1):
                cc = c*c
                if a+b+c > maxperimeter or cc > aa + bb: break
                if aa + bb == cc:
                    trips.append((a,b,c, gcd(a, b) == 1))
    return trips

def pytrip(trip=(3,4,5),perim=100, prim=1):
    a0, b0, c0 = a, b, c = sorted(trip)
    t, firstprim = set(), prim>0
    while a + b + c <= perim:
        t.add((a, b, c, firstprim>0))
        a, b, c, firstprim = a+a0, b+b0, c+c0, False
    
    t2 = set()
    for a, b, c, firstprim in t:
        a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
        if  a5 - b5 + c7 <= perim:
            t2 |= pytrip(( a - b2 + c2,  a2 - b + c2,  a2 - b2 + c3), perim, firstprim)
        if  a5 + b5 + c7 <= perim:
            t2 |= pytrip(( a + b2 + c2,  a2 + b + c2,  a2 + b2 + c3), perim, firstprim)
        if -a5 + b5 + c7 <= perim:
            t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
    return t | t2

def pt2(maxperimeter=100):
    
    trips = pytrip((3,4,5), maxperimeter, 1)
    return trips

def printit(maxperimeter=100, pt=pt1):
    trips = pt(maxperimeter)
    print("  Up to a perimeter of %i there are %i triples, of which %i are primitive"
          % (maxperimeter,
             len(trips),
             len([prim for a,b,c,prim in trips if prim])))
  
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
    print(algo.__doc__)
    for maxperimeter in range(mn, mx+1, mn):
        printit(maxperimeter, algo)
Task: Remove duplicate elements






PHP: $list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');
$unique_list = array_unique($list);


Python: items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
Task: Look-and-say sequence






PHP: <?php

function lookAndSay($str) {

	return preg_replace_callback('#(.)\1*#', function($matches) {
	
		return strlen($matches[0]).$matches[1];
	}, $str);
}

$num = "1";

foreach(range(1,10) as $i) {

	echo $num."<br/>";
	$num = lookAndSay($num);
}

?>


Python: def lookandsay(number):
    result = ""

    repeat = number[0]
    number = number[1:]+" "
    times = 1

    for actual in number:
        if actual != repeat:
            result += str(times)+repeat
            times = 1
            repeat = actual
        else:
            times += 1

    return result

num = "1"

for i in range(10):
    print num
    num = lookandsay(num)
Task: Stack






PHP: $stack = array();

empty( $stack ); // true

array_push( $stack, 1 ); // or $stack[] = 1;
array_push( $stack, 2 ); // or $stack[] = 2;

empty( $stack ); // false

echo array_pop( $stack ); // outputs "2"
echo array_pop( $stack ); // outputs "1"


Python: from collections import deque
stack = deque()
stack.append(value) 
value = stack.pop()
not stack
Task: Conditional structures






PHP: <?php

$foo = 3;

if ($foo == 2)


if ($foo == 3)

else


if ($foo != 0)
{

}
else
{

}

?>


Python: if x == 0:
    foo()
elif x == 1:
    bar()
elif x == 2:
    baz()
else:
    qux()

match x:
    0 => foo()
    1 => bar()
    2 => baz()
    _ => qux()

(a) ? b : c
Task: Sorting algorithms_Stooge sort






PHP: function stoogeSort(&$arr, $i, $j)
{
	if($arr[$j] < $arr[$i])
	{
		list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);
	}
	if(($j - $i) > 1)
	{
		$t = ($j - $i + 1) / 3;
		stoogesort($arr, $i, $j - $t);
		stoogesort($arr, $i + $t, $j);
		stoogesort($arr, $i, $j - $t);
	}
}


Python: >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
	if j is None:
		j = len(L) - 1
	if L[j] < L[i]:
		L[i], L[j] = L[j], L[i]
	if j - i > 1:
		t = (j - i + 1) // 3
		stoogesort(L, i  , j-t)
		stoogesort(L, i+t, j  )
		stoogesort(L, i  , j-t)
	return L

>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
Task: Read a configuration file






PHP: <?php

$conf = file_get_contents('parse-conf-file.txt');

$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);





$conf = preg_replace_callback(
    '/^([a-z]+)\s*=((?=.*\,.*).*)$/mi',
    function ($matches) {
        $r = '';
        foreach (explode(',', $matches[2]) AS $val) {
            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;
        }
        return $r;
    },
    $conf
);

$conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf);

$ini = parse_ini_string($conf);

echo 'Full name       = ', $ini['FULLNAME'], PHP_EOL;
echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;
echo 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;
echo 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;
echo 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;


Python: def readconf(fn):
    ret = {}
    with file(fn) as fp:
        for line in fp:
            
            line = line.strip()
            if not line or line.startswith('
            
            boolval = True
            
            if line.startswith(';'):
                
                line = line.lstrip(';')
                
                if len(line.split()) != 1: continue
                boolval = False
            
            bits = line.split(None, 1)
            if len(bits) == 1:
                
                k = bits[0]
                v = boolval
            else:
                
                k, v = bits
            ret[k.lower()] = v
    return ret


if __name__ == '__main__':
    import sys
    conf = readconf(sys.argv[1])
    for k, v in sorted(conf.items()):
        print k, '=', v
Task: Sort using a custom comparator






PHP: <?php
function mycmp($s1, $s2)
{
    if ($d = strlen($s2) - strlen($s1))
        return $d;
    return strcasecmp($s1, $s2);
}

$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
usort($strings, "mycmp");
?>


Python: strings = "here are Some sample strings to be sorted".split()

def mykey(x):
    return -len(x), x.upper()

print sorted(strings, key=mykey)
Task: Sorting algorithms_Selection sort






PHP: function selection_sort(&$arr) {
    $n = count($arr);
    for($i = 0; $i < count($arr); $i++) {
        $min = $i;
        for($j = $i + 1; $j < $n; $j++){
            if($arr[$j] < $arr[$min]){
                $min = $j;
            }
        }
        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
    }
}


Python: def selection_sort(lst):
    for i, e in enumerate(lst):
        mn = min(range(i,len(lst)), key=lst.__getitem__)
        lst[i], lst[mn] = lst[mn], e
    return lst
Task: Apply a callback to an array






PHP: function cube($n)
{
   return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);


Python: def square(n):
    return n * n
  
numbers = [1, 3, 5, 7]

squares1 = [square(n) for n in numbers]     

squares2a = map(square, numbers)            

squares2b = map(lambda x: x*x, numbers)     

squares3 = [n * n for n in numbers]         
                                            

isquares1 = (n * n for n in numbers)        

import itertools
isquares2 = itertools.imap(square, numbers)
Task: Singleton






PHP: class Singleton {
  protected static $instance = null;
  public $test_var;
  private function __construct(){

  }
  public static function getInstance(){
    if (is_null(self::$instance)){
      self::$instance = new self();
    }
    return self::$instance;
  }
}

$foo = Singleton::getInstance();
$foo->test_var = 'One';

$bar = Singleton::getInstance();
echo $bar->test_var; //Prints 'One'

$fail = new Singleton(); //Fatal error


Python: >>> class Borg(object):
	__state = {}
	def __init__(self):
		self.__dict__ = self.__state
	

	
>>> b1 = Borg()
>>> b2 = Borg()
>>> b1 is b2
False
>>> b1.datum = range(5)
>>> b1.datum
[0, 1, 2, 3, 4]
>>> b2.datum
[0, 1, 2, 3, 4]
>>> b1.datum is b2.datum
True
>>>
Task: Case-sensitivity of identifiers






PHP: <?php



$dog = 'Benjamin';
$Dog = 'Samba';
$DOG = 'Bernie';

echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n";


function DOG() { return 'Bernie'; }

echo 'There is only 1 dog named ' . dog() . "\n";


Python: >>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'
>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)
The three dogs are named  Benjamin ,  Samba , and  Bernie
>>>
Task: Loops_Downward for






PHP: for ($i = 10; $i >= 0; $i--)
  echo "$i\n";


Python: for i in xrange(10, -1, -1):
    print i
Task: Loops_For






PHP: for ($i = 1; $i <= 5; $i++) {
  for ($j = 1; $j <= $i; $j++) {
    echo '*';
  }
  echo "\n";
}


Python: for i in 1..5:
  for j in 1..i:
    stdout.write("*")
  echo("")
Task: Long multiplication






PHP: <?php
function longMult($a, $b)
{
  $as = (string) $a;
  $bs = (string) $b;
  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)
    {
      for($p = 0; $p < $pi; $p++)
        {
          $regi[$ai][] = 0;
        }
      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)
        {
          $regi[$ai][] = $as[$ai] * $bs[$bi];
        }
    }
  return $regi;
}

function longAdd($arr)
{
  $outer = count($arr);
  $inner = count($arr[$outer-1]) + $outer;
  for($i = 0; $i <= $inner; $i++)
    {
      for($o = 0; $o < $outer; $o++)
        {
          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;
          @$sum[$i] += $val;
        }
    }
  return $sum;
}

function carry($arr)
{
  for($i = 0; $i < count($arr); $i++)
    {
      $s = (string) $arr[$i];
      switch(strlen($s))
        {
          case 2:
            $arr[$i] = $s{1};
            @$arr[$i+1] += $s{0};
            break;
          case 3:
            $arr[$i] = $s{2};
            @$arr[$i+1] += $s{0}.$s{1};
            break;
        }
    }
  return ltrim(implode('',array_reverse($arr)),'0');
}

function lm($a,$b)
{
  return carry(longAdd(longMult($a,$b)));
}

if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')
  {
    echo 'pass!';
  }; // 2^64 * 2^64


Python: 
print 2**64*2**64
Task: Bulls and cows






PHP: <?php
$size = 4;

$chosen = implode(array_rand(array_flip(range(1,9)), $size));

echo "I've chosen a number from $size unique digits from 1 to 9; you need
to input $size unique digits to guess my number\n";

for ($guesses = 1; ; $guesses++) {
    while (true) {
        echo "\nNext guess [$guesses]: ";
        $guess = rtrim(fgets(STDIN));
        if (!checkguess($guess))
            echo "$size digits, no repetition, no 0... retry\n";
        else
            break;
    }
    if ($guess == $chosen) {
        echo "You did it in $guesses attempts!\n";
        break;
    } else {
        $bulls = 0;
        $cows = 0;
        foreach (range(0, $size-1) as $i) {
            if ($guess[$i] == $chosen[$i])
                $bulls++;
            else if (strpos($chosen, $guess[$i]) !== FALSE)
                $cows++;
        }
        echo "$cows cows, $bulls bulls\n";
    }
}

function checkguess($g)
{
  global $size;
  return count(array_unique(str_split($g))) == $size &&
    preg_match("/^[1-9]{{$size}}$/", $g);
}
?>


Python: 

import random

digits = '123456789'
size = 4
chosen = ''.join(random.sample(digits,size))

print  % (size, size)
guesses = 0
while True:
    guesses += 1
    while True:
        
        guess = raw_input('\nNext guess [%i]: ' % guesses).strip()
        if len(guess) == size and \
           all(char in digits for char in guess) \
           and len(set(guess)) == size:
            break
        print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size
    if guess == chosen:
        print '\nCongratulations you guessed correctly in',guesses,'attempts'
        break
    bulls = cows = 0
    for i in range(size):
        if guess[i] == chosen[i]:
            bulls += 1
        elif guess[i] in chosen:
            cows += 1
    print '  %i Bulls\n  %i Cows' % (bulls, cows)
Task: Sorting algorithms_Bubble sort






PHP: function bubbleSort(array $array){
    foreach($array as $i => &$val){
        foreach($array as $k => &$val2){
            if($k <= $i)
                continue;
            if($val > $val2) {
                list($val, $val2) = [$val2, $val];
                break;
            }
        }
    }
    return $array;
}


Python: def bubble_sort(seq):
    
    changed = True
    while changed:
        changed = False
        for i in range(len(seq) - 1):
            if seq[i] > seq[i+1]:
                seq[i], seq[i+1] = seq[i+1], seq[i]
                changed = True
    return seq

if __name__ == "__main__":
   

   from random import shuffle

   testset = [_ for _ in range(100)]
   testcase = testset.copy() 
   shuffle(testcase)
   assert testcase != testset  
   bubble_sort(testcase)
   assert testcase == testset
Task: File input_output






PHP: <?php

if (!$in = fopen('input.txt', 'r')) {
    die('Could not open input file.');
}

if (!$out = fopen('output.txt', 'w')) {
    die('Could not open output file.');
}

while (!feof($in)) {
    $data = fread($in, 512);
    fwrite($out, $data);
}

fclose($out);
fclose($in);
?>


Python: import shutil
shutil.copyfile('input.txt', 'output.txt')
Task: Arithmetic_Integer






PHP: <?php
$a = fgets(STDIN);
$b = fgets(STDIN);

echo
    "sum:                 ", $a + $b, "\n",
    "difference:          ", $a - $b, "\n",
    "product:             ", $a * $b, "\n",
    "truncating quotient: ", (int)($a / $b), "\n",
    "flooring quotient:   ", floor($a / $b), "\n",
    "remainder:           ", $a % $b, "\n",
    "power:               ", $a ** $b, "\n"; // PHP 5.6+ only
?>


Python: x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))

print "Sum: %d" % (x + y)
print "Difference: %d" % (x - y)
print "Product: %d" % (x * y)
print "Quotient: %d" % (x / y)     
                                   
print "Remainder: %d" % (x % y)    
print "Quotient: %d with Remainder: %d" % divmod(x, y)
print "Power: %d" % x**y


raw_input( )
Task: Matrix transposition






PHP: function transpose($m) {
  if (count($m) == 0) // special case: empty matrix
    return array();
  else if (count($m) == 1) // special case: row matrix
    return array_chunk($m[0], 1);

  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value
  return call_user_func_array('array_map', $m);
}


Python: m=((1,  1,  1,   1),
   (2,  4,  8,  16),
   (3,  9, 27,  81),
   (4, 16, 64, 256),
   (5, 25,125, 625))
print(zip(*m))
Task: Man or boy test






PHP: <?php
function A($k,$x1,$x2,$x3,$x4,$x5) {
    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {
        return A(--$k,$b,$x1,$x2,$x3,$x4);
    };
    return $k <= 0 ? $x4() + $x5() : $b();
}  

echo A(10, function () { return  1; },
           function () { return -1; },
           function () { return -1; },
           function () { return  1; }, 
           function () { return  0; }) . "\n";
?>


Python: 
import sys
sys.setrecursionlimit(1025)

def a(in_k, x1, x2, x3, x4, x5):
    k = [in_k]
    def b():
        k[0] -= 1
        return a(k[0], b, x1, x2, x3, x4)
    return x4() + x5() if k[0] <= 0 else b()

x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
Task: Find limit of recursion






PHP: <?php
function a() {
    static $i = 0;
    print ++$i . "\n";
    a();
}
a();


Python: import sys
print(sys.getrecursionlimit())
Task: Perfect numbers






PHP: function is_perfect($number)
{
    $sum = 0;
    for($i = 1; $i < $number; $i++)
    {
        if($number % $i == 0)
            $sum += $i;
    }
    return $sum == $number;
}

echo "Perfect numbers from 1 to 33550337:" . PHP_EOL;
for($num = 1; $num < 33550337; $num++)
{
    if(is_perfect($num))
        echo $num . PHP_EOL;
}


Python: def perf1(n):
    sum = 0
    for i in range(1, n):
        if n % i == 0:
            sum += i
    return sum == n
Task: Sorting algorithms_Bead sort






PHP: <?php
function columns($arr) {
    if (count($arr) == 0)
        return array();
    else if (count($arr) == 1)
        return array_chunk($arr[0], 1);

    array_unshift($arr, NULL);

    $transpose = call_user_func_array('array_map', $arr);
    return array_map('array_filter', $transpose);
}

function beadsort($arr) {
    foreach ($arr as $e)
        $poles []= array_fill(0, $e, 1);
    return array_map('count', columns(columns($poles)));
}

print_r(beadsort(array(5,3,1,7,4,1,1)));
?>


Python: 
from itertools import zip_longest


def beadsort(l):
    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))



print(beadsort([5,3,1,7,4,1,1]))
Task: Arbitrary-precision integers (included)






PHP: <?php
$y = bcpow('5', bcpow('4', bcpow('3', '2')));
printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y));
?>


Python: >>> y = str( 5**4**3**2 )
>>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y)))
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Task: Inverted index






PHP: <?php

function buildInvertedIndex($filenames)
{
    $invertedIndex = [];

    foreach($filenames as $filename)
    {
        $data = file_get_contents($filename);

        if($data === false) die('Unable to read file: ' . $filename);

        preg_match_all('/(\w+)/', $data, $matches, PREG_SET_ORDER);

        foreach($matches as $match)
        {
            $word = strtolower($match[0]);

            if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];
            if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;
        }
    }

    return $invertedIndex;
}

function lookupWord($invertedIndex, $word)
{
    return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;
}

$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);

foreach(['cat', 'is', 'banana', 'it'] as $word)
{
    $matches = lookupWord($invertedIndex, $word);

    if($matches !== false)
    {
        echo "Found the word \"$word\" in the following files: " . implode(', ', $matches) . "\n";
    }
    else
    {
        echo "Unable to find the word \"$word\" in the index\n";
    }
}


Python: 

from pprint import pprint as pp
from glob import glob
try: reduce
except: from functools import reduce
try:    raw_input
except: raw_input = input


def parsetexts(fileglob='InvertedIndex/T*.txt'):
    texts, words = {}, set()
    for txtfile in glob(fileglob):
        with open(txtfile, 'r') as f:
            txt = f.read().split()
            words |= set(txt)
            texts[txtfile.split('\\')[-1]] = txt
    return texts, words

def termsearch(terms): 
    return reduce(set.intersection,
                  (invindex[term] for term in terms),
                  set(texts.keys()))

texts, words = parsetexts()
print('\nTexts')
pp(texts)
print('\nWords')
pp(sorted(words))

invindex = {word:set(txt
                        for txt, wrds in texts.items() if word in wrds)
            for word in words}
print('\nInverted Index')
pp({k:sorted(v) for k,v in invindex.items()})

terms = ["what", "is", "it"]
print('\nTerm Search for: ' + repr(terms))
pp(sorted(termsearch(terms)))
Task: Least common multiple






PHP: echo lcm(12, 18) == 36;

function lcm($m, $n) {
    if ($m == 0 || $n == 0) return 0;
    $r = ($m * $n) / gcd($m, $n);
    return abs($r);
}

function gcd($a, $b) {
    while ($b != 0) {
        $t = $b;
        $b = $a % $b;
        $a = $t;
    }
    return $a;
}


Python: >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0

>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
Task: Loops_Break






PHP: while (true) {
    $a = rand(0,19);
    echo "$a\n";
    if ($a == 10)
        break;
    $b = rand(0,19);
    echo "$b\n";
}


Python: from random import randrange

while True:
    a = randrange(20)
    print(a)
    if a == 10:
        break
    b = randrange(20)
    print(b)
Task: Hello world_Line printer






PHP: <?php
file_put_contents('/dev/lp0', 'Hello world!');
?>


Python: lp = open("/dev/lp0")
lp.write("Hello World!\n")
lp.close()
Task: Trabb Pardo–Knuth algorithm






PHP: <?php



function f($n)
{
    return sqrt(abs($n)) + 5 * $n * $n * $n;
}

$sArray = [];
echo "Enter 11 numbers.\n";
for ($i = 0; $i <= 10; $i++) {
    echo $i + 1, " - Enter number: "; 
    array_push($sArray, (float)fgets(STDIN)); 
}
echo PHP_EOL;

$sArray = array_reverse($sArray);

foreach ($sArray as $s) {
    $r = f($s);
    echo "f(", $s, ") = ";
    if ($r > 400) 
        echo "overflow\n";
    else
        echo $r, PHP_EOL;
}
?>


Python: Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def f(x): return abs(x) ** 0.5 + 5 * x**3

>>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!")
	           for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1])))

11 numbers: 1 2 3 4 5 6 7 8 9 10 11
11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0
>>>