[英]Python set combinations of adjacent letters
I have a sequence of letters and want to find all combinations of letters possible by cutting off the letters around a certain letter. 我有一系列字母,想要通过切掉某个字母周围的字母来找到所有可能的字母组合。
C is my special letter here and X can be anything, so with a sequence: C是我的特殊字母,X可以是任何字母,所以有一个序列:
XCXX
So all the possible combinations would be: 因此,所有可能的组合将是:
XCXX
XCX
XC
CXX
CX
C
Is there a python function for this, or should I code it from scratch? 是否有一个python函数,或者我应该从头开始编码?
Thank you 谢谢
I would have coded it from scratch like this: 我会从头开始编码,如下所示:
def cuts(s,i):
return [ s[a:b] for a in range(i+1) for b in range(i+1,len(s)+1)]
where s
is the string and i
is the index of your "special letter" in s
. 其中
s
是字符串, i
是s
“特殊字母”的索引。 Example: 例:
>>> cuts('XCXX', 1)
['XC', 'XCX', 'XCXX', 'C', 'CX', 'CXX']
Try counting the number of elements before and after your special element C
. 尝试计算特殊元素
C
之前和之后的元素数量。 Then your combinations are uniquely defined by those two numbers, and you can just use string slicing to get a specific one. 然后,您的组合由这两个数字唯一定义,您可以使用字符串切片来获取特定的组合。
No, but you could do it as a one-liner. 不,但你可以做一个单线。
data = "XCXX"
cIndex = data.index("C")
permutations = [data[i:j+1] for i in range(cIndex+1)
for j in range(cIndex, len(data))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.