Coding, Python

Python fun #4: Create sorted list of all possible numbers using same digits (of a number)

Let’s say the number is 123.

Then the statement:

[int(''.join(x)) for x in permutations(list(str(123)))]

will create a sorted list of all possible numbers using ‘1’,’2′ and ‘3’.
which is, [123, 132, 213, 231, 312, 321]

What it is doing

The part, permutations(list(str(‘123’ is creating a permutated tuple list of splitted string ‘123’.
And the int(”.join(x)) is converting each tuple to back to Integer.

However, you need to

import permutations from itertools

so, the generalized version would be:

import permutations from itertools
[int(''.join(x)) for x in list(permutations(list(str(n))))]
Coding, Python, software

Python: Some Performance Scores

I just finished reading Sebastian Raschka’s analytic discussion of Pyhton tweaks where the author tested with Python version: 3.3.3

Now, as I am a huge “fan” of Pythonic 1-liners, I made a summary of the article containing 1-liner-analysis-result.

Adding elements to dictionaries
Adding keys “By exploiting thrown KeyError exceptions via an try-except loop” is slightly(~1.2x) faster than “(first,) checking if a key already exists in the Python dictionary using if-else loop”

Continue reading

Coding, Python

Python fun #3 : Directly Input from a text file to a processed 2-D list (in 1 statement)

Suppose you have input file like this(triangle.txt) to use as input …

with open('triangle.txt') as f:
    D = [[int(w) for w in line.split()] for line in f]

This will create a nice table-like 2-D list, i.e. a list of lists. The member list(s) can be of variable size. You can modify the int(w) for w in line.split() part to incorporate your processing.

Continue reading