-2

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!

  • 6
    If you have a notion of 'adjacency', then what you have is not a *set* but a *sequence*, and the things you want are *subsequences*. – AakashM Feb 09 '12 at 16:08
  • 1
    What is the rule by which [1,3] should be excluded? What is the rule by which [] should be excluded? Since we are talking about **sets**, why do you specifically include [2,3] but exclude [3,2], when they are the same set? – Karl Knechtel Feb 09 '12 at 16:10

1 Answers1

3
>>> 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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • That's pretty great, thanks. Could you advise on putting them into a dictionary as keys? – user1195889 Feb 09 '12 at 16:14
  • @user1195889: You can convert a list to a tuple by calling `tuple(your_list)`. What will the values be? You may be able to use a dict comprehension to construct the dictionary. – Mark Byers Feb 09 '12 at 16:16
  • Thanks, I thought that was the case. Is it possible to put them in an array. Would that consist of lists of lists? – user1195889 Feb 09 '12 at 16:16
  • @user1195889: "Is it possible to put them in an array." No. Arrays cannot contain lists. They can only contain "basic values". See: http://docs.python.org/library/array.html. – Mark Byers Feb 09 '12 at 16:19