如何在for循环中保存i的值,而不让迭代影响它



在这个代码块中:

def lin_search(A,N,X):
first_occurance = 0
counter = 0
for i in range(0, N):
if counter != X:
if A[i] == 0:
first_occurance = i
counter += 1
print('True at ' + str(first_occurance) + ' ' + str(counter))
else:
continue
elif counter == X:
print('Memory has enough space for ' + str(X) + ' amount starting at index ' + str(first_occurance))
break;

first occurrence被分配给i时,我希望它保持在那个精确的值,即使for循环继续。假设A[2] == 0first_occurance变成了2。无论for循环运行多长时间,我都希望first_occurance保持为2。

如果我运行

memory = [1,0,0,0,1,1,0,0,1,1,1,0,0,0,0,0]
lin_search(memory, len(memory), 4)

first_occurance应该是11,因为这是有4个连续0 的索引

将first_occurance初始化为None。它只会得到一次赋值当条件

if(first_occurance == None):

将得到满足。一旦first_occurance将被分配给任何值,上述条件就不成立。通过这种方式,首次出现将仅初始化一次。

此处

str(first_occurance if first_occurance else 0)

提供了额外的if-else条件,这样str就不会应用于None。然后它会给出"无"。如果first_occurance为None,则只给出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;

但不在这个问题的范围内问题解决方案

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

修改您的解决方案

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

如果首先将first_occurance设置为None,则可以检查变量以前是否设置过。请注意,我明确地检查first_occurance是否为0,因为0可以是一个有效值,即first_occurance可以位于第一个索引处。在这种情况下,这并不重要,但如果您在if块中做更多的工作,则可能会如此。如果您确信除了在if条件内分配first_occurance之外,您不想做任何其他事情,那么您只能对代码进行一次更改:if A[i] == 0 and first_occurance == 0:

def lin_search(A,N,X):
first_occurance = None # set it to None to begin with
counter = 0
for i in range(0, N):
if counter != X:
if A[i] == 0 and first_occurance is None: # ensure that first_occurance is only set once
first_occurance = i
counter += 1
print('True at ' + str(first_occurance) + ' ' + str(counter))
else:
continue
elif counter == X:
print('Memory has enough space for ' + str(X) + ' amount starting at index ' + str(first_occurance or 0))
break;
# if you want to use first_occurance down the line and it needs to be set to 0, do it here
if not first_occurance:
first_occurance = 0

最新更新