-2

Below is the code snippet,

sieve=[0]*(1000001)
def countDivisors():
    global sieve
    print("@2")
    for i in range(1,1000001):
        j=i
        while(j<1000001):
            sieve[j]+=1
            j+=i
class Solution:
    # @param A : list of integers
    # @return a list of integers
    countDivisors()
    def solve(self, A):
        n=len(A)
        ans=[]
        global sieve
        for i in range(n):
            ans.append(sieve[A[i]])
        return ans
                
print("main")          
s=Solution()
print("s declared")
A = [[3, 5, 4, 2],[8, 5, 6, 2]]
for i in A:
    print(s.solve(i))

Output:

@2
main
s declared
[2, 2, 3, 2]
[4, 2, 4, 2]

Why "@2" before "main" is getting printed first. What is the execution sequence of the code and why? How it's different from the below code? In the below code snippet the 'countDivisor()' is called in 'init()'.

sieve=[0]*(1000001)
def countDivisors():
    global sieve
    print("@2")
    for i in range(1,1000001):
        j=i
        while(j<1000001):
            sieve[j]+=1
            j+=i
class Solution:
    # @param A : list of integers
    # @return a list of integers
    def __init__(self):
        countDivisors()
    def solve(self, A):
        n=len(A)
        ans=[]
        global sieve
        for i in range(n):
            ans.append(sieve[A[i]])
        return ans
  • 4
    Because you call `countDivisors()` while declaring the class. – deceze Aug 08 '21 at 17:37
  • 1
    Does this answer your question? [Order of execution and style of coding in Python](https://stackoverflow.com/questions/2985047/order-of-execution-and-style-of-coding-in-python) – Mohamed Raza Aug 08 '21 at 17:41
  • 1
    Given that the sole purpose of `countDivisors()` is to initialize a global variable (`sieve`), the call to it doesn't belong inside the `Solution` class at all - neither in the class body, nor in the `__init__()` method. The call to the function should be at the top level of your code, probably just after the definition of the function. – jasonharper Aug 08 '21 at 17:51

1 Answers1

1

Unlike a def statement, the body of a class statement is executed in order to prepare the namespace used to define the class. Your class statement is roughly equivalent to

countDivisors()


def solve(self, A):
    n=len(A)
    ans=[]
    global sieve
    for i in range(n):
        ans.append(sieve[A[i]])
    return ans


Solution = type('Solution', (), {'solve': solve})
chepner
  • 497,756
  • 71
  • 530
  • 681