Initialize first_occurance to None. It will only get assigned value once
when the condition
if(first_occurance == None):
will be satisfied. Once first_occurance will be assigned to any value, the above condition doesn't hold true. By this first_occurance will be initialized only once.
Here
str(first_occurance if first_occurance else 0)
The extra if-else condition is provided so that str is not applied to None. Then it will give 'None'. if first_occurance is None then just give 0.
def lin_search(A,N,X):
first_occurance = None
counter = 0
for i in range(0, N):
if counter != X:
if A[i] == 0:
if(first_occurance == None):
first_occurance = i
counter += 1
print('True at ' + str(first_occurance if first_occurance else 0) + ' ' + str(counter))
else:
continue
elif counter == X:
print('Memory has enough space for ' + str(X) + ' amount starting at index ' + str(first_occurance if first_occurance else 0))
break;
Not in scope of this question though
Solution for your problem
def lin_search(memory):
stack = []
for index, i in enumerate(memory):
if(i == 0):
stack.append(i)
if(len(stack) == 4):
return index - 3
else:
stack.clear()
return -1 #not found
modification to your solution
def lin_search(A,N,X):
first_occurance = None
counter = 0
for i in range(0, N):
if counter != X:
if A[i] == 0:
if(first_occurance == None):
first_occurance = i
counter += 1
print('True at ' + str(first_occurance) + ' ' + str(counter))
else:
first_occurance = None
counter = 0
if counter == X:
print('Memory has enough space for ' + str(X) + ' amount starting at index ' + str(first_occurance))
break
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…