欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

函数基础练习题

程序员文章站 2024-02-24 16:05:17
...

完成一个函数,可以接收输入多个数,每一次都能返回到目前为止的最大值,最小值

def max1():
    max_ = min_ =None
    while True:
        x = input('>>>>>>')
        nums = [int(c) for c in x.replace(',','').split()]
        if not nums:
            continue
        if max_ is  None:
            max_ =min_ = nums[0]
        max_ = max(max_,*nums)
        min_ = min(min_,*nums)
        print(max_,min_)

max1()

递归函数

斐波那契数列:

递归实现:

def fib1(n):
    if n <3:
        return 1
    return fib1(n-1)+fib1(n-2)

print(fib1(35))

循环实现:

a = 0
b = 1
n =35

for i in range(n):
    a,b=b,a+b
print(a)

递归性能优化:

def fib3(n,a=0,b=1):
    a,b=b,a+b
    if n ==1:
        return a
    return fib3(n-1,a,b)
print(fib3(35))

求n的阶乘:

递归实现:

def foo(n):
    if n < 2:
        return 1
    return foo(n-1)*n

print(foo(5))

循环实现:

a =1
for i in range(5,0,-1):
    a = a*i
print(a)

循环变递归:

def foo(n,a=1):
    a = a*n
    if n < 2:
        return a
    return foo(n-1,a)

print(foo(5))