2

我编写了一个简单的 map() 函数,它遍历一个列表并打印列表中尽可能多的“*”。我看到我的代码有一个小问题,我'None'在输出中看到了一个额外的问题。有人可以帮我调试这个问题吗?

Problem Statement:
-----------------
Define a procedure histogram() that takes a list of integers and prints a
histogram to the screen. For example, histogram([4, 9, 7]) should print the
following:

****
*********
*******

源代码

def print_asterisks(num):
    print ''.join('*' for i in xrange(num))

def histogram(s):
    map(print_asterisks, s)

def main():
    # Test inputs
    print histogram([4,7,5])


if __name__ == "__main__":
    import sys
    sys.exit(main())

输出

****
*******
*****
None
4

4 回答 4

4

在这一行:

print histogram([4,7,5])

您正在打印函数的返回值histogram,即None. 您只需要调用该函数:

histogram([4,7,5])
于 2015-03-24T04:36:29.420 回答
1

写直方图([4,7,5])而不是打印直方图([4,7,5])


def print_asterisks(num):
    print ''.join('*' for i in xrange(num))

def histogram(s):
    map(print_asterisks, s)

def main():
    # Test inputs
    histogram([4,7, 5])

如果 __name__ == "__main__":
    导入 sys
    sys.exit(main())
于 2015-03-24T05:02:30.050 回答
1

由于该函数histogram没有返回任何内容。print histogram([4,7,5])打印None

def print_asterisks(num):
    print ''.join('*' for i in xrange(num))

def histogram(s):
    map(print_asterisks, s)

def main():
    # Test inputs
    histogram([4,7,5])


if __name__ == "__main__":
    import sys
    sys.exit(main())

输出:

****
*******
*****
于 2015-03-24T04:42:50.383 回答
1

代替

def main():
    # Test inputs
    print histogram([4,7,5])

def main():
    # Test inputs
    histogram([4,7,5])

注意:该函数histogram没有任何返回语句。

于 2015-03-24T04:53:03.737 回答