3 回答
TA贡献1797条经验 获得超6个赞
使用列表推导式的更 Pythonic 方式
def number_game(x,y):
if x > y:
return [n for n in range(y,x) if n%2==0]
elif y==x:
return []
else:
return [n for n in range(x,y) if n%2!=0]
TA贡献1786条经验 获得超13个赞
使用Generators(yield关键字)查看解决方案
def number_game(x,y):
num = range(min(x,y),max(x,y))
for e in num:
if x > y and e%2 == 0:
yield e
elif x < y and e%2 != 0:
yield e
# you have to materialize generators to lists before comparing them with lists
print(list(number_game(2,12)) == [3, 5, 7, 9, 11])
print(list(number_game(0,0)) == [])
print(list(number_game(2,12)) == [3, 5, 7, 9, 11])
print(list(number_game(200,180)) == [180, 182, 184, 186, 188, 190, 192, 194, 196, 198])
print(list(number_game(180,200)) == [181, 183, 185, 187, 189, 191, 193, 195, 197, 199])
添加回答
举报