您的位置:首页 > 编程语言 > Python开发

python实现range函数

2015-07-28 20:45 585 查看
用python的代码实现range相关的功能.
#!/usr/bin/env python

def r(start,end=None,step=1):
if step>0:
if not end:
start, end = 0, start
check = lambda x,y:x<y
elif step<0:
check = lambda x,y:x>y
else:
raise ValueError("range() step argument must not be zero")

tmp = []
while check(start, end):
tmp.append(start)
start+=step
return tmp

print r(2,6)
print r(1,10,2)
print r(10,-9,-4)
print r(-10)
print r(1,10,0)


结果:
$ python ran.py
[2, 3, 4, 5]
[1, 3, 5, 7, 9]
[10, 6, 2, -2, -6]
[]
Traceback (most recent call last):
File "ran.py", line 25, in <module>
print r(1,10,0)
File "ran.py", line 13, in r
raise ValueError("range() step argument must not be zero")
ValueError: range() step argument must not be zero
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: