def sucontain(A):
C = A.split()
def magic(x):
B = [C[i]==C[i+1] for i in range(len(C)-1)]
return any(B)
N = [x for x in C if magic(x)]
return N
Phrase = "So flee fleeting candy can and bandage"
print (sucontain(Phrase))
这个函数的目标是创建一个单词列表,这些单词位于每个连续单词的内部。例如,函数将字符串“”So fleed fleeting candy can and bandage“”作为输入,并返回['fleed','and'],因为fleed在fleeting(下一个单词)中,'and'在'bandage'中。如果没有找到类似的案例,则应返回空列表[]。我的代码现在返回的是[],而不是['fleed','和']。有人能指出我做错了什么吗?谢谢
展望未来可能会有问题。与其测试当前单词是否在下一个单词中,不如检查前一个单词是否在当前单词中。这几乎总是让事情变得简单。你知道吗
另外,使用描述性变量名,而不是
C
和A
和x
和B
和N
和magic
。你知道吗你的
magic
函数肯定有问题。它接受x
作为参数,但不在任何地方使用它。你知道吗下面是一个不使用附加函数的替代版本:
enumerate()
函数允许我们将索引和值循环在一起,这使得执行测试非常简单。C[i+1]
是下一个值,w
是当前值,因此w in C[i+1]
检查当前值是否包含在下一个值中。我们使用C[:-1]
确保在最后一项之前停止一项,否则C[i+1]
将导致索引器错误。你知道吗只要把连续的单词配对,就可以很容易地理解
相关问题 更多 >
编程相关推荐