CSC111 Lab 10 Addendum 2014

From dftwiki3
Revision as of 08:29, 8 April 2014 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- This code is part of the CSC111 Lab 10 pages. <br /> <source lang="python"> class PlanetList: def __init__( self ): self._li...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 09:29, 8 April 2014 (EDT)


This code is part of the CSC111 Lab 10 pages.

class PlanetList:
    def __init__( self ):
        self._list = [("Earth", 12756 ),
                      ("Venus", 12104 ),
                      ("Mercury", 4880 ),
                      ("Moon", 3476 ) ]
        
    def toString( self ):
        justNames = [ name for name,diameter in self._list ]
        return ", ".join( justNames )

    def addNewPlanetFromInput( self ):
        name = input( "What is the name of the new planet? " )
        name = name.strip().capitalize()
        justNames = [ name for name,diameter in self._list ]
        if name in justNames:
            print( "This planet is alread in the list!" )
            return
        diameter = int( input( "What is the diameter of this planet? " ) )
        self._list.append( (name, diameter) )

    def getNoOfPlanets( self ):
        return len( self._list )

    def isEmpty( self ):
        return len( self._list )==0
    
    def getSmallest( self ):
        if self.getNoOfPlanets() == 0:
            return None
        listOrderedBySize = [ (diam, name) for name, diam in self._list ]
        listOrderedBySize.sort()
        
        # return the name (2nd argument) of the first in list
        return listOrderedBySize[0][1]

    def getLargest( self ):
        if self.getNoOfPlanets() == 0:
            return None
        listOrderedBySize = [ (diam, name) for name, diam in self._list ]
        listOrderedBySize.sort()
        listOrderedBySize.reverse()
        
        # return the name (2nd argument) of the first in list
        return listOrderedBySize[0][1]