2

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
Amit Sharma
  • 53
  • 1
  • 7

1 Answers1

4

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
PyPingu
  • 1,697
  • 1
  • 8
  • 21