python 二分插入、遍历目录

这两道题是之前面试测试开发遇到的,今天分享给大家。

遍历文件

python 遍历文件夹下所有文件,并打印出所有文件名

import os 
import cProfile

def getfiles(file_path):
    files = os.listdir(file_path)
    for file in files:
        file_d = os.path.join(file_path,file)
        if os.path.isdir(file_d):
            getfiles(file_d)
        else:
            print(file_d)
            

cProfile.run("getfiles(r'/Users/xiaotianlv/project/blog_env')")
print("---------------")

二分法

python 在顺序列表中,二分法查找且插入一个数

def middle_search(lis, n):
    num = 0
    min = 0
    max = len(lis)-1
    while min <= max :
        num += 1
        mid = min + (max-min)//2
        if min == max:
            if lis[mid] >n:
                lis.insert[mid,n]
            else:
                lis.insert(mid+1, n)
            print(num)
            return lis
        elif lis[mid] >= n:
            max = mid - 1
        else:
            min = mid + 1
            # print(lis(min))
        
lis = [1,2,3,4,5,6,7,8]
n = 4
print(middle_search(lis, n))

491527167486_.pic_hd.jpg

单元测试

import unittest

def div(a, b):
    return a // b   # 整除

class TestSequenceFunc(unittest.TestCase):

    def setUp(self):
        print("每个用例执行前运行")

    def tearDown(self):
        print("after every test case")

    def test_1_div_1(self):
        self.assertEqual(div(1,1), 1 // 1)

    def test_3_div_0(self):
        print('3//0')
        self.assertRaises(ZeroDivisionError, div, 3, 0 )

斐波那契数列

import time

def fbis(num):
    result = [0,1]
    for i in range(num-2):
        result.append(result[-2] + result[-1])
    return result

def main():
    result = fbis(10)
    fobj = open('/Users/xiaotianlv/Desktop/result.txt', 'w+')
    for i, num in enumerate(result):
        print("第%d个数是: %d" %(i, num))
        fobj.write("%d" %num)
        time.sleep(1)

if __name__ == '__main__':
    main()

你可能感兴趣的:(python 二分插入、遍历目录)