【问题标题】:python backtracking on a dictionarypython在字典上回溯
【发布时间】:2017-03-05 17:26:06
【问题描述】:

所以,我总共有n 个问题,每个问题都有点。

我必须创建在uv 问题之间以及在xy 之间累积的所有可能的问题集,并且我必须使用回溯来做到这一点。

为此,我考虑过使用字典,例如: 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)

我正在考虑可能排列字典中的所有项目(uv 之间的长度排列)并获得满足“接受”功能条件的项目,但肯定有更聪明的方法去做吧。

【问题讨论】:

    标签: list function dictionary


    【解决方案1】:

    您需要重写 reject()accept() 函数的逻辑,因为您的代码将永远不会到达 if accept(ar) 给定的输入。试着在纸上运行你的代码,你会弄明白的。

    我还建议将 get_points(arr) 重构为如下内容:

    def get_points(arr):
        return sum(arr.values())
    

    更少的逻辑 == 更少的错误。

    【讨论】:

    • 所以您是说实际的回溯功能本身会经历所有可能性,只是我的接受和拒绝功能不好吗?因为我怀疑是这种情况谢谢你的建议顺便说一句:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多