用python的代码实现range相关的功能.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#!/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
)
|
结果:
1
2
3
4
5
6
7
8
9
10
11
|
$ 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
|
本文转自 nonono11 51CTO博客,原文链接:http://blog.51cto.com/abian/1679387,如需转载请自行联系原作者