【发布时间】:2018-09-07 14:19:00
【问题描述】:
我正在尝试生成由四个字母组成的 5 字符字符串的组合(恰好两个相等,另一个重复的两个相等)和一个数字。
正确组合示例:
1aabb
b1aab
ca3ac
不正确组合示例:
1aaaa -> incorrect because there are more than 2 equal letters
1aaab -> Same as the previous
1abcd -> No 2 equal letters + 2 equal different letters
这是我正在使用的代码:
from itertools import combinations, permutations, product
LETTERS = 'bcdfghjklmnpqrstvwxz'
DIGITS = '2456789'
def aabb1(letters=LETTERS, digits=DIGITS):
"""Generate the distinct 5-character strings consisting of four
letters (exactly two are equal and another repeat two are equal) and one digit.
"""
combs = []
for (a, b), (i, j), (x, y), d, k in product(
permutations(letters, 2), # Two letters (a repeated).
combinations(range(4), 2), # Positions for the repeated letter.
combinations(range(2), 2), # Positions for the second repeated letter.
digits, # One digit.
range(5)): # Positions for the digit.
result = []
result[i:i] = a,
result[j:j] = a,
result[x:x] = b,
result[y:y] = b,
result[k:k] = d,
combs.append(''.join(result))
print(len(combs))
return combs
它显示我有 79,800 个组合,但这是不正确的,因为我计算的是重复组合:
问题是因为它选择了一些字母,例如a出现两次,然后重复的字母,如f出现两次,所以我们会得到类似:a3faf但后来它选择了第一个字母为f,第二个为a,然后再次获得a3faf。
在数学中,我可以通过除以 2 来解决它:
但不确定如何在我的代码中正确执行此操作。
你能建议我如何在我的代码中防止它吗?意思是,得到没有重复的组合。
【问题讨论】:
-
您可以使用set,因为集合不允许重复条目。
-
正如@SamLittlefair 所说,您可以使用
set。
标签: python math combinatorics