2
L=[2,4,5,6,2,1,6,6,3,2,4,5,3,4,5]

I want to know how many times an arbitrary sub-sequence shows up, s=[2,4,5] for instance would return 2 times.

I tried L.count(s) but it does not work because I think it is expecting to look for something like [random numbers ... [2,4,5] ... random numbers] instead of 2,4,5 without the brackets.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
RTG_FRE
  • 87
  • 1
  • 7

2 Answers2

5
>>> L = [2,4,5,6,2,1,6,6,3,2,4,5,3,4,5]
>>> s = [2,4,5]
>>> sum(1 for i in range(len(L)) if L[i:i+len(s)]==s)
2

Almost the same thing, slightly shorter (uses the fact that True can behave like the number 1):

>>> sum(L[i:i+len(s)]==s for i in range(len(L)))
2
Oleh Prypin
  • 33,184
  • 10
  • 89
  • 99
  • I think it's a bit unreadable, taking advantage of the fact that bool is an int. – Elazar Apr 27 '13 at 23:04
  • 4
    @Elazar No it is **not** a bit unreadable, come back here you have read this: http://stackoverflow.com/a/3175293/1219006 – jamylak Apr 27 '13 at 23:06
  • @jamylak I did. A year ago, it would have taken me more than a couple of seconds to get that, and I came to Python from C. If I am not the worse programmer in the world (which is possible, I admit) it means it's less readable than using the `if` construct. It's my own personal view, anyway. – Elazar Apr 27 '13 at 23:14
  • @Elazar Are you saying you read that linked question a year ago? nvm I misread the first part, didn't see the period. Basically it is considered Pythonic to do this, it can be your own personal view if you dislike it... – jamylak Apr 27 '13 at 23:16
  • @Elazar Don't worry you are not the first, someone always argues that this may be unreadable, but they always know what it means and are just worried for other people, I imagine that's how you are thinking. You needn't worry since this causes people to think about what's going on anyway and they figure it out. – jamylak Apr 27 '13 at 23:24
  • @jamylak "this causes people to think about what's going on anyway" - when is it not true with unreadable code? I thought our purpose is to make them think less about such details. – Elazar Apr 27 '13 at 23:28
  • 1
    Your string-based one is dangerous: it'll also find `[2, 4, 5]` in `[22, 4, 5]`. – DSM Apr 27 '13 at 23:56
  • Important note: This **does** count overlaps. The original question is ambiguous as to what is wanted. In my case this is fine but maybe people reading this will not want this. Example: `L, s = [1,1,1], [1,1]` will return 2. – AnnanFay Jul 09 '17 at 15:29
0
x=0
for i in range(len(L)):
    if L[i:i+len(s)]==s:
        x+=1

or make it list-comprehension:

len([None for i in range(len(L)) if L[i:i+len(s)]==s])
Elazar
  • 20,415
  • 4
  • 46
  • 67