Python:Dictionaries,cTurtle和一点递归的麻烦

时间:2013-11-24 22:58:45

标签: python dictionary

我应该做以下

  

更改applyProduction函数以使规则字典   将每个符号不映射到单个替换字符串,而是映射到列表   替代字符串,其中一个是每次a随机选择的   需要更换。 (您可以随机选择一个元素   使用随机模块中的选择功能的列表。)如   applyProduction的原始版本,某些符号可能不是   在规则中列出,在这种情况下,他们应该被留下   不变。

applyProduction函数看起来像

def applyProduction(axiom,rules,n):
    for i in range(n):
        newString = ""
        for ch in axiom:
            newString = newString + rules.get(ch,ch)
        axiom = newString
    return axiom

而我所做的就是

def applyProduction(axiom,rules,n):
    for i in range(n):
        newString = ""
        for ch in axiom:
            listOfRules = rules.get(ch)
            doIt = random.choice(listOfRules)
            newString = newString + doIt
        axiom = newString
    return axiom

所以我试图获得与字母ch相关的字典的所有值。然后随机选择它们。我认为我要做的是做到这一点的方式,它应该有效,但是当我这样做时,我得到了错误

Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    lsystem('F-F-F',{'F':'F-F-F-GG', 'F':'F+G++F', 'G':'GG'}, 3,(-100,-100),0,120,25)
  File "C:\Python33\lsystems.py", line 61, in lsystem
    instructions = applyProduction(axiom,rules,depth)
  File "C:\Python33\lsystems.py", line 16, in applyProduction
    doIt = random.choice(listOfRules)
  File "C:\Python33\lib\random.py", line 249, in choice
    i = self._randbelow(len(seq))
TypeError: object of type 'NoneType' has no len()

我真的不知道这意味着什么。任何帮助表示赞赏。

涉及的其他功能。

def drawLS(aTurtle,instructions,angle,distance):
    stateSaver = []
    for cmd in instructions:
        if cmd == 'F':
            aTurtle.forward(distance)
        elif cmd == 'G':
            aTurtle.up()
            aTurtle.forward(distance)
            aTurtle.down()
        elif cmd == 'B':
            aTurtle.backward(distance)
        elif cmd == '+':
            aTurtle.right(angle)
        elif cmd == '-':
            aTurtle.left(angle)
        elif cmd == '[':
            pos = aTurtle.position()
            head = aTurtle.heading()
            stateSaver.append((pos,head))
        elif cmd == ']':
            pos,head = stateSaver.pop()
            aTurtle.up() 
            aTurtle.setposition(pos)
            aTurtle.setheading(head)
            aTurtle.down() 

def lsystem(axiom,rules,depth,initialPosition,heading,angle,length):
    aTurtle = Turtle()
    aTurtle.speed(0)       # this line improves on Listing 9.8
    aTurtle.shape('blank') # this line improves on Listing 9.8
    aTurtle.up()
    aTurtle.setposition(initialPosition)
    aTurtle.down()
    aTurtle.setheading(heading)
    ## The variable "instructions" was called "newRules" in Listing 9.8,
    ## which was misleading regarding what kind of thing it names.
    instructions = applyProduction(axiom,rules,depth)
    drawLS(aTurtle,instructions,angle,length)
    aTurtle.exitOnClick()

1 个答案:

答案 0 :(得分:1)

  

TypeError:“NoneType”类型的对象没有len()

     

我真的不知道这意味着什么。任何帮助表示赞赏。

在第16行中,random.choice(listOfRules)失败,因为 listOfRule 而不是列表。

在第15行中,listOfRules = rules.get(ch)返回,因为它没有找到 ch 的条目。