I understand that loops are a bad idea in python and I should avoid them.
Well, I have several of those I want to avoid.
I have a list of stuff named lipid:
class bead:
x = 0
y = 0
z = 0
LID = 0
t = 0
class lipid:
h = bead()
b = bead()
t = bead()
LID = 0
and I am doing the following (code below):
- initializing a 2d array of
hs going over all the lipids and - determine if they are counted as
Uor down - adding value to the appropriate
h
How can I avoid, at least, the first loop?
1:
class h:
cU = 0
cD = 0
hU = 0
hD = 0
h = 0
for i in range(0,8):
hs.append([])
for j in range(0,8):
index = (i,j)
hn = h()
hs[i].append(hn)
2 and 3:
for LID in lipids:
l = lipids[LID]
up = l.h.z > l.t.z
X = (int)(l.b.x*8/L)
Y = (int)(l.b.y*8/L)
Z = (l.b.z)*0.5
if up:
hs[X][Y].hU += Z
hs[X][Y].cU += 1
else:
hs[X][Y].hD += Z
hs[X][Y].cD += 1
Loops are not a bad idea. It is just that loop-intensive code can be slow. But it is nothing specific to the loops, it is just that Python is not as fast in general as some other languages. I suggest you do not avoid loops if they are the most natural expression of your algorithm. If your code turns out slower of what you expect or need, then look for ways of optimizing it (profiling, to start with).
The article on Analysis of Algorithms in Wikipedia might me useful for you.