Given:
numma = [1,2,3,4], n = 7
I expected the following code to return:
[[1,2,3],[1,2,4]]
Instead, it returns a list with four copies of:
[1,2,4]
and six copies of:
[1,2,3,4]
The script is intended to take the elements of the list numbers = numma in order, and form a new list (this_chain) with them, as long as the sum of the elements in this_chain does not exceed n = 7.
When adding a new element would break that condition, the list this_chain is appended to another list (all_chains), and the process begins again. If the original list (numbers) runs out of elements, the current this_chain is appended to all_chains and the script finishes, returning the list (of lists) called all_chains.
When I run it step by step, it follows the expected behavior, but upon reaching the return statement (step 84), instead of returning all_chains and finish, the arrow moves half a step downwards and then jumps back to the first statement (for i in
...). Then it goes back down and appends another copy of the current this_chain to all_chains, and so on, taking 66 additional steps and returning the output I mentioned above.
It was suggested to me to iterate over a tuple, instead of over a list, but since I want to remove elements from the iteration sequence I do not see how it could be done.
I am pretty puzzled. The four questions I'd like to ask, in order of importance, are the following:
Why does the program not finish upon reaching the return statement? I believed a return statement would always terminate any script.
Given the behavior described above, why does the script finally end, instead of keeping on appending copies of valid lists to the list called all_chains?
Why does the script append invalid elements to the list all_chains, that is, lists whose elements sum up more than n = 7?
Why are elements already in all_chains removed (or modified), so that they are not present in the final output, even if they were appended to the list all_chains previously?
My code:
def chain(numbers, n, all_chains=[], sum=0, this_chain=[]):
for i in range(len(numbers)):
if numbers[i] not in this_chain:
sum += numbers[i]
if sum <= n:
this_chain.append(numbers[i])
chain(numbers, n, all_chains, sum, this_chain)
else:
if this_chain not in all_chains:
all_chains.append(this_chain)
mocha = numbers[:]
mocha.remove(this_chain[-1])
chain(mocha, n, all_chains, sum=0, this_chain=[])
all_chains.append(this_chain)
return all_chains
numma = [1,2,3,4]
chain(numma, 7, chains=[], sum=0, this_chain=[])
[[1,2,3],[1,2,4]]
? What is the code supposed to do? – interjay Jan 26 '16 at 11:51L
. At leastn
would be needed if all other use the default values. – M4rtini Jan 26 '16 at 11:58