Home > Back-end >  StopIteration exception raised in a function
StopIteration exception raised in a function

Time:04-01

I have the following function in my python script:

def subset_sum (list_of_int,target):
    #create iterable
    itr = chain.from_iterable(combinations(list_of_int, n) for n in range(2,len(list_of_int)-1))
    #number of iteration rounds
    rounds = 1000000
    i = cycle(itr)
    #instantiate a list where iterations based on number of rounds will be stored
    list_of_iteration = []
    #loop to create a list of the first n rounds
    for x in range(rounds):
        list_of_iteration.append(next(i)) 
    #find the first list item that = target 
    for y in list_of_iteration:
        if sum(y) == target: 
            return list(y)

My question is why am I getting a StopIteration error? When I test this formula in a small data set it works fine without any issues. However, when I apply it to the larger dataset the exception comes up.

It says that the issue is in line list_of_iteration.append(next(i))

What am I doing wrong?

these is the stack trace:

 File "XXXXXXXXXXXXXXXX", line 19, in subset_sum
    list_of_iteration.append(next(i))

StopIteration

KeyboardInterrupt

CodePudding user response:

The variable "itr" must be empty. If you try to next() a cycle() on an empty iterator you get a StopIteration. Try this:

empty = []
i = cycle(empty)
print(next(i))

CodePudding user response:

The StopIteration error is an exception that is thrown from the next method when there is no next element in the iterator that next is called on.

In your code, the iterator i must have fewer elements than required by the value of rounds.

  • Related