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.
yield
statement exactly once. That's why it can only produce one value. – Bickfordans
and notx
... plus the comment from timgeb - it must be in a loop where you test for x to reachlen(items)
– Madness