Search code examples
pythonscipycorrelationrecommendation-engine

Python - Correlation: Error unsupported operand type(s) for /: 'generator' and 'int'


I am trying to execute a python code and I am getting an error

unsupported operand type(s) for /: 'generator' and 'int'

Code :

def getCorrelation(user1,user2):
    ## user1 and user2 are two series
    list1=[1,2,3,4,5,6,78,9,12]
    user1=np.array(user1[i] for i in list1)

    user2=np.array(user2[i] for i in list1)


    return correlation(user1,user2)

getCorrelation(user1,user2)

Solution

  • Your user expressions produce arrays containing a generator:

    In [108]: np.array(i for i in alist)                                                 
    Out[108]: array(<generator object <genexpr> at 0x7f0b7bc98e60>, dtype=object)
    

    With a proper list comprehension:

    In [109]: np.array([i for i in alist])                                               
    Out[109]: array([1, 2, 3, 4])
    

    The traceback should show that the error occurs when such an array is passed to the correlation function.

    In [110]: np.array(i for i in alist)/2                                               
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-110-a87b95ad6f4b> in <module>
    ----> 1 np.array(i for i in alist)/2
    
    TypeError: unsupported operand type(s) for /: 'generator' and 'int'
    

    Or testing a simple generator:

    In [111]: g = (i for i in alist)                                                     
    In [113]: g                                                                          
    Out[113]: <generator object <genexpr> at 0x7f0b7bc9b0f8>
    In [114]: g/2                                                                        
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-114-f5357a50c56f> in <module>
    ----> 1 g/2
    
    TypeError: unsupported operand type(s) for /: 'generator' and 'int'