【问题标题】:Generate every permutation with unique restrictions生成具有唯一限制的每个排列
【发布时间】:2018-06-08 15:20:26
【问题描述】:

我正在尝试创建一个测试脚本,该脚本将根据多个列表生成所有可能的值排列。但是,对于哪些值可以与其他值匹配存在一些限制。到目前为止,我想出了以下几点:

fieldTypes = ['Text', 'Float', 'Double', 'Short', 'Long', 'Date']
domainTypes = ['Coded', 'Range']
rangeSplitPolicies = ['Default', 'Duplicate', 'Geometry_Ratio']
rangeMergePolicies = ['Default', 'Area_Weighted', 'Sum_Values']
codedSplitPolicies = ['Default', 'Duplicate']
codedMergePolicies = ['Default']

for fieldType in fieldTypes:
    for domainType in domainTypes:
        # Skip incompatible domainType-fieldType permutations
        if domainType == 'Coded' and fieldType == 'Date' \
        or domainType == 'Range' and fieldType == 'Text':
           break

        # Range domain-type handling
        if domainType == 'Range':
            for splitPolicy in rangeSplitPolicies:
                # Date fields require special handling and only support the 
                # the default keyword for their split and merge policies
                if fieldType == 'Date':
                    permutation = '{0}-{1}'.format(
                        fieldType,
                        domainType,
                        'Default',
                        'Default')
                else:
                    for mergePolicy in rangeMergePolicies:
                        permutation = '{0}-{1}-{2}-{3}'.format(
                            fieldType,
                            domainType,
                            splitPolicy,
                            mergePolicy)

        # Coded-value domain-type handling
        else:
            for splitPolicy in codedSplitPolicies:
                for mergePolicy in codedMergePolicies:
                    permutation = '{0}-{1}-{2}-{3}'.format(
                        fieldType,
                        domainType,
                        splitPolicy,
                        mergePolicy)

        # Do more stuff...

显然,这不是很优雅。如果可能的话,我想使用一个生成器,因为我只需要获得每个排列一次,但我真的不确定最好的方法是组织它并获得 field 和 domainType 的所有可能排列以及为每个域类型制定适当的拆分和合并策略,同时执行以下细微限制:

  • 日期字段不支持基于编码值的域
  • 文本字段不支持基于范围的域
  • 日期字段仅支持其拆分和合并策略的“默认”关键字。

我现在只是将排列转换为字符串,但它可以作为元组、列表或任何易于解析的东西返回。

提前感谢您的任何见解。

【问题讨论】:

  • 你能显示一些输入输出对吗?
  • @BallpointBen 你的意思是预期的返回值可能是什么?现在它没有设置为一个函数,所以我对输入输出对的意思感到困惑
  • 在下一次迭代中 break 内部循环而不是 continue 可能是个问题。因此,将break 替换为continue"... 此外,您可能应该在AND 操作周围使用括号。 (dt == "..." and ft = "...") or (...)

标签: python optimization generator permutation


【解决方案1】:

听起来您的意思并不是真正的排列,而是笛卡尔积。

考虑执行以下操作:

def gen(domain_types, field_types):
    for d, f in itertools.product(domain_types, field_types):
        if is_okay(d, f):
            yield d, f

我知道你有更多的领域需要担心,但这个例子就足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-14
    • 2021-02-15
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 2018-11-08
    相关资源
    最近更新 更多