'StopIteration exception raised in a function
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
Solution 1:[1]
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))
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kurt |
| Solution 2 | ChrisB |
