Iteration in python taking acount the previous output values

34 Views Asked by At

I am new in Python and I would like to ask this question:

I want to write a code, which repeats itself taking into account the previous values.

For example let us we want firsly to have as output the difference between 100 (:= an initial value, which we need to define in inside the loop) and our input number x. Thus, if the first time we give the value 5 for x, then the first output is 95. We want the second to be 95 minus the new given x, so, if the second x is 3, our second difference will be 95-3= 92 and so on til e.g. the difference will be 0.

If this example helps, I would be glad for some help to understand the general method.

I would like to understand a loop in python with these specific characteristics. I f this simple example helps, I would be happy to get understanding through that.

1

There are 1 best solutions below

2
Razumov On

I found this idea quite interesting, I came up with the following example:

import itertools

def sub_to_zero(val):
    while val > 0:
        sub = (yield val)
        if sub is not None:
            val -= sub
    yield None

subs = itertools.cycle([5, 3, 2, 1, 2, 3, 4])
nums = sub_to_zero(100)

nums.send(None)
while True:
    x = nums.send(next(subs))
    if x is None:
        break
    print(x)

The key idea is to use a generator with an initial value, and then make use of the .send() method to decrement that value each time we want to access the next item.

For general info on generators and using send: https://realpython.com/introduction-to-python-generators/#how-to-use-send

For info on the quirky initial send(None) that is needed: Send method using generator. still trying to understand the send method and quirky behaviour