0

i am trying to convert my function i want it do the same as:

    def get_num(function, starting_index):
        yield starting_index
        while True:
            yield function(starting_index)
            starting_index = function(starting_index)

so im i want the new function to return a genexp that does exactly the same, of course without using 'yield', and all in one line, is possible? Thanks

user2918984
  • 121
  • 4
  • 13
  • Why do you want to do this? IMHO, this looks much better than the generator expression equivalent. – rlms Nov 30 '13 at 18:53
  • Half homework, half teaching myself, i don't necessarily need a code, an idea, or the beginning of something is good too! – user2918984 Nov 30 '13 at 19:02
  • @TimPeters my "favourite" being [this one](http://stackoverflow.com/questions/20248760/python-generator-endless-stream-without-using-yield/20249240#20249240) – Jon Clements Nov 30 '13 at 19:11
  • 4
    What kind of awful homework is this?! It doesn't teach you how to program, it teaches you how to use Stack Overflow to find ways to horribly abuse whichever language it's set for. – rlms Nov 30 '13 at 19:15

2 Answers2

2

Well, first, you might want to avoid redundant calls to the function:

def get_num(fn, start):
    while True:
        yield start
        start = fn(start)
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
0

A recursive version of your original function:

def get_num(f, x):
    yield x
    yield from get_num(f, f(x))

On the same theme:

>>> p = lambda x, f, c: chain((x,), (i for i in p(f(x), f, c))) if c(x) else (x, None)
>>> p(1, lambda x: x*2, lambda x: x < 100)
<itertools.chain object at 0x01633DD0>
>>> list(_)
[1, 2, 4, 8, 16, 32, 64, 128, None]

This does what the original function does, but stops if x satisfies some condition.

Then because it has to be a generator expression?! we do this:

>>> g = (i for i in _)
>>> next(g)
1
>>> next(g)
2
>>> next(g)
4
>>> next(g)
8
>>> next(g)
16

The conditional function c is necessary to stop infinite recursion. If Python was a bit more of a functional language (i.e. lazy evaluation being more common, and tail recursion being optimized) then this wouldn't be necessary.

rlms
  • 10,650
  • 8
  • 44
  • 61