【发布时间】:2021-09-28 13:39:47
【问题描述】:
我收到 3 个整数,“x”、“y”和“z”。然后是最后一个整数“n”。
我必须像排列一样找到 x、y 和 z 之间的所有可能组合,但我只需要保存所有值的总和不等于 n (x + y + z != n) 的那些组合.
我已经通过一个大的 for 循环完成了这项工作。如您所见,打印输出确认此逻辑有效,因此可以使用您使用的任何 3 个整数找到所有可能的组合。每个组合都临时保存在一个不断被覆盖的列表中。
我过滤了组合,因此您可以使用打印功能仅查看列表中值的总和不是 n 的组合。但是,当我想保存找到的每个组合时,它只是保存重复的值,并且似乎 append 方法没有按我的需要工作。
# Example:
#
# Input: x = 1
# y = 1
# z = 1
# n = 2
#
# Output = [[0,0,0],[0,0,1],[0,1,0],[1,0,0],[1,1,1]]
x = int(input())
y = int(input())
z = int(input())
n = int(input())
list_x = [x for x in range(x+1)] #numbers from 0 to x
list_y = [y for y in range(y+1)] #numbers from 0 to y
list_z = [z for z in range(z+1)] #numbers from 0 to z
results = []
#Big for loop which makes the permutation
combination = [0,0,0]
for num_x in list_x:
combination[0] = num_x
for num_y in list_y:
combination[1] = num_y
for num_z in list_z:
combination[2]=num_z
if sum(combination) != n: #Find combinations where total sum != to n
print(combination) #print the combination found
results.append(combination) #save the combination in a list of lists
print(results) #print the lists of lists
非常感谢任何形式的帮助。谢谢。
【问题讨论】:
标签: arrays list for-loop append permutation