Well, let us do exercise number 4, which is finding the divisors of an integer number. There are many ways to find a solution. Let's outline the objective and possible solution.
Objective:
1. User will input an integer
2. Find and Print the divisors
3. Also, Count the number of divisors
My First solution is given below.
This code can be modified a little bit to include the numbers in the list instead of printing the numbers. Now the modified code appends the divisors to a list. The purpose of this code is to understand the behavior of the empty list and learn how to append the code. The following code is the modified version of the previous one.
If we want to use list comprehension we can be more compact. But, personally, I am not a big fan of list comprehension. My personal opinion against is, sometimes it gets more complex to decode a list comprehension code which goes against the simplicity of Python. However, the following code is the list comprehension version.
Again, from an efficiency standpoint, if we look carefully, the code is wasting half of its iterations by finding nothing. Let me explain with an example. Say, we are finding the divisors of 24. The divisors of 24 are [1, 2, 3, 4, 6, 8, 12, 24]. The way this divisor finder program is now working is checking with every number starting from 1, incrementing at one step, checking again and running the same process up to all the way to the input integer.
We already know that the number itself (24 in this case) and 1 is always will be in its divisor list. And there is no possibility of getting any divisor when the program starts to check beyond half of the number (i.e., after 12 there will be no divisors). So, we can make use of this point by checking only up to half of the numbers. The code is below-
Although I did not do any quantitative comparison of efficiency, it should be twice faster than the previous one. Again, other optimizations can be done (e.g., for even inputs the odd numbers cant be a divisor, some error handling for floating-point inputs) but they are not the purpose of this topic.
No comments:
Post a Comment