問題描述:產生40個數,范圍是363-429之間,平均值為402
思路:
1 產生一個隨機數
2 使用平均數減去隨機數求出第二個數,生成20組
3 將排序打亂
# -*- coding: cp936 -*- import random import string ###################產生隨機整數################### ###################第一個數隨機產生,第二個使用平均數求出################### #count 數字的個數 #average 平均數 #begin 起始區間 #end 結束區間 def int_random (count, average, begin, end): #print "wzh_random" numarr = [0 for x in range(2)]; i = 0; while (1): num_first = random.randrange(begin, end); #第二個數 num_second = average * 2 - num_first; if (num_second >= begin and num_second <= end): numarr[i] = num_first; i = i + 1; numarr[i] = num_second; break return numarr; ###################產生隨機數################### ###################第一個數隨機產生,第二個使用平均數求出################### #count 數字的個數 #average 平均數 #begin 起始區間 #end 結束區間 def float_random (count, average, begin, end): #print "wzh_random" numarr = [0 for x in range(2)]; i = 0; while (1): num = random.uniform(begin, end); #取兩位小數 num_first = round(num, 2); #第二個數 num_second = average * 2 - num_first; if (num_second >= begin and num_second <= end): numarr[i] = num_first; i = i + 1; numarr[i] = num_second; break return numarr; ###################寫文件################### def write_file (filename, content): fo = open (filename, "ab"); fo.write(content); fo.close(); def show_list (list): for i in list: print i, print; ###################主函數調用產生整形隨機數################### #40個數字,平均數400,363 - 429 之間 def test_random_int(): count = 40; average = 402; begin = 363; end = 429; numarr_count = 0; numarr = [0 for x in range(count)]; for i in range (count / 2): list = int_random (40, 402, 363, 429) j = 0; for j in range (len(list)): numarr[numarr_count] = list[j]; numarr_count += 1; content = ''; #打亂排序 print "數據未打亂:"; show_list (numarr) random.shuffle(numarr); print "數據打亂:"; show_list (numarr) for i in numarr: content = content + ' ' + str(i); #print content; #追加寫入文件 filename = "test.txt"; print "文件名稱:",filename; write_file (filename, content) write_file (filename, "\n"); ###################主函數調用產生實型隨機數################### #40個數字,平均數400,363 - 429 之間 def test_random_float(): count = 40; average = 402; begin = 363; end = 429; numarr_count = 0; numarr = [0 for x in range(count)]; for i in range (count / 2): list = float_random (40, 402, 363, 429) j = 0; for j in range (len(list)): numarr[numarr_count] = list[j]; numarr_count += 1; content = ''; #打亂排序 print "數據未打亂:"; show_list (numarr) random.shuffle(numarr); print "數據打亂:"; show_list (numarr) for i in numarr: content = content + ' ' + str(i); #print content; #追加寫入文件 filename = "test.txt"; print "文件名稱:",filename; write_file (filename, content) write_file (filename, "\n"); #調用測試產生整形隨機數 test_random_int(); #調用測試產生實型隨機數 test_random_float();