Amit Sharma
Amit Sharma

Reputation: 53

Python code is not throwing error but the desired output is not the same

Unable to receive the output of the python code.I have tried debugging the code by printing each line

def get_sum_metrics(predictions, metrics=[]):  
    for i in range(0,3):
        metrics.append(lambda x:x+i)

    sum_metrics = 0
    for metric in metrics:
        sum_metrics += metric(predictions)

    return sum_metrics

def main():
    print(get_sum_metrics(0))
    print(get_sum_metrics(1))
    print(get_sum_metrics(2))
    print(get_sum_metrics(3,[lambda x:x]))
    print(get_sum_metrics(0))
    print(get_sum_metrics(1))
    print(get_sum_metrics(2))


if __name__=='__main__':
    main()

expected output should be.. 3 6 9 15 3 6 9

        but getting..
        6
        18
        36
        18
        24
        45
        72

Upvotes: 2

Views: 1486

Answers (1)

PyPingu
PyPingu

Reputation: 1747

Your issue here is related to mutable default arguments and the problem of creating a lambda in a loop as shown in this question

Those two things fixed gives you:

def get_sum_metrics(predictions, metrics=None):
    if metrics is None:
        metrics = []  
    for i in range(0,3):
        f = lambda x, i=i: x+i
        metrics.append(f)
    sum_metrics = 0
    for metric in metrics:
        sum_metrics += metric(predictions)
    return sum_metrics

Upvotes: 4

Related Questions