Py学习  »  Python

python-如何使用回溯生成在向量的数字之间添加+和-的所有可能性,以便总和为正

Bianca G • 6 年前 • 2321 次点击  

我必须制作一个python应用程序,它生成在向量的数字之间添加+和-的所有可能性,因此总和应该是正的,使用回溯。我写这篇文章是因为我不太懂怎么做。

作为输入,我的应用程序得到一个整数向量:a1,a2。。。安。

我举例说明了回溯应该如何工作,但我不知道是否有可能实现。

(示例)对于5个数字:

a1 a2 a3 a4 a5

a1 + a2 + a3 + a4 + a5
a1 - a2 + a3 + a4 + a5
a1 - a2 - a3 + a4 + a5
a1 - a2 - a3 - a4 + a5
a1 - a2 - a3 - a4 - a5   
a1 + a2 - a3 + a4 + a5   
a1 + a2 - a3 - a4 + a5   
a1 + a2 - a3 - a4 - a5   
a1 + a2 + a3 - a4 + a5   
a1 + a2 + a3 - a4 - a5   
a1 + a2 + a3 + a4 - a5

这是我已经写过的:

def first():
    return int(a[0])

def next(nr):
    return int(a[nr+1])

def sum(x):
    suma = 0
    for i in range(0,len(x)):
        suma += x[i] 
    if(suma <= 0):
        return False
    return True

def equal(x):
    for i in range(0,len(x)-1):
        for j in range(i+1,len(x)):
            if(x[i]==x[j]):
                return False
    return True

def isSet(x):
    if equal(x) == False:
        return False
    return True

def consistent(x,dim):
    return isSet(x)

def solution(x,dim):
    return len(x) == dim and sum(x)

def solutionFound(x,dim):
    print(x)

def backtracking(x,dim):
    # ---idea of code that doesn't work
    x=[first()] #candidate solution
    nr = -1
    while len(x)>0:
        choosed = False
        while not choosed and x[-1] < dim and nr < dim-1:
            x[-1] = next(nr) #increase the last component
            nr += 1
            choosed = consistent(x, dim)
        if choosed:
            if solution(x, dim):
                solutionFound(x, dim)
            x.append(first()) # expand candidate solution
        else:
            nr -= 1
            x = x[:-1] #go back one component
---
a = input(">>> write numbers: ").split()
n = len(a)
backtracking([],n)

五十、 E:非常感谢大家的回答。你帮助我了解了更多的python语言。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53184
文章 [ 4 ]  |  最新文章 6 年前