如何使列表中元素的第一个结果等于0,然后使用此结果计算下一个结果?

时间:2017-02-23 13:55:53

标签: python list function loops formula

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


print(formula([1, 1, 1, 0, 1, 0, 0, 1]))

当我运行此结果时,我得到结果#[2, 2, 2, 1, 0],这些不是我预期的结果。

'''
For the elements in listA = [1, 1, 1, 0, 1, 0, 0, 1]

For the 1st element:
i == 1, because this is the first element, the program is supposed to compute 0 which is why I set the start = 0

For the 2nd element: 
i == 1, the formula computes:
max(start + service_time - (count_zero + 1) * interarrival, 0)
max(0 #start from 1st element + 3 #service_time - (count_zero + 1) #no zeros right before second element * interarrival, 0)
max(0 + 3 - (0 + 1) * 1, 0)
max(3 - (1)*1, 0) 
max(3 - 1, 0)
max(2, 0) #the max of these two numbers is 2 is the programs is supposed to print 2


For the 3rd element: 
i == 1, so the formula computes:
max(start + service_time - (count_zero + 1) * interarrival, 0)
max(2 #start from 2nd element + 3 #service_time - (count_zero + 1) #no zeros right before third element * interarrival, 0)
max(2 + 3 - (0 + 1)*1, 0)
max(5 - 1*1, 0) 
max(5 - 1, 0)
max(4, 0) #the max of these two numbers is 4, the program is supposed to print 4


For the 4th element:
i == 0, the program simply counts this zero and doesn't do anything else, nothing is printed as expected.


For the 5th element: 
i == 1, so the formula computes:
max(start + service_time - (count_zero + 1) * interarrival, 0)
max(4 #start from 2nd element + 3 #service_time - (count_zero + 1) #one zero right before fifth element * interarrival, 0)
max(4 + 3 - (1 + 1)*1, 0)
max(7 - 2*1, 0) 
max(7 - 2, 0)
max(5, 0) #the max of these two numbers is 4, the program is supposed to print 4


For the 6th element:
i == 0, the program simply counts this zero and doesn't do anything else, nothing is printed as expected. 


For the 7th element:
i == 0, the program also simply counts this zero and doesn't do anything else, nothing is printed as expected.


For the 8th element: 
i == 1, so the formula computes:
max(start + service_time - (count_zero + 1) * interarrival, 0)
max(5 #start from 5th element + 3 #service_time - (count_zero + 1) #two zeros right before third element * interarrival, 0)
max(5 + 3 - (2 + 1)*1, 0)
max(8 - 3*1, 0) 
max(5, 0)
max(5, 0) #the max of these two numbers is 5, the program is supposed to print 5

'''

如何更正此错误?基本上我试图在i == 1等于0时为第一个元素创建第一个结果,然后将此结果用作start来计算下一个结果,然后将下一个结果用作{{1之后计算结果。

我试图尽可能清楚地解释问题,请问是否不清楚。

1 个答案:

答案 0 :(得分:0)

你有i==1,公式计算。您的逻辑都不知道列表的任何第一个元素。

你可以尝试枚举,这给出了位置。

for i, x in enumerate(listA):
    if i == start:
        # at start of list 

    if x == 1:
        # compute formula 

顺便说一句,不要将result作为默认参数存储到函数中,使其成为局部变量

start永远不会更新。它始终为零......您是否打算将此函数递归?