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()

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM