python开发_random

和java中的random()函数一样,在python中也有类似的模块random,即随机数

下面是我做的demo

运行效果:

==========================================

代码部分:

==========================================

 1 #python random
 2 
 3 import random
 4 
 5 def get_random():
 6     '''get a random number.
 7     return Random float x, 0.0 <= x < 1.0'''
 8     return random.random()
 9 
10 def get_uniform(a, b):
11     '''Return a random floating point number N such that
12     a <= N <= b for a <= b and b <= N <= a for b < a.
13     The end-point value b may or may not be included in the
14     range depending on floating-point rounding in the
15     equation a + (b-a) * random().
16     '''
17     return random.uniform(a, b)
18 
19 def get_randrange(n):
20     '''return an Integer from 0 to n
21     and the number n must be greater than 0
22     or n > 0
23     '''
24     return random.randrange(n)
25 
26 def get_randrange_ex(start, stop, step):
27     '''返回一个从start开始到stop结束,步长为step的随机数'''
28     return random.randrange(start, stop, step)
29 
30 def choice(s):
31     '''从一个字符串中随机获取一个字符串,传入的参数s是不能为空或者不能为None'''
32     if s != '' and s != None:
33         return random.choice(s)
34     else:
35         print('the param is empty or equals None!')
36 
37 def shuffle(items):
38     '''对一个序列进行洗牌的操作'''
39     random.shuffle(items)
40     return items
41 
42 def sample(items, n):
43     '''从一个序列中随机抽出n个数,当然,在这n个数中,可能出现有重复的数'''
44     return random.sample(items, n)
45 
46 def main():
47     r = get_random()
48     print('获取一个0.0-1.0之间的随机数:{}'.format(r))
49     r = get_uniform(2, 100)
50     print('获取一个2.0-100.0之间的随机数:{}'.format(r))
51     r = get_randrange(100)
52     print('获取一个0-100之间的随机数:{}'.format(r))
53     r = get_randrange_ex(3, 100, 25)
54     print('获取一个3-100之间的随机数:{}'.format(r))
55     tem_str = 'this is a test message!'
56     r = choice(tem_str)
57     print('从[{}]中随机取出一个字符:{}'.format(tem_str, r))
58     tem_items = [1, 2, 3, 4, 5, 6, 7]
59     tem_r = tem_items[:]
60     shuffle(tem_items)
61     print('对序列{}进行洗牌操作:{}'.format(tem_r, tem_items))
62 
63     tem_list = sample(tem_r, 3)
64     print('从{}中随机抽出3个数:{}'.format(tem_r, tem_list))
65 
66 if __name__ == '__main__':
67     main()

 

 

posted @ 2013-08-15 12:27  Hongten  阅读(2940)  评论(0编辑  收藏  举报
Fork me on GitHub