如何创建3个简单的函数来返回孤立的字符,返回重复的字符,并返回删除#comment的字符串



Function1:remove_all_dup('abbcdddeabcc')应返回'aceab'

函数2:remove_no_rep('abbcdddeabcc')应返回'bbdddcc'

函数3:remove_py_com('"abbc#d: " not fun#ction')应返回'"abbc#d: " not fun'

(注意,#只有在"内部时才被移除,并且它们必须是并且通常成对使用。(

这种锻炼真的让我很难过,因为他们已经绝望了好几个月了。尽管在while循环中提供了一个while循环的解决方案,但我的逻辑无法遵循。但如果我看到不同的解决方法,也许这一切都会有意义。

请帮帮我。

这是我到目前为止为最后一个功能所做的:

def remove_py_com(txt):
for letter in txt:
if '"' not in txt or txt.find("#")<txt.find('"'):
return txt[:txt.find("#")]
elif "#" not in txt:
return txt
elif "#" in txt and '"' in txt:
after=txt[txt.find("#"):]
for letter in after:
if after[1:].find("#")<after.find('"'):
return txt
for bullshit in after[after.find('"'):]:
txt=after[after.find('"'):] # so python go to top and check tail-txts again and again... but problem is "after" is not going for what's coming after the "quote"
# Maybe I can create 2 functions for this in a function to make it all clear for the mentally retarded like myself                                    

对于函数1和2,您可以考虑定义函数来计算字符串中的每个字符是否有重复的邻居。

def find_duplicates(s):
# compare each element with the next element
comparisons = [i==j for i, j in zip(s[1:], s[:-1])]
# a character is a duplicate if it is equal to one of it's neighbours
is_duplicate = [i or j for i, j in zip([False] + comparisons, comparisons + [False])]
return is_duplicate

这应该返回一个带有TrueFalse的列表。例如:

>>> find_duplicates("abbcdddeabcc")
[False, True, True, False, True, True, True, False, False, False, True, True]

然后,您可以使用此函数来过滤原始字符串。

def remove_all_dup(s):
is_duplicate = find_duplicates(s)
return "".join([ch for i, ch in enumerate(s) if not is_duplicate[i]])

def remove_no_rep(s):
is_duplicate = find_duplicates(s)
return "".join([ch for i, ch in enumerate(s) if is_duplicate[i]])

这应该返回:

>>> remove_all_dup('abbcdddeabcc')
'aceab'
>>> remove_no_rep('abbcdddeabcc')
'bbdddcc'

最新更新