CSC111 Examples of Operations on Lists

From dftwiki3
Revision as of 10:38, 28 March 2014 by Thiebaut (talk | contribs) (Part 1: Passing Simple Types)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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


Important Behavior of Lists

Part 1: Passing Simple Types

 

# 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

def main():
    # -------------------------------------------------------
    x = -5
    print( "x = ", x )
    x = makeIntPositiveV1( x )
    print( "after calling makeIntPositiveV1(): x = ", x )

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

main()


Output
x =  -5
after calling makeIntPositiveV1(): x =  5

x =  -5
after calling makeIntPositiveV2(): x =  -5


Part 2: Passing Lists


       
# 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]

def main():
    # -------------------------------------------------------
     
    Lorg = [ -1, 2, 3, 4, -5, 6]
    L = Lorg[:]
    print( "L = ", L )
    L = makePositiveV1( L )
    print( "after calling makePrositiveV1:", L )

    print()

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

main()


Output
L =  [-1, 2, 3, 4, -5, 6]
after calling makePrositiveV1: [1, 2, 3, 4, 5, 6]

L =  [-1, 2, 3, 4, -5, 6]
after calling makePrositiveV2: [1, 2, 3, 4, 5, 6]