Python error when calling NumPy from class method with map

前端 未结 5 1665
我寻月下人不归
我寻月下人不归 2021-02-12 23:58

The following code throws me the error:

Traceback (most recent call last):
  File \"\", line 25, in 
    sol = anna.main()
  File \"\", line 17, in         


        
5条回答
  •  别那么骄傲
    2021-02-13 00:23

    You can replace numpy by the built in function math.sqrt like this:

    import math  
    
    class anaconda():
    
        def __init__(self):
            self.mice = range(10000)
    
        def eat(self, food):
            calc = math.sqrt(food ** 5)
            return calc
    
        def main(self):
    
            sol = list(map(self.eat, self.mice))
            return sol
    
    
    if __name__ == '__main__':
        anna = anaconda()
        sol = anna.main()
        print(len(sol))
    

    I think that the problem of your code is that you are probably reaching a limit (not sure yet why it raises that confusing error) because 10000**5 is a reeeally big number. You can check this out by reducing your range(10000) to range(1000). You will notice that your code runs perfectly fine then:

    import numpy as np  
    
    class anaconda():
    
        def __init__(self):
            self.mice = range(1000)
    
        def eat(self, food):
            calc = np.sqrt((food ** 5))
            return calc
    
        def main(self):
    
            sol = list(map(self.eat, self.mice))
            print sol
            return sol
    
    
    if __name__ == '__main__':
        anna = anaconda()
        sol = anna.main()
        print(len(sol))
    

    This runs perfectly fine, just by reducing range(10000) to range(1000)

提交回复
热议问题