learningjoe learningjoe -4 years ago 146
Python Question

python for loop in matrix to assign values

I was creating a program that will create a grid and the program will
deside its position by a matrix array you assign at the input.

code:

def onbekende_naam(hoogtes):
print(hoogtes)
i = 0
j = 0
pos1 = set()

for hoogtes_subs in hoogtes:
j = 0
for hoogtes in hoogtes:
print("i = " + str(i))
print("j = " + str(j))
pos1.add((i, j))
print pos1
j += 1
i += 1
#pos1.add((i, j))

return pos1

#verwerking
print (onbekende_naam(hoogtes))


input:

4 4
1 2 3 4
5 6 7 8
9 1 2 3
4 5 6 7
12 1


output:

[['1', '2', '3', '4'], ['5', '6', '7', '8'], ['9', '1', '2', '3'], ['4', '5', '6', '7']]
i = 0
j = 0
set([(0, 0)])
i = 0
j = 1
set([(0, 1), (0, 0)])
i = 0
j = 2
set([(0, 1), (0, 0), (0, 2)])
i = 0
j = 3
set([(0, 1), (0, 3), (0, 0), (0, 2)])
i = 1
j = 0
set([(0, 1), (0, 3), (0, 0), (0, 2), (1, 0)])
i = 1
j = 1
set([(0, 1), (0, 0), (0, 2), (1, 0), (0, 3), (1, 1)])
i = 1
j = 2
set([(0, 1), (1, 2), (0, 0), (0, 2), (1, 0), (0, 3), (1, 1)])
i = 1
j = 3
set([(0, 1), (1, 2), (0, 0), (0, 2), (1, 3), (1, 0), (0, 3), (1, 1)])
i = 2
j = 0
set([(0, 1), (1, 2), (0, 0), (0, 2), (2, 0), (1, 3), (1, 0), (0, 3), (1, 1)])
i = 3
j = 0
set([(0, 1), (1, 2), (0, 0), (3, 0), (0, 2), (2, 0), (1, 3), (1, 0), (0, 3), (1, 1)])
set([(0, 1), (1, 2), (0, 0), (3, 0), (0, 2), (2, 0), (1, 3), (1, 0), (0, 3), (1, 1)])


as you can see it stops incrementing j when the i value is bigger than 2

I'm fairly new at this so thanks for helping

Answer Source

It looks like you use the same name in your second for loop. Can you try if changing this works?

def onbekende_naam(hoogtes):
    print(hoogtes)
    i = 0
    j = 0
    pos1 = set()

    for hoogtes_subs in hoogtes:
        j = 0
        for another_name_hoogtes in hoogtes:
            print("i = " + str(i))
            print("j = " + str(j))
            pos1.add((i, j))
            print pos1
            j += 1
        i += 1
        #pos1.add((i, j))

    return pos1

#verwerking
print (onbekende_naam(hoogtes)) 

Also: when I run your original code I get the following error:

TypeError: 'int' object is not iterable

Why didn't you get this error?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download