php切片概念,php – 实现python切片符号

我试图用另一种语言(php)重新实现python

slice notation,并寻找可以模仿python逻辑的代码片段(以任何语言或伪代码)。也就是说,给定列表和三(开始,停止,步骤)或其一部分,确定所有参数的正确值或默认值,并将切片返回为新列表。

我试着看着the source.这个代码远远超出了我的c技能,但我不能不同意这个评论说:

/* this is harder to get right than you might think */

此外,如果这样的事情已经完成,指针将不胜感激。

这是我的测试台(确保您的代码在发布之前通过):

#place your code below

code = """

def mySlice(L, start=None, stop=None, step=None):

or

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)

如何使用它:

>保存到一个文件(test.py)

>把你的python,php或javascript代码放在“”“之间

>运行python test.py | python或python test.py | php或python test.py |节点

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值