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

9 comments:

韋雅萍志 said...

Poverty tries friends...................................................................

亦奈美妮 said...

良言一句三冬暖,惡語傷人六月寒。......................................................................

王雅吳玉婷奇 said...

愛,拆開來是心和受兩個字。用心去接受對方的一切,用心去愛對方的所有。......................................................................

瑞陳彥 said...

從來名利地,皆起是非心。.....................................................

峻胡邦慧v帆 said...

Man proposes, God disposes..................................................................

316 said...

愛情是一種發明,需要不斷改良。只是,這種發明和其他發明不一樣,它沒有專利權,隨時會被人搶走。.................................................................

盛灵林 said...

喜歡自己的另一層意義是「接納自己」。..................................................

宜DimpleHollow欣 said...

很精彩的部落格 期待你的繼續加油..................................................

盛春成 said...

培養健全孩子最好的方法是父母先成為健全的人。......................................................................

Post a Comment