Reputation: 894
I have a collection of points - lying on a grid. Each point is specified by a 1d integer array of size 3. The bounding box is specified by the coordinates of two diagonally opposite corners of this cube/cuboid. I wrote up the following code in python to do this -
import random as r
list = [[r.randint(-3,3) for j in range(3)] for i in range(90)]
#initialize itmin and itmax
itmin = list[0]
itmax = list[0]
#propagation
for i in range(len(list)):
for j in range(3):
itmax[j]=max(itmax[j],list[i][j])
itmin[j]=min(itmin[j],list[i][j])
print itmax
print itmin
The output to this - when run on python is -
[-1, 3, 1]
[-1, 3, 1]
Whereas , I would have expected it to be
[ 3, 3, 3]
[-3,-3,-3]
Can Anybody please point out to me what I am doing wrong? You could also try it out online - http://ideone.com/gNvG6I Please comment if you feel the question is not fleshed out properly.
Upvotes: 3
Views: 2296
Reputation: 76194
Your itmin
and itmax
variables point to the same list, so when you modify one, the other one is also modified.
During initialization, make shallow copies of the initial list, so that each variable gets their own separate copy.
itmin = list[0][:]
itmax = list[0][:]
Alternatively, skip the loop entirely and get the max & min using list comprehensions.
import random as r
list = [[r.randint(-3,3) for j in range(3)] for i in range(90)]
itmax = [max(point[i] for point in list) for i in range(3)]
itmin = [min(point[i] for point in list) for i in range(3)]
print itmax
print itmin
Result:
[3, 3, 3]
[-3, -3, -3]
Upvotes: 2