如果 IF 条件不满足,则循环回代码的开头



我正试图从给定的数组中找到一个3个数字的随机样本,其中它的和为0。

输出应该存储所有满足它的三元组,比如下面

输出-[-1,0,1],[-1,2,-1]

import random
nums = [-1,0,1,2,-1,-4]
l = 0
w=[]
def fun():
k = random.sample(nums, 3)
for i in k:
l = l+i
if l == 0:
print(k)
w.append(k)
else:
fun()
fun()
print(w)

我试过另一种方法,但没有成功。请修改我的代码使其工作,提前谢谢。

import random
nums = [-1,0,1,2,-1,-4]
k = random.sample(nums, 3)
l = 0
w = []
for i in k:
l = l+i
if l == 0:
w.append(k)
#print(w)
else:
#go back to the top of the program
print(w)

如果您只是想找到任何解决方案,您可以通过以下猜测来完成:

import random
nums = [-1,0,1,2,-1,-4]
num = 3
def find_by_guessing(nums, num, target=0):
while True:
guess = random.sample(nums, num)
if sum(guess) == target:
return guess
sol = find_by_guessing(nums, num)
print(sol)

打印

[1, -1, 0]

如果你想找到所有可能的解决方案,你可能不想猜测,而是想搜索所有候选人,例如:

from itertools import combinations
def find_all(nums, num, target=0):
solutions = []
for candidate in combinations(nums, num):
if sum(candidate) == target:
solutions.append(list(candidate))
return solutions
sol = find_all(nums, num)
print(sol)

打印

[[-1, 0, 1], [-1, 2, -1], [0, 1, -1]]

最新更新