该函数接受字符串x的列表作为输入,并返回一个整数ptr



函数接受字符串x列表的输入并返回一个整数ptr
如果且仅当x[ptr]是x中至少一个其他字符串的子字符串。
否则,返回-1
有人能帮我理解这句话吗?

输出应该是这样的。

def test1_exercise_7(self):
list1 = ["goat"]
ptr = fun_exercise_7(list1)
self.assertTrue(ptr == -1)
def test2_exercise_7(self):
list1 = ["soul", "soulmate", "origin"]
ptr = fun_exercise_7(list1)
self.assertTrue(ptr == 0)
def test3_exercise_7(self):
list1 = ["FASER", "submission", "online", "drive", "frequent"]
ptr = fun_exercise_7(list1)
self.assertTrue(ptr == -1)
def test4_exercise_7(self):
list1 = ["banana", "applejuice", "kiwi", "strawberry", "apple", "peer"]
ptr = fun_exercise_7(list1)
self.assertTrue(ptr == 4)

函数会得到一个字符串列表。它应该在列表中找到一个元素,该元素是列表中其他元素的子字符串。它应该返回包含子字符串的元素的索引,如果没有,则返回-1

例如,在第二个示例中,soulsoulmate的子字符串,因此它返回0,即soul的索引。在最后一个示例中,appleapplejuice的子字符串,因此它返回4,即apple的索引。在其他两个示例中,没有一个字符串是其他字符串的子字符串,因此它们返回-1

该描述没有说明如果有多个元素满足条件该怎么办,例如在["soul", "mate", "soulmate"]中,soulmate都是soulmate的子串,在["soul", "ice", "soulmate", "juice"]soulsoulmate的子串并且icejuice的子串。我想你可以使用你为它设计的任何算法来返回你遇到的第一个元素的索引

我认为,您必须返回一个字符串的索引,它是给定列表中其他字符串的子字符串。如果没有符合上述条件的字符串,则必须返回-1

以下功能将有助于实现这一点!

def fun_exercise_7(words):
for idx,word in enumerate(words):
matching=[idx for i,w in enumerate(words) if i!=idx if word in w]
if matching:
return matching[0]
else:
continue
return -1