-1

I got a little bit of a problem here. I'm trying to make a nested loop, but the second loop only runs one time.

Here is the code:

def solver(numbers, gleichung_list = [], temp = []):
    perm = itertools.permutations(numbers)
    permlist = [list(y) for y in perm]
    oper = itertools.product(['+', '-', '*', '/'], repeat=len(numbers)-1)
    for gleichung in permlist:
        print(gleichung)
        for ops in oper:
            print(ops)
            temp = [None] * (len(numbers)*2-1)
            temp[::2] = list(gleichung)
            temp[1::2] = list(ops)
            print(temp)
            print(ops)

    numbers = [1, 2]
    solver(numbers)

But when i run it, this is what i got:

[1, 2]
('+',)
[1, '+', 2]
('+',)
('-',)
[1, '-', 2]
('-',)
('*',)
[1, '*', 2]
('*',)
('/',)
[1, '/', 2]
('/',)
[2, 1]

Why don't the second loop run?

Georgy
  • 12,464
  • 7
  • 65
  • 73
pashafst
  • 11
  • 2
  • 1
    Does this answer your question? [Why can't I iterate twice over the same data?](https://stackoverflow.com/questions/25336726/why-cant-i-iterate-twice-over-the-same-data) – Georgy Apr 20 '20 at 10:19

2 Answers2

1

The product() function returns an iterator and not a list, so your nested loop run once on this iterator and then there is no more items. Add oper = list(oper) before your first loop to correct this problem.

Olivier Pirson
  • 737
  • 1
  • 5
  • 24
0

oper has come to an end in the first run of the loop and there is nothing left for iterating in the second run. If you just redefine oper in the loop it will be alright.

def solver(numbers, gleichung_list = [], temp = []):
    perm = itertools.permutations(numbers)
    permlist = [list(y) for y in perm]
    for gleichung in permlist:
        oper = itertools.product(['+', '-', '*', '/'], repeat=len(numbers)-1)
        print(gleichung)
        for ops in oper:
            print(ops)
            temp = [None] * (len(numbers)*2-1)
            temp[::2] = list(gleichung)
            temp[1::2] = list(ops)
            print(temp)
            print(ops)