analitics

Pages

Thursday, February 3, 2011

Python - calendar

Two simple example about calendar python module.
Show calendar 04 - 2011 :

>>> import calendar
>>> tc = calendar.TextCalendar(calendar.SUNDAY)
>>> print tc.formatmonth(2011,04)
     April 2011
Su Mo Tu We Th Fr Sa
                1  2
 3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

>>>
Show calendar in HTML format :
>>> import calendar
>>> hc = calendar.HTMLCalendar(calendar.SUNDAY)
>>> print hc.formatmonth(2011,04)
;
The result is a HTML table with the calendar.
This is all .

Tuesday, August 3, 2010

Random module - another example

Random module is a module used in everyday programming.
Even if it is not used in the final software, he helps us to test various types of random data.
We present you a simple example - play with cards.
We chose a list of cards of one color for not having a large number of elements.
We exemplify the use of random module by analogy with a game of cards.
That it means: shuffle cards , select just one from cards and a choice selection of a defined number of cards.
Below you see the code used as an example.

>>> import random
>>> choice=random.choice
>>> shuffle=random.shuffle
>>> for i in range (9):
...     print choice(cards)
... 
Q
K
10
Q
2
2
10
K
6
>>> shuffle(cards)
>>> cards
[4, 7, 10, 'J', 3, 'Q', 6, 2, 'K', 9, 'A', 8, 5]
>>> sample=random.sample
>>> sample(cards,5)
[8, 'J', 2, 'Q', 10]
>>> sample(cards,5)
['A', 9, 4, 'K', 'Q']
>>> 
The random module docs