2

I have a list of binary values: 1 = syncable, 0 =unsyncable. Each binary value represents whether or not a person was syncable that day.

person1=[1,1,0,1,1,0,1,1,1]

I want to make another list, calculating how many days a person was syncable consecutively. When a 0 appears, the counter basically resets.

So for the example above, the output would look like:

person1=[1,2,0,1,2,0,1,2,3]

My issue is whenever the list comes across a 0. I don't know how to get it to reset. I've tried several ways, none of which works.

x=[1,1,1,1,1]
y=[]

for index, value in enumerate(x):
     y.append(value+sum(x[:index]))

print(y)
...

[1, 2, 3, 4, 5]

Any help is appreciated. I think using recursion might help.

dyao
  • 983
  • 3
  • 12
  • 25

2 Answers2

2

Do this:

i = 0
y = []
for value in person1:
    if value:
        i += 1
    else:
        i = 0
    y.append(i)

There is no reason to create a list of ones. You just need to keep track of a counter.

zondo
  • 19,901
  • 8
  • 44
  • 83
2

Using itertools.groupby, you could generate a list with sum of syncs.

import itertools

person1=[1,1,0,1,1,0,1,1,1]
syncs = [sum(v) for _, v in itertools.groupby(person1)]

Output:

[2, 0, 2, 0, 3]

And if you just want to get the most consecutive days the person was "syncable", just do:

max_syncs = max[sum(v) for _, v in itertools.groupby(person1) if _]
DevLounge
  • 8,313
  • 3
  • 31
  • 44
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
  • Thank you for the answer! Can you explain what the `if _` part of the list comprehension does? – dyao Mar 11 '16 at 20:37
  • [Here](http://stackoverflow.com/questions/6903022/why-do-we-use-in-variable-names) you can find references about _. – Mauro Baraldi Mar 11 '16 at 22:16