当条件满足时,Python break语句不会终止程序
我在试着解Leet码上的两个和II。输入是一个已排序的升序列表和一个目标值。我的算法应该输出两个元素的索引,它们相加到目标值。我尝试在实现中使用二进制搜索,下面是我的代码:当条件满足时,Python break语句不会终止程序,python,algorithm,Python,Algorithm,我在试着解Leet码上的两个和II。输入是一个已排序的升序列表和一个目标值。我的算法应该输出两个元素的索引,它们相加到目标值。我尝试在实现中使用二进制搜索,下面是我的代码: def twoSum(nums, target): total_array_index = len(nums)-1 current_index = 0 binary_start_index = current_index + 1 binary_end_index = total_array
def twoSum(nums, target):
total_array_index = len(nums)-1
current_index = 0
binary_start_index = current_index + 1
binary_end_index = total_array_index
binary_mid_index = (binary_start_index+binary_end_index)/2
current_sum = nums[current_index]+nums[binary_mid_index]
while current_sum is not target:
#exit out the loop if no solution is found
if current_index == total_array_index:
print('no solution found!')
break
while (binary_start_index<=binary_end_index):
#condition meets, but "break" statement does not terminate loop ONLY when input list is large
if current_sum == target:
current_index = current_index-1
break
if current_sum > target:
binary_end_index = binary_mid_index - 1
binary_mid_index = (binary_start_index+binary_end_index)/2
current_sum = nums[current_index]+nums[binary_mid_index]
else:
binary_start_index = binary_mid_index + 1
binary_mid_index = (binary_start_index+binary_end_index)/2
current_sum = nums[current_index]+nums[binary_mid_index]
current_index = current_index + 1
binary_start_index = current_index + 1
binary_end_index = total_array_index
current_sum = nums[current_index]+nums[binary_mid_index]
return [current_index,binary_mid_index]
break
只将您从当前的循环中分离出来,而不是从外部循环中分离出来
您使用多个while
s-您还需要在外部while
上设置内部中断条件,并以内部中断时计算为false
的方式组合其两个条件
或者在第一个while之前设置一个breakOuter=FALSE
,在内部while
上设置breakOuter=True
,直接在break
之前设置breakOuter=FALSE
并在外部while
条件中添加和breakOuter==FALSE
,我认为最简单的方法就是使用
return
而不是
break
这很有效。但是,break语句在特定条件下失败真的很奇怪。如果它有效,请“接受”问题:),关于break语句-它在某些条件下不会失败,这只是break如何工作-根据定义,“break”语句只破坏一个范围。如果你只有一个循环-它将打破这个-如果你有两个循环,你将需要两个中断,以此类推。一旦您的方法完成了它的工作,您就需要“返回”并停止执行其他不必要的代码行
break