python 以不同形式打印矢量

python printing vectors in different forms

编写一个名为“vectormath.py”的程序来进行 3 维的基本矢量计算: 加法、点积和归一化。

我的映射函数有错误。

示例输入:

Enter vector A:

1 3 2

Enter vector B:

2 3 0

示例输出

A+B = [3, 6, 2]

A.B = 11

|A| = 3.74

|B| = 3.61

代码:

import math
def addition(a,b):
    return[a[0]+b[0] , a[1] + b[1] , a[2] + b[2]]

def  Dotproduct(a , b):
    return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]

def norm(a):
    square = a[0]**2 + a[1]**2 + a[2]**2
    return math.sqrt(square)

def main():
    vector_A = input("Enter vector A:\n").split(" ")
    vector_A = map(int,vector_A)
    vector_B = input("Enter vector B:\n").split(" ")
    vector_B = map(int, vector_B)
    
    print(addition(vector_A,vector_B))
    print(addition(vector_A,vector_B))
    print(norm(vector_A))
    print(norm(vector_B))
    
if __name__ == "__main__":
    main()

替换

vector_A = map(int,vector_A)vector_A = list(map(int, vector_A))

vector_B = map(int,vector_B)vector_B = list(map(int, vector_B))

这里 map(int, vector_A) returns 一个映射对象,它是一个迭代器。

list() 采用迭代器和 returns 一个列表,您需要在代码中进行进一步的矢量计算。

截至目前,您正在将 map object 传递给函数 addition, Dotproduct and norm,它实际上应该是定义的计算列表。

以上更改将地图对象转换为列表。