簡體   English   中英

當條件滿足時,Python break語句不會終止程序

[英]Python break statement will not terminate program when condition meets

我試圖在Leet Code上解決Two Sum 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_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]

雖然我確實通過了7/16測試,但它在第8次測試時超時,輸入非常大。 我不認為這是算法的問題。 在嘗試手動打印'current_index'和'binary_mid_index'后,我的程序成功找到了正確的索引,它給了我正確的'current_sum'。 但是當輸入列表很大時,程序根本不會“打破”while循環。 這與Python有關嗎?

這是測試輸入:

nums=[12,13,23,28,43,44,59,60,61,68,70,86,88,92,124,125,136,168,173,173,180,199,212,221,227,230,277,282,306,314,316,321,325,328,336,337,363,365,368,370,370,371,375,384,387,394,400,404,414,422,422,427,430,435,457,493,506,527,531,538,541,546,568,583,585,587,650,652,677,691,730,737,740,751,755,764,778,783,785,789,794,803,809,815,847,858,863,863,874,887,896,916,920,926,927,930,933,957,981,997]

target = 542

break只會讓你擺脫當前的循環while不是外循環。

你可以使用多個while - 你需要在外部設置內部中斷條件,並且在內部中斷while將其評估為false的方式組合它的兩個條件。

可替換地設置一個breakOuter = FALSE也先之前,設置breakOuter = True在內while你S前直接break並添加and breakOuter == false到外部while條件

我認為最簡單的方法就是使用

return 

代替

break 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM