消除相邻数字的困境

时间:2018-09-28 07:59:42

标签: python

我正在编写一个函数,以删除列表中的相邻等效数字。我实际上不到一分钟就写了remove_adjacent(nums)。但是我似乎陷入了这种发情的境地,在这里我写的东西根本不是pythonic。而且它的速度不如我想要的快。第二种解决方案是Google编写的预期解决方案。这是我一直在研究的Google基本编码问题解决方案文档,但是我忘记了它是从哪里获得的,但是它是从Google开发中获得的。

# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.

def remove_adjacent(nums):

  index, index_1 = 0, 1
  while index_1 < len(nums):
      if nums[index] == nums[index_1]:
          nums = nums[:index] + nums[index+1:]
      else:
          index = index_1
          index_1 += 1 
  return nums

#Googles solution
def remove_adjacent2(nums):
    result = []
    for num in nums:
        if result == [] or num not in result:
            result.append(num)
    return result

我觉得我的问题源于我以前使用C和C ++的经验。关于如何改进有什么想法?我是否需要蛮力练习?不断重申“我是这样写的,但是这样写是更多的python”

2 个答案:

答案 0 :(得分:2)

有一个itertools recipe,它看起来像:

def unique_justseen(iterable, key=None):
    "List unique elements, preserving order. Remember only the element just seen."
    # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
    # unique_justseen('ABBCcAD', str.lower) --> A B C A D
    return map(next, map(itemgetter(1), groupby(iterable, key)))

答案 1 :(得分:2)

完美itertools.groupby

from itertools import groupby

lst = [1, 2, 2, 3]
print([next(x) for _, x in groupby(lst)])
# [1, 2, 3]