3 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
使用列表推導(dǎo)式的更 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貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
使用Generators(yield關(guān)鍵字)查看解決方案
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])
添加回答
舉報(bào)