Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove consecutive duplicates from a list using yield generator? [closed]

i'm trying to compress a list using generator:

examples

[1, 1, 1, 1, 2, 2, 2, 1, 1, 1] == [1, 2, 1]

[5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0])) == [5, 4, 5, 6, 5, 7, 8, 0]

I tried to use a generator that checks if the 1st and 2nd element are equal then check 2nd and 3rd and so on until it is no longer equal "when it reaches 4" and then yield "5" then it would repeat the process starting with "4"

code

test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0] # sample list
from typing import Iterable
def compress(items: list) -> Iterable:

    x = 0
    while items[x] == items[x + 1]:
        x += 1
    yield items[x]


ans = compress(test)
for x in ans:
    print(ans)

but i keep getting

generator object compress at 0x00000254D383C820. why won't it loop?

if i try and use next() it only goes up to 5 and wont check the other numbers.

any assistance is greatly appreciated.

like image 501
bienology Avatar asked Nov 28 '22 19:11

bienology


2 Answers

As others have explained, your structure is incorrect - you're only encountering the yield once outside the loop. The ideal way would be to iterate over pairs of consecutive numbers and yield the first one in the loop if they are different.

However, here's a canonical method via itertools.groupby which removes consecutive duplicates:

from itertools import groupby 
from operator import itemgetter

list(map(itemgetter(0), groupby(l)))
# [1, 2, 1]
like image 121
cs95 Avatar answered Dec 20 '22 02:12

cs95


So there are several flaws, all of them described as comments to the question post.

  • there is a loop missing that would yield more than one value
  • you print ans and not x, which logically is the generator object.

Is this code working for you?

test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0]

def compress(items):
    for i, d in enumerate(items[:-1]):
        if d == items[i+1]:
            continue
        yield d
    yield items[-1]

for x in compress(test):
    print(x)
like image 34
Dr. V Avatar answered Dec 20 '22 03:12

Dr. V