具有重复元素和分隔空间的置换(可以留为空白)

时间:2018-12-22 07:41:58

标签: python algorithm permutation

我有一些重复的元素和分隔的空间:

# Elements
people = [0, 0, 1]
# Index
seats = ['a', 'a', 'b', 'b', 'c', 'd']

元素数不能大于索引数。如果元素数少于索引数,则每种索引类型都可以将一个索引保留为空白。

from collections import Counter


def _is_elem_valid(people, seats) -> bool:
    """Valid elements check."""
    counter = 0
    for seat, c in Counter(seats).items():
        if c > 1:
            counter += 1

    # "True" is valid.
    # In this case is 6 >= 3 >= 2.
    return len(seats) >= len(people) >= counter

相同类型的索引为无序连续。否则规则与常规排列相同。

因此结果将显示如下:

# None represent blank seats.
# Sorry about PEP8.
# Actual elements: (filled to the length of index)
[0, 0, 1, None, None, None]

# Index:
['a', 'a', 'b', 'b', 'c', 'd']
# Correspond to normal index:
[[0], [0], [1], [1], [2], [3]]

# For all 'a'
[ 0,   0,   1,  None,None,None]
[ 0,   1,   0,  None,None,None]
# For all 'b'
[ 0,  None, 0,   1,  None,None]
[ 1,  None, 0,   0,  None,None]
# For 'c'
[ 0,  None, 1,  None, 0,  None]
[ 1,  None, 0,  None, 0,  None]
[ 0,  None, 0,  None, 1,  None]
# For 'd'
[ 0,  None, 1,  None,None, 0  ]
[ 1,  None, 0,  None,None, 0  ]
[ 0,  None, 0,  None,None, 1  ]

我对置换算法不太熟悉。这里有什么有效的解决方案吗?

0 个答案:

没有答案