【发布时间】:2017-03-05 17:26:06
【问题描述】:
所以,我总共有n 个问题,每个问题都有点。
我必须创建在u 和v 问题之间以及在x 和y 之间累积的所有可能的问题集,并且我必须使用回溯来做到这一点。
为此,我考虑过使用字典,例如: questions = {"Q1":5, "Q2":3, "Q3": 4, "Q4" : 10, "Q5" : 6, "Q6" : 7},所以有 6 个问题,第一个问题(“Q1”)有 5 分,以此类推
我开始编码,但我不知道如何创建回溯函数本身,我不明白如果这有意义的话,我不知道如何处理所有可能性。
questions = {"Q1":5, "Q2":3, "Q3": 4, "Q4" : 10, "Q5" : 6, "Q6" : 7}
u = 3 #
v = 5 # between u and v questions
x = 5 #
y = 100 #between x and y points
def get_points(ar):
s = 0
for key, value in ar.items():
s = s + int(value)
return s
def get_NOQuestions(ar):
return len(ar)
def reject(candidate):
if (get_points(candidate) > y and get_NOQuestions(candidate) < v) or (get_NOQuestions(candidate) >= v and get_points(candidate) < x):
return False
return True
def accept(candidate):
if get_points(candidate) >= x and get_points (candidate) <= y and get_NOQuestions(candidate) >= u and get_NOQuestions(candidate) <= v:
return True
return False
def output(candidate):
print(candidate)
ar = {}
def backtracking(k):
for key, value in questions.items():
ar[key] = value
if not reject(ar):
if accept(ar):
output(ar)
else:
backtracking(k+1)
backtracking(0)
这是我目前得到的,显然'回溯'功能不起作用,因为它没有经历所有可能性(不是它应该采用这种形式,它只是一个for)
我正在考虑可能排列字典中的所有项目(u 和 v 之间的长度排列)并获得满足“接受”功能条件的项目,但肯定有更聪明的方法去做吧。
【问题讨论】:
标签: list function dictionary