簡體   English   中英

我不明白為什么這個 for 循環這么快?

[英]I don't understand why is this for loop so fast?

今天我正在解決 Project Euler 的問題 #43 Problem ,我遇到了一個有點有趣的問題。 我不明白為什么我的代碼這么快?

from itertools import permutations
def main():
    numbers1_9 = [0,1,2,3,4,5,6,7,8,9]
    list_of_all_permutations = list(permutations(numbers1_9, 10))
    length_of_my_list = len(list_of_all_permutations)
    number_of_times_it_ran=0
    result = []
    for n in list_of_all_permutations:
        number_of_times_it_ran+=1
        if n[0] == 0:
            continue
        elif n[3] % 2 == 0 and (n[2]+n[3]+n[4]) % 3 == 0 and n[5] % 5 ==0 and int(str(n[4])+str(n[5])+str(n[6])) % 7 == 0 and (n[5]+n[7]-n[6]) % 11 == 0 and int(str(n[6])+str(n[7])+str(n[8])) % 13 == 0 and int(str(n[7])+str(n[8])+str(n[9])) % 17 == 0:
            temp_list = []
            for digits_of_n in n:
                temp_list.append(str(digits_of_n))
            result.append(int("".join(temp_list)))
            print(f"Added {temp_list}, Remaining: {length_of_my_list-number_of_times_it_ran}")
    print(f"The code ran {number_of_times_it_ran} times and the result is {sum(result)}")

if __name__ == "__main__":
    main()

我的意思是它經歷了 3,628,800 次 for 循環,檢查了所有這些參數,只用了一秒鍾。

Added ['1', '4', '0', '6', '3', '5', '7', '2', '8', '9'], Remaining: 3142649
Added ['1', '4', '3', '0', '9', '5', '2', '8', '6', '7'], Remaining: 3134251
Added ['1', '4', '6', '0', '3', '5', '7', '2', '8', '9'], Remaining: 3124649
Added ['4', '1', '0', '6', '3', '5', '7', '2', '8', '9'], Remaining: 2134649
Added ['4', '1', '3', '0', '9', '5', '2', '8', '6', '7'], Remaining: 2126251
Added ['4', '1', '6', '0', '3', '5', '7', '2', '8', '9'], Remaining: 2116649
The code ran 3628800 times, and the result is 16695334890

這是 output。代碼在 1.3403266999521293 秒內完成。

由於邏輯運算符的短路特性,它運行得如此之快。 if語句中的前三個條件很容易計算,它們過濾掉了所有排列中的絕大多數(大約 97%),因此您幾乎不需要執行更昂貴的操作,如int(str(n[4])+str(n[5])+str(n[6]))

因此,當您有一堆要使用and連接的條件,並且測試它們的順序對邏輯無關緊要時,您應該先測試最容易測試或最有可能失敗的條件。

暫無
暫無

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

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