I am trying to redefine python notation of a fragment in another language (php) and look for a fragment (in any language or pseudo-code) that would imitate python logic, That is, given the list and triple (start, stop, step) or part of it, determine the correct values or default values for all parameters and return the slice as a new list.
I tried to study the source . This code far surpasses my skills, but I cannot disagree with the comment saying:
Also, if something similar has already been done, pointers will be greatly appreciated.
This is my stand (make sure your code goes through before publication):
#place your code below code = """ def mySlice(L, start=None, stop=None, step=None): or <?php function mySlice($L, $start=NULL, $stop=NULL, $step=NULL) ... or function mySlice(L, start, stop, step) ... """ import itertools L = [0,1,2,3,4,5,6,7,8,9] if code.strip().startswith('<?php'): mode = 'php' if code.strip().startswith('def'): mode = 'python' if code.strip().startswith('function'): mode = 'js' if mode == 'php': var, none = '$L', 'NULL' print code, '\n' print '$L=array(%s);' % ','.join(str(x) for x in L) print "function _c($s,$a,$e){if($a!==$e)echo $s,' should be [',implode(',',$e),'] got [',implode(',',$a),']',PHP_EOL;}" if mode == 'python': var, none = 'L', 'None' print code, '\n' print 'L=%r' % L print "def _c(s,a,e):\n\tif a!=e:\n\t\tprint s,'should be',e,'got',a" if mode == 'js': var, none = 'L', 'undefined' print code, '\n' print 'L=%r' % L print "function _c(s,a,e){if(a.join()!==e.join())console.log(s+' should be ['+e.join()+'] got ['+a.join()+']');}" print n = len(L) + 3 start = range(-n, n) + [None, 100, -100] stop = range(-n, n) + [None, 100, -100] step = range(-n, n) + [100, -100] for q in itertools.product(start, stop, step): if not q[2]: q = q[:-1] actual = 'mySlice(%s,%s)' % (var, ','.join(none if x is None else str(x) for x in q)) slice_ = 'L[%s]' % ':'.join('' if x is None else str(x) for x in q) expect = eval(slice_) if mode == 'php': expect = 'array(%s)' % ','.join(str(x) for x in expect) print "_c(%r,%s,%s);" % (slice_, actual, expect) if mode == 'python': print "_c(%r,%s,%s);" % (slice_, actual, expect) if mode == 'js': print "_c(%r,%s,%s);" % (slice_, actual, expect)
how to use it:
- save to file (
test.py ) - put your python, php or javascript code between
""" s - run
python test.py | python python test.py | python or python test.py | php python test.py | php or python test.py | node python test.py | node