Tupilwe Sinyangwe
Tupilwe Sinyangwe

Reputation: 129

How to fix 'type error: 'float' object is not iterable' in my program?

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

Once I remove the max from the equation result.append(max(start_waiting_time + service_time - (count_zero + 1) * interarrival), 0) then I get results but these results are not what I hoped for.

This is the code when the max is removed from the equation:

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]

These results are correct except that the result is never supposed to be negative which was the reason for me adding max to the equation, I was trying to tell the program to compute 0 if the result becomes negative. Therefore, the result I expected was:

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

The difference is that the last output in the result is 0 and not -0.4639967758134991.

Upvotes: 0

Views: 383

Answers (1)

erhesto
erhesto

Reputation: 1186

From python3 documentation:

Help on built-in function max in module builtins:

max(...) max(iterable[, key=func]) -> value max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument. (END)

In your code, you've used max on single float value, which is result of an expression:

start_waiting_time + service_time - (count_zero + 1) * interarrival

So if you'll pass tuple with your expression and 0 to the max function, as this:

result.append(max((start_waiting_time + service_time - (count_zero + 1) * interarrival,0)))

it should work as you've expected.

Upvotes: 1

Related Questions