-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
3
  • 4
    Because you call countDivisors() while declaring the class. Commented Aug 8, 2021 at 17:37
  • 1
    Does this answer your question? Order of execution and style of coding in Python Commented Aug 8, 2021 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. Commented Aug 8, 2021 at 17:51

1 Answer 1

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})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.