Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to build a function that sums two numpy arrays into a new array if and only if the distinct indices are euqal.

x = np.array([2,1,1,1])
y=np.array([2,1,0,1])   

overlap = np.zeros(4)
for i in range(0,len(x)):
    if x[i] == y[i]:
        overlap[i]= x[i]+y[i]

print(overlap)
[4. 2. 2. 2.]

That worked as expected. Now I want to define the function, but the ouput is different, despite that the code is exactly the same.

    def sum_overlap(x,y):
       overlap = np.zeros(4)
       for i in range(0,len(x),1):
           if x[i] == y[i]:
              overlap[i] = x[i] + y[i]
              print(overlap)

sum_overlap(x,y)
[4. 0. 0. 0.]
[4. 2. 0. 0.]
[4. 2. 2. 0.]
[4. 2. 2. 2.]

I think it has something to do with the iterator, but i cant figure it out.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

Your print statement is in the loop, so everytime it gets called it prints out the list. Take the print statement out of the loop but remain in the function and your outputs should be the same


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...