python几个面试题整理

1.下面代码会输出什么:

def f(x,l=[]):
    for i in range(x):
        l.append(i*i)
    print l

f(2)
f(3,[3,2,1])
f(3)

答案

[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]

对于第一种情况,很容易理解,没有创建新表,只是在l中添加两个元素,分别为0,1;
对于第二种情况,在内存中会创建一个新的表,在新表中增加了三个元素;
对于第三种情况比较难理解,此时,并没有创建新表,而是在原来的表l中新增了三个元素,0,1,4
2.

补充缺失的代码

def print_directory_contents(sPath):
    """
    这个函数接受文件夹的名称作为输入参数,
    返回该文件夹中文件的路径,
    以及其包含文件夹中文件的路径。

    """
    # 补充代码

答案

def print_directory_contents(sPath):
    import os                                       
    for sChild in os.listdir(sPath):                
        sChildPath = os.path.join(sPath,sChild)
        if os.path.isdir(sChildPath):
            print_directory_contents(sChildPath)
        else:
            print sChildPath
posted @ 2018-09-20 11:28  二师兄不讲英文  阅读(156)  评论(0编辑  收藏  举报