简体   繁体   English

Codeacademy上的python数学除以int与float时表现怪异。 动态类型/广播问题

[英]python math on codeacademy acting weird when dividing by int vs float. dynamically typed/cast issues

Ok so the problem asks to find the median(middle number) in a list of numbers. 好的,因此问题要求在数字列表中找到中位数(中间数)。 If the list has an even amount of numbers return the average of the two middle numbers. 如果列表中的数字数量为偶数,则返回两个中间数字的平均值。

I came across some code doesn't work on the site but does in PyCharm. 我遇到了一些无法在网站上运行的代码,但在PyCharm中却可以。 I imagine it is because some of the code on code academy's learning python is old (for example their print function and raw_input() are now deprecated) 我想这是因为代码学院的学习python上的某些代码是旧的(例如,现在不赞成使用它们的print函数和raw_input())

The below does not work on CodeAcademy 以下内容不适用于CodeAcademy

def median(ls):
    ls = sorted(ls)
    length = len(ls)
    median = 0.0
    temp = 0

    if length % 2 == 0:
        temp = int(length / 2)
        median = float (ls[temp-1] + ls[temp]) / 2 #why is this a problem?
        return median
    else:
        temp=int((length-1) / 2)
        median = ls[temp]
        return median

Note: the above returns 4.0 instead of 4.5 when passed [4,5,5,4] 注意:以上通过[4,5,5,4]时返回4.0而不是4.5

however when I change the /2 to /2.0 like below it works. 但是,当我将/ 2更改为/2.0时,如下所示。

def median(ls):
    ls = sorted(ls)
    length = len(ls)
    median = 0.0
    temp = 0

    if length % 2 == 0:
        temp = int(length / 2)
        median = float (ls[temp-1] + ls[temp]) / 2.0 #here
        return median
    else:
        temp=int((length-1) / 2)
        median = ls[temp]
        return median

Note: the above correctly returns 4.5 when passed [4,5,5,4] 注意:以上通过[4,5,5,4]时正确返回4.5

So even though I've figured out how to solve the problem, I want to know why it happened in the event that even though both code examples work in newer versions of python, is one is more correct or 'cleaner' and why? 因此,即使我已经找到解决问题的方法,但我想知道为什么即使两个代码示例都在较新的python版本中工作,但还是更干净或更干净,为什么会发生呢?为什么?

Ok so what I believe happened in the first code example that was returning weird results is that Python casted the first two numbers to ints in order to divide by int (yielding 4 when passed [4,4,5,5] (after sorting)) and then casted that answer (4) to a float giving 4.0. 好的,所以我相信在返回奇怪结果的第一个代码示例中发生的事情是,Python将前两个数字强制转换为int以除以int(在传递[4,4,5,5]时产生4)(排序后) ),然后将该答案(4)强制转换为浮点数为4.0。 but when I divided by 2.0 it casted those numbers to floats first giving the correct 4.5. 但是当我除以2.0时,它会将这些数字先转换为浮点数,然后给出正确的4.5。 This also allowed me to remove the explicit cast to float and when tested worked on code academy 这也允许我删除显式强制转换为float,并且在代码学院进行测试时

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM