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
Bryan0Z
V2EX  ›  Python

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

  •  
  •   Bryan0Z · 2018-08-06 09:51:34 +08:00 · 3928 次点击
    这是一个创建于 2083 天前的主题,其中的信息可能已经有所发展或是发生改变。

    算法题是这个:
    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 条回复    2018-08-07 23:12:52 +08:00
    NotNil1
        1
    NotNil1  
       2018-08-06 09:57:39 +08:00
    因为 2 和 3 是两个语言
    mccally
        2
    mccally  
       2018-08-06 09:58:18 +08:00   ❤️ 2
    变量都整数,除法被除数也不是浮点数。
    python2 默认是整型运算,python3 是浮点运算。
    cxxcoding
        3
    cxxcoding  
       2018-08-06 09:59:22 +08:00   ❤️ 1
    你在 py2 py3 里分别执行 1/2 看看结果

    看我 github
    cosven
        4
    cosven  
       2018-08-06 10:08:37 +08:00   ❤️ 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  
       2018-08-06 10:51:01 +08:00
    不应该说居然,应该说果然...
    1313213
        6
    1313213  
       2018-08-06 11:11:17 +08:00
    正常,py2 和 py3 的差别太大了
    mooncakejs
        7
    mooncakejs  
       2018-08-06 11:15:42 +08:00 via iPhone   ❤️ 1
    每次碰到这种问题 默默的在心里骂 Python 一百遍
    ArthurMarcel
        8
    ArthurMarcel  
       2018-08-06 12:10:48 +08:00   ❤️ 1
    本来就不一样啊....3 和 2 很多地方实际上不兼容,甚至是直接舍弃了很多 2 的实现方式。想要结果一直可以 math.floor 或者'a//b'。建议多看下 3 和 2 细节上的区别(不踩坑是不可能的)~
    Bryan0Z
        9
    Bryan0Z  
    OP
       2018-08-06 14:05:44 +08:00 via Android
    @cosven 谢谢~去研究了一下,发现差别挺多的
    DamonLin
        10
    DamonLin  
       2018-08-07 23:12:52 +08:00
    2 和 3 差别很大
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   919 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 21ms · UTC 22:10 · PVG 06:10 · LAX 15:10 · JFK 18:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.