---
title: "Python中的随机函数"
author: "runfeel"
date: "2013-07-11T10:40:00Z"
tags: []
slug: "python"
draft: false
lastmod: "2013-07-12T14:07:24Z"
id: 1904648
url: "https://runfeel.iteye.com/blog/1904648"
---

Python中提供了内建的函数来产生伪随机数random模块提供了函数random能过产生一个值的范围0。0-1.0之间的浮点数。

```
import randpm
for i in range(10):
      x = random.random()
      print x
```

随机数列表：

我们编写一个产生随机数列表的函数，randomList，它的参数是一个整数。返回列表的一个长度等于之歌整数

```
import random
def randomList(n):
      a = [0]*n
      for i in range(n):
            a[i] = random.random()
      return a
```

计数

解决像这样问题的好办法是把他分成几个子问题，在寻找子问题的解决办法。我们想计算在给定范围内的随机数的出现个数，我们写过一个程序，遍历一个字符串，计算给定的字符串出现的次数

```
count = 0
for char in fruit:
     if char == 'a':
        count = count + 1
     print count
第一步：list替换fruit ： num替换char。不雅着急改变其他部分。
count = 0
for num in list:
     if num == 'a':
        count = count +１
　　print count
第二步：修改测试条件，检查num是否出现在low和high之间。
count = 0
for num in list:
     if low < num < high:
        count = count + 1
    print count
第三步：封装代码在inBuchet中，参数是list,low,high
def inBucket(list,low,high):
      count = 0
      for num in list:
           if low < num < high:
              count = count + 1
     return count
```

我们使用一个列表来存储着八个整数的结果：

```
numBuckets = 8
buckets = [0]*numBuckets
bucketWidth = 1.0/numBuckets
for i in range(numBuckets):
     low = i * bucketWidth
     high = low + bucketWidth
     buckets[i] = inBucket(list.low,high)
print buckets
```