Sunday, 23 February 2014

Maximizing efficiency

In the lab last week we solved problems related to loops and comprehensions. Converting a comprehension to a loop expression is not difficult, but during the conversion we have to think as a programmer, which is, to maximize the efficiency of the program.

We certainly have a number of ways to solve the same task. An example is the "stack" and "queue" problem we met in a previous lab. If the data is stored in a "first in, last out" method, while taking out (or storing)each object, all items in the list have to be shifted once to one side. If the "first in ,first out" method is used, then when taking out one object, the others just remain in their original position, thus it requires less computation.

While using a loop or a recursion, we shall reduce the number of iterations. For example:

lst = []
for i in range(1, 4):
   for j in range(1, 4):
      if (i * j) not in lst:
         lst.append(i * j)

return lst

To get the same result we can also have:

lst = []
for i in range(1, 4):
   for j in range(i, 4):
      lst.append(i * j)

return lst

They return the same result [1, 2, 3, 4, 6, 9], but the latter code takes less number of iterations, thus the latter one is more efficient.

No comments:

Post a Comment