V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
lbfeng
V2EX  ›  Python

遇到百思不得其解的 bug

  •  
  •   lbfeng · 2015-10-05 02:11:19 +08:00 · 2909 次点击
    这是一个创建于 3136 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码在此: http://7xn6e9.com1.z0.glb.clouddn.com/ai.txt
    生成 5*5 的数次迷宫,从左上角跳到右下角,数字表示要跳的格数,我用广度优先可以算出结果,现在想用 uniform cost, 总是出现 IndexError : index out of range 。
    运行结果:

    Rook Jumping Maze size (5-10)?5
    [4, 2, 2, 1, 4]
    [3, 3, 2, 2, 2]
    [4, 1, 2, 1, 1]
    [1, 1, 1, 3, 1]
    [4, 1, 1, 3, 0]
    explore node
    (0, 0)
    action S
    explore child
    (0, 0) (4, 0) # 第一个是 parent, 第二个是 child
    push it in the frontier
    action E
    ** # parent 的坐标
    0 0
    **
    explore child
    (0, 0) (0, 4)
    push it in the frontier
    explore node
    (4, 0)
    action N
    explore child
    (4, 0) (0, 0)
    action E
    **
    0 4
    **
    explore child # parent 突然变了??
    (0, 4) (0, 8) # child node 出错了
    push it in the frontier
    explore node
    (0, 4)
    action S
    explore child
    (0, 4) (4, 4)
    push it in the frontier

    6 条回复    2015-10-05 12:57:31 +08:00
    yxwzaxns
        1
    yxwzaxns  
       2015-10-05 06:39:13 +08:00 via Android
    题目太长不看
    lbfeng
        2
    lbfeng  
    OP
       2015-10-05 07:44:50 +08:00
    @yxwzaxns

    for child_node in expend(RJM, node, action):
    child_node.distance = node.distance + 1
    child_node.parent = node
    print "explore child"
    print child_node.parent, child_node
    if not ((child_node in [node for distance, node in frontier]) or (child_node in explored)):
    heappush(frontier, (child_node.distance,child_node))
    print "push it in the frontier"
    else:
    ....

    我已经解决了。
    “[node for distance, node in frontier]” 这里的 node 影响了 for 循环里的 node “ expend(RJM, node, action):”
    为什么呢?
    mulog
        3
    mulog  
       2015-10-05 08:26:16 +08:00
    因为 list comprehension 没有自己的 namespace, 注意不要和外面的变量重名
    aec4d
        4
    aec4d  
       2015-10-05 09:47:22 +08:00
    @mulog python3 列表推导式有自己的命名空间 python2 中可以用 map 也有自己的命名空间
    mulog
        5
    mulog  
       2015-10-05 09:54:30 +08:00
    @aec4d 是,窝不严谨了 :p
    21grams
        6
    21grams  
       2015-10-05 12:57:31 +08:00
    TL;DR
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3142 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:06 · PVG 21:06 · LAX 06:06 · JFK 09:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.