Python - Week 5 - Comprehensions
As I settle in new job in a new country, starting February, I am making additional efforts to learn Python.
So I will tackle a problem this week, with multiple solutions, each more Pythonic than the previous one.
Here is the problem statement:
Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed.
Example:
0100,0011,1010,1001
Then the output should be:
1010
I deviated from the problem statement (not a good thing!).
But I wanted to learn new tricks with Python. So I will excuse myself here.
The way I approached the problem was to take a number (num) and find all binaries starting from 0 until num.
Now for each of the binary, I checked if the equivalent decimal is divisible by 5.
Some interesting points to note:
So I will tackle a problem this week, with multiple solutions, each more Pythonic than the previous one.
Here is the problem statement:
Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed.
Example:
0100,0011,1010,1001
Then the output should be:
1010
I deviated from the problem statement (not a good thing!).
But I wanted to learn new tricks with Python. So I will excuse myself here.
The way I approached the problem was to take a number (num) and find all binaries starting from 0 until num.
Now for each of the binary, I checked if the equivalent decimal is divisible by 5.
- Line 7 shows a way to convert a number to its binary string. Here b stands for binary and it uses format method to spit the binary.
- Line 12 - 14 is the C way of calculating this the decimal number out of a binary.
- Line 28 is a Pythonic way of converting a binary to decimal.
- Line 40 does away with all the loops and uses comprehensions - it basically picks each binary, checks if the decimal equivalent meets to divisibility criteria and prints that binary.
- List comprehensions are written in square brackets because they are ultimately a way to construct a new list. - Line 40
- Anytime we start thinking about performing an operation on each item in a sequence, we’re in the realm of list comprehensions.
- List comprehensions derive from set notation; they are a way to build a new list by running an expression (our if in Line 40) on each item in a sequence, one at a time, from left to right. List comprehensions are coded in square brackets and are composed of an expression and a looping construct that share a variable name.
- To perform true integer division use // operator. / operator will return float if one is float, while // will return integer.
- // always truncates fractional remainders down to their floor, regardless of types. Its result type depends on the types of its operands.
Comments
Post a Comment