开始使用免费开始使用

下一步

之前,您已经编写过根据上一步来确定下一步的 Python 代码。现在请把这段代码放入一个 for 循环中,以便我们模拟一次随机漫步。

numpy 已以 np 导入。

本练习是课程的一部分

Python 中级

查看课程

练习说明

  • 创建一个列表 random_walk,其中包含第一步,即整数 0。
  • 完成 for 循环:
  • 循环应运行 100 次。
  • 每次迭代,将 step 设为列表 random_walk 的最后一个元素。您可以使用索引 -1 实现。
  • 接着,让 if-elif-else 结构为您更新 step
  • step 追加到 random_walk 的代码已给出。
  • 打印 random_walk

交互式实操练习

通过完成这段示例代码来试试这个练习。

# NumPy is imported, seed is set

# Initialize random_walk


# Complete the ___
for x in ___(___) :
    # Set step: last element in random_walk
    ___

    # Roll the dice
    dice = np.random.randint(1,7)

    # Determine next step
    if dice <= 2:
        step = step - 1
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    # append next_step to random_walk
    random_walk.append(step)

# Print random_walk
编辑并运行代码