簡體   English   中英

如何減少 python 程序的運行時間(程序在執行時花費大量時間)

[英]How to reduce the run - time of python program ( program takes a lot of time in execution)

我正在解決 hackerank 上的小黃人游戲問題,但我沒有通過代碼運行時間過多的測試用例。 代碼是:

def minion_game(word):
    # initialize the scores of player 1 and 2 to 0
    # initialize the jump for index
    # initialize a string of vowels
    scoreOfStuart, scoreOfKevin, adder, vowels = 0, 0, 1, "AEIOU"

    i = 0
    while i < len(word):
        # initialize a list to store all the possible substrings for each length of substrings
        listOfSubStrings = []
        listOfSubStrings = [word[j : j + adder] for j in range(len(word) - i)]
        # end nested for loop ---- now a list of all possible substrings is present
        # another nested for loop to determine the score
        listOfStuart = [j for j in listOfSubStrings if j[0] not in vowels]
        listOfKevin = [j for j in listOfSubStrings if j[0] in vowels]
        scoreOfStuart += len(listOfStuart)
        scoreOfKevin += len(listOfKevin)

        # increment in adder by 1
        adder += 1
        i += 1
    # printing the scores
    if scoreOfStuart > scoreOfKevin:
        print("Stuart", scoreOfStuart)
    elif scoreOfStuart < scoreOfKevin:
        print("Kevin", scoreOfKevin)
    else:
        print("Draw")


if __name__ == "__main__":
    string = input().upper()
    minion_game(string)

我嘗試了列表理解而不是 for 循環來將字符串附加到列表中,並且嘗試了簡單的 while 循環而不是 main for 循環,運行時間仍然沒有減少。 任何幫助將不勝感激。

除了檢查第一個字母外,您根本不使用子字符串,因此您可以擺脫對它們的全部計算:

def minion_game(word):
    scoreOfStuart, scoreOfKevin, vowels = 0, 0, set("AEIOU")
    for i in range(len(word)):
        for j in range(len(word)-i)):
            if word[j] in vowels:
                scoreOfKevin += 1
            else:
                scoreOfStuart += 1

    # printing the scores
    if scoreOfStuart > scoreOfKevin:
        print("Stuart", scoreOfStuart)
    elif scoreOfStuart < scoreOfKevin:
        print("Kevin", scoreOfKevin)
    else:
        print("Draw")

此外,您會注意到您也不需要執行嵌套循環,您只需將單詞迭代一次即可,因為有len(word)-i字符串以相同的字母開頭。 例如word bananai==1 ,有子串a , an , ana , anan , anana總共len(word)-i == 6 - 1 == 5 ,這樣你就可以直接把這個分數加到Kevin上

def minion_game(word):
    scoreOfStuart, scoreOfKevin, vowels = 0, 0, set("AEIOU")
    for i in range(len(word)):
        if word[i] in vowels:
            scoreOfKevin += len(word)-i
        else:
            scoreOfStuart += len(word)-i

    # printing the scores
    if scoreOfStuart > scoreOfKevin:
        print("Stuart", scoreOfStuart)
    elif scoreOfStuart < scoreOfKevin:
        print("Kevin", scoreOfKevin)
    else:
        print("Draw")

問題不在於使用 for lop 或列表理解或 while 循環。 所有這些方法都取決於單詞的長度。 讓我們說n。 所以在你所有的算法中,時間復雜度都是 o(n)。 Hackerrank 希望你在小於 o(n) 的時間內解決這個問題。

在此處了解有關時間復雜度的更多信息

在競爭性編程中的任何問題中,都可以根據對輸入的約束對算法的時間復雜度進行一些估計:

| Constraint      | Required Time Complexity                   |
|-----------------|--------------------------------------------|
| n <= 10         | O(n!)                                      |
| n <= 20         | O(2n)                                      |
| n <= 500        | O(n3)                                      |
| n <= 5000       | O(n2)                                      |
| n <= 10^6       | O(n) or O(n log n)                         |
| n can be > 10^6 | O(1) or O(log n) (and in some cases O(√n)) |

這應該讓您直觀地了解到 go 的方式。

在這里,您將生成所有子字符串並根據第一個字母進行過濾。 我們真的需要子串還是只需要計數。 從問題https://www.hackerrank.com/challenges/the-minion-game/problem可以重復(ANA 在 BANANA 中出現兩次。因此,Kevin 將獲得 2 分)。

解決方案:考慮字符串的第一個字母,您可以查看有多少子字符串組合以您正在迭代的字母開頭,並將該數字添加到 kevin 或 stuart,而不是一次添加一個。 如果你需要代碼。 最好的地方將是問題的討論部分。

暫無
暫無

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

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