下面是我正在使用的简单函数
当我执行规范中作为示例调用的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
您的代码不适用于
crane
到bane
的原因是,您没有考虑a
输入的长度(在本例中cr
,因此长度为2):所发生的事情是,
pos = introcs.find_str(word, a)
给出了的索引,其中输入a
开始,并且您假设a
的长度总是1
。相反,它应该是:相关问题 更多 >
编程相关推荐