简体   繁体   English

如何将列表的所有元素相乘以最终答案Python numpy无法正常工作

[英]How to multiply all elements of the list to final answer Python numpy not working

Sorry about this. 为此事道歉。 I'm new to Python and am doing a leetcode problem and I am currently trying to multiply all the numbers in the list together to get a final result. 我是Python的新手,正在处理leetcode问题,我目前正在尝试将列表中的所有数字相乘以得出最终结果。 Here is my code: 这是我的代码:

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

However I get this error: 但是我得到这个错误:

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

Is there any other way to multiply all the elements in a list and storing in a value. 还有其他方法可以将列表中的所有元素相乘并存储在值中。

Try casting the numbers back into an integer: 尝试将数字转换回整数:

return list(map(int, arr))

Or alternatively: 或者:

arr.append(int(result))

This is what I've ran in Spyder 3.5: 这是我在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)

This is the output I've got: 这是我得到的输出:

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

The code works perfectly fine with Spyder. 该代码与Spyder完美配合。

Similar to @Pranav's answer I ran your code with a random generated list and it worked successfully. 与@Pranav的答案类似,我使用随机生成的列表运行了您的代码,并且该代码成功运行。 Note that when the list exceeds 37 items then numpy.prod() will begin to fail and return 0 as the calculation has now exceeded the data type limit size. 请注意,当列表超过37个项目时,numpy.prod()将开始失败并返回0,因为计算现在已超出数据类型限制大小。 You can get pretty big pretty quickly using numpy.prod(). 您可以使用numpy.prod()快速变大。 Looking at the error double check your list items are integers or floats. 查看错误,再次检查您的列表项是整数还是浮点数。

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)

Could you provide us with the list that you are using when testing the function? 您能否向我们提供测试功能时使用的列表? That will help with reproducing your error. 这将有助于重现您的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM