回溯不会经历所有可能性

时间:2017-03-17 13:02:01

标签: python backtracking

我试图解决问题:

我有一个有问题名称和一些要点的字典;

例如Qs = {"question1": 13, "question2": 1},表示question113个点,第二个点有1等。

我试图在uv个问题以及xy点之间创建所有问题子集。

这是我的代码:

class GrowingList(list):
    def __setitem__(self, index, value):
        if index >= len(self):
            self.extend([None]*(index + 1 - len(self)))
        list.__setitem__(self, index, value)


questions = {"Q1":5, "Q2":1, "Q3": 1, "Q4": 4}
u = 1 #
v = 3 # between u and v questions


x = 1   #
y = 7 #between x and y points


solution = GrowingList()

def main():

    Backtracking(0)



def Backtracking(k):
        for c in questions.keys():
                solution[k] = c
               # print ("candidate: ", solution)
                if not reject(k):
                #    print ("not rejected: ", solution)
                    if accept(k):
                                print (solution)
                                if (k == v-1):
                                    return ; 
                                else:
                                    Backtracking(k+1)
def reject(k):
    if len(solution) != len(set(solution)):  #check whether the question already exists
        return True

    points = 0
    for q in solution:
        if q in questions:
            points = points + questions[q]

    if points >y or k+1 > v: #check if the candidate solution has between the given number of questions and points
          return True
    return False

def accept(k):
    if len(solution) != len(set(solution)):  #check whether the question already exists
        return False

    points = 0
    for q in solution:
        if q in questions:
            points = points + questions[q]
    if x <= points <= y and u <= k+1 <= v:   #if the candidate solution has between the given number of points and questions, we found a solution
          return True
    return False

main()

因此,对于u = 1,v = 3,x = 1而y = 7,我只能

['Q1']
['Q1', 'Q2']
['Q1', 'Q2', 'Q3']
['Q2', 'Q4', 'Q3']
['Q2', 'Q1', 'Q3']
['Q2', 'Q1', 'Q3']
['Q2', 'Q4', 'Q3']

但我错过了很多解决方案,例如1个元素的其余问题子集。

['Q2']
['Q3']
['Q4']

也应该在解决方案中,还有更多。

2 个答案:

答案 0 :(得分:0)

这将做你想要的,但不使用回溯,如果这是至关重要的。根据您的需要,您可能只想使用迭代器const enhance = compose( withProps({ statuses: ['ordered', 'received'], }), withProps( // how do I pass props from this container to component ? ), withState('error', 'setError', false), withState('successAdded', 'setSuccessAdded', false), withState('loading', 'setLoading', false), withState('confirmModal', 'setConfirmModal', false), ... export default enhance(ComponentForm); 而不是将其转换为列表。

subsets(qs_between, min_set_size, max_set_size)

答案 1 :(得分:0)

直截了当的方法

import itertools
from pprint import pprint

u, v = 1, 3

x, y = 1, 7

Q = ['Q' + str(g) for g in range(u, v + 1)]
points = range(x, y + 1)

n = v - u + 1

result = []

for i in range(1, n + 1):
    for c in itertools.combinations(Q, i):
        result += [dict(zip(c, x)) for x in itertools.product(points, repeat=i)]

# print result
pprint(result)

一些输出

{'Q1': 7, 'Q3': 7, 'Q2': 5}
{'Q2': 1}
{'Q1': 7, 'Q3': 1, 'Q2': 6}
{'Q1': 3, 'Q3': 3}
{'Q1': 7}    
{'Q1': 3, 'Q3': 4}

循环使用powerset也可以。对于powerset中的元素clen(c)参数需要repeat