[Python] How do I call next() in my sympy summation each time for the values in the summation...

Discussão em 'Python' iniciado por Stack, Janeiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I'm coding in python and I'm using sympy. I'm specifically using summations. In my summation, I'm using next() in my formula so that I can go to the next value of a variable each time in my summation but I'm having problems.

    The value of next() in my summation only travels up 1 once and then it uses that same value for the whole summation. I want to be able to use the next value each time in my summation as if I said in python: next("iterable") next("iterable") next("iterable")

    The code I'm using right now is:

    from sympy import summation, Eq, symbols

    x = symbols('x')


    class DynamicIterator:
    def __init__(self, func, a, b):
    self.func = func # Function to generate values
    self.counter = 0 # Keeps track of the current index
    self.a = a
    self.b = b
    self.can_advance = True # Default to allowing automatic advancement
    self.advanced = False # Flag to control when to advance

    def __iter__(self):
    return self

    def __next__(self):
    if not self.can_advance:
    raise StopIteration # Stop iteration if cannot advance

    value = self.func(self.counter, self.a, self.b) # Generate the value
    self.counter += 1 # Increment the counter

    if x != 0:
    self.counter += 1

    return value

    def control_advance(self, can_advance):
    """Control whether the iterator can advance or not."""
    self.can_advance = can_advance

    # Define the function that returns the value of `l`
    def generate_combinations(n, a, c):
    l = 0
    l += 1
    return l # Only return `l`

    # Create an instance of the iterator
    expressions = DynamicIterator(generate_combinations, 1, 200)
    # Define a lambda to get the next value of `l`
    next_expr = lambda: next(expressions) + x


    total = summation(next_expr(), (x, 1, 3))
    print(total)


    As you can see in next_expr variable that is where it is calling next(). In my summation from the values 1 2 and 3 it only does what I want for 1 and then it stays the same and doesn't go to the next values for the rest of the values in the summation.

    Can someone please help me fix this problem?

    Continue reading...

Compartilhe esta Página