Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a custom generator function with python [closed]

I have this

for A in [0, -0.25, 0.25, -0.5, 0.5, -0.75, 0.75, -1.0, 1.0, -1.25, 1.25, -1.5, 1.5, -1.75, 1.75, -2.0, 2.0, -2.25, 2.25, -2.5, 2.5, -2.75, 2.75, -3.0, 3.0, -3.25, 3.25, -3.5, 3.5, -3.75, 3.75, -4.0, 4.0, -4.25, 4.25, -4.5, 4.5, -4.75, 4.75, -5.0, 5.0]:

Is it possible to make it with generator function? I have now this:

def frange(start, stop, step=1.0):
    while start <= stop:
        yield start
        start += step

and use like this:

for error in self.frange(-2.5, 2.5, 0.25):

but its returns [-2.5, 2.25, ... , 0 , 2.25, 2.5] and for my program it's very hard to calculate. because I finding the value the near to zero, but I don't know how much combinations it could be.

I need go from zero and next value must be in minus and plus value. like [0, -0.25, 0.25...].

like image 947
Jiří Vyplašil Avatar asked Dec 08 '25 05:12

Jiří Vyplašil


1 Answers

Maybe you meant a generator instead of a lambda:

def opposing_numbers(increment, maximum):
     yield 0
     value = increment
     while value <= maximum:
         yield -value
         yield value
         value += increment

Then call it as:

opposing_numbers(0.25, 5)
like image 155
mhlester Avatar answered Dec 09 '25 20:12

mhlester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!