一系列彩色球的排列,而没有两个彼此相邻的相同颜色?

时间:2019-02-18 13:02:21

标签: python permutation

输入是一个字符串(a,b,c,d,...)。在此字符串中,a表示相同颜色的球,b表示另一种颜色的b球,等等。因此(2,1,3)表示2个红色球,1个蓝色球和3个黄色球。

输出1是可能的排列数量,而没有2个相同颜色的球彼此相邻。

输出2是所有这些排列的列表。

例如:

输入:(2,1,3)

输出1: 10个排列

输出2: 131323, 132313, 231313, 312313, 313123, 等

所以我的主要问题是:我该如何过滤Python程序中两个或两个以上相同颜色的球彼此相邻的排列?

4 个答案:

答案 0 :(得分:1)

以下代码将解决您的问题:

import numpy as np
num = 221333 ## Any random permutation
lst = list(map(int, str(num)))
req_array = np.diff(lst)
if 0 in req_array:
    print ("Yes")

以上代码在以下逻辑中起作用:

  1. 逐个迭代排列列表。上面的代码用于该列表中的1个此类元素
  2. number转换为array
  3. 减去连续元素
  4. 如果数组为零,则存在一个组合,其中2个球的颜色相同

答案 1 :(得分:0)

这有点令人费解,并且可能有一个更有效的版本,但这应该可以解决问题:

output2=['12234','22341','1234','12344']

permut=[]
for num in b: #For every element in the list output2
    for n,i in enumerate(num): #For every index and number inside every element of the list
        if n>0: #This is only for the next line to work on the first iteration
            if num[n]==num[n-1]: #If a number is the same than the previous number
                permut.append(num) #append into a new list the whole permutation number
                break #Go to the next loop
            else:
                continue
        else:
            continue

答案 2 :(得分:0)

绝对不是最整洁的处理方式,而是使用以下问题的答案:

https://stackoverflow.com/a/36343769/9742036

关于如何检查列表中是否有相等的邻居,这应该可以解决问题。

我们首先生成一个代表您的球组合的列表,查看它们的所有排列,然后过滤掉无效的那些。

from itertools import permutations
from operator import eq

input = (2, 1, 3)

# Produce a list to represent the objects to order. (2,1,3) -> [0, 0, 1, 2, 2, 2]
list_of_items = []
current_item = 1
for value in input:
    for number in range(value):
        list_of_items.append(current_item)

    current_item += 1



count_of_valid_permutations = 0
set_of_valid_permutations = set()

# Generate all permutations of our list
for permutation in permutations(list_of_items):
    # Permutations treat each ball as unique, even if the same colour, so check we're not over counting.
    if permutation not in set_of_valid_permutations:

        # Use the eq operator and map it to the permutation to see if any neighbours are equal.
        hasEqualNeigbours = any(map(eq, permutation, permutation[1:]))
        # If not, then this is a valid permutation.
        if not hasEqualNeigbours:
            # Record the permutation as seen.
            set_of_valid_permutations.add(permutation)
            count_of_valid_permutations += 1


print(count_of_valid_permutations)
print(set_of_valid_permutations)

答案 3 :(得分:0)

假设output2是排列字符串的数组,则可以通过舍弃具有(至少)两个连续颜色代码的排列来过滤该数组:

import re
output2 = filter(lambda perm: not re.search(r"(\d)\1", perm), output2)

正则表达式解释:\d与任何数字匹配。周围的括号标记为“匹配组”。 \1解析为第一个匹配组。因此,(\d)\1会与任意两个连续的相同数字匹配。

如果output2不是数组,而是用逗号分隔的字符串列表,则可以像这样将其拆分,以获得数组:

output2 = output2.split(', ')
相关问题