Python Translator

Please put small code samples here from other languages, and we will try to translate it into PythonLanguage. The goal is to ease the learning curve for Python.


In AplLanguage: +/M where M is any numeric matrix of rank 2 thru X (integer), result is another matrix of rank (x-1), where the projection is summed up. Example of APL operation on a matrix (rank 2) results in a vector (rank 1):
     | 1 2 3 |
 M = | 4 5 6 |
     | 7 8 9 |

'' +/ (reads Plus reduce) means the operator "+" is applied to the data. For a 1 dimensional vector, it just adds everything (to a scalar of rank 0). But it works on higher dimensions, too. The above would sum to:

     | 12 15 18 |

If the input were a 3d matrix, the output would be a 2d matrix resulting from summing along the third dimension. The APL standard supports matrices up to at least 63 dimensions. So although it would be easy to implement sum for a 1-vector or a 2-matrix in any language, it is more complicated to handle X dimensions, yet the APL code is still just +/M -- so this problem was obviously posed by a SmugAplWeenie?. :-)

Python bites back :)

How's this (generalised OO version):
 class Matrix(list):
    def _reduce(self, f):
        try:
            return Matrix([f(x) for x in zip(*self)])
        except TypeError:
            try:
                return Matrix([Matrix(x)._reduce(f) for x in zip(*self)])
            except TypeError:
                return f(self)

def r_sum(self): return self._reduce(sum)

def r_mul(self): mul = lambda x: reduce(operator.mul, x) return self._reduce(mul)

a = Matrix([1,2,3]) b = Matrix([[1,2,3]]) c = Matrix([[1,2,3], [4,5,6], [7,8,9]]) d = Matrix([[[1,2,3], [4,5,6], [7,8,9]], [[10,11,12], [13,14,15], [16,17,18]], [[19,20,21],[22,23,24], [25,26,27]]])

>>> print a.r_sum() 6 >>> print b.r_sum() [1, 2, 3] >>> print c.r_sum() [12, 15, 18] >>> print d.r_sum() [[30, 33, 36], [39, 42, 45], [48, 51, 54]]

It'll hit an upper limit when it runs out of stack, but should be able to handle a 64d matrix Not that I'm aware of - Python tends to use the SamuraiPrinciple - though you can probably estimate by analysing the algorithm. That said, you're probably better off NOT using pure python for heavy number crunching (for a low number of dimensions Python should be fine - for a large number, you'll probably run out of memory - if not experience heat death of the universe). The Numeric or NumPy? package may be suitable, however. if you do run out of stack, you could always use StacklessPython

-- TaroOgawa


In PerlLanguage: Taken from (http://www.perlmonks.net/index.pl?node_id=6940). The expected output is the primes between 2 and 99, each on a new line:

 perl -e 'while($l++<99){$_.=x;print $l,$/if! /^x$|^(xx+)\1+$/}'

In Python:
 import re
 for i in range(1,100):
    if not re.match(r"^x$|^(xx+)\1+$", "x"*i):
        print i

Or if you want to be a little bit more Pythonic (and faster too):
 def primes(low, high):
    m = re.compile(r"^x$|^(xx+)\1+$")
    primes = [str(i) for i in range(low, high+1) if not m.match("x"*i)]
    print "\n".join(primes)


In PerlLanguage:
 #!/usr/local/bin/perl -w
 use strict;
 use Tie::File;

my $file = shift; my @array;

tie @array, 'Tie::File', $file or die "$file can't be opened:$!\n";

$array[1] = 'blah'; # line 2 of the file is now 'blah' print "[" . $array[2] . "]\n"; # display line 3 of the file push( @array, "new line" ); # add a line to the file

Here's what this example does.

$ cat junk 1 SimpleType?.pm 2 badshebang.pl 3 bitshift.pl 4 cat $ ./tie_array.pl junk [3 bitshift.pl] $ cat junk 1 SimpleType?.pm blah 3 bitshift.pl 4 cat new line

Basically I am asking what is the Python equiv. of Tie::File

Python:
 #! /usr/local/bin/python
 class Tie(list):
     def __init__(self, filename):
         self.f = open(filename, 'r+')
         list.__init__(self, [line[:-1] for line in self.f])
         self.f.seek(0)

def close(self): if self.f: for line in self: print >> self.f, line self.f.close() self.f = None

def __del__(self): self.close()

if __name__ == '__main__': import sys fn = sys.argv[1] array = Tie(fn) array[1] = 'blah' print "[%s]" % array[2] array.append("newline")


In PerlLanguage:

print __FILE__ . "[" . __LINE__ . "] here is some debug on line foo of file bar\n";

You'll want to define a HelperFunction for that. Something like this:

 import traceback

def log(*args): caller = traceback.extract_stack()[-2] print "%s:%d: %s" % (caller[0], caller[1], ''.join(str(a) for a in args))

And using caller[2] would give you the function name.


How does one do constructor overloading in Python? In JavaLanguage:

 class MyObject {
          public MyObject() {
                 System.out.println("uno");
          }
 }

class MyClass { private int a; private MyObject my;

public MyClass(int a) { this.a = a; }

public MyClass(MyObject? my) { this.my = my; }

}

class MyTest {

public static void main(String args[]) { MyClass mc1 = new MyClass(42); MyClass mc2 = new MyClass(new MyObject()); } }

You don't. Python uses DynamicTypes? and thus doesn't offer any kind of "overloading" based on argument type. The way this is typically done in Python:

class MyObject:
    def __init__(self): print "UNO"

class MyClass: pass

def MyClassWithInt(a):
    new_instance = MyClass()
    new_instance.a = a
    return new_instance

def MyClassWithObject(my):
    new_instance = MyClass()
    new_instance.my = my
    return new_instance

if __name__ == '__main__':
    mc1 = MyClassWithInt(42)
    mc2 = MyClassWithObject(MyObject())

You could also use class methods as factories instead of the module-level functions used here, but there's no practical difference for this contrived example.


Printing a hello message to someone, asking for their name:

In CeeLanguage:
 #include <stdio.h>

int main(void) { char name[30]; printf("What's your name?"); scanf("%s", name); printf("Hello, %s\n", name); return 0; }

In Python:

 name = raw_input("What's your name? ")
 print "Hello, %s" % name

(Note that the Python version does not suffer from the BufferOverflow bug that the C version has.)


In CeePlusPlus:
 /*pretty sure this code would compile*/
 #include <iostream.h>
 main()
 {
 	int arr[] = { 1,2,3,4,5,6,7,8,9,10};
 	cout << "This is my array, watch as I output it";
 	for(int i =0;i < 10; i ++)
 	{
 		cout << arr[i];
 	}
 	cout << "\nThis is my c++ example code to output an array, I wonder what it would be in python?";

}
-- camthompson@shaw.ca

 arr = range(1,11)	# alternatively: arr = [ 1,2,3,4,5,6,7,8,9,10 ]
 print "This is my array, which I will output."
 for i in arr:
	print i,
 print "\nNot so different, just a bit simpler, isn't it?"

If you don't mind Python's list output style, you can avoid the loop:

 arr = range(1,11)	
 print 'This is my array, which I will output.'
 print arr
 print "Even simpler, isn't it?"

If you do mind Python's list output style, you can convert and trim the edges:

 arr = range(1,11)	
 print 'This is my array, which I will output.'
 print str(arr)[1:-1]
 print "This is a bit of a cheat."

Or more obscurely:

 arr = range(1,11)	
 print 'This is my array, which I will output.'
 print ' '.join([str(i) for i in arr])
 print "Rather different, isn't it?"

Or even more obscurely:
 arr = range(1,11)	
 print 'This is my array, which I will output.'
 print 10*"%s "%tuple(arr)
 print "TMTOWTDI but not all are equally good."


In PerlLanguage: taken from http://www.perlmonks.net/index.pl?node_id=358667
 #
 # draw the pegs on the board based on the information
 # contained in the board object
 #
 # dx, dy, radius, units are global vars
 #
 # $can is a Tk::Canvas object
 sub placePegs {
        my $can = shift;
        my $board = shift;
        my $hole = 0;
        my $tag;
        my $radius = 10;

$tag = "HOLE_$hole"; $can->create(oval => $dx*($units/2)-$radius, $dy-$radius, $dx*($units/2)+$radius, $dy+$radius, -fill => $board->{'holes'}[$hole]->{'peg'}, -tag => [$tag] ); $can->bind( $tag, '<Button>' , [\&selectPeg, $hole] ); $hole++; }

In Python:
 #
 # draw the pegs on the board based on the information
 # contained in the board object
 #
 def placePegs ( can, board, width, height ):
        hole    = 0
        radius  = 10
        units   = 10;
        dx = width  / units;
        dy = height / units;

tag = "HOLE_" + str(hole) item = can.create_oval ( dx*(units/2)-radius, dy-radius, dx*(units/2)+radius, dy+radius, fill = 'white', #$board->{'holes'}[$hole]->{'peg'}, tag = tag ) # for some reason I have to pass this e thing in. can.tag_bind( tag, '<Button>' , lambda e, h=hole: selectPeg(e,h))

hole = hole + 1

mailto:sheldonplankton@yahoo.com

"e" gets the Event object. The Perl program throws it away in the linked page; that's what that first "shift" in selectPeg does. Have you read http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm ?


From GuySteele's LL1-discuss mailing list posting:

 (defun @eval (exp env cont)
  (cond ((numberp exp) (funcall cont exp))
        ((stringp exp) (funcall cont exp))
        ((symbolp exp) (@lookup exp env cont))
        ((eq (first exp) 'LAMBDA)
         (funcall cont (list 'CLOSURE (second exp) (rest (rest exp)) env)))
        ((eq (first exp) 'IF)
         (@eval (second exp) env
                #'(lambda (test)
                    (@eval (cond (test (second exp)) (t (third exp))) env cont))))
        ((eq (first exp) 'LETREC)
         (let ((newenv (pairlis (mapcar #'first (second exp))
                                (make-list (length (second exp)))
                                env)))
           (@evletrec (second exp) newenv (third exp) newenv cont)))
        (t (@eval (first exp) env
                  #'(lambda (fn)
                      (@evlis (rest exp) env
                              #'(lambda (args) (@apply fn args cont))))))))

(defun @lookup (name env cont) (cond ((null env) (funcall cont name)) ((eq (car (first env)) name) (funcall cont (cdr (first env)))) (t (@lookup name (rest env) cont))))

(defun @evlis (exps env cont) (cond ((null exps) (funcall cont '())) (t (@eval (first exps) env #'(lambda (arg) (@evlis (rest exps) env #'(lambda (args) (funcall cont (cons arg args)))))))))

(defun @evletrec (bindings slots body env cont) (cond ((null bindings) (@eval body env cont)) (t (@eval (second (first bindings)) env #'(lambda (fn) (rplacd (first slots) fn) ;the side effect that "ties the knot" (@evletrec (rest bindings) (rest slots) body env cont))))))

(defun @apply (fn args cont) (cond ((eq fn '+) (funcall cont (+ (first args) (second args)))) ((eq fn '*) (funcall cont (* (first args) (second args)))) ((eq fn 'print) (princ (first args)) (fresh-line) (funcall cont (first args))) ((eq fn 'call/cc) (@apply (first args) (list (list 'CONTINUATION cont)) cont)) ((atom fn) (funcall cont 'UNDEFINED-FUNCTION)) ((eq (first fn) 'CLOSURE) (@evlis (third fn) (pairlis (second fn) args (fourth fn)) #'(lambda (vals) (funcall cont (first (last vals)))))) ((eq (first fn) 'CONTINUATION) (funcall (second fn) (first args))) (t (funcall cont 'UNDEFINED-FUNCTION))))

This implements a ContinuationPassingStyle interpreter for a Lisp-like language that has only arithmetic and call/cc. It's in CommonLisp, though most of the functions have equivalents in Scheme (and hopefully in Python too). Steele's original posting is here: http://www.ai.mit.edu/~gregs/ll1-discuss-archive-html/msg00569.html.

I'm only half doing this to be a smartass, BTW. I'm hoping to write an interpreter for a language with CallWithCurrentContinuation in the near future, and I'd rather write it in Python than Scheme. But it looks like Scheme (or CL) will be the path of least resistance at this point. -- JonathanTang

see http://www.ps.uni-sb.de/~duchier/python/continuations.html, which is a little old as you'll notice that lambdas in Python now close...

Without actually translating the code, perhaps using something along these lines (plus possibly a generator - "yield")?:
 def add(x, y, c):
    c(x+y)

def mul(x, y, c): c(x*y)

def print_and_stop(val): print val

def myfunc(x, y, c): if x > 20: mul(x, y, c) else: add(x, 1, lambda z: myfunc(z, y, c)) myfunc(0, 7, print_and_stop)

Be aware that if you plan to use heavy recursion you MUST use StacklessPython.
In PrologLanguage: very basic differentiation

  test :-
    diff(a*x^i+b*x^j+c*x^k,x,Dx),
    write(Dx). 
    % should output i*a*x^(i-1)+j*b*x^(j-1)+k*c*x^(k-1)

diff(A+B,X,DA+DB) :- diff(A,X,DA),diff(B,X,DB). diff(A*X^N,X,N*A*X^(N-1)).

I guess this one is too hard for python (at least in comparable number of lines) It's not so much being too hard, it's just that it hasn't been written. Here's a proof of concept. It's so fragile it'll break if you breathe on it, and the remainder is left as an exercise for the reader... ;-) [permission is given to incorporate this code in any product using an OpenSourceLicence?]
 class Var(object):
    def __init__(self, name, multiplier=1, power=1, adds=None):
        self.name = name
        self.multiplier = multiplier
        self.power = power
        if not adds:
            adds = []
        self.adds = adds

def __add__(self, add): if add == 0: return self return Var(self.name, self.multiplier, self.power, self.adds+[add])

def __mul__(self, multiplier): if multiplier == 0: return 0 return Var(self.name, multiplier, self.power, self.adds)

def __pow__(self, power): if power == 0: return self.multiplier return Var(self.name, self.multiplier, power, self.adds)

def diff(self): multiplier = self.multiplier * self.power power = self.power - 1 out = multiplier * Var(self.name) ** power for elem in self.adds: try: out += elem.diff() except AttributeError?: pass return out

def __str__(self): out = "" if self.multiplier != 0: if self.multiplier != 1: out = "%s*"%self.multiplier if self.power != 0: out += self.name if self.power != 1: out += "**%s"%self.power adds = [str(elem) for elem in self.adds] out = [out] + [add for add in adds if add] return " + ".join(out)

x = Var("x") z = 3*x**3 + 2*x**2 + 1*x**1 + 4*x**0

print z print z.diff()

Output is:
 3*x**3 + 2*x**2 + x + 4
 9*x**2 + 4*x + 1

--TaroOgawa


See PythonTranslatorHoleExample for several refactorings of a rather long Perl example into a somewhat shorter Python version

Already attempted:


Question about translating AmbInRuby moved to AmbInPython


To Taro and other Snake masters

I have added some comments in VbIsBadForNewbies where reference is made of "poor Gui" availability of working with PythonLanguage. Please refactor the whole section by adding stuff, unless the comments were no longer valid.

Also looking for more help pls.

Thanks -- DavidLiu
Moved from PythonIdioms:

Question about the StatePattern in Python: I have a class Food, and there are many instances. I want each instance to have behaviour that changes at runtime, independently of the other instances. But I want it to be 'inheritance-style', instead of the 'composition-style' which is usual for StatePattern.

For example, I have a Floater class, and I want a particular food to take on the Floater behaviour -- as if it had inherited from Floater -- without affecting Food or any of the other foods. Here's what I've come up with.
 class Food:
     def __getattr__(self, name): # If we don't have it
         method = getattr (self.state, name)
         return lambda *args: method (*((self,) + args))

class Floater: def move (f, x): print 'Moving: %i' % x move = staticmethod (move) #not a decorator since I can't use 2.4 at the moment

food = Food() food.state = Floater food.move(4) # works

This seems to do the job, but is there a 'cleaner' way?

 class State(object):
    def __getattr__(self, name): # If we don't have it
        try:
            method = getattr (self.state, name)
        except AttributeError?, msg:
            classname = repr(self.__class__).split(".")[-1][:-2]
            raise AttributeError?("In class %s, state %s"%(classname, msg))
        return method

class Food(State): pass

class Floater(object): def move(x): print 'Moving: %i' % x move = staticmethod(move) #Use a decorator in 2.4

food = Food() food.state = Floater food.move(4) # works food.blah(8)

''But a better way is just to swap the class:"
 class State(object):
    def get_state(self):
        return self.__class__
    def set_state(self, state):
        self.__class__ = state
    state = property(get_state, set_state)

class Person(State): pass

class Runner(State): def move(self, x): print 'Moving: %i' % x

class Sitter(State): def move(self, x): print 'Not moving: %i' % x

person = Person() person.state = Runner person.move(4) person.state = Sitter person.move(4)

Another thing to question is whether you need StatePattern as python can swap its functions at runtime:
 class Person(object):
    def move_standing(self, x):
        print 'Moving: %i' % x

def move_sitting(self, x): print 'Not moving: %i' % x

def move(self, x): return self.move_sitting(x)

def stand(self): self.move = self.move_standing

def sit(self): self.move = self.move_sitting

person = Person() person.move(4) person.stand() person.move(6) person.sit() person.move(8)

-- TaroOgawa

Thanks, that's very useful and interesting information.


CategoryComparisons

EditText of this page (last edited May 21, 2010) or FindPage with title or text search