【问题标题】:How to multiply all elements of the list to final answer Python numpy not working如何将列表的所有元素乘以最终答案 Python numpy 不起作用
【发布时间】:2018-12-05 21:45:21
【问题描述】:

对此感到抱歉。我是 Python 新手,正在做一个 leetcode 问题,我目前正在尝试将列表中的所有数字相乘以获得最终结果。这是我的代码:

import numpy 

class Solution:
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        arr = []

        for i in range(len(nums)):
            temp = nums[:i] + nums[i + 1 : len(nums)]
            result = numpy.prod(temp)
            arr.append(result)
        return arr

但是我得到这个错误:

Line 56: Exception: Type <class 'numpy.int64'>: Not implemented

有没有其他方法可以将列表中的所有元素相乘并存储在一个值中。

【问题讨论】:

  • 第 56 行是哪一行?
  • 让我们看看我是否可以通过智能手机做到这一点:import operator; from functools import reduce; multiply_all = lambda series: reduce(series, operator.__mul__)
  • @MateenUlhaq 不太确定,因为这是在 leet 代码中
  • 能否请您发布完整的代码?
  • 我猜你不能在 leetcode 中使用numpy

标签: python python-3.x list numpy


【解决方案1】:

与@Pranav 的回答类似,我使用随机生成的列表运行了您的代码,并且运行成功。请注意,当列表超过 37 个项目时,numpy.prod() 将开始失败并返回 0,因为计算现在已超过数据类型限制大小。使用 numpy.prod() 可以很快变得相当大。 查看错误仔细检查您的列表项是整数还是浮点数。

import numpy 
import random

class Solution:
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        arr = []

        for i in range(len(nums)):
            temp = nums[:i] + nums[i + 1 : len(nums)]
            result = numpy.prod(temp)
            arr.append(result)
        return arr

x = random.sample(range(0,100), 37)
answer = Solution()
product = answer.productExceptSelf(x)
print(product)

您能否向我们提供您在测试该功能时使用的列表?这将有助于重现您的错误。

【讨论】:

    【解决方案2】:

    这是我在 Spyder 3.5 中运行的:

    import numpy
    
    class Solution:
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        arr = []
    
        for i in range(len(nums)):
            temp = nums[:i] + nums[i+1 : len(nums)]
            result = numpy.prod(temp)
            arr.append(result)
        return arr
    
    a = [1, 2, 3, 4, 5, 6, 7]
    solutionObject = Solution()
    pES = solutionObject.productExceptSelf(a)
    print(pES)
    

    这是我得到的输出:

    [5040, 2520, 1680, 1260, 1008, 840, 720]
    

    代码与 Spyder 完美配合。

    【讨论】:

      【解决方案3】:

      尝试将数字转换回整数:

      return list(map(int, arr))
      

      或者:

      arr.append(int(result))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-17
        • 2014-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-16
        相关资源
        最近更新 更多