天天看点

函数进阶习题

目录

​​一、1000以内的完美数​​

​​二、求多个参数的中位数​​

​​三、返回质因子​​

​​ 四、台阶走法​​

一、1000以内的完美数

def judge(n):
    s = []
    for i in range(1,n):
        if (n % i == 0):
            s.append(i)
    if n == sum(s):
        return True
    else:
        return False

def search():
    for i in range(1,10000):
        if judge(i):
            print(i)

if __name__ == '__main__':
    search()      
函数进阶习题

二、求多个参数的中位数

def median(*args):
    if (len(args) % 2 == 0):
        return (args[len(args) // 2 - 1] + args[len(args) // 2]) / 2
    else:
        return args[len(args) // 2]

if __name__ == '__main__':
    print(median(10,20,30,40,50,60,70))      
函数进阶习题

三、返回质因子

def factor(num):
    # s = []
    # for i in range(1,n + 1):
    #     if (n % i == 0):
    #         if i == 1:
    #             continue
    #         for j in range(2,i + 1):
    #             if i == 2:
    #                 s.append(i)
    #                 continue
    #             if (i % j == 0):
    #                 break
    #             else:
    #                 if i not in s:
    #                     s.append(i)
    # return s
    factors ,factor = [],2
    while num > 1:
        if num % factor == 0:
            if factor not in factors:
                factors.append(factor)
            num //=factor
        else:
            factor +=1
    return factors

if __name__ == '__main__':
    n = int(input('请输入一个整数'))
    print(factor(n))      
函数进阶习题

 四、台阶走法

def go_upstairs(num):
    if num == 1:
        return 1
    elif num ==2 :
        return 2
    elif num ==3:
        return 4
    else:
        return go_upstairs(num-1)+go_upstairs(num-2)+go_upstairs(num-3)
num = int(input("请输入台阶数:"))
steps = go_upstairs(num)
print(steps)