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

删除回忆录丶 提交于 2021-02-11 12:33:50

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/56734903/python-code-is-not-throwing-error-but-the-desired-output-is-not-the-same

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!