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
countDivisors()while declaring the class.countDivisors()is to initialize a global variable (sieve), the call to it doesn't belong inside theSolutionclass 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.