I am trying to find a random sample of 3 numbers from a given array from where its sum results to 0.
Output should be storing all the triplets which satisfy it, like below
output - [-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)
Another way i have tried, but no luck. kindly please modify my code to make it work thank you in advance.
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)
CodePudding user response:
If you are trying to just find any solution, you could do it by guessing as follows:
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)
prints
[1, -1, 0]
If you want to find all possible solutions, you probably want to not guess but search all candidates exhausitvely, e.g. as follows:
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)
prints
[[-1, 0, 1], [-1, 2, -1], [0, 1, -1]]