如何从数组中删除特定元素,同时不删除其以后出现的元素

2024-05-29 11:03:22 发布

您现在位置:Python中文网/ 问答频道 /正文

从用户处获取整数输入,然后从一个数组中删除元素,该数组中有许多连续的ocurence。你知道吗

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

我在元素不重复的时候试过了。我的代码非常适合“aaabbcc”这样的例子。你知道吗

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

Tags: 用户in元素fordataifcountexit
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

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

有一种方法:

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

相关问题 更多 >

    热门问题