Search code examples
pythonpython-3.6rankingrank

Ranking in python


Good day guys, I am struggling to write a function to rank numbers. The code is working but two things ain't working well. We know if two numbers are the same, they get the same position (or rank) but from my code, the two same numbers have different rankings. Also when it gets to 21st, the code prints 21th in instead of 21st. How can I solve this issue. This the code

a = [20,50,67,100,93,89,72,81,79,66,49,73,29,50,52,69,71,70,71,84,67]

 def ranker(zed):
      prefixes = ["st", "nd", "rd" ,"th"]
      zed.sort(reverse =True) 
      found = [ ]

     for dig in zed:
          pre =  len(found) + 1
          if len(found) > 3:
                found.append(str(dig) + " " + str(pre) + prefixes[ 3 ])
     else:
           found.append(str(dig) + " " + str(pre) + prefixes[ len(found) ])
           print(found) 
           ranker(a)

Solution

  • I believe this is what you want.

    a = [20,50,67,100,93,89,72,81,79,66,49,73,29,50,52,69,71,70,71,84,67]
    def ranker(zed):
        prefixes = ["st", "nd", "rd" ,"th"]
        zed.sort(reverse =True)
        found = [ ]
        for dig in zed:
            pre = len(found) + 1
            if found and dig==int(found[-1].split(' ')[0]):
                found.append(found[-1])
            else:
                if pre > 3:
                    if pre>20 and pre%10<3 and pre%100<10 or pre%100>20:
                        found.append(str(dig) + " " + str(pre) + prefixes[len(found)%10])
                    else:
                        found.append(str(dig) + " " + str(pre) + prefixes[ 3 ])
                else:
                    found.append(str(dig) + " " + str(pre) + prefixes[len(found)])
        print(found)
    ranker(a)