0

In my introduction to programming class, we had the following function in the exam however the last output is very unexpected.

def r2d2(a):
    b = True
    for k in range(len(a)):
        b = b and bb8(a,k)
    return b
def bb8(a,k):
    a[k] = a[k]-1
    return a[k] >= 0

In this program we set a to:a=[1,2,3,4] and call the following:

print(r2d2(a))
print(a)
print(r2d2(a))
print(a)

the program output for the first 3 commands are:

True
[0, 1, 2, 3]
False

which are expected. however, the fourth output is [-1, 1, 2, 3]. Isn't it supposed to be [-1,0,1,2]?

I tried manipulating the code to understand the reason however I couldn't come up with a solution.

Michael M.
  • 10,486
  • 9
  • 18
  • 34

1 Answers1

0

You're confused about how the statement b and bb8(a, k) is evaluated.

For optimization purposes, Python will never even run the bb8 function if b == False, because then the statement must also be false. Therefore, once b becomes False , the bb8 function will never be run again, so no more values in a are decremented. It is as if the function has ended at this point.

Michael M.
  • 10,486
  • 9
  • 18
  • 34