Reputation: 75
I'm coding in python and I'm having an issue with my sympy summation. I want to use my sympy summation so that I can call next() everytime the value of x (which is my symbol) changes.
The problem is that when I use next() the function only moves once and stays the same for the whole summation.
I want the value of num to go from 1 to 2 to 3 to 4 and so on since that's what happens when you repeatedly call next(), everytime the value of x goes up.
I already coded an iterator that lets me control when to move forward with next() and when not to so I know this is possible. My code is below:
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
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):
range_size = c - a + 1
p = a + (n // range_size)
l = a + (n % range_size)
return l # Only return `l`
# Parameters for `a` and `b`
# Create an instance of the iterator
expressions = DynamicIterator(generate_combinations, 1, 256 - 1)
# Define a lambda to get the next value of `l`
next_expr = lambda: next(expressions)
#print(next_expr())
# expressions.control_advance(True)
#print(next_expr())
if x != 0:
num = int(next_expr())
else:
num = 1
formula = num + x
total = summation(formula, (x, 1, 3))
print(total)
As you can see in this code, I'm just simply adding num to x. The value of num should change from 1 to 2 to 3 since it should be calling next() each time. I want this to occur everytime x in the summation changes values and goes up by 1.
I specifically want my code like this guys and I don't want any for loops or any other type of loops. I want everything closed form so I can use it in other projects too. Can someone show me what to do?
if x != 0:
num = int(next_expr())
else:
num = 1
right here is where i want it. I want it to say that num value is the next value everytime x the symbol goes up.
Upvotes: 0
Views: 62