Tất cả thử thách
Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Dot Product of Two Vectors

Multiply two vectors element by element and add the results: the core operation of every neuron.

Bạn sẽ học được gì

  • Multiply vectors element by element and sum
  • Understand the core operation of a neuron
  • Work with number arrays

Đề bài

Xem bản dịch

Every neuron starts with the same calculation: multiply each input by its weight and add everything up. That is the dot product of two vectors:

a · b = a₁×b₁ + a₂×b₂ + … + aₙ×bₙ

Implement dot_product(a, b).

Input

a, b: Two lists of numbers with the same length.

Output

Return the dot product as a decimal number.

Ràng buộc

1 ≤ length of a = length of b ≤ 1,000

-1,000 ≤ each value ≤ 1,000

Ví dụ

Ví dụ 1
Đầu vào:
a = [1.0, 2.0, 3.0]
b = [4.0, 5.0, 6.0]

Kết quả mong đợi:
expected = 32.0
Đầu vào:
std::vector<double> a = {1.0, 2.0, 3.0};
std::vector<double> b = {4.0, 5.0, 6.0};

Kết quả mong đợi:
double expected = 32.0;
Đầu vào:
double[] a = new double[] {1.0, 2.0, 3.0};
double[] b = new double[] {4.0, 5.0, 6.0};

Kết quả mong đợi:
double expected = 32.0;

Giải thích

1×4 + 2×5 + 3×6 = 4 + 10 + 18 = 32.

Ví dụ 2
Đầu vào:
a = [0.5, -1.5]
b = [2.0, 4.0]

Kết quả mong đợi:
expected = -5.0
Đầu vào:
std::vector<double> a = {0.5, -1.5};
std::vector<double> b = {2.0, 4.0};

Kết quả mong đợi:
double expected = -5.0;
Đầu vào:
double[] a = new double[] {0.5, -1.5};
double[] b = new double[] {2.0, 4.0};

Kết quả mong đợi:
double expected = -5.0;

Giải thích

0.5×2 + (-1.5)×4 = 1 - 6 = -5.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

Multiply matching positions from the two lists and combine the results into one total.

Gợi ý 2

A single pass is enough because each pair contributes independently to the final value.

Gợi ý 3

Make sure the lists have the same length, and keep the accumulator in a numeric type that preserves decimals if needed.

Độ phức tạp mong đợi

O(n) time, O(1) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.