推荐学习书目
› 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
Bryan0Z
V2EX  ›  Python

同一段代码在 Python2 和 Python3 下面跑结果居然不一样

  •  
  •   Bryan0Z · Aug 6, 2018 · 5250 views
    This topic created in 3019 days ago, the information mentioned may be changed or developed.

    算法题是这个:
    https://leetcode.com/problems/median-of-two-sorted-arrays/description/

    There are two sorted arrays nums1 and nums2 of size m and n respectively.

    Find the median of the two sorted arrays.

    我写的代码在这里: https://gist.github.com/BryanJin/409a6ef9a52d544621b6e0ca430b3762
    之前在 leetcode 上死活不通过,自己 debug 了半天没发现问题,结果是 Python 版本错了。
    测试输入: [1, 2] [3, 4]
    Python2 的运行结果是 2
    Python3 的运行结果是 2.5
    为啥会有这种神奇的现象

    10 replies  •  2018-08-07 23:12:52 +08:00
    NotNil1
    NotNil1
    Aug 6, 2018
    1
    因为 2 和 3 是两个语言
    mccally
    mccally
    Aug 6, 2018❤️2
    2
    变量都整数,除法被除数也不是浮点数。
    python2 默认是整型运算,python3 是浮点运算。
    cxxcoding
    cxxcoding
    Aug 6, 2018❤️1
    3
    你在 py2 py3 里分别执行 1/2 看看结果

    看我 github
    cosven
    cosven
    Aug 6, 2018❤️2
    4
    这是 3 和 2 典型的不兼容地方之一
    要想得到 int 可以使用 `a // b` 来进行除法
    为什么会有这个改动: https://www.python.org/dev/peps/pep-0238/#abstract

    2 和 3 更多不兼容的地方: http://python-future.org/compatible_idioms.html#division
    melonrice
    melonrice
    Aug 6, 2018
    5
    不应该说居然,应该说果然...
    1313213
    1313213
    Aug 6, 2018
    6
    正常,py2 和 py3 的差别太大了
    mooncakejs
    mooncakejs
    Aug 6, 2018 via iPhone❤️1
    7
    每次碰到这种问题 默默的在心里骂 Python 一百遍
    ArthurMarcel
    ArthurMarcel
    Aug 6, 2018❤️1
    8
    本来就不一样啊....3 和 2 很多地方实际上不兼容,甚至是直接舍弃了很多 2 的实现方式。想要结果一直可以 math.floor 或者'a//b'。建议多看下 3 和 2 细节上的区别(不踩坑是不可能的)~
    Bryan0Z
    Bryan0Z
    OP
    Aug 6, 2018 via Android
    9
    @cosven 谢谢~去研究了一下,发现差别挺多的
    DamonLin
    DamonLin
    Aug 7, 2018
    10
    2 和 3 差别很大
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2368 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 12:17 · PVG 20:17 · LAX 04:17 · JFK 07:17
    ♥ Do have faith in what you're doing.