不正确! (错误的值和/或错误的返回类型)

时间:2018-07-28 11:30:35

标签: python string python-3.x return-type

def token(t):
    running_cost = []
    total_cost = 0
    for y in t:
        running_cost.append(y)

    for k in range(len(running_cost)):
        total_cost += float(running_cost[k])

    total_cost = '{:,.2f}' .format(total_cost)
    return total_cost

当我通过测试器运行代码时,我得到的是:

  

预计:1.17

     

实际:1.17

     

不正确! (错误的值和/或错误的返回类型)

我想代码不需要字符串返回类型,但是我必须将其字符串化的原因是因为代码要求我将所有带浮点数的值都返回到小数点后2位,无论它是否为0。

1 个答案:

答案 0 :(得分:1)

您可以将返回值四舍五入-浮动为2位数字,无需将其设为字符串。

def token(t):
    running_cost = []
    total_cost = 0
    for y in t:
        running_cost.append(y)

    for k in range(len(running_cost)):
        total_cost += float(running_cost[k])

    total_cost = '{:,.2f}' .format(total_cost)
    return total_cost

def tok2(t):
    """Creates float values from all elements of t, sums them, then rounds to 2 digits."""
    return round(sum(map(float,t)),2)

test = ['2.1093','4.0']


print(token(test), type(token(test)))
print(tok2(test), type(tok2(test)))

返回:

6.11 <class 'str'>   # you return a formatted string
6.11 <class 'float'> # I return a rounded float

参考:


编辑:如果您被禁止使用return float(total_cost)

,也可以通过进行round()来解决问题
相关问题