Reputation: 25
I currently have the following function that counts the variations on an array with some specifications:
def count_pump_switches(arr):
count = 0
for i in range(1,len(arr)):
if arr[i - 1] != arr[i] and arr[i] != 0 and i % 5 !=0:
count += 1
return count
My goal is to change it so that the output is a list that stores the count, for example, 5 to 5 indexes. For example in this array: [0,0,0,0,1,0,0,0,0,1], instead of the output being 2, it should be [1,1]
Upvotes: 0
Views: 35
Reputation: 148880
You need a second loop level:
def count_pump_switches(arr):
counts = []
for n in range(0,len(arr), 5):
count = 0
for i in range(n+1, n+5):
if i >= len(arr): break
if arr[i - 1] != arr[i] and arr[i] != 0 and i % 5 !=0:
count += 1
counts.append(count)
return counts
Demo:
>>> count_pump_switches([0,0,0,0,1,0,0,0,0,1])
[1, 1]
>>> count_pump_switches([1,2,3,4,5,6,7,8,9,0])
[4, 3]
Upvotes: 1
Reputation: 1050
See if this code works for you:
import math
def count_pump_switches(arr):
changes = []
for i in range(len(arr)):
ci = math.floor(i/5)
if (ci >= len(changes)):
changes.append(0)
if arr[i] != 0:
changes[ci] += 1
return changes
Upvotes: 0