Skip to content
Snippets Groups Projects
Commit 0f69793c authored by graeser's avatar graeser Committed by graeser@PCPOOL.MI.FU-BERLIN.DE
Browse files

Using generators instead of explicit iterators is much more elegant

[[Imported from SVN: r2387]]
parent 7923cd32
No related branches found
No related tags found
No related merge requests found
......@@ -17,22 +17,6 @@ class Iterate:
class FileIterator:
def __init__(self, file):
self.file = file
def __iter__(self):
return self
def next(self):
l = self.file.readline()
if l=='':
raise StopIteration
return l
class BufferedIterator:
def __init__(self, it, size=1):
......@@ -79,90 +63,47 @@ class BufferedIterator:
def FileIterator(file):
l = file.readline()
while (l!=''):
yield l
l = file.readline()
class UntilIterator:
def __init__(self, it, stop, withLast=True):
self.it = it
self.stop = stop
self.withLast = withLast
self.stoped = False
def __iter__(self):
return self
def next(self):
if self.stoped:
raise StopIteration
try:
item = self.it.next()
except StopIteration:
self.stoped = True
raise StopIteration
if self.stop(item):
self.stoped = True
if self.withLast:
return item
def UntilIterator(it, stop, withLast=True):
while (True):
item = it.next()
if (stop(item)):
if (withLast):
yield item
else:
self.it.back()
raise StopIteration
return item
class FilterIterator:
def __init__(self, it, include, mutate=(lambda x:x)):
self.mutate=mutate
self.include=include
self.it = it
self.stoped = False
def __iter__(self):
return self
def next(self):
if self.stoped:
raise StopIteration
try:
item = self.it.next()
while not(self.include(item)):
item = self.it.next()
return self.mutate(item)
except StopIteration:
self.stoped = True
raise StopIteration
it.back()
return
yield item
def FilterIterator(it, include, mutate=(lambda x:x)):
while (True):
item = it.next()
if (include(item)):
yield mutate(item)
class HierarchyIterator:
def __init__(self, it, up, down, hideupdown=False):
self.it = it
self.up = up
self.down = down
self.hideupdown = hideupdown
self.level = 0
def __iter__(self):
return self
def HierarchyIterator(it, up, down, hideupdown=False):
level = 0
while (True):
item = it.next()
upItem = up(item)
downItem = down(item)
if (upItem):
level += 1
if (not hideupdown) or ((not upItem) and (not downItem)):
yield (item, level)
if (downItem):
level -= 1
if level < 0:
level = 0
def next(self):
item = self.it.next()
if self.up(item):
self.level += 1
if (self.hideupdown):
return self.next()
r = (item, self.level)
if self.down(item):
self.level -= 1
if self.level < 0:
self.level = 0
if (self.hideupdown):
return self.next()
return r
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment