gpt4 book ai didi

python - 递归删除列表中相邻的重复项

转载 作者:太空宇宙 更新时间:2023-11-03 18:29:12 25 4
gpt4 key购买 nike

我查找并找到了一个接近的示例,但在此链接中找到了答案:Remove adjacent duplicate elements from a list不会针对此问题运行测试用例。这就是我到目前为止所拥有的一切:

def remove_dups(thelist):
"""Returns: a COPY of thelist with adjacent duplicates removed.

Example: for thelist = [1,2,2,3,3,3,4,5,1,1,1],
the answer is [1,2,3,4,5,1]

Precondition: thelist is a list of ints"""
i = 1
if len(thelist) == 0:
return []
elif len(thelist) == 1:
return thelist
elif thelist[i] == thelist[i-1]:
del thelist[i]
return remove_dups(thelist[i:])


def test_remove_dups():
assert_equals([], remove_dups([]))
assert_equals([3], remove_dups([3,3]))
assert_equals([4], remove_dups([4]))
assert_equals([5], remove_dups([5, 5]))
assert_equals([1,2,3,4,5,1], remove_dups([1,2,2,3,3,3,4,5,1,1,1]))

# test for whether the code is really returning a copy of the original list
mylist = [3]
assert_equals(False, mylist is remove_dups(mylist))

编辑虽然我确实明白上面使用 itertools.groupby 链接的接受答案是可行的,但我认为它不会告诉我我的代码有什么问题,并且如果我从 itertools 导入 grouby ,就会违背练习的目的。

最佳答案

from itertools import groupby

def remove_dups(lst):
return [k for k,items in groupby(lst)]

如果你真的想要一个递归解决方案,我会建议类似的东西

def remove_dups(lst):
if lst:
firstval = lst[0]

# find lowest index of val != firstval
for index, value in enumerate(lst):
if value != firstval:
return [firstval] + remove_dups(lst[index:])

# no such value found
return [firstval]
else:
# empty list
return []

关于python - 递归删除列表中相邻的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22671772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com