AcWing语法基础课【Python3】版题解-函数/类和对象/常用库
【AcWing 0x00. 语法基础课【Python3】版题解-顺序/判断/循环语句】
【AcWing 0x01. 语法基础课【Python3】版题解-内置数据结构/字符串】
【AcWing 0x02. 语法基础课【Python3】版题解-函数/类和对象/常用库】
函数
例题
def factorial(n):
res = 1
for i in range(1, n+1):
res *= i
return res
n = int(input())
print(factorial(n))
解析:用循环求阶乘。
def myMax(x, y):
return x if x > y else y
x, y = map(int, input().split())
print(myMax(x, y))
解析:用三目运算符实现求最大值。
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))
解析:用循环求最大公约数。
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函数可以以元组的形式返回多个值。
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个数。
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)
解析:用双重循环遍历并打印矩阵。
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×Fn−1,F1=1。
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=Fn−1+Fn−2,F1=F2=