python写出两个(密集)向量相加的函数
时间: 2023-05-27 12:06:47 浏览: 95
以下是两个密集向量相加的Python函数示例:
```python
def add_dense_vectors(vec1, vec2):
"""
Add two dense vectors element-wise.
Args:
vec1 (list): a dense vector represented as a list of numbers
vec2 (list): another dense vector represented as a list of numbers
Returns:
list: a dense vector representing the sum of vec1 and vec2
"""
assert len(vec1) == len(vec2), "The two vectors must have the same length."
return [vec1[i] + vec2[i] for i in range(len(vec1))]
def main():
vec1 = [1, 2, 3, 4, 5]
vec2 = [5, 4, 3, 2, 1]
result = add_dense_vectors(vec1, vec2)
print(result) # Output: [6, 6, 6, 6, 6]
if __name__ == '__main__':
main()
```
另一个示例:
```python
import numpy as np
def add_dense_vectors(vec1, vec2):
"""
Add two dense vectors using NumPy.
Args:
vec1 (list): a dense vector represented as a list of numbers
vec2 (list): another dense vector represented as a list of numbers
Returns:
list: a dense vector representing the sum of vec1 and vec2
"""
assert len(vec1) == len(vec2), "The two vectors must have the same length."
return list(np.array(vec1) + np.array(vec2))
def main():
vec1 = [1, 2, 3, 4, 5]
vec2 = [5, 4, 3, 2, 1]
result = add_dense_vectors(vec1, vec2)
print(result) # Output: [6, 6, 6, 6, 6]
if __name__ == '__main__':
main()
```
这两个函数都需要两个相同长度的密集向量作为输入,并返回一个向量,其中每个元素等于相应的两个输入向量的元素之和。第一个函数使用纯Python来实现,而第二个函数使用NumPy库来实现。
阅读全文