python基础

1.装饰器

import time
#装饰器,计算代码运行时间
def cal_time(func):
    def wrapper(*args, **kwargs):
        t1 = time.time()
        result = func(*args, **kwargs)
        t2 = time.time()
        # print(t1)
        # print(t2)
        print("%s running time: %s secs." % (func.__name__, t2 - t1))
        return result

    return wrapper


@cal_time
def linear_search(li, val):
    for ind, v in enumerate(li):
        if v == val:
            return ind
    else:
        return None

@cal_time
def binary_search(li, val):
    left = 0
    right = len(li) - 1
    while left <= right:    # 候选区有值
        mid = (left + right) // 2
        if li[mid] == val:
            return mid
        elif li[mid] > val: # 待查找的值在mid左侧
            right = mid - 1
        else: # li[mid] < val 待查找的值在mid右侧
            left = mid + 1
    else:
        return None

li = list(range(100000000))
linear_search(li, 38900000)
binary_search(li, 38900000)

 

posted @ 2020-04-29 11:38  圣君灬七夜  阅读(249)  评论(0编辑  收藏  举报