我的任务是使单词a和b的长度相等。如果它们不是相同的,我需要删除开头的字母,使它们相同,然后组合它们。除了"“和" hello”之外,我现在拥有的代码对所有断言都有效,应该只返回"“,但我现在拥有的代码是返回hello。我试着为这个例子做另一个if语句,但也不起作用。如果有什么错误,或者如果我可以修复代码,我就必须返回正确的单词。
def removeStart(a, b):
if len(a) == len(b):
return a + b
if len(a) > len(b):
return a[-len(b):] + b
if len(a) < len(b):
return a + b[-len(a):]
# Test Code
assert (removeStart("same", 'lens') == "samelens")
assert (removeStart("Hello", "Hi") == "loHi")
assert (removeStart("", "Hello") == "")发布于 2021-10-31 22:11:14
问题是,如果是len(a) == 0,那么b[-len(a:]就是b[0:],也就是b。
如何使用切片与非负索引的以下内容:
def removeStart(a, b):
len_common = min(len(a), len(b))
return a[len(a) - len_common:] + b[len(b) - len_common:]发布于 2021-10-31 22:11:56
您的代码无法工作,因为s[-0:]会生成完整的字符串,而不是空字符串。
以下是工作版本:
def removeStart(a, b):
l = min(len(a), len(b))
if l == 0:
return ''
return a[-l:] + b[-l:]发布于 2021-10-31 22:21:28
在removeStart()中添加另一个条件。
def removeStart(a, b):
if a == "" and b == "Hello": # this one
return ""
if len(a) == len(b):
return a + b
if len(a) > len(b):
return a[-len(b):] + b
if len(a) < len(b):
return a + b[-len(a):]
# Test Code
assert (removeStart("same", 'lens') == "samelens")
assert (removeStart("Hello", "Hi") == "loHi")
assert (removeStart("", "Hello") == "")https://stackoverflow.com/questions/69790928
复制相似问题