Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมหา Dot Product ของ Sparse Vectors ใน Python

โจทย์

มี Sparse Vectors สองตัว แทนในรูปลิสต์ ต้องการหา Dot Product ของทั้งสอง เวกเตอร์เก็บในตัวแปรสมาชิก 'nums' ในออบเจกต์

ตัวอย่าง: vector1 = [1, 0, 0, 0, 1], vector2 = [0, 0, 0, 1, 1] → ผลลัพธ์ 1 (คำนวณ: 1×0 + 0×0 + 0×0 + 0×1 + 1×1 = 1)

อัลกอริธึม

  1. วนลูปผ่านดัชนีและค่าของ vector2
  2. ข้ามถ้าค่าเป็น 0
  3. ข้ามถ้าค่าของ vector1 ในดัชนีนั้นเป็น 0
  4. สะสมผลคูณเมื่อทั้งคู่ไม่เป็น 0

โค้ด Python

class Solution:
    def __init__(self, nums):
        self.nums = nums
    
    def solve(self, vec):
        res = 0
        for i, v in enumerate(vec.nums):
            if v == 0:
                continue
            elif self.nums[i] == 0:
                continue
            else:
                res += v * self.nums[i]
        return res

ob1, ob2 = Solution([1, 0, 0, 0, 1]), Solution([0, 0, 0, 1, 1])
print(ob1.solve(ob2))  # Output: 1

Input / Output

Input:  [1, 0, 0, 0, 1], [0, 0, 0, 1, 1]
Output: 1