Search code examples
pythonalgorithmpowerset

How to create subsequences for sequence e.g. [1,2,3] not including non-adjacent subsequences (e.g. [1,3]) in Python


So for example, if I have the sequence [1,2,3], what would be an algorithm to produce the subseqeunces:

[1]
[2]
[3]
[1,2]
[2,3]
[1,2,3]

but not

[1,3]

nor

[3,2]

I'm then hoping to insert these as the keys in a dictionary along with the result from looking up these unique subsets in a database forming the value. I wonder if you could help with that?

Thanks very much!


Solution

  • >>> x = [1, 2, 3]
    >>> [x[a:b + 1] for a in range(len(x)) for b in range(a, len(x))]
    [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
    

    Or to get them in the order you requested:

    >>> [x[a : a + n] for n in range(1, len(x) + 1)
                      for a in range(0, len(x) - n + 1)]
    [[1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]
    

    I'm then hoping to insert these as the keys in a dictionary

    You can't use lists as keys in a dictionary because a dictionary requires that its keys are hashable and you can't hash lists.

    >>> {[1] : 'foo'}
    Traceback (most recent call last):
      File "<pyshell#16>", line 1, in <module>
        {[1] : 'foo'}
    TypeError: unhashable type: 'list'
    

    You'll need to use tuples as your keys instead.