2022.12.23-Python100day-day05-函数

1、写一个函数,传入一个文件名,返回这个文件的后缀名

例如: hello.py ----> py/.py
def get_suffix(filename:str, *, has_dot: bool=True)->str:
    """
    获取文件的后缀名
    写在 * 前面的参数 称为 位置参数  * 后面的参数 称为 命名关键字参数
    :param filename:  文件名
    :param has_dot: 后缀名是否包含  .
    :return:后缀名
    """
    position = filename.rfind('.')  # 先找到. 的位置
    if position <= 0:
        return ''
    if not has_dot:
        position = position + 1  # 看看是否需要 . 如果想要从 position 开始切片 如果不想要                                         从 position+1 开始切片
    return filename[position:]
    if pos > 0:
        return filename[pos+1:]  # . 的位置往后的内容
    return ''
if __name__ =="__main__":
    print(get_suffix('hello.py'))
    print(get_suffix(filename='hello.py', has_dot=True))
    print(get_suffix('hello.py.txt'))
    print(get_suffix(filename='hello.py.txt', has_dot=True))
    print(get_suffix(filename='hello'))
    print(get_suffix(filename='hello.'))
    print(get_suffix(filename='.hello'))
在设计函数的时候  函数的参数个数是暂时 无法确定的
*args  -----> 可变参数   可以接受零个 或者 任意 多个 位置参数 -----> 将所有的位置参数打包成一个元组
**kwargs -----> 可以接受 0个 或者 任意 多个 关键字参数 -----> 将所有的关键字参数打包成一个字典
位置参数---> position argument
关键字参数----> keywords argument  给关键字参数赋值时,需要按照字典的方式去进行赋值
关键字参数  在  位置参数 的 后面的
def add(*args, **kwargs):
    print(args, type(args))
    print(kwargs, type(kwargs))

    total = 0
    for arg in args:
        if type(arg) in (int, float):
            total += arg
    for value in kwargs.values():
        if type(value) in (int, float):
            total += value
    return total
print(add())
print(add(1))
print(add(1, 2, c=3, b=2.5, a=1, d='hello'))
print(add(1, '2', 3))
print(add(1, 2, 3, 4))

 

运算符 从程序里面剥离出来
fn -----> 一个实现二元运算的函数(可以做任意的二元运算)
python中的一等函数:
1、函数可以作为函数的参数
2、函数可以作为函数的返回值
3、函数可以赋值给变量

def calculate(init_value, fn, *args, **kwargs):
    total = init_value
    for arg in args:
        if type(arg) in (int, float):
            total = fn(total, arg)
    for value in kwargs.values():
        if type(value) in (int, float):
            total += fn(total, value)
    return total

def add(x, y):
    return x + y

def mul(x, y):
    return x * y

def sub(x, y):
    return x - y

print(calculate(0, add, 11, 22, 33, 44))
print(calculate(1, mul, 11, 22, 33, 44))
print(calculate(100, sub, 11, 22, 33, 44))

2、lambda: 没有名字 而且 一句话 就能写完的函数 唯一的表达式 就是函数 的 返回值

 

 

3、排序算法

def bubble_sort(items: list, ascending: bool = True, gt=lambda x, y: x > y) -> list:
    """
    冒泡排序的算法
    :param items: 待排序的列表
    :param ascending: 是否使用升序排列
    :param gt: 比较两个元素大小的函数
    :return: 排序后的列表
    """
    items = items[:]
    for i in range(1, len(items)):
        swapped = False
        for j in range(0, len(items) - 1):
            if gt(items[j], items[j+1]):
                items[j], items[j+1] = items[j+1], items[j]
                swapped = True
        if not swapped:
            break

    if not ascending: # 是否是升序 还是 降序
        items = items[::-1]

    return items
def seq_search(items:list, key) -> int:
    """
    顺序查找(浙近时间复杂度 O(n))
    :param items: 待查找的列表
    :param key: 要查找的元素
    :return: 找到 返回元素的索引 找不到就返回 -1
    """
    for index, item in enumerate(items):
        if item == key:
            return index
    return -1

补充:

1 return, 如果什么都不接的话,其实就是void类型函数的返回,返回后不再执行return后面的语句

如果函数执行成功返回0,不成功返回非0,一般情况下非0值常用-1来表示。

2 return 0:一般用在主函数结束时,表示程序正常终止,即告诉系统程序正常

3 return -1::表示返回一个代数值,一般用在子函数结尾。表示程序异常终止,即告诉系统程序异常

4 return 1:与return -1相同
————————————————
版权声明:本补充部分为CSDN博主「IT_job」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/IT_job/article/details/79132940

def bin_search(items:list, key) -> int:
    """
    是对顺序列表进行查找
    二分查找(浙近时间复杂度 O(log2 n))
    :param items:待查找的列表(元素有序)
    :param key:要找的元素
    :return:找到 返回元素的索引 找不到返回-1
    """
    start = 0
    end = len(items) - 1
    while start <= end:
        mid = (start + end) // 2
        if key > items[mid]:
            start = mid + 1
        elif key < items[mid]:
            end = mid - 1
        else:
            return mid
    return -1
if __name__ == '__main__':
    nums = [35, 96, 12, 78, 56, 64, 39, 80]
    print(bubble_sort(nums, ascending=True))
    print(nums)

    words = ['apple', 'watermelon', 'hello', 'zoo', 'internationalization']
    print(bubble_sort(words, gt=lambda x, y: len(x) > len(y), ascending=False))
    print(words)

    nums2 = [12, 25, 39, 56, 64, 78, 80, 96]

    print(seq_search(nums, 12))
    print(seq_search(nums, 80))
    print(seq_search(nums, 95))
    print('-' * 10)
    print(bin_search(nums2, 12))
    print(bin_search(nums2, 80))
    print(bin_search(nums2, 95))

 4、函数栈

5、递归函数

递归函数 函数调用栈 的 空间  如果无限制的 会占用 满  调用栈的 空间, 函数的会报错的
不管函数 是调用 别的函数  还是调用自身,一定要做到快速收敛
在比较有限地调用次数内 能够 结束 不能无限制的进行调用
递归函数的两个要点:
1、递归公式(n次和n-1次的关系)
2、收敛条件(什么时候会停止递归函数的调用)

def foo():
    print('foo')

def bar():
    foo()
    print('bar')

def main():
    a, b = 5, 10
    bar()
    print(a, b)
    print('game over!')

def fac(num: int) -> int:
    if num == 0:
        return 1
    return num * fac(num-1)

if __name__ == '__main__':
    # main()
    for i in range(10):
        print(i, fac(i))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值