Python Forum

Full Version: Help with a custom function needed
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I was trying to get a custom function to perform an equation known as Spearman's rank correlation coefficient (read about here: https://en.wikipedia.org/wiki/Spearman%2...oefficient) and I have run into some issues. from using the debbuger I have noticed that after the second time of looping the for item in Xlist loop everything inside for item2 in XlistS is ignored and I have no idea why. its also outputting -71 which for this function shouldn't be possible. your help would be appreciated.
def srcc(Xlist, Ylist):
    XlistS = reversed(sorted(Xlist))
    index = 0
    add = 0
    whieght = 0
    divide = 0
    XlistW = []
    for item in Xlist:
        for item2 in XlistS:
            if item == item2:
                add += (index + 1)
                divide += 1
            index += 1
        index = 0
        whieght = add / divide
        XlistW.append(whieght)
    YlistS = reversed(sorted(Ylist))
    index = 0
    add = 0
    whieght = 0
    divide = 0
    YlistW = []
    for item in Ylist:
        for item2 in YlistS:
            if item == item2:
                add += (index + 1)
                divide += 1
            index += 1
        index = 0
        whieght = add / divide
        YlistW.append(whieght)
    count = 0
    Flist = []
    F = 0
    di = 0
    while count < len(Xlist):
        F = ((XlistW[count] - YlistW[count]) ** 2)
        Flist.append(F)
        count += 1
        for item in Flist:
            di += item
    di *= 6
    di = di / (len(Xlist) * (len(Xlist) -1))
    di = 1 - di
    return di
X = [1, 2, 3, 4, 5]
Y = [5, 4, 3, 2, 1]
print(srcc(Xlist = X, Ylist = Y))
        
   
        
        
XlistS = reversed(sorted(Xlist))
XlistS is iterator. That is what reversed() built-in function returns. After first iteration of the loop it is exhausted (i.e. empty).
you can do
XlistS = Xlist[::]
XlistS.sort(reverse=True)
Also looking at 2-16 and 17-32, it's clear the need of another function.