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

โปรแกรมหาลิสต์ผลคูณของทุกสมาชิกยกเว้น index ปัจจุบันใน Python

สมมติว่าเรามีรายการตัวเลข nums ต้องหาใหม่ลิสต์ที่แต่ละ index i เป็นผลคูณของทุกตัวในลิสต์เดิมยกเว้น index i ห้ามใช้การหาร

ตัวอย่าง: nums = [2, 3, 4, 5, 6] ผลลัพธ์ [360, 240, 180, 144, 120]

ขั้นตอนการแก้ปัญหา (Prefix & Suffix Product)

  1. ถ้า len(nums) < 1 คืนค่า nums
  2. l = len(nums), สร้าง left และ right ขนาด l เติม None
  3. temp = 1, วนลูป i จาก 0 ถึง l-1:
    • ถ้า i == 0: left[i] = temp
    • อื่นๆ: temp *= nums[i-1], left[i] = temp
  4. temp = 1, วนลูป i จาก l-1 ถึง 0:
    • ถ้า i == l-1: right[i] = temp
    • อื่นๆ: temp *= nums[i+1], right[i] = temp
  5. สำหรับทุก i: left[i] *= right[i]
  6. คืนค่า left

ตัวอย่างโค้ด Python

class Solution:
    def solve(self, nums):
        if len(nums) < 1:
            return nums
        l = len(nums)
        left = [None] * l
        right = [None] * l
        temp = 1
        for i in range(len(nums)):
            if i == 0:
                left[i] = temp
            else:
                temp = temp * nums[i - 1]
                left[i] = temp
        temp = 1
        for i in range(len(nums) - 1, -1, -1):
            if i == len(nums) - 1:
                right[i] = temp
            else:
                temp = temp * nums[i + 1]
                right[i] = temp
        for i in range(len(nums)):
            left[i] = left[i] * right[i]
        return left

ob = Solution()
nums = [2, 3, 4, 5, 6]
print(ob.solve(nums))  # Output: [360, 240, 180, 144, 120]

อินพุต / เอาต์พุต

Input: [2, 3, 4, 5, 6]

Output: [360, 240, 180, 144, 120]