[英]appending in list if sum of elements makes given number
I tried to do my homework, where instruction said I need to give a number and the program needs to give me a list of elements which sum into the given number but those elements need to be x**2 For example: if i put in 22, program must give me [2, 4, 16], because elements in list are sum of my input, thank you我试着做我的作业,指令说我需要给出一个数字,程序需要给我一个元素列表,这些元素总和为给定的数字,但这些元素需要是 x**2 例如:如果我输入22、程序必须给我[2, 4, 16],因为list中的元素是我输入的总和,谢谢
Code:代码:
def number(n):
ys = []
for xs in range(1, n + 1):
if 2 ** xs <= n:
ys.append(2 ** xs)
xs += 1
else:
xs += 1
return ys
print(number(22))
This should probably work.这应该可以工作。
def number(n):
ys = []
for xs in range(n,0,-1):
if 2**xs <= n:
ys.append(2**xs)
n -= 2**xs
xs -= 1
return ys[::-1]
You kept on checking for the same n, but each time you append a new element in your ys, you should subtract it from the number n.您一直在检查相同的 n,但是每次在 ys 中添加一个新元素时,都应该从数字 n 中减去它。 Also, working from high to low might make things easier.
此外,从高到低的工作可能会使事情变得更容易。
And lastly, the invert slice at the end is just so it returns in the order you asked.最后,最后的反转切片只是按照您要求的顺序返回。 You can leave that out and it would return [16, 4, 2].
你可以忽略它,它会返回 [16, 4, 2]。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.