0

I need to sort this list of instances using the third value which represents the XP. My function creates an instance of the CodeFighter class using CodeFighter(*codefighter) and I'm not sure how I can sort this without returning a value??

These are the values I'm using to create the instances:

[["Warrior", "1", "1050"], ["Ninja!", "21", "995"], ["Recruit", "3", "995"]]

def sortCodefighters(codefighters):
    res = [CodeFighter(*codefighter) for codefighter in codefighters]
    res.sort(reverse=True)
    return list(map(str, res))

class CodeFighter:
    def __init__(self,name,id,xp):
        self.name=name
        self.id=int(id)
        self.xp =int(xp)
    ??????
4
  • Man, i need to fill code in place of "????" Commented Sep 6, 2017 at 13:32
  • Init function doesn't need to return Commented Sep 6, 2017 at 14:04
  • This question is similar to a problem in codefights.com website! What is the point, really? At least try and phrase your own question instead of copying and pasting the problem from another website! Commented Sep 18, 2017 at 3:04
  • BTW, The question (meant to teach classes in Python) intended the user to opt for something in the lines of __lt__() operator. Commented Sep 18, 2017 at 3:16

1 Answer 1

1

'Your class doesnt need to return a value, it needs an attribute which it can use for sorting. In your case you want to use the 'XP' value to sort. You can use the operator class to sort the classes using the attribute 'XP':

import operator


class CodeFighter:
    def __init__(self,name,id,xp):
        self.name=name
        self.id=int(id)
        self.xp =int(xp)

    def __str__(self):
        return 'Name: %s, ID: %s, XP: %s' % (self.name, self.id, self.xp)


def sortCodefighters(codefighters, reversed=False):
    res = [CodeFighter(*codefighter) for codefighter in codefighters]
    return sorted(res, key=operator.attrgetter('xp'), reverse=reversed)


fighters = [["Warrior", "1", "1050"], ["Ninja!",  "21", "965"], ["Recruit", "3", "995"]]
fighters = sortCodefighters(fighters, reversed=True)
for fighter in fighters:
    print(fighter)

>> Name: Warrior, ID: 1, XP: 1050
>> Name: Recruit, ID: 3, XP: 995
>> Name: Ninja!, ID: 21, XP: 965

and if you flip the reversed value when calling your sortCodefighters function:

fighters = [["Warrior", "1", "1050"], ["Ninja!",  "21", "965"], ["Recruit", "3", "995"]]
fighters = sortCodefighters(fighters, reversed=False)
for fighter in fighters:
    print(fighter)

>> Name: Ninja!, ID: 21, XP: 965
>> Name: Recruit, ID: 3, XP: 995
>> Name: Warrior, ID: 1, XP: 1050
Sign up to request clarification or add additional context in comments.

2 Comments

TypeError: unorderable types: CodeFighter() < CodeFighter()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.