【问题标题】:Can you explain the assign function in Norvig's Sudoku code?你能解释一下 Norvig 的数独代码中的赋值函数吗?
【发布时间】:2017-07-19 13:29:05
【问题描述】:

我有 Peter Norvig 在他的数独求解器中使用的 Python 代码。我不明白为什么 assign 应该对 'values' 做任何事情,因为因为代码中没有任何地方 'values' 得到更新,并且 'values' 仅在 if 条件语句中使用。能否请您解释一下,提前谢谢!

def assign(values, s, d):
    """Eliminate all the other values (except d) from values[s] and 
propagate.
     Return values, except return False if a contradiction is 
detected."""
    other_values = values[s].replace(d, '')
    if all(eliminate(values, s, d2) for d2 in other_values):
        return values
    else:
        return False


 def eliminate(values,s,d):
    '''Eliminate d from values[s]; propagate when values or places <=2.
Return values, except return False if a contradiction is detected.'''
    if d not in values[s]:
        return values ## Already eliminated
    values[s] = values[s].replace(d,'')

    if len(values[s]) == 0:
        return False ##Contradiction: removed last value
    elif len(values[s]) == 1:
        d2 = values[s]
        if not all(eliminate(values, s2, d2) for s2 in peers[s]):
            return False

    for u in units[s]:
        dplaces = [s for s in u if d in values[s]]
        if len(dplaces) == 0:
            return False ## Contradiction: no
        elif len(dplaces) == 1:
            # d can only be in one place in unit; assign it there
            if not assign(values,dplaces[0],d):
                return False
    return values

【问题讨论】:

  • 你到底有什么不明白的?
  • eliminate 是做什么的? replace 是做什么的?
  • 为什么调用函数后值会不一样?
  • 什么是整体代码,我们无法告诉你一个函数的用途,而不知道它会在什么情况下使用。它会告诉您该函数在 cmets 中的作用
  • @PythonCPPMATLAB:我预计你会因为缺乏必要的研究而被否决。简单的调试实践,甚至是几个战略性放置的print 语句,都可以准确追踪values 的更新位置和方式。请参阅这个可爱的 debug 博客寻求帮助。

标签: python algorithm constraints sudoku


【解决方案1】:

values 更新为eliminate 的副作用:

values[s] = values[s].replace(d,'')

这将从values 的s 条目中删除所有值d。见replace。

【讨论】:

猜你喜欢
  • 2021-10-27
  • 1970-01-01
  • 2011-09-22
  • 1970-01-01
  • 2018-11-03
  • 2023-03-26
  • 2011-04-20
  • 2017-01-15
相关资源
最近更新 更多