I have an issue in writing a code for a problem related to the element updation of an array based on the majority voting of its past 5 elements including the element itself.
Explanation: Suppose we have an array having elements in binary form. arr= [0 , 1, 0, 0, 0, 1, 0, 1 , 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1]
Now, according to our problem, we have to find the majority value of the past 5 elements including the number itself. So for the first 4 elements, the new updated value would be Zero, and then the value at the 4th index will be based on the majority voting of past elements that is [0, 1, 0, 0, 0]. So the majority value for index 4 is '0' as the count of '0' is greater than the count of '1' in a given window. Similarly, we have to do the same for all the elements.
input arr= [0 , 1, 0, 0, 0, 1, 0, 1 , 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1]
Output arr=[0 , 0, 0, 0, 0, 0, 0, 0 , 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
CodePudding user response:
Use:
arr = [0 , 1, 0, 0, 0, 1, 0, 1 , 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1]
out = [int(sum(arr[max(i-5, 0):i]) >= 3) for i in range(1, len(arr) 1)]
print(out)
# Output
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
Variation:
out = [int(sum(arr[max(i-4, 0):i 1]) >= 3) for i in range(len(arr))]