我编写了一个函数,以删除在两个字符串中重复的部分。我首先将字符串转换为列表,然后遍历两个列表以查找相同位置的字符是否相同。问题是进行迭代时,代码将跳过索引2。(例如:list =“ index”,迭代器在迭代“ i”之后跳至“ d”)。
我尝试使用“替换”方法进行字符串操作,但没有得到想要的结果。“替换”方法删除了我想要的零件。
def popp(s,t):
s_lis=list(s)
t_lis=list(t)
ind=0
for i,j in zip(s_lis,t_lis):
if i==j:
s_lis.pop(ind)
t_lis.pop(ind)
else:ind+=1
return s_lis,t_lis
# test the code
print(popp('hackerhappy','hackerrank'))
expected result: ['h','p','p','y'] ['r','n','k']
actual result: ['k', 'r', 'h', 'a', 'p', 'p', 'y'], ['k', 'r', 'r', 'a', 'n', 'k']
首先,您应该使用itertools.zip_longest,它会从最长的子序列中拉出一个zip。您正在使用zip
它,使您不需要的最短子序列成为拉链。
所以在我们的情况下
print(list(zip_longest(s_lis, t_lis)))
#[('h', 'h'), ('a', 'a'), ('c', 'c'), ('k', 'k'), ('e', 'e'),
#('r', 'r'), ('h', 'r'), ('a', 'a'), ('p', 'n'), ('p', 'k'), ('y', None)]
然后,您应该使用另一个列表来追加非公共字符,而不是对您要通过进行迭代的同一列表进行操作,s_lis.pop(idx)
因此,如果元组中的字符不匹配,那么如果不匹配则追加它们
from itertools import zip_longest
def popp(s,t):
s_lis = list(s)
t_lis = list(t)
s_res = []
t_res = []
#Use zip_longest to zip the two lists
for i, j in zip_longest(s_lis, t_lis):
#If the characters do not match, and they are not None, append them
#to the list
if i != j:
if i!=None:
s_res.append(i)
if j!=None:
t_res.append(j)
return s_res, t_res
输出将如下所示:
print(popp('hackerhappy','hackerrank'))
#(['h', 'p', 'p', 'y'], ['r', 'n', 'k'])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句