简体   繁体   中英

Implementing class for sorted list

I am trying to create a class called Fruit and make use of it to produce a sorted list of fruits and store them in a SortedList . However, the problem I am facing now is that I am supposed to sort them based on length first and if they have the same length, then sort by alphabetical order.

These are my codes so far:

class Node:
    # Constructor
    def __init__(self):
        self.nextNode = None

class Fruit(Node):
    def __init__(self, name):
        self.name = name
        self.nextNode = None
    def __str__(self):
        return f"'{self.name}'"
    def __eq__(self,otherNode):
        if otherNode == None:
            return False
        else:
            return self.name == otherNode.name
    def __lt__(self, otherNode):
        if otherNode == None:
            raise TypeError("'<' not supported between instances of 'Temp' and 'NoneType'")
        while len(self.name) < len(otherNode.name):
#            if len(self.name) == len(otherNode.name):
#                 while 
#                     return self.name and otherNode.name
#            else:
                return self.name and otherNode.name
    
class SortedList:
    def __init__(self):
        self.headNode = None
        self.currentNode = None
        self.length = 0
    def __appendToHead(self, newNode):
        oldHeadNode = self.headNode
        self.headNode = newNode
        self.headNode.nextNode = oldHeadNode
        self.length += 1
    def insert(self, newNode):
        self.length += 1
        # If list is currently empty
        if self.headNode == None:
            self.headNode = newNode
            return
        # Check if it is going to be new head
        if newNode < self.headNode:
            self.__appendToHead(newNode)
            return
        # Check it is going to be inserted between any pair of Nodes (left,right)
        leftNode = self.headNode
        rightNode = self.headNode.nextNode
        while rightNode != None:
            if newNode < rightNode:
                leftNode.nextNode = newNode
                newNode.nextNode = rightNode
                return
            leftNode = rightNode
            rightNode = rightNode.nextNode
        # Once we reach here it must be added at the tail
        leftNode.nextNode = newNode
    def __str__(self):
        # We start at the head
        output =""
        node= self.headNode
        firstNode = True
        while node != None:
            if firstNode:
                output = node.__str__()
                firstNode = False
            else:
                output += (',' + node.__str__())
            node= node.nextNode
        return output

# Main program for fruit
l = SortedList()
# Populate a sorted list with fruitnames
fruits = ['Cherry', 'Apricot','lime','blueberry','Apple','Date']
print('Before sorting')
print(fruits)
for fruit in fruits:
    l.insert(Fruit(fruit))
print('\nAfter sorting')
print(l)

The part that has error is in Fruit class.
My Output now is:

Before sorting
['Cherry', 'Apricot', 'lime', 'blueberry', 'Apple', 'Date']

After sorting
'lime','Date','Apple','Cherry','Apricot','blueberry'

The expected output is:

Before sorting
['Cherry', 'Apricot', 'lime', 'blueberry', 'Apple', 'Date']
After sorting
'Date','lime','Apple','Cherry','Apricot','blueberry'

How to fix it?

import functools

def compare(fruit1, fruit2):
  if len(fruit1) < len(fruit2):
    return -1
  elif len(fruit1) > len(fruit2):
    return 1
  elif fruit1 < fruit2:
    return -1
  elif fruit1 > fruit2:
    return 1
  else:
    return 0

sorted(fruitList, key=functools.cmp_to_key(compare))

This should work

You can sort the fruits first using the sorted function before you arrange them in length:

fruits = ['Cherry', 'Apricot','lime','blueberry','Apple','Date']
sorted_fruits = sorted(fruits)
print(sorted_fruits)
print('Before sorting')
print(fruits)
for fruit in sorted_fruits:
    l.insert(Fruit(fruit))
print('\nAfter sorting')
print(l)

Output:

['Apple', 'Apricot', 'Cherry', 'Date', 'blueberry', 'lime']

Before sorting
['Cherry', 'Apricot', 'lime', 'blueberry', 'Apple', 'Date']

After sorting
Date,lime,Apple,Cherry,Apricot,blueberry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM