Python error when calling NumPy from class method with map

前端 未结 5 1661
我寻月下人不归
我寻月下人不归 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:15

    Plain Python

    Actually, you need neither numpy nor math because sqrt(x) is x**0.5. So:

    sqrt(x**5) = x ** (5/2) = x ** 2.5
    

    It means you could replace your code with:

    class anaconda():
        def __init__(self):
            self.mice = range(10000)
    
        def eat(self, food):
            calc = food ** 2.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))
    

    NumPy

    If you want to use NumPy, you can enjoy the fact that you can work with arrays as if they were scalars:

    import numpy as np
    
    class anaconda():
    
        def __init__(self):
            self.mice = np.arange(10000)
    
        def eat(self, food):
            return food ** 2.5
    
        def main(self):
            return self.eat(self.mice)
    
    
    if __name__ == '__main__':
        anna = anaconda()
        sol = anna.main()
        print(len(sol))
    

    Short refactor

    Removing all the unneeded object-oriented-with-weird-names, your code becomes:

    import numpy as np
    print(np.arange(10000) ** 2.5)
    

提交回复
热议问题