AcWing 0x02. 语法基础课【Python3】版题解-函数/类和对象/常用库

AcWing语法基础课【Python3】版题解-函数/类和对象/常用库

【AcWing】

【AcWing 语法基础课】

【AcWing 0x00. 语法基础课【Python3】版题解-顺序/判断/循环语句】

【AcWing 0x01. 语法基础课【Python3】版题解-内置数据结构/字符串】

【AcWing 0x02. 语法基础课【Python3】版题解-函数/类和对象/常用库】

函数

例题

【AcWing 804. n的阶乘】

def factorial(n):
    res = 1
    for i in range(1, n+1):
        res *= i
    return res

n = int(input())
print(factorial(n))

解析:用循环求阶乘。

【AcWing 805. x和y的最大值】

def myMax(x, y):
    return x if x > y else y

x, y = map(int, input().split())
print(myMax(x, y))

解析:用三目运算符实现求最大值。

【AcWing 808. 最大公约数】

def myGCD(a, b):
    divisor = 1
    ran = min(a, b)
    for i in range(1, ran+1):
        if a % i == 0 and b % i == 0:
            divisor = i
    return divisor
    
a, b = map(int, input().split())
print(myGCD(a, b))

解析:用循环求最大公约数。

【AcWing 811. 交换数值】

def mySwap(x, y):
   x, y = y, x
   return x, y
   
x, y = map(int, input().split())
s = mySwap(x, y)
print(s[0], s[1])

解析:Python3函数可以以元组的形式返回多个值。

【AcWing 812. 打印数字】

def printSize(a, size):
    return a[:size]

n, size = map(int, input().split())
a = list(map(int, input().split()))
for i in printSize(a, size):
    print(i, end=' ')

解析:使用列表切片返回前size个数。

【AcWing 813. 打印矩阵】

def print2D(matrix, row, col):
    for i in range(row):
        for j in range(col):
            print(matrix[i][j], end=" ")
        print()

row, col = map(int, input().split())
matrix = [list(map(int, input().split())) for i in range(row)]
print2D(matrix, row, col)

解析:用双重循环遍历并打印矩阵。

【AcWing 819. 递归求阶乘】

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n-1)

n = int(input())
print(factorial(n))

解析:阶乘数列通项公式为 F n = n × F n − 1 , F 1 = 1 F_n = n\times F_{n-1},F_1 = 1 Fn=n×Fn1,F1=1

【AcWing 820. 递归求斐波那契数列】

def fibonacci(n):
    if n == 1 or n == 2:
        return 1
    return fibonacci(n-1) + fibonacci(n-2)

n = int(input())
print(fibonacci(n))

解析:斐波那契数列通项公式为 F n = F n − 1 + F n − 2 , F 1 = F 2 = 1 F_n = F_{n-1}+F_{n-2},F_1 = F_2 = 1 Fn=Fn1+Fn2,F1=F2=

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值