Sunday, January 25, 2015

Finding all Possible Combinations of Characters in a String

Here is a very simple but useful function I found here. It expects a string as a parameter and returns a list of all possible permutations of the letters. See the code by going to http://codepad.org/uLu0OvIX

The way the function works is pretty simple:

It simply uses a list comprehension to gather the results.
It uses two ranges: range(len(val)), which simply cycles through every index in that string, 
and range(start + 1, len(val), which for each index in the string
cycles through all indexes from that index up. Now by slicing between the two ranges, we get
every possible permutation of the characters in the string. If the list comprehension is confusing you, 
look at this post: A Beginners Guide to List Comprehensions.

Hope this tip is helpful!