Python:需要帮助调试相对简单的函数吗

2024-06-01 01:22:53 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我正在使用的简单函数

当我执行规范中作为示例调用的3个测试时,我在第3个测试(crane to bane)中得到一个错误

我知道错误具体在after变量中,因为我希望它只是ane,相反,我在运行测试时看到rane打印出来

我尝试了以下内容,每次,这些更改都会在规范中调用的前两个测试中导致意外错误

after = word[pos:]
after = word[pos-1:]
def replace_first(word,a,b):
    """
    Returns: a copy of word with the FIRST instance of a replaced by b
    
    Example: replace_first('crane','a','o') returns 'crone'
    Example: replace_first('poll','l','o') returns 'pool'
    Example: replace_first('crane','cr','b') returns 'bane'
    
    Parameter word: The string to copy and replace
    Precondition: word is a string
    
    Parameter a: The substring to find in word
    Precondition: a is a valid substring of word
    
    Parameter b: The substring to use in place of a
    Precondition: b is a string
    """
    pos = introcs.find_str(word,a)
    print(pos)
    
    before = word[:pos]
    print(before)
    
    after  = word[pos+1:]
    print(after)
    
    result = before+b+after
    print(result)
    
    return result

以下是我运行测试时的输出:

Testing replace_first
2
cr
ne
crone
2
po
l
pool
0

rane
brane
assert_equals: expected 'bane' but instead got 'brane'
Line 25 of tests.py: introcs.assert_equals('bane', result)
Quitting with Error

Tags: oftoposparameterexample错误resultreplace
1条回答
网友
1楼 · 发布于 2024-06-01 01:22:53

您的代码不适用于cranebane的原因是,您没有考虑a输入的长度(在本例中cr,因此长度为2):

    ...
    after  = word[pos+1:]
    ...

所发生的事情是,pos = introcs.find_str(word, a)给出了的索引,其中输入a开始,并且您假设a的长度总是1。相反,它应该是:

    ...
    after  = word[pos+len(a):]
    ...

相关问题 更多 >