简体   繁体   English

如果元素总和为给定数字,则追加到列表中

[英]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.

相关问题 如何在列表中找到一对数字,使总和为给定数字 - How to find pair of numbers in a list which makes a sum as given number 列表中总和等于或小于给定数字的元素列表 - list of elements from a list that sum is equal or less than to a given number 如何打印列表的元素,其总和等于 python 中的给定数字? - how to print elements of a list whose sum is equal to a given number in python? 在列表中的所需数字前面附加元素 - Appending elements in front of a desired number in a list 用它们所有可能组合的 2 位数字随机填充列表,以便列表元素的总和给出一个给定的数字 - Fill a list randomly with 2 digits of all possible combinations of them so that the sum of the elements of the list gives a given number 来自2个范围的2个元素的总和将是一个给定的数字 - Sum of 2 elements from 2 ranges that will be one given number 如何快速计算从字典列表中分配给列总和的元素数量? - How can I count the number of elements given to a column sum from a list of dictionaries quickly? 找到给定总和和给定元素数量的正整数的排列 - Find permutations of positive integers given sum and given number of elements 用于在列表中创建给定数量元素的 Python 习惯用法 - Python idiom for creating a given number of elements in a list 矩阵(列表)的元素总和,但仅在另一个矩阵(列表)中给出的索引处 - Sum of elements of a matrix (list), but only at indexes given in another matrix (list)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM