Programming Python
cyber_ula  

How to return a list of numbers of the power of 2 in Python?

Today is the day when I should solve the next problem of the Project Euler Challenge, but I decided to change my plan and consider the problem how to search a number in a list of numbers of the power of 2 which leads to return a list of numbers of the power of 2.

I think it gives you the chance, my dear reader, to follow with me with a coding exercise.  I find this problem interesting to solve in different ways.

When I was reading a book called “Learning Python Powerful Object-Oriented Programming” written by Mark Lutz, I encountered for exercise in Chapter 15, when the author defines the problem:

Program logic alternatives.

Consider the following code, which uses a while loop and found flag to search a list of powers of 2 for the value of 2 raised to the fifth power (32). It’s stored in a module file called power.py.

He encourages the reader to start to rewrite this file differently. As you can see, the problem seems to start with a while loop and boolean flag. The author writes all power of 2 in the L list. He wants to search 32 in the list. And what the program does is to find an index of 32 which is 5. But consider also example like a number out of the list, then of course result is ‘not found’.

You can try it out, and check it by yourself.

Then let’s start to solve refactor this problem in some ways which were recommended by the author.

First, rewrite this code with a while loop else clause to eliminate the found flag and final if statement.

Rewrite the example to use a for loop with an else clause, to eliminate the explicit list-indexing logic

I use here: try…except because I want to catch the ValueError, which in some way throw an error.

Remove the loop completely by rewriting the example with a simple in operator membership expression

As you see, still L is not changed, but we removed the loop and here it looks much cleaner.

Use a for loop and the list append method to generate the powers-of-2 list (L) instead of hardcoding a list literal

I commented (green colour) the code that allows you to generate a powers-of-list-2, based on the length of L. The length is 7 so we can change it soon.

A map(function, list) tool that can generate a powers-of-2 list and list comprehensions

And here we start using map function and list comprehensions and generate all numbers in the L list using these shortcuts:

Our analysis of this problem leads us to find solutions on how to return a list of numbers of the power of 2 in Python.

You can go further and try to generalize all these problems and change base 2 on any number or change length of L list and try to put it in function to be more generic.

Everything is up to you. Happy Coding!

Leave a Reply