Next quiz is posted as code snippet. It is quite interesting code. What it does? And where in your system you already have this code? (in little different format) (If you have not follow tip in page http://python.org/download/)
Quiz of the week: Where in your system you have this code?
class LazyList:
def __init__(self, g):
self.sofar = []
self.fetch = g.next
def __getitem__(self, i):
sofar, fetch = self.sofar, self.fetch
while i >= len(sofar):
sofar.append(fetch())
return sofar[i]
def times(n, g):
for i in g:
yield n * i
def merge(g, h):
ng = g.next()
nh = h.next()
while 1:
if ng < nh:
yield ng
ng = g.next()
elif ng > nh:
yield nh
nh = h.next()
else:
yield ng
ng = g.next()
nh = h.next()
def m235():
yield 1
# Gack: m235 below actually refers to a LazyList.
me_times2 = times(2, m235)
me_times3 = times(3, m235)
me_times5 = times(5, m235)
for i in merge(merge(me_times2,
me_times3),
me_times5):
yield i
#Print as many of these as you like -- *this* implementation is memory-
#efficient.
if __name__ == '__main__':
m235 = LazyList(m235())
for i in range(5):
print [m235[j] for j in range(15*i, 15*(i+1))]
TrustyTony 888 pyMod Team Colleague Featured Poster
TrustyTony 888 pyMod Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.