August 17th, 2004, 12:37 PM
-
newb: loop comparison
well ..... my concern is: do those two loops the same? if yes which one should be preferred and why?
I'm a bit confused b/c I don't really know if the range function is inclusive or not (I'm opted for not in that code)
assuming digit and maxDigit are both times the same value
Code:
for digit in range(maxDigit + 1):
blah...
and
Code:
while digit <= maxDigit:
blah...
digit += 1
any help really appreciated
August 17th, 2004, 01:47 PM
-
The easiest way to find the answer to questions like this is to try it and see. The Python interactive console makes it very easy to experiment, so take advantage of it:
Code:
>>> maxDigit = 10
>>> for digit in range(maxDigit+1):
... print digit,
...
0 1 2 3 4 5 6 7 8 9 10
>>> digit = 0
>>> while digit <= maxDigit:
... print digit,
... digit += 1
...
0 1 2 3 4 5 6 7 8 9 10
>>>
You can also get interactive help from within the session:
Code:
>>> help(range)
Help on built-in function range:
range(...)
range([start,] stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
>>>
Dave - The Developers' Coach
August 17th, 2004, 02:32 PM
-
August 18th, 2004, 12:53 AM
-
You might also want to look at the xrange() function. Its the same deal as range(), only being a generator, xrange() doesn't create the entire list in-memory. So for large numbers its much more efficient.
Mark.
August 18th, 2004, 01:03 PM
-
thx ... nice to know I'll of course test it, but it'll normally proof to be better when it's in the memory in my case
August 18th, 2004, 06:01 PM
-
Of course
. May i ask why it would be better in memory? Since there isn't usually any knoticable differences between the two, only the latter is more memory efficent.
Mark.
August 19th, 2004, 09:58 AM
-
I'm checking for 'Noble Numbers' and therefor I init a matrice with all the powers in my range and then I start to check if they are 'noble' ... so perhaps it'd be faster if it's in memory or perhaps this assumption is just bs
August 20th, 2004, 08:00 PM
-
The list is still in memory, that hasn't changed, the difference is that with a generator the values are created as-needed rather than all at once (so takes up more memory).
August 21st, 2004, 05:16 AM
-
thx ... now I get what you mean ... for my case it doesn't work now b/c the structure of the code had the other one in mind