【问题标题】:How to delete specific elements from an array while not deleting its later occurences如何从数组中删除特定元素而不删除其以后出现的元素
【发布时间】:2019-09-03 01:12:10
【问题描述】:

从用户那里获取整数输入,然后从数组中删除具有许多连续出现的数组中的元素。

例如,输入数组是“aabcca”,用户的输入是 2。 那么答案应该是“ba”。

我在元素不重复时尝试过。我的代码非常适合“aaabbccc”之类的示例。

for j in range(t, (n+1)):
    if (t == n):
        if (count == k):
            array = [x for x in array if x != temp]
        print array
        exit()
    if (t == n and count == k):
        array = [x for x in array if x != temp]
        print array
        exit()
    if temp == data[j]: 
        count += 1
        t += 1
    if temp != data[j]:
        if count == k:
            array = [x for x in array if x != temp]
        temp = data[t]
        count = 1
        t += 1

【问题讨论】:

  • 你能解释一下为什么input array is "aabcca" and the input from the user is 2. Then the answer should be "ba".吗?
  • @recnac 这是问题陈述。例如,如果您有一个字符串 aaabca 并且用户输入是 3,那么输出应该是 bca。只有用户提到的长度的连续字符应该被删除。另一个例子是如果数组是 abbcb 并且输入是 2 那么输出将是 acb。
  • 谢谢,我一定是在某个地方迷路了@Atharva Biwalkar

标签: python arrays algorithm list


【解决方案1】:

这是一种方法:

def remove_consecutive(s, n):
    # Number of repeated consecutive characters
    count = 0
    # Previous character
    prev = None
    # Pieces of string of result
    out = []
    for i, c in enumerate(s):
        # If new character
        if c != prev:
            # Add piece of string without repetition blocks
            out.append(s[i - (count % n):i])
            # Reset count
            count = 0
        # Increase count
        count += 1
        prev = c
    # Add last piece
    out.append(s[len(s) - (count % n):])
    return ''.join(out)

print(remove_consecutive('aabcca', 2))
# ba
print(remove_consecutive('aaabbccc', 2))
# ac
print(remove_consecutive('aaabbccc', 3))
# bb

【讨论】:

    【解决方案2】:

    您可以使用sliding windowtwo pointers 来解决它。

    关键是使用[start, end]范围记录一个连续的seq,只添加长度小于n的seq:

    def delete_consecutive(s, n):
        start, end, count = 0, 0, 0
        res, cur = '', ''
        for end, c in enumerate(s):
            if c == cur:
                count += 1
            else:
                # only add consecutive seq less than n
                if count < n:
                    res += s[start:end]
                count = 1
                start = end
                cur = c
    
        # deal with tail part
        if count < n:
            res += s[start:end+1]
    
        return res
    

    测试和输出:

    print(delete_consecutive('aabcca', 2))      # output: ba
    print(delete_consecutive('aaabbccc', 3))    # output: bb
    

    希望对您有所帮助,如果您还有其他问题,请发表评论。 :)

    【讨论】:

    • 非常感谢@recnac。我看到关键是使用了一个我没有做的功能。
    猜你喜欢
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2011-01-27
    相关资源
    最近更新 更多