[英]Given a number, generate a list of all possible combination of X and O with length n
For example, if function(2)
then it would produce 例如,如果
function(2)
,它将产生
['XX','XO','OX','OO']
I am not sure how I would approach this problem 我不确定如何解决这个问题
Unless this is an assignment, use product
from itertools, like this: 除非这是一项任务,否则请使用itertools的
product
,如下所示:
>>> import itertools as it
>>> list(it.product('XO', repeat=2))
[('X', 'X'), ('X', 'O'), ('O', 'X'), ('O', 'O')]
If you want to know how to do this the "long" way, an implementation for the product
method is available in the documentation: 如果您想知道如何“长距离”执行此操作,可以在文档中找到
product
方法的实现:
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
If you want to make your own function do something like this: 如果要创建自己的函数,请执行以下操作:
def crossProduct(A, B):
#returns cross product of elements in A x elements in B
return [a+b for a in A for b in B]
suits = 'CDHS'
ranks = '123456789JQKA'
cards = cross(suits,ranks)
print cards # prints out all 52 cards
If function(n - 1)
produces a list of all possible combinations of length n - 1
, you can recursively generate the combinations of length n
by returning 如果
function(n - 1)
生成长度为n - 1
的所有可能组合的列表,则可以通过返回来递归地生成长度为n
的组合
1) 'X' concatenated with each element in function(n - 1)
1)'X'与
function(n - 1)
每个元素串联
2) 'O' concatenated with each element in function(n - 1)
2)'O'与
function(n - 1)
每个元素串联
Like so: 像这样:
def function(n):
if n < 1:
return []
elif n == 1:
return ['X', 'O']
else:
return ['X' + string for string in function(n - 1)] + ['O' + string
for string in function(n - 1)]
If you cannot use itertools
, I suggest to consider binary number representation . 如果您不能使用
itertools
,我建议考虑使用二进制数表示法 。 If you iterate through all numbers between 0
and 2^n - 1
, their 0-padded binary representations will yield all possible combinations of 0
and 1
: 如果您遍历
0
到2^n - 1
之间的所有数字,则其0填充的二进制表示形式将产生0
和1
所有可能组合:
n = 3
for i in xrange(1<<n):
print bin(i)[2:].zfill(n)
Will print: 将打印:
000
001
010
011
100
101
110
111
(About the string manipulations, see this question ) (关于字符串操作,请参阅此问题 )
The remaining part of the task is how to convert 101
to XOX
, which can be done manually or, maybe, with maketrans
/ translate
. 任务的其余部分是如何将
101
转换为XOX
,这可以手动完成,也可以使用maketrans
/ translate
。
Note, that this works only for binary alphabets, like XO
or |-
. 注意,这仅适用于二进制字母,例如
XO
或|-
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.