V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · 4744 views
    This topic created in 2835 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
        1
    NotNil1  
       Aug 6, 2018
    因为 2 和 3 是两个语言
    mccally
        2
    mccally  
       Aug 6, 2018   ❤️ 2
    变量都整数,除法被除数也不是浮点数。
    python2 默认是整型运算,python3 是浮点运算。
    cxxcoding
        3
    cxxcoding  
       Aug 6, 2018   ❤️ 1
    你在 py2 py3 里分别执行 1/2 看看结果

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