Tuesday, April 24, 2012

Python tricks

I'm taking part in Udacity course, of computer program design with Peter Norvig. Nice thing to do in your spare time. Whole course is based on Python ;) So the first Unit is over. Material didn't get hardcore yet ( I hope it will in the future ), but I've learned some python tricks.

First one is how to assign number to an item in an elegant way. Let's say we have card ranks (first udacity unit is about poker) encoded as follows: 2 3 4 5 6 7 8 9 T J Q K A, and we want to give them priorities according to their importance: 2->2, 3->3, ... , T->10, J->11, Q->12, K->13, A->14. Nothing simplier:
rank = 'Q' #our rank to check
'--23456789TJQKA'.index(rank)
Second trick is how to make list have only unique elements. In python it shows to be as simple as that:
my_list = [1, 1, 2, 3, 3, 3, 4, 5]
my_list = list(set(my_list))

After this my_list has only one occurrence of each value. Be aware that the ordering of elements in list may change.

No comments:

Post a Comment