用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