[Python] How can I keep going to the next number in my iterable for all the values of my sympy...

Discussão em 'Python' iniciado por Stack, Fevereiro 14, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working in python and I'm specifically using sympy summations. I have an iterator that just goes up by 1 by using next(). For all of the values of my sympy summation, I want to keep going up by 1 by using next().

    What I mean by this is that when x is 1 then it should be 1 when it runs next(), then when x is 2 it should be 2 because it runs next() again and when it's 3 it should be 3 because it runs next() again and so on.

    The code I'm using is:

    from sympy import symbols, summation, gcdex, Piecewise, Eq, Abs, Mul, Le, mod_inverse, solve, invert, Mod, Max, log, \
    floor, simplify, And, Ge
    import random

    x = symbols('x')

    #just a placeholder function that I was trying to change how next() operates so it can go up by 1 each tine i call next()
    def callFunc(args):
    if args:
    return args
    return args

    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 generate_combinations(n, a, c):
    range_size = c - a + 1
    l = a + (n % range_size)
    return l # Only return `l`

    # Create an instance of the iterator
    expressions = DynamicIterator(generate_combinations, 1, 2 ** 256 + 1)

    def next_expr():
    iterate = next(expressions)
    return iterate

    def formula109(l, integer):
    random_number = random.randint(integer, integer+1) + l
    random_number2 = random_number - l # i removed the x so you can see how the values are the same each time without me using x.

    return random_number2

    logic = formula109(x, callFunc(next_expr()))
    total = summation(logic, (x, 1, 900000))
    print(total)

    #see what numbers are for each value of x
    terms = [logic.subs(x, k) for k in range(1, 10)]
    print(terms)


    As you can see when you run this, the values stay at 2 the entire time. I know that if I add x to it then it will go up but that's not what I want. I want to be able to use next() each time by itself to iterate up each time for every value of x. Can someone please show me what to do?

    The output is:

    1800000
    [2, 2, 2, 2, 2, 2, 2, 2, 2]

    Continue reading...

Compartilhe esta Página