Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

python - Calling a function twice with different argument changes the values of function output that is already called

I got this weird problem that I cannot even make a title with concision.

Here, I first describe the problem, and show an arbitrary code that is a simplified version of my original code that generates the same problem.

I have a function(say 'A') of another function(say 'B'). 'A' returns output of 'B'. And B has two different modes with respect to its parameter.

Now, If I call 'A' twice with identical parameter to 'B', it shows same results twice.

But If I insert 'B' Twice in 'A' with different parameter, but output only the first 'B', 'A' shows the output of 'second B'.

Here is the code. (I repeat that this is just an arbitrary code that I created to show the problem with ease.)

arr=[]
for i in range(5):
  arr.append(i)

def B(arr, rand=False):
  cnt=[]
  if rand:    
    ind=np.random.choice(arr, len(arr))    
    for i, val in enumerate(arr):
      if val in arr:
        arr[arr.index(val)]+=1

  for i in arr:
    if i>2:
      cnt.append(i)
  return cnt

def A(arr):
  firstB=B(arr)
  secondB=B(arr, rand=True)
  return np.std(firstB)

for i in range(5):
  print(A(arr))

if you remove secondB, output will be

0.5
0.5
0.5
0.5
0.5

But if you retain secondB, eventhough the output is still firstB, the outputs vary. like this.

0.5
0.816496580927726
1.118033988749895
1.4142135623730951
1.4142135623730951

How is this like this?

question from:https://stackoverflow.com/questions/65951265/calling-a-function-twice-with-different-argument-changes-the-values-of-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...