我正在解决一个问题,我必须对此问题进行编码 -
>>> getNumbers(10)
[100, 64, 36, 16, 4, 0, 4, 16, 36, 64, 100]
>>> getNumbers(9)
[81, 49, 25, 9, 1, 1, 9, 25, 49, 81]
我的代码得到答案,但我对我的代码不满意,请提出一些改进此代码的选项。
def getNumbers(num):
myList=[]
mylist=[]
if num%2==0:
for numbers in range(num,-2,-2):
myList.append(numbers**2)
for numbers in range(2,num+2,2):
mylist.append(numbers**2)
print myList+mylist
elif num%3==0:
for numbers in range(num,-1,-2):
myList.append(numbers**2)
for numbers in range(1,num+2,2):
mylist.append(numbers**2)
print myList+mylist
else:
print(mylist)
4 for loops !!!这就是取笑我的地方!!!
答案 0 :(得分:1)
喜欢这个吗?
def getNumbers(n):
return [i * i for i in range(-n, n + 1, 2)]