Finding all possible permutations of a given string in python

The itertools module has a useful method called permutations(). The documentation says: itertools.permutations(iterable[, r]) Return successive r length permutations of elements in the iterable. If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated. Permutations are emitted in lexicographic sort order. So, if … Read more

How do you get the magnitude of a vector in Numpy?

The function you’re after is numpy.linalg.norm. (I reckon it should be in base numpy as a property of an array — say x.norm() — but oh well). You can also feed in an optional ord for the nth order norm you want. Say you wanted the 1-norm: And so on.

Checking if a number is prime in Python

A pretty simple and concise brute-force solution to check whether a number N is prime: simply check if there is any divisor of N from 2 up to the square root of N (see why here if interested). The following code is compatible with both Python 2 and Python 3: And here’s a simpler Python 3 only … Read more

Convert pandas data frame to series

It’s not smart enough to realize it’s still a “vector” in math terms. Say rather that it’s smart enough to recognize a difference in dimensionality. 🙂 I think the simplest thing you can do is select that row positionally using iloc, which gives you a Series with the columns as the new index and the values … Read more

How to increase plt.title font size?

fontsize can be assigned inside dictionary fontdict which provides additional parameters fontweight, verticalalignment , horizontalalignment The below snippet should work plt.title(‘Temperature \n Humidity’, fontdict = {‘fontsize’ : 100})

Replace and overwrite instead of appending

You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace: The other way is to read the file then open it again with open(myfile, ‘w’): Neither truncate nor open(…, ‘w’) will change the inode number of the file (I tested twice, once with Ubuntu 12.04 NFS and once with ext4). By the way, this … Read more