[英]I'm trying to remove substrings from a string using recursion in python
這是我到目前為止得到的代碼,但它沒有按預期工作,我不確定是什么造成了問題。
def removeSubstrings(s, sub):
if len(s) == 0:
return ''
if sub == s[0]:
return removeSubstrings(s[1:], s)
else:
return s[0] + removeSubstrings(s[1:], sub)
這是測試程序:
from recursion import *
allPassed = True
def removeSubstringsMain():
global allPassed
testCases = [(1, 'abcdef', 'abc', 'def'),
(2, 'abcdef', 'def', 'abc'),
(3, 'abcdef', 'bcd', 'aef'),
(4, 'abcdef', '', 'abcdef'),
(5, 'abcdef', 'abcdef', ''),
(6, 'aabbaabb', 'aa', 'bbbb'),
(7, 'abcdef', 'xyz', 'abcdef'),
(8, 'aabbaabb', 'a', 'bbbb')]
for num, message, substring, expected in testCases:
result = removeSubstrings(message, substring)
if result != expected:
print(f'Remove Substrings Test {num} Failed. Expected {expected} got {result}')
allPassed = False
def main():
removeSubstringsMain()
# closestMain() ignore
# strDistMain() ignore
if allPassed:
print('All tests passed')
main()
這是來自測試人員的錯誤消息:
Remove Substrings Test 1 Failed. Expected def got abcdef Remove Substrings Test 2 Failed. Expected abc got abcdef Remove Substrings Test 3 Failed. Expected aef got abcdef Remove Substrings Test 5 Failed. Expected got abcdef Remove Substrings Test 6 Failed. Expected bbbb got aabbaabb Remove Substrings Test 8 Failed. Expected bbbb got abbaabb
if sub == s[0]:
測試第一個字符是否為 substring。 這僅在 substring 只有 1 個字符長時才有效。
您可以使用startswith()
來測試 substring 是否在s
的開頭。 然后你需要在遞歸時切掉整個 substring 。
您需要將空 substring 視為基本情況,因為所有字符串都以空字符串開頭,但刪除它不會改變任何內容,因此這將是一個無限循環。
def removeSubstrings(s, sub):
if len(s) == 0:
return ''
if len(sub) == 0:
return s
if s.startswith(sub):
return removeSubstrings(s[len(sub):], sub)
else:
return s[0] + removeSubstrings(s[1:], sub)
而不是你的 function removeSubstrings,為什么不使用內置的字符串替換?
result = message.replace(substring, "")
看起來有人已經給了你一個很好的答案。 這是我的。 類似的方法,但使用大於一個字符的切片。
def removeSubstrings(s, sub) -> str:
if len(s) == 0:
return ''
loc = s.find(sub)
if loc == -1 or sub == '':
return s
return removeSubstrings(s[:loc], sub) + removeSubstrings(s[loc+len(sub):], sub)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.