码迷,mamicode.com
首页 > 编程语言 > 详细

python基础

时间:2020-04-29 13:09:49      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:__name__   arch   python   return   port   rgs   div   bin   int   

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)

 

python基础

标签:__name__   arch   python   return   port   rgs   div   bin   int   

原文地址:https://www.cnblogs.com/shengjunqiye/p/12801105.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!