【问题标题】:A smarter function to decide if C is an exact cover of S?一个更聪明的函数来决定 C 是否是 S 的精确覆盖?
【发布时间】:2020-05-01 22:50:15
【问题描述】:

到目前为止,代码可以正常工作,但是 split、new-list 和 map 的所有这些功能只会让它变得更难。是否有集合比较/差异的混合能够执行我的代码正在执行的相同功能?

编辑:所有这些函数,例如 new_list 旨在准备 C 中的集合列表,以便能够通过循环传递它。循环确保

1.s中的所有元素都存在于c中。

2.第二部分确保解决方案中没有重复元素。 (eg. if len(c) == len(set(new_list) 我想我只是在这里发现了一个语义错误。

3. 使用set(new_list) == set(s) 确保无论顺序如何,两个集合都是相等的。

import re

s = [2,4,8]
c = [[2], [4], [2, 4]]

new_list = (re.sub("[^0-9,]", "", str(c)))
new_list = new_list.split(',')
new_list = list(map(str, new_list))
if ('') in new_list:
    del new_list[new_list.index('')]
new_list = list(map(int, new_list))


if all(elem in new_list for elem in s):
    if len(c) == len(set(new_list)):
        if set(new_list) == set(s):
            print('This is a Yes solution')
else:
            print('This is a No solution')

【问题讨论】:

  • 如果您清楚地解释所有 new_list 正则表达式的目标是什么,这将有所帮助。
  • new_list 这件事很奇怪。你只是想压平c吗?有很多更好的方法可以做到这一点。

标签: python np-complete


【解决方案1】:

你做的太多了。

  1. 扁平化通过列表理解更容易完成。
  2. 您可以只比较集合是否相等,不需要单独进行all elem 检查,因为已经保证集合是否相等。

def exact_cover(s, c):
    c_flat = [item for sub in c for item in sub]
    c_set = set(c_flat)
    return len(c_set) == len(c_flat) and c_set == set(s)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多