Friday 11 February 2011

Random python thoughts, sorted by number of occurrences

This is just a memo about ease of working with ranges, random choices and sorting.
Let's see a piece of code:
import random
import string
from operator import itemgetter

sample_dict = {}
for x in range(random.choice(range(2,25))):
    r_num = random.choice(range(0,x+1))
    lst = random.sample(string.letters,r_num)
    for l in lst:
        if l in sample_dict.keys():
            sample_dict[l] += 1
        else:
            sample_dict[l] = 1
print sample_dict
itms = sample_dict.iteritems()
print sorted(itms,key=itemgetter(1),reverse=True)
This is python, so there is no need for explaining. But it's worth to mention some cool things for newcomers.
When you need a list of numbers just choose your range - range(2,25).
And if you need just a random number from this range - random.choice(range(2,25)).
And if you need a few letters, you can get them from string.letters, like this random.sample(string.letters,5). Now you have five random letters.
The script above is counting, how often these random letters are repeated, by using them as dict keys. When you have such dict you must sort it by values in order to show occurences of every key - sorted(sample_dict.iteritems(),key=itemgetter(1),reverse=True)

No comments:

Post a Comment