簡體   English   中英

為什么在我嘗試運行此代碼時會顯示 memory 錯誤?

[英]Why is there a memory error showing when I try to run this code?

所以我必須編寫一個 function 來執行此操作:編寫名為 remove_all_from_string 的 function,它接受兩個字符串並返回第一個字符串的副本,並刪除第二個字符串的所有實例。 您可以假設第二個字符串只有一個字母,例如“a”。 例如remove_all_from_string("house", "h")將 output "use" 或remove_all_from_string("haus", "h")將 output "aus"。

它必須具有: 帶有參數的 function 定義。 一個 while 循環。 查找方法。 切片和 + 運算符。 退貨單。

def remove_all_from_string(word, letter):
    while letter in word:
        x = word.find(letter)
        if x == -1:
            continue
        else:
            new = list(word)
            new[x] = ""
            word = str(word[:x]) + word.join(new)
    return word

print(remove_all_from_string("Mississippi", "i"))

每次我嘗試運行它時,Python 都會顯示一條錯誤消息:

Traceback (most recent call last):
  File "scratchpad.py", line 22, in <module>
    print(remove_all_from_string("Mississippi", "i"))
  File "scratchpad.py", line 19, in remove_all_from_string
    word = str(word[:x]) + word.join(new)
MemoryError

有人可以幫忙嗎? 謝謝你的任何答案!

由於word.join(new)你一次又一次地添加word ,你的代碼陷入了一個永遠的循環 ant 單詞增長到無窮大。

您可以修復代碼的方式:

def remove_all_from_string(word, letter):
    while letter in word:
        x = word.find(letter)
        if x == -1:
            continue
        else:
            new = list(word)
            new[x] = ""
            word = "".join(new[:x] + new[x+1:])
    return word

print(remove_all_from_string("Mississippi", "i"))

實現這個 function 的更好方法:

def remove_all_from_string(word, letter):
    return word.replace(letter, "")

您正在將變量“word”的副本累積到自身中,這導致變量中的數據呈指數增長,從而導致計算機內存不足。 鑒於任務描述,這是一個錯誤。

看起來您可能是編程新手,我建議您采用以下策略來幫助自己:打印所有變量的值(並為重要的中間結果添加新變量),這樣您就可以看到您的程序實際在做什么。 一旦了解了程序的作用,就可以開始修復它。

def remove_all_from_string(word, letter):
    debug_loop_count = 0
    while letter in word:
        debug_loop_count += 1
        if debug_loop_count > 2: # (change this to number control the # of loops you print)
            print(f"breaking loop because debug_loop_count exceeded")
            break
        print(f"--- begin loop iteration #{debug_loop_count}, word: '{word}'")
        x = word.find(letter)
        if x == -1:
            print(f"--- end loop iteration #{debug_loop_count} x={x} (continue)")
            continue
        else:
            new = list(word)
            print(f"variable new is: '{new}' x={x}")
            new[x] = ""
            print(f"variable new is updated to: '{new}' x={x}")
            str1 = str(word[:x])
            str2 = word.join(new)
            print(f"variable str1 is: '{str1}'")
            print(f"variable str2 is: '{str2}'")
            word = str1 + str2
            print(f"variable word now contains: '{word}'")
            print(f"--- end iteration loop #{debug_loop_count}")
    print(f"!!! end of function, word = {word}")
    return word


print(remove_all_from_string("Mississippi", "i"))

簡化 while 循環的邏輯:

已經有了解決問題的“最佳”方法的答案。 一般來說,如果我認為我需要一個 while 循環,那我通常是錯的,但如果它們是必需的,我猜它們就是必需的。

def remove_all_from_string_converted(word: str, letter: str) -> str:
    while letter in word:
        index: int = word.find(letter)
        word = word[:index] + word[index+1:]  # 'join' isn't necessary unless it's also required by a rule
    return word

print(remove_all_from_string_converted("Mississippi", "i"))

Output: Msssspp

暫無
暫無

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

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