CSC111 Examples of Operations on Lists

From dftwiki3
Revision as of 09:25, 25 March 2014 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- <source lang="python"> # ListFunctions.py # some functions that use lists # def box( caption ): length = len( caption )+2 print( "\n\n\n+" + "-"*length +...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 10:25, 25 March 2014 (EDT)


# ListFunctions.py
# some functions that use lists
#

def box( caption ):
    length = len( caption )+2
    print( "\n\n\n+" + "-"*length + "+" )
    print( "| " + caption  + " |" )
    print( "+" + "-"*length + "+\n" )
    
# change a number from negative to positive
# Version 1 returns the variable that was passed as a parameter
# Version 2 does not (it is not valid code)
def makeIntPositiveV1( x ):
    if x < 0:
        x = -x
    return x

def makeIntPositiveV2( x ):
    if x < 0:
        x = -x

        
# change all negative numbers in L to positive values
# Version 1 returns the list after having modified it
# Version 2 does not return the list (correct code)
def makePositiveV1( L ):
    for i in range( len( L ) ):
        if L[i] < 0:
            L[i] = -L[i]
    return L

def makePositiveV2( L ):
    for i in range( len( L ) ):
        if L[i] < 0:
            L[i] = -L[i]

# reformat(): gets a line that is made of 5 columns of numbers
# returns a line that contains only the numbers from column 3 and 4
def reformat( line ):
    words = line.split()
    newList = [ words[3-1], words[4-1] ]
    separator = " "
    return separator.join( newList )

# gets a list of names. Returns a list of names that start with
# the letter S.
def getSNames( nameList ):
    newList = []
    # traverse the list
    for name in nameList:
        # test first letter of name for 's' or 'S'
        if name[0] in ['s', 'S']:
            newList.append( name )
    return newList

# getMostVisited( columnarText )
def getMostVisited( tourismData ):
    newList = []
    # break text into lines...
    for line in tourismData.split( "\n" ):

        # break line into columns
        fields = line.split()
        
        # if line doesn't have the 10 columns required, skip it...
        if len( fields ) != 10:
            continue

        
        # isolate fields of interest 
        country = fields[0]
        population = float( fields[2] )

        # pair them, with number first 
        pair = ( population, country )

        # add to list
        newList.append( pair )

    # sort list by population
    newList.sort()

    return newList[-1]

    
def main():
    # -------------------------------------------------------
    box( "What happens when we pass simple type variables" )
    x = -5
    print( "x = ", x )
    x = makeIntPositiveV1( x )
    print( "after calling makeIntPositiveV1(): x = ", x )

    x = -5
    print( "x = ", x )
    makeIntPositiveV2( x )
    print( "after calling makeIntPositiveV2(): x = ", x )

    # -------------------------------------------------------
    box( "What happens when we pass lists" )
    
    Lorg = [ -1, 2, 3, 4, -5, 6]
    L = Lorg[:]
    print( "L = ", L )
    L = makePositiveV1( L )
    print( "after calling makePrositiveV1:", L )

    L = Lorg[:]
    print( "L = ", L )
    makePositiveV2( L )
    print( "after calling makePrositiveV2:", L )

    # -------------------------------------------------------
    box( "Demo of functions working with lists" )
    textLine = "10 20.5 30 40.5 50.9"
    newLine = reformat( textLine )
    print( "textLine = '%s'" % textLine )
    print( "newLine  = '%s'" % newLine )

    # -----------    
    seven = [ "Sleepy", "Sneezy", "Bashful", "Happy", "Grumpy", "Dopey", "Doc" ]
    Sdwarves = getSNames( seven )
    print( "\n\nSnow White's friends with name starting with s: ",
           ", ".join( Sdwarves ) )
    
    # -----------
    tourismData = """
    United-States	North-America	67.0 million	62.7 million	Increase 6.8	Increase 4.9
    China	Asia	57.7 million	57.6 million	Increase 0.3	Increase 3.4
    Malaysia	Asia	25.0 million	24.7 million	Increase 1.3	Increase 0.6
    Spain	Europe	57.7 million	56.2 million	Increase 2.7	Increase 6.6
    France	Europe	83.0 million	81.6 million	Increase 1.8	Increase 5.0
    Italy	Europe	46.4 million	46.1 million	Increase 0.5	Increase 5.7
    Turkey	Europe	35.7 million	34.7 million	Increase 3.0	Increase 10.5
    Germany	Europe	30.4 million	28.4 million	Increase 7.3	Increase 5.5
    United-Kingdom	Europe	29.3 million	29.3 million	Decrease 0.1	Increase 3.6
    Russia	Europe	25.7 million	22.7 million	Increase 13.4	Increase 11.9
    """
    # taken from http://en.wikipedia.org/wiki/Tourism

    mostVisitedPair = getMostVisited( tourismData )
    pop, country = mostVisitedPair
    print( "\n\nMost visited country = ", country )
    

    
main()