一、题目
Basic mathematical functions operate element-wise on arrays. They are available both as operator overloads and as functions in the NumPy module.
You are given two integer arrays A and B of dimensions NxM.
Your task is to perform the following operations:
1. Add ( A + B )
2. Subtract ( A - B )
3. Multiply ( A * B )
4. Interger Division ( A / B )
5. Mod ( A % B )
6. Power ( A ** B )
Note
There is a method numpy.floor_divide() that works like numpy.divide() except is performs a floor division.
Input Format
The first line contains two space seperated integers, N and M.
The next N lines contains M space seperated integers of array A.
The following N lines contains M space separated integers of array B.
Sample Input
1 4
1 2 3 4
5 6 7 8
Sample Output
[[ 6 8 10 12]]
[[-4 -4 -4 -4]]
[[ 5 12 21 32]]
[[0 0 0 0]]
[[1 2 3 4]]
[[ 1 64 2187 65536]]
二、代码
# Enter your code here. Read input from STDIN. Print output to STDOUT
import numpy as np
N, M = map(int, input().split())
A = np.array([[*map(int, input().split())] for _ in range(N)])
B = np.array([list(map(int, input().split())) for _ in range(N)])
print(A + B)
print(np.subtract(A, B))
print(np.multiply(A, B))
print(A // B)
print(np.mod(A, B))
print(np.power(A, B))
三、解读
1、解题:
要求读取两个整数数组 A
和 B
,然后对它们执行几种基本的数学运算,并打印结果。
2、import numpy as np
导入 NumPy 库,并将其简称为 np
,以便在代码中使用。
3、N, M = map(int, input().split())
读取用户输入的第一个行,该行包含两个以空格分隔的整数 N
和 M
。
4、A = np.array([[*map(int, input().split())] for _ in range(N)])
1)创建一个 NumPy 数组 A
,包含 N
行,每行有 M
个整数。
2)input().split()
读取每一行的输入,将其分割成字符串列表。
3)map(int, input().split())
将这些字符串转换为整数。
4)*map(int, input().split())
是 Python 3.5 及更高版本中的一个新特性,称为“星号表达式”。它将 map
对象解包成实际的参数。
5)列表推导式 [...] for _ in range(N)
重复这个过程 N
次,为数组的每一行创建一个整数列表。
6)np.array([...])
将这些列表转换为一个 NumPy 数组。
5、B = np.array([list(map(int, input().split())) for _ in range(N)])
这行代码与创建数组 A
的过程类似,用于创建另一个 NumPy 数组 B。
6、为什么有A、B两种不同的创建方式?
1)语法糖: A
的创建方式使用了 Python 3.5 引入的星号表达式(*
),这是一种语法糖,使得代码更简洁。它直接将 map
对象解包成参数,而不需要显式地调用 list()。
2)可读性:B
的创建方式更传统,对于不熟悉星号表达式的人来说,可能更容易理解。它显式地将 map
对象转换为列表,然后再将这些列表转换为 NumPy 数组。
3)尽管两种方式在语法上有所不同,但它们的最终效果是相同的:都创建了一个包含整数的二维 NumPy 数组。选择哪种方式取决于个人偏好和对 Python 语法的熟悉程度。