Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

Thank you

like image 252
Anake Avatar asked May 29 '26 10:05

Anake


1 Answers

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. Example:

>>> cuts('XCXX', 1)
['XC', 'XCX', 'XCXX', 'C', 'CX', 'CXX']
like image 122
phynfo Avatar answered May 31 '26 15:05

phynfo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!