用 Python 编写程序,查找除当前索引外所有元素的乘积列表

pythonserver side programmingprogramming更新于 2026/2/2 5:00:17

假设我们有一个名为 nums 的数字列表,我们必须找到一个新列表,使得新生成的列表中索引 i 处的每个元素都是原始列表中除索引 i 处的所有数字的乘积。这里我们必须在不使用除法的情况下解决它。

因此,如果输入为 nums = [2, 3, 4, 5, 6],则输出将为 [360, 240, 180, 144, 120]

为了解决这个问题,我们将遵循以下步骤 −

  • if size of nums < 1,则
    • 返回 nums
  • l := nums 的大小
  • left := 大小为 l 的列表,最初所有值均为 null
  • right := 大小为 l 的列表,最初所有值均为 null
  • temp := 1
  • 对于 i,范围从 0 到 nums 的大小,执行
    • 如果 i 与 0 相同,则
      • left[i] := temp
    • 否则,
      • temp := temp * nums[i - 1]
      • left[i] := temp
  • temp := 1
  • 对于 i 在 nums 的大小范围 - 1 到 0 内,减少 1,执行
    • 如果 i 与 nums 的大小 - 1 相同,则
      • right[i] := temp
    • 否则,
      • temp := temp * nums[i + 1]
      • right[i] := temp
  • 对于 i 在 0 到 nums 的大小范围内,执行
    • left[i] := left[i] * right[i]
  • 返回 left

让我们看看下面的实现以便更好地理解 −

示例

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))

输入

[2, 3, 4, 5, 6]

输出

[360, 240, 180, 144, 120]

相关文章


有用资源