如何修复'类型错误:'浮动'对象在我的程序中是不可迭代的?

时间:2017-02-23 10:57:24

标签: python function loops math max

def formula(listA, count_zero=0, start_waiting_time = 0, result=[], service_time=random.expovariate(1.2), interarrival=1):
    for i in listA:
        if i == 1:
            result.append(max(start_waiting_time + service_time - (count_zero + 1) * interarrival), 0)
            count_zero = 0
         elif i == 0:
            count_zero += 1
    return result

# Test case
print(formula([1, 1, 1, 0, 1, 0, 0, 1]))

#This returns result: TypeError 'float' object is not iterable

从等式max中移除result.append(max(start_waiting_time + service_time - (count_zero + 1) * interarrival), 0)后,我得到了结果,但这些结果并非我所希望的。

这是从等式中移除max时的代码:

def formula(listA, count_zero=0, start_waiting_time = 0, result=[], service_time=random.expovariate(1.2), interarrival=1):
    for i in listA:
        if i == 1:
            result.append(start_waiting_time + service_time - (count_zero + 1) * interarrival)
            count_zero = 0
        elif i == 0:
            count_zero += 1
    return result

#[1.536003224186501, 1.536003224186501, 1.536003224186501, 0.5360032241865009, -0.4639967758134991]

这些结果是正确的,除了结果永远不应该是负数,这是我将max添加到等式中的原因,我试图告诉程序如果结果变为负数则计算0。因此,我预期的结果是:

#[1.536003224186501, 1.536003224186501, 1.536003224186501, 0.5360032241865009, 0]

不同之处在于结果中的最后一个输出为0而不是-0.4639967758134991。

0 个答案:

没有答案