美文网首页
计算机科学和Python编程导论-第9课

计算机科学和Python编程导论-第9课

作者: 瘦长的丰一禾 | 来源:发表于2018-08-08 23:14 被阅读56次
一些models

Continuous
Discrete
Deterministic
Stochastic
Static
Dynamic

How would you randomly generate an even number x, 0 <= x < 100? 
Fill out the definition for the function genEven(). 
Please generate a uniform distribution over the even numbers between 0 and 100 (not including 100).

In [37]: def genEven():
    ...:     x = random.randint(0, 98)
    ...:     while x % 2 != 0:
    ...:         x = random.randint(0, 98)
    ...:     return x

L2 Problem 3A 
Write a deterministic program, deterministicNumber, that returns an even number between 9 and 21.

In [61]: def deterministicNumber():
    ...:     random.seed(0) # This will be discussed in the video "Drunken Simulations"
    ...:     return 2 * random.randint(5, 10)
    ...: 


L2 Problem 3B
Write a uniformly distributed stochastic program, stochasticNumber, that returns an even number between 9 and 21.

In [42]: def stochasticNumber():
    ...:     return 2 * random.randint(5, 10)
    ...: 

L2 Problem 7

In [65]: random.seed(9001)
    ...: for i in range(random.randint(1, 10)):
    ...:     print (random.randint(1, 10))
    ...:     
5

In [66]: random.seed(9001)
    ...: d = random.randint(1, 10)
    ...: for i in range(random.randint(1, 10)):
    ...:     print (d)
    ...:     
1
1
1
1
1

In [67]: random.seed(9001)
    ...: d = random.randint(1, 10)
    ...: for i in range(random.randint(1, 10)):
    ...:     if random.randint(1, 10) < 7:
    ...:         print (d)
    ...:     else:
    ...:         random.seed(9001)
    ...:         d = random.randint(1, 10)
    ...:         print (random.randint(1, 10))
    ...:         
1
1
5
1
1

课本代码练习:其中有些内容书上有错误

In [76]: class Location(object):
    ...:    def __init__(self, x, y):
    ...:        """x和y为数值型"""
    ...:        self.x, self.y = x, y
    ...:    def move(self, deltaX, deltaY):
    ...:        """deltaX和deltaY为数值型"""
    ...:        return Location(self.x + deltaX, self.y + deltaY)
    ...:    def getX(self):
    ...:        return self.x
    ...:    def getY(self):
    ...:        return self.y
    ...:    def distFrom(self, other):
    ...:        ox, oy = other.x, other.y
    ...:        xDist, yDist = self.x - ox, self.y - oy
    ...:        return (xDist**2 + yDist**2)**0.5
    ...:    def __str__(self):
    ...:        return '<' + str(self.x) + ', ' + str(self.y) + '>'
    ...: class Field(object):
    ...:    def __init__(self):
    ...:        self.drunks = {}
    ...:    def addDrunk(self, drunk, loc):
    ...:        if drunk in self.drunks:
    ...:            raise ValueError('Duplicate drunk')
    ...:        else:
    ...:            self.drunks[drunk] = loc
    ...:    def moveDrunk(self, drunk):
    ...:        if drunk not in self.drunks:
    ...:            raise ValueError('Drunk not in field')
    ...:        xDist, yDist = drunk.takeStep()
    ...:        currentLocation = self.drunks[drunk]
    ...:        #使用Location的move方法获得一个新位置
    ...:        self.drunks[drunk] = currentLocation.move(xDist, yDist)
    ...:    def getLoc(self, drunk):
    ...:        if drunk not in self.drunks:
    ...:            raise ValueError('Drunk not in field')
    ...:        return self.drunks[drunk]
    ...: 
    ...: import random
    ...: class Drunk(object):
    ...:    def __init__(self, name = None):
    ...:        """假设name是字符串"""
    ...:        self.name = name
    ...:    def __str__(self):
    ...:        if self != None:
    ...:            return self.name
    ...:        return 'Anonymous'
    ...: class UsualDrunk(Drunk):
    ...:    def takeStep(self):
    ...:        stepChoices = [(0,1), (0,-1), (1, 0), (-1, 0)]
    ...:        return random.choice(stepChoices)
    ...:        return random.choice(stepChoices)
    ...:  

In [68]: def walk(f, d, numSteps):
    ...:    """假设f是一个Field对象,d是f中的一个Drunk对象,numSteps是正整数。
    ...:    将d移动numSteps次;返回这次游走最终位置与开始位置之间的距离"""
    ...:    start = f.getLoc(d)
    ...:    for s in range(numSteps):
    ...:        f.moveDrunk(d)
    ...:    return start.distFrom(f.getLoc(d))
    ...: def simWalks(numSteps, numTrials, dClass):
    ...:    """假设numSteps是非负整数,numTrials是正整数,
    ...:    dClass是Drunk的一个子类。
    ...:    模拟numTrials次游走,每次游走numSteps步。
    ...:    返回一个列表,表示每次模拟的最终距离"""
    ...:    Homer = dClass()
    ...:    origin = Location(0, 0)
    ...:    distances = []
    ...:    for t in range(numTrials):
    ...:        f = Field()
    ...:        f.addDrunk(Homer, origin)
    ...:        distances.append(round(walk(f, Homer, numTrials), 1))
    ...:    return distances
    ...: def drunkTest(walkLengths, numTrials, dClass):
    ...:    """假设walkLengths是非负整数序列
    ...:        numTrials是正整数,dClass是Drunk的一个子类
    ...:        对于walkLengths中的每个步数,运行numTrials次simWalks函数,并输出结果"""
    ...:    for numSteps in walkLengths:
    ...:        distances = simWalks(numSteps, numTrials, dClass)
    ...:        print(dClass.__name__, 'random walk of', numSteps, 'steps')
    ...:        print(' Mean =', round(sum(distances)/len(distances), 4))
    ...:        print(' Max =', max(distances), 'Min =', min(distances))
    ...:  

In [77]: drunkTest((10, 100, 1000, 10000), 100, UsualDrunk)
UsualDrunk random walk of 10 steps
 Mean = 9.233
 Max = 20.9 Min = 0.0
UsualDrunk random walk of 100 steps
 Mean = 8.663
 Max = 19.0 Min = 1.4
UsualDrunk random walk of 1000 steps
 Mean = 9.06
 Max = 23.0 Min = 0.0
UsualDrunk random walk of 10000 steps
 Mean = 8.435
 Max = 22.7 Min = 0.0


In [78]: drunkTest((0, 1), 100, UsualDrunk)
UsualDrunk random walk of 0 steps
 Mean = 8.698
 Max = 22.8 Min = 0.0
UsualDrunk random walk of 1 steps
 Mean = 8.394
 Max = 19.8 Min = 0.0

修正simWalks 中,函数调用 walk(f, Homer, numTrials) 应该是 walk(f, Homer,numSteps)


In [79]: def walk(f, d, numSteps):
    ...:    """假设f是一个Field对象,d是f中的一个Drunk对象,numSteps是正整数。
    ...:    将d移动numSteps次;返回这次游走最终位置与开始位置之间的距离"""
    ...:    start = f.getLoc(d)
    ...:    for s in range(numSteps):
    ...:        f.moveDrunk(d)
    ...:    return start.distFrom(f.getLoc(d))
    ...: def simWalks(numSteps, numTrials, dClass):
    ...:    """假设numSteps是非负整数,numTrials是正整数,
    ...:    dClass是Drunk的一个子类。
    ...:    模拟numTrials次游走,每次游走numSteps步。
    ...:    返回一个列表,表示每次模拟的最终距离"""
    ...:    Homer = dClass()
    ...:    origin = Location(0, 0)
    ...:    distances = []
    ...:    for t in range(numTrials):
    ...:        f = Field()
    ...:        f.addDrunk(Homer, origin)
    ...:        distances.append(round(walk(f, Homer, numSteps), 1))
    ...:    return distances
    ...: def drunkTest(walkLengths, numTrials, dClass):
    ...:    """假设walkLengths是非负整数序列
    ...:        numTrials是正整数,dClass是Drunk的一个子类
    ...:        对于walkLengths中的每个步数,运行numTrials次simWalks函数,并输出结果"""
    ...:    for numSteps in walkLengths:
    ...:        distances = simWalks(numSteps, numTrials, dClass)
    ...:        print(dClass.__name__, 'random walk of', numSteps, 'steps')
    ...:        print(' Mean =', round(sum(distances)/len(distances), 4))
    ...:        print(' Max =', max(distances), 'Min =', min(distances))
    ...:   

In [80]: drunkTest((0, 1), 100, UsualDrunk)
UsualDrunk random walk of 0 steps
 Mean = 0.0
 Max = 0.0 Min = 0.0
UsualDrunk random walk of 1 steps
 Mean = 1.0
 Max = 1.0 Min = 1.0

In [81]: drunkTest((10, 100, 1000, 10000), 100, UsualDrunk)
UsualDrunk random walk of 10 steps
 Mean = 2.612
 Max = 7.2 Min = 0.0
UsualDrunk random walk of 100 steps
 Mean = 9.057
 Max = 25.5 Min = 0.0
UsualDrunk random walk of 1000 steps
 Mean = 29.859
 Max = 74.1 Min = 2.8
UsualDrunk random walk of 10000 steps
 Mean = 95.894
 Max = 297.1 Min = 15.8

相关文章

网友评论

      本文标题:计算机科学和Python编程导论-第9课

      本文链接:https://www.haomeiwen.com/subject/jsxfbftx.html