【问题标题】:Returning value in a function to use in the same function repeatedly?在函数中返回值以重复在同一个函数中使用?
【发布时间】:2016-07-11 12:18:53
【问题描述】:

我正在为乌龟开发一个随机行走生成器。用户输入 0 到 1 之间的行、列和概率值。在我的 main 函数中,根据生成的随机数的值,乌龟将朝它所面对的方向转动或向前走一步。

我的问题是我需要一遍又一遍地重复这个函数,(通过一个循环)但每次都将函数上一次运行的值合并到下一次。我所做的每一次尝试(通过返回一个带有值的元组并将这些值输入到函数的每次运行中,除了第一个)都导致函数的相同值被一遍又一遍地返回。

   #Random Walk Generator#
    import random
    import sys


    def move_turtle(row, col, direct, turn_prob ):
        dir_list = ['right', 'down', 'left', 'up']
        random.random()
        if random.random()<=turn_prob:
            p= dir_list.index(direct)
            if p==0:
                p2=1
            elif p==1:
                p2=2
            elif p==2:
                p2= 3
            elif p==3:
                p2 =0
            d2= dir_list[p2]
            direct= d2

        else: 
            if direct == 'right':
                col= col+1
            if direct== 'down':
                row=row+1
            if direct =='left':
                col= col-1
            if direct== 'up':
                row= row-1

        rettup = (row,col,direct)

        return rettup


    N= input('Enter the integer number of rows => ')
    print N
    M= input('Enter the integer number of cols => ')
    print M
    p= input("Enter the turtle's turn probability (< 1.0) => ")
    print p

    seed_value = 10*M + N
    random.seed(seed_value)

    dir_list = ['right', 'down', 'left', 'up']
    rand_index = random.randint(0,3)
    d = dir_list[rand_index]

    print 'Initial direction:',d
    tup= move_turtle(M,N,d,p)

    for c in range(249):
        if c==0:
            move_turtle(M,N,d,p)
        else:
            move_turtle(tup[0],tup[1],tup[2],p)
        '''
        if R>= M or R<= -1 or C>=N or C<=-1:
            print 'After', c, 'time steps the turtle fell off the', D, 'in column',C
            '''
        if c==20 or c==40 or c==60 or c==80 or c==100 or c==120 or c==140 or c==180 or c==200 or c==220 or c==240 or c==250:
            print 'Time step',c,': position (',N/2,',',M/2,')direction',d

【问题讨论】:

  • 您永远不会改变方向 :) 将 rand_indexd = dir_list[rand_index] 放入循环中。

标签: python loops return


【解决方案1】:

问题是您每次调用move_turtle 时都没有更新tup。您还在循环前额外调用了move_turtle。这不是必需的,因为循环在c == 0 时执行初始调用。所以应该是:

for c in range(249):
    if c == 0:
        tup = move_turle(M, N, d, p)
    else:
        tup = move_turtle(tup[0], tup[1], tup[2], p)

【讨论】:

  • 是的。现在似乎运行正常。非常感谢……我坚持的时间比我愿意承认的要长……
猜你喜欢
  • 1970-01-01
  • 2015-10-31
  • 1970-01-01
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多