Python Forum
Help with a custom function needed
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with a custom function needed
#1
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))
        
   
        
        
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 511 Nov-23-2023, 02:53 PM
Last Post: rob101
  Custom function that prints function text gyaan_anveyshak 3 2,062 Jan-28-2020, 05:43 AM
Last Post: perfringo
  Custom Function to Return Database Values rm78 0 1,764 Sep-05-2019, 01:01 PM
Last Post: rm78
  Duplicate output when calling a custom function from the same file? road2knowledge 2 2,342 May-10-2019, 07:58 AM
Last Post: road2knowledge

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020