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"
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.
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]
So there are several flaws, all of them described as comments to the question post.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With