Posts

Showing posts from March, 2019

Python - Week 10 - Math Problems

Few more Math problems solved using Python Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. So for example sum of squares of first 100 natural numbers from 1 to 100 is 25502500. And square of sum of first 100 natural numbers from 1 to 100 is 338350. Here is the code: Again, a simple solution to a simple problem. I have separated the two functions for modularity Line 4 shows how comprehensions can be used to solve these kind of problems. Line 6 is the way to sum over iterables. Here sum just takes in an iterable (could have been a dictionary or a map as well) and does the magic. No need to write additional code here. An object is iterable if it is either a physically stored sequence in memory, or an object that generates one item at a time in the context of an iteration operation. List objects are considered iterable because they support the iteration protocol—they respond to the iter call with an ...

Python - Week 9 - Simple Math problems

This week I tackled 3 math problems. Not much of Python here, but I wanted to check out how Math problems are handled. In the end, it all depends on the algorithm deployed and the libraries/constructs available. Here is the first problem: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. This is not a complicated problem and the solution itself is pretty straightforward. The only Pythonic construct used here is the else for the loop which is executed only if the for loop runs successfully (which it anyway does here). The more interesting use of this else statement would have been the cases where we may break the loop. Now lets look at the second problem: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ......