Question

def odd():
    for i in xrange(0, 100):
        if i % 2 == 1:
            print i

I have this small function. I would like to know:

  1. If there is a way to make it consume less memory?
  2. What are the tools and techniques you can use to efficiently measure and improve memory consumption?

I have this question in mind after looking at the following question: odd numbers

Was it helpful?

Solution

There is a recent answer on Stackoverflow about memory consumption measurement.

As for the memory consumption of your loop, it is negligible, and does not depend on the upper bound of the range, since xrange() does not really store much more than the next value it will return.

OTHER TIPS

Not sure about the question if is actually about memory consumption and an algorithm to make it more efficient or if it's tied to a specific language and how it does things in the background.

If it's about memory consumption and an algorithm to improve the solution a good workaround is to use a recursive (or iterative) solution with some simple conditionals.

Example instead of going through the 100 numbers in your loop (im not a python dev so ill write this easy solution in javascript that can be easily tested in chrome's console) you can try something like this:

    var iteration = 0;
var odd = function(val,max){
    iteration++;
    //base case
    if ( val > max ) return;
    if ( val % 2 == 1 ){
        console.log(val);
        odd(val+2,max);
    }else odd(val+1,max);   
}

odd(0,100);
console.log("Total iterations: "+iteration);

It results in only going through 52 iterations instead the 100.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top