0

I have a np array, let's say

[1, 1, 1, 1, 0, 1, 0, 1, 0]

Now I want to modify the number at index i s.t. it is 0, if one of the previous n elements was a 1. But this calculation should not be static w.r.t to the original array, but dynamic, i.e. considering already changed values. Let's say n=2, then I want to get

[1, 0, 0, 1, 0, 0, 0, 1, 0]

How do I do that efficiently without a for loop? Simple indexing will run over the whole array in one iteration, ignoring newly changed values, meaning the result would be

[1, 0, 0, 0, 0, 0, 0, 0, 0]

right?

Update: In a loop I would do this:

for i in range(a.shape[0]):
    FoundPrevious = False
    for j in range(n):
        if i - j < 0:
            continue
        if a[i - j] == 1:
            FoundPrevious = True
            break
    if FoundPrevious:
        a[i] = 0
6
  • Can you show how you would do it in a loop. That will make it easier to convert. Commented Aug 31, 2018 at 19:08
  • Sure, edited the code Commented Aug 31, 2018 at 19:11
  • A list solution is probably the best you'll get. The problem is inherently iterative, and it's faster to iterate on a list than an array. Commented Aug 31, 2018 at 19:12
  • Could you give me more details on this @hpaulj? Commented Aug 31, 2018 at 19:13
  • 1
    Shouldn't the correct output be [1, 0, 0, 1, 0, 0, 0, 1, 0]? Commented Aug 31, 2018 at 19:18

2 Answers 2

4

The problem is inherently iterative, but you can simplify things by doing a single pass over your list.

arr = [1, 1, 1, 1, 0, 1, 0, 1, 0]
n = 2
newarr = []

for i in arr:
    newarr.append(0 if sum(newarr[-n:]) else i)

print (newarr)
[1, 0, 0, 1, 0, 0, 0, 1, 0]
Sign up to request clarification or add additional context in comments.

2 Comments

When I saw the pic, I thought it was scott , LOL :-)
@Wen Almost, scott is from TAMU :p
1

As other answerers and commenters have noted, the intrinsic interative nature of the problem makes a solution without a for-loop non-obvious.

Another approach to simplifying this problem is:

import numpy as np

a = np.array([1, 1, 1, 1, 0, 1, 0, 1, 0])
n = 2

for i in range(a.shape[0]):
    i0 = i - 2 if i >= 2 else 0
    if 1 in a[i0:i]:
        a[i] = 0

print(a)
# [1 0 0 1 0 0 0 1 0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.