I need a function which returns subsegments for a given segment. For example, sub_combinations("ABCD")
should yield:
("A", "B", "C", "D")
("A", "B", "CD")
("A", "BC", "D")
("A", "BCD")
("AB", "C", "D")
("AB", "CD")
("ABC", "D")
("ABCD")
("ABD", "C") *
("AC", "BD") *
("AC", "B", "D") *
("ACD", "B") *
("AD", "BC") *
("AD", "B", "C") *
("A","C","B","D")
is not valid since it is not in sequence order. In other words, ("A","B","C","D")
is instead correct.
("AC", "B", "D")
is valid since "C" follows "A" in sequential order, and "B" follows "AC".
This is as far as I've gotten:
def sub_combinations(segment):
for i in range(1, len(segment)):
for j in sub_combinations(segment[i:]):
yield (segment[:i],) + j
yield (segment,)
for i in sub_combinations("ABCD"):
print(i)
('A', 'B', 'C', 'D')
('A', 'B', 'CD')
('A', 'BC', 'D')
('A', 'BCD')
('AB', 'C', 'D')
('AB', 'CD')
('ABC', 'D')
('ABCD',)
However this is missing those extra combinations.
Any suggestions on how to proceed?
See Question&Answers more detail:
os