2002 prentice hall. all rights reserved. 1 5.2 sequences sequence (also called arrays in e.g. java)...

39
2002 Prentice Hall. All rights reserved. 1 5.2 Sequences Sequence (also called arrays in e.g. Java) Series of items that are often related Strings are sequences in Python – The range function returns a sequence Elements/items in the sequence • Referred to by subscripts; the first is always zero • Obtain one by using sequenceName[ subscript ] • Can also be referred to negatively – -1 would be the last element of the sequence! >>> range(3, 12) >>> [3, 4, 5, 6, 7, 8, 9, 10, 11] >>>

Post on 21-Dec-2015

219 views

Category:

Documents


1 download

TRANSCRIPT

2002 Prentice Hall. All rights reserved.

1

5.2 Sequences

• Sequence (also called arrays in e.g. Java)– Series of items that are often related

– Strings are sequences in Python

– The range function returns a sequence

– Elements/items in the sequence• Referred to by subscripts; the first is always zero

• Obtain one by using sequenceName[ subscript ]• Can also be referred to negatively

– -1 would be the last element of the sequence!

>>> range(3, 12)>>> [3, 4, 5, 6, 7, 8, 9, 10, 11]>>>

2002 Prentice Hall. All rights reserved.

2

5.2 Sequences

 

 

Fig. 5.1 Sequence with elements and indices.

-45

6

0

72

1543

-89

0

62

-3

1

6453

-78c[ 11 ]

c[ 10 ]

c[ 9 ]

c[ 8]

c[ 7 ]

c[ 4 ]

c[ 3 ]

c[ 2 ]

c[ 1 ]

c[ 0 ]

c[ 6 ]

c[ 5 ]

Position number of the element within sequence c

Name sequence (c)

c[ -1 ]

c[ -11 ]

c[ -10 ]

c[ -9 ]

c[ -8]

c[- 7 ]

c[ -4 ]

c[- 3 ]

c[ -2 ]

c[ -6 ]

c[ -5 ]

c[ -12 ]

2002 Prentice Hall. All rights reserved.

3

5.3 Creating Sequences

• Creations– Strings

• Use quotes• string1 = ""

– Lists• Use brackets

• Separate multiple items with a comma• list1 = []

– Tuples• Use parentheses

• Separate multiple items with a comma• tuple = ()• singleton = 1, - this is a one element tuple or a

singleton

2002 Prentice Hall. All rights reserved.

4

5.4 Using Lists and Tuples

• Differences– Lists are mutable, tuples are immutable

– Tuples and lists can both contain the same data

– Most often used for different purposes

>>> >>> aList = [3, 6, 9]>>> aList[2] = 141>>> aList[3, 6, 141]>>> >>> aTuple = (3, 6, 9)>>> aTuple[2] = 141Traceback (most recent call last): File "<stdin>", line 1, in ?TypeError: object doesn't support item assignment>>>

2002 Prentice Hall. All rights reserved.

5

5.4.1 Using Lists

• Lists– Not restricted to values of the same type, but ..

• .. mostly used to hold data of the same type

(Java: arrays declared to hold items of same type)

– The length is not usually predetermined and can vary throughout the program

– Accessing elements out of range• Python exits and an out of range error is displayed

Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> aList = [ 1 ]>>> print aList[ 13 ]Traceback (most recent call last): File "<stdin>", line 1, in ?IndexError: list index out of range

2002 Prentice Hall.All rights reserved.

6

Fig05_03.py

1 # Fig. 5.3: fig05_03.py2 # Creating, accessing and changing a list.3 4 aList = [] # create empty list5 6 # add values to list7 for number in range( 1, 11 ):8 aList += [ number ]9 10 print "The value of aList is:\n", aList 11 12 # access list values by iteration13 print "\nAccessing values by iteration:"14 15 for item in aList:16 print item,17 18 print 19 20 # access list values by index21 print "\nAccessing values by index:"22 print "Subscript Value"23 24 for i in range( len( aList ) ):25 print "%9d %7d" % ( i, aList[ i ] )26 27 # modify list28 print "\nModifying a list value..."29 print "Value of aList before modification:\n", aList30 aList[ 0 ] = -100 31 aList[ -3 ] = 1932 print "Value of aList after modification:\n", aList

Adds the values 1 to 10 to the list

Prints the list, both all at once and one at a time

Prints the list in comparison to its subscripts

Sets the value of the first item to -100

Sets the value of the 8th item to 19

2002 Prentice Hall.All rights reserved.

7# Fig. 5.3: fig05_03.py# Creating, accessing and changing a list. aList = [] # create empty list # add values to listfor number in range( 1, 11 ): aList += [ number ] print "The value of aList is:\n", aList # access list values by iterationprint "\nAccessing values by iteration:" for item in aList: print item, print # access list values by indexprint "\nAccessing values by index:"print "Subscript Value" for i in range( len( aList ) ): print "%9d %7d" % ( i, aList[ i ] ) # modify listprint "\nModifying a list value..."print "Value of aList before modification:\n", aListaList[ 0 ] = -100 aList[ -3 ] = 19print "Value of aList after modification:\n", aList

The value of aList is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Accessing values by iteration:1 2 3 4 5 6 7 8 9 10 Accessing values by index:Subscript Value 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 Modifying a list value...Value of aList before modification: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Value of aList after modification: [-100, 2, 3, 4, 5, 6, 7, 19, 9, 10]

2002 Prentice Hall.All rights reserved.

8

Fig05_05.py

1 # Fig. 5.5: fig05_05.py2 # Creating a histogram from a list of values.3 4 values = [] # a list of values5 6 # input 10 values from user7 print "Enter 10 integers:"8 9 for i in range( 10 ):10 newValue = int( raw_input( "Enter integer %d: " % ( i + 1 ) ) )11 values += [ newValue ]12 13 # create histogram, starting with the headline14 print "\nCreating a histogram from values:"15 print "%s %10s %10s" % ( "Element", "Value", "Histogram" )16 17 for i in range( len( values ) ):18 print "%7d %10d %s" % ( i, values[ i ], "*" * values[ i ] )

Prompts the user for 10 integers

Outputs as many *’s as the number entered into the list by the user

Another example

2002 Prentice Hall.All rights reserved.

9

Fig05_05.pyProgram Output

Enter 10 integers:Enter integer 1: 19Enter integer 2: 3Enter integer 3: 15Enter integer 4: 7Enter integer 5: 11Enter integer 6: 9Enter integer 7: 13Enter integer 8: 5Enter integer 9: 17Enter integer 10: 1 Creating a histogram from values:Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *

2002 Prentice Hall.All rights reserved.

10

values = [5, 19, 7, 3, 23]

for i in range( len( values ) ): .. # here we get the subscript, so we can output things like # ‘the 3. element is 7’

for i in values: .. # here we get the item directly, but not the subscript

for i in .. ?

subscripts_items.py

Two obvious ways of accessing all elements in a sequence

2002 Prentice Hall. All rights reserved.

11

5.4.2 Using Tuples

• Tuples– Used to contain data that is related but not necessarily of the

same type• Each data item represents a unique piece of the overall portion

– In this case tuples are usually not iterated though

– The needed data is known before creating the tuple, e.g. a person’s name, age and birth date

• Again this is not required but is a general rule

2002 Prentice Hall.All rights reserved.

12

Fig05_06.py

Program Output

1 # Fig. 5.6: fig05_06.py2 # Creating and accessing tuples.3 4 # retrieve hour, minute and second from user5 hour = int( raw_input( "Enter hour: " ) )6 minute = int( raw_input( "Enter minute: " ) )7 second = int( raw_input( "Enter second: " ) )8 9 currentTime = hour, minute, second # create tuple10 11 print "The value of currentTime is:", currentTime12 13 # access tuple14 print "The number of seconds since midnight is", \15 ( currentTime[ 0 ] * 3600 + currentTime[ 1 ] * 60 +16 currentTime[ 2 ] )

Enter hour: 9Enter minute: 16Enter second: 1The value of currentTime is: (9, 16, 1)The number of seconds since midnight is 33361

Creates a tuple that holds the time entered by the user (NB: the commas create the tuple, parentheses optional!)

Tuples are also accessed using brackets

Converts the time to seconds

2002 Prentice Hall.All rights reserved.

13

Fig05_07.py1 # Fig. 5.7: fig05_07.py2 # Unpacking sequences.3 4 # create sequences5 aString = "abc"6 aList = [ 1, 2, 3 ]7 aTuple = "a", "A", 18 9 # unpack sequences to variables10 print "Unpacking string..."11 first, second, third = aString12 print "String values:", first, second, third13 14 print "\nUnpacking list..."15 first, second, third = aList16 print "List values:", first, second, third17 18 print "\nUnpacking tuple..."19 first, second, third = aTuple20 print "Tuple values:", first, second, third21 22 # swapping two values23 x = 324 y = 425 26 print "\nBefore swapping: x = %d, y = %d" % ( x, y )27 x, y = y, x # swap variables28 print "After swapping: x = %d, y = %d" % ( x, y )

Creates a string, a list and a tuple

Unpacks the tuple into elements

Unpacks the string into characters

Unpacks the list into elements

The technique can also be used to swap two items (neat!)

Sequence unpacking - A useful shortcut to assign values to multiple variables in one statement

2002 Prentice Hall.All rights reserved.

14

Fig05_07.py

output

1 # Fig. 5.7: fig05_07.py2 # Unpacking sequences.3 4 # create sequences5 aString = "abc"6 aList = [ 1, 2, 3 ]7 aTuple = "a", "A", 18 9 # unpack sequences to variables10 print "Unpacking string..."11 first, second, third = aString12 print "String values:", first, second, third13 14 print "\nUnpacking list..."15 first, second, third = aList16 print "List values:", first, second, third17 18 print "\nUnpacking tuple..."19 first, second, third = aTuple20 print "Tuple values:", first, second, third21 22 # swapping two values23 x = 324 y = 425 26 print "\nBefore swapping: x = %d, y = %d" % ( x, y )27 x, y = y, x # swap variables28 print "After swapping: x = %d, y = %d" % ( x, y )

Sequence unpacking - A useful shortcut to assign values to multiple variables in one statement

Unpacking string...String values: a b c Unpacking list...List values: 1 2 3 Unpacking tuple...Tuple values: a A 1 Before swapping: x = 3, y = 4After swapping: x = 4, y = 3

2002 Prentice Hall. All rights reserved.

15

5.4.4 Sequence Slicing

• Slicing– Allows access to a portion of a string or other sequence at once– theSequence [ start:end ]– Returns the portion of the sequence from the starting position

up to (but not including) the ending position

>>> >>> aTuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)>>> print aTuple[2:4](2, 3)>>> print aTuple[1:9](1, 2, 3, 4, 5, 6, 7, 8)>>> print aTuple[-3:-1](7, 8)>>> >>> aString = 'elementary, my dear Watson'>>> print aString[13:17]y de>>> >>> print aString[0:len(aString)/2] # printing half the stringelementary, m

2002 Prentice Hall. All rights reserved.

16

5.5 Dictionaries

• Dictionaries– Mapping that consists of key-value pairs

• Referred to as hashes or maps in other languages

– Unordered collection of references

– Each value is referenced though its key

– Curley braces ({}) are used to create a dictionary

– Creating a dictionary: { key1:value1, … }– Keys must be immutable values such as strings, numbers and

tuples

– Values can be of any Python data type

2002 Prentice Hall.All rights reserved.

17

Fig05_09.py1 # Fig. 5.09: fig05_09.py2 # Creating, accessing and modifying a dictionary.3 4 # create and print an empty dictionary5 emptyDictionary = {}6 print "The value of emptyDictionary is:", emptyDictionary7 8 # create and print a dictionary with initial values9 grades = { "John": 87, "Bill": 76, "Laura": 92, "Edwin": 89 }10 print "\nAll grades:", grades11 12 # access and modify an existing dictionary13 print "\nBill's current grade:", grades[ "Bill" ]14 grades[ "Bill" ] = 9015 print "Bill's new grade:", grades[ "Bill" ]16 17 # add to an existing dictionary18 grades[ "Michael" ] = 9319 print "\nDictionary grades after modification:"20 print grades21 22 # delete entry from dictionary23 del grades[ "John" ]24 print "\nDictionary grades after deletion:"25 print grades

Alters and displays the new grade for Bill

Creates a grades dictionary using names as the key and their grade as the value

Creates an empty dictionary

Adds a new name to the grades dictionary (simply set the value of the new key)

Removes the name john from the dictionary with the del keyword

2002 Prentice Hall.All rights reserved.

18

Fig05_09.py4 # create and print an empty dictionary5 emptyDictionary = {}6 print "The value of emptyDictionary is:", emptyDictionary7 8 # create and print a dictionary with initial values9 grades = { "John": 87, "Bill": 76, "Laura": 92, "Edwin": 89 }10 print "\nAll grades:", grades11 12 # access and modify an existing dictionary13 print "\nBill's current grade:", grades[ "Bill" ]14 grades[ "Bill" ] = 9015 print "Bill's new grade:", grades[ "Bill" ]16 17 # add to an existing dictionary18 grades[ "Michael" ] = 9319 print "\nDictionary grades after modification:"20 print grades21 22 # delete entry from dictionary23 del grades[ "John" ]24 print "\nDictionary grades after deletion:"25 print grades

The value of emptyDictionary is: {} All grades: {'Edwin': 89, 'John': 87, 'Bill': 76, 'Laura': 92} Bill's current grade: 76Bill's new grade: 90 Dictionary grades after modification:{'Edwin': 89, 'Michael': 93, 'John': 87, 'Bill': 90, 'Laura': 92} Dictionary grades after deletion:{'Edwin': 89, 'Michael': 93, 'Bill': 90, 'Laura': 92}

Note: unordered! (‘Michael’ not inserted at the end)

2002 Prentice Hall. All rights reserved.

19

5.6 List and Dictionary Methods

• List methods– append - add values on to the end of a list

– A list of methods is provided in Fig. 5.12

• Dictionary methods– Allows manipulation of the items just as in a list

– A list of methods is provided in Fig. 5.14

2002 Prentice Hall.All rights reserved.

20

Fig05_10.py

Program Output

1 # Fig. 5.10: fig05_10.py2 # Appending items to a list.3 4 playList = [] # list of favorite plays5 6 print "Enter your 5 favorite Shakespearean plays.\n"7 8 for i in range( 5 ):9 playName = raw_input( "Play %d: " % ( i + 1 ) )10 playList.append( playName )11 12 print "\nSubscript Value"13 14 for i in range( len( playList ) ):15 print "%9d %-25s" % ( i + 1, playList[ i ] )

 Enter your 5 favorite Shakespearean plays. Play 1: Richard IIIPlay 2: Henry VPlay 3: Twelfth NightPlay 4: HamletPlay 5: King Lear Subscript Value 1 Richard III 2 Henry V 3 Twelfth Night 4 Hamlet 5 King Lear

Has the user enter 5 plays

Appends the items onto the list using the append method

Displays the items for the user

method append

2002 Prentice Hall.All rights reserved.

21

Fig05_11.py

Program Output

1 # Fig. 5.11: fig05_11.py2 # Student poll program.3 4 responses = [ 1, 2, 6, 4, 8, 5, 9, 7, 8, 10,5 1, 6, 3, 8, 6, 10, 3, 8, 2, 7,6 6, 5, 7, 6, 8, 6, 7, 5, 6, 6,7 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 ]8 9 print "Rating Frequency"10 11 for i in range( 1, 11 ):12 print "%6d %13d" % ( i, responses.count( i ) )

Rating Frequency 1 2 2 2 3 2 4 2 5 5 6 11 7 5 8 7 9 1 10 3

Uses the count method to tally up the total of each number in the lint

Creates a list of 40 numbers from 1 through 10

method count

2002 Prentice Hall. All rights reserved.

22

5.6 List MethodsMethod Purpose

append( item ) Inserts item at the end of the list.

count( element ) Returns the number of occurrences of element in the list.

extend( newList ) Inserts the elements of newList at the end of the list.

index( element ) Returns the index of the first occurrence of element in the list. If element is not in the list, a ValueError exception occurs. [Note: We discuss exceptions in Chapter 12, Exception Handling.]

insert(index, item) Inserts item at position index.

pop( [index] ) Parameter index is optional. If this method is called without arguments, it removes and returns the last element in the list. If parameter index is specified, this method removes and returns the element at position index.

remove( element ) Removes the first occurrence of element from the list. If element is not in the list, a ValueError exception occurs.

reverse() Reverses the contents of the list in place (rather than creating a reversed copy).

sort( [compare-function] )

Sorts the content of the list in place. The optional parameter

compare-function is a function that specifies the compare

criteria. The compare-function takes any two elements of the list (x and y) and returns -1 if x should appear before y, 0 if the orders of x and y do not matter and 1 if x should appear after

y. [Note: We discuss sorting in Section 5.9.]

Fig. 5.12 List methods.

cf. the comparable interface in Java

2002 Prentice Hall. All rights reserved.

23

Intermezzo

1. Write a function list_minmax which takes a list as an argument, sorts it and returns a tuple with the minimum and maximum values (see pages 178 and 180).

2. Call the function on 10 lists of different lengths with random numbers between 1 and 1000 (see on page 162 how to add a number to a list) and print the results.

2002 Prentice Hall. All rights reserved.

24

solutionimport random

def list_minimax(aList):

aList.sort()

return aList[0], aList[ len(aList)-1 ]

for i in range(10):

mylist = [] # create empty list

length = random.randrange( 5, 11 ) # choose length of list

while length > 0:

mylist += [ random.randrange (1, 1001) ] # add random element to list

length -= 1

min, max = list_minimax( mylist ) # unpack the returned tuple

print mylist, " -- min, max: %d, %d" %(min, max)

[4, 356, 587, 589, 604, 660, 711, 824, 873, 971] -- min, max: 4, 971[83, 159, 231, 389, 760, 989] -- min, max: 83, 989[151, 176, 404, 780, 894] -- min, max: 151, 894..

2002 Prentice Hall.All rights reserved.

25

Fig05_13.py

1 # Fig. 5.13: fig05_13.py2 # Dictionary methods.3 4 monthsDictionary = { 1 : "January", 2 : "February", 3 : "March",5 4 : "April", 5 : "May", 6 : "June", 7 : "July",6 8 : "August", 9 : "September", 10 : "October",7 11 : "November", 12 : "December" }8 9 print "The dictionary items are:"10 print monthsDictionary.items()11 12 print "\nThe dictionary keys are:"13 print monthsDictionary.keys()14 15 print "\nThe dictionary values are:"16 print monthsDictionary.values()17 18 print "\nUsing a for loop to get dictionary items:"19 20 for key in monthsDictionary.keys():21 print "monthsDictionary[", key, "] =", monthsDictionary[ key ]

Prints out all items, both key and value

Prints out all the keys in the dictionary

Prints out just the values in the dictionary

Loops though using the keys to display all the items in the dictionary

dictionary methodsCreates a dictionary with

the month number as the key and the month name as the value

2002 Prentice Hall.All rights reserved.

26

Fig05_13.pyProgram Output

The dictionary items are:[(1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December')] The dictionary keys are:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] The dictionary values are:['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] Using a for loop to get dictionary items:monthsDictionary[ 1 ] = JanuarymonthsDictionary[ 2 ] = FebruarymonthsDictionary[ 3 ] = MarchmonthsDictionary[ 4 ] = AprilmonthsDictionary[ 5 ] = MaymonthsDictionary[ 6 ] = JunemonthsDictionary[ 7 ] = JulymonthsDictionary[ 8 ] = AugustmonthsDictionary[ 9 ] = SeptembermonthsDictionary[ 10 ] = OctobermonthsDictionary[ 11 ] = NovembermonthsDictionary[ 12 ] = December

2002 Prentice Hall. All rights reserved.

27

5.6 Dictionary Methods – part of fig 5.14

Method Description

clear() Deletes all items from the dictionary.

copy() Creates and returns a shallow copy of the dictionary (the elements in the new dictionary are references to the elements in the original dictionary).

get( key [, returnValue] ) Returns the value associated with key. If key is not in the

dictionary and if returnValue is specified, returns

the specified value. If returnValue is not specified,

returns None.

has_key( key ) Returns 1 if key is in the dictionary; returns 0 if key is not in the dictionary.

items() Returns a list of tuples that are key-value pairs.

keys() Returns a list of keys in the dictionary.

popitem() Removes and returns an arbitrary key-value pair as a tuple of two elements. If dictionary is empty, a Key-Error exception occurs. [Note: We discuss exceptions in Chapter 12, Exception Handling.] This method is useful for accessing an element (i.e., print the key-value pair) before removing it from the dictionary.

2002 Prentice Hall. All rights reserved.

28

Shallow vs. Deep Copy

>>> dictionary = { "listKey" : [ 1, 2, 3 ] }>>> shallowCopy = dictionary.copy() # make a shallow copy>>>>>> dictionary[ "listKey" ].append( 4 )>>>>>> print dictionary{'listKey': [1, 2, 3, 4]}>>>>>> print shallowCopy{'listKey': [1, 2, 3, 4]} 

>>> from copy import deepcopy>>> deepCopy = deepcopy( dictionary ) # make a deep copy>>>>>> dictionary[ "listKey" ].append( 5 )>>>>>> print dictionary{'listKey': [1, 2, 3, 4, 5]}>>>>>> print shallowCopy{'listKey': [1, 2, 3, 4, 5]}>>>>>> print deepCopy{'listKey': [1, 2, 3, 4]}

Fig. 5.15 Difference between a shallow copy and a deep copy.

2002 Prentice Hall. All rights reserved.

29

5.7 Passing values to functions

• Pass-by-value– Copies the value and passes the copy

• Pass-by-reference– Allows a function to access the caller data and to modify it

– Can increase performance• Prevents the copying of large data

– Can weaken security• Allows direct access to the data – side effects

• Python: Pass by object reference– Combination of pass-by-value and pass-by-reference..

2002 Prentice Hall. All rights reserved.

30

5.8 Passing Lists to Functions

• To pass a list pass it without its brackets• Original list can be changed by the function• Items in the list that are immutable (numbers or

strings) cannot be changed by the function when passed individually

• In general: mutable objects can be changed when passed to a function (lists, dictionaries), immutable objects cannot (strings, tuples, numbers)

2002 Prentice Hall.All rights reserved.

31

Fig05_16.py

1 # Fig. 5.16: fig05_16.py2 # Passing lists and individual list elements to functions.3 4 def modifyList( aList ): # multiply all elements in the list by 2 5 for i in range( len( aList ) ):6 aList[ i ] *= 278 9 def modifyElement( element ):10 element *= 2 # multiply single element by 2 11 12 aList = [ 1, 2, 3, 4, 5 ]13 14 print "Effects of passing entire list:"15 print "The values of the original list are:"16 17 for item in aList:18 print item,19 20 modifyList( aList )21 22 print "\n\nThe values of the modified list are:"23 24 for item in aList:25 print item,26 27 print "\n\nEffects of passing list element:"28 print "aList[ 3 ] before modifyElement:", aList[ 3 ]29 modifyElement( aList[ 3 ] )30 print "aList[ 3 ] after modifyElement:", aList[ 3 ]31 32 print "\nEffects of passing slices of list:"33 print "aList[ 2:4 ] before modifyList:", aList[ 2:4 ]34 modifyList( aList[ 2:4 ] )35 print "aList[ 2:4 ] after modifyList:", aList[ 2:4 ]

Passes the entire list, the changes in the function will affect the list

Passes an element, it will not permanently be modified in the list

Passes a slice of the list, no permanent change to list

Again: no type declaration, so function body assumes it gets a list! NB: good documentation helps you use your function as intended, no help from a compiler

2002 Prentice Hall.All rights reserved.

32

Fig05_16.py

1 # Fig. 5.16: fig05_16.py2 # Passing lists and individual list elements to functions.3 4 def modifyList( aList ): # multiply all elements in the list by 2 5 for i in range( len( aList ) ):6 aList[ i ] *= 278 9 def modifyElement( element ):10 element *= 2 # multiply single element by 2 11 12 aList = [ 1, 2, 3, 4, 5 ]13 14 print "Effects of passing entire list:"15 print "The values of the original list are:"16 17 for item in aList:18 print item,19 20 modifyList( aList )21 22 print "\n\nThe values of the modified list are:"23 24 for item in aList:25 print item,26 27 print "\n\nEffects of passing list element:"28 print "aList[ 3 ] before modifyElement:", aList[ 3 ]29 modifyElement( aList[ 3 ] )30 print "aList[ 3 ] after modifyElement:", aList[ 3 ]31 32 print "\nEffects of passing slices of list:"33 print "aList[ 2:4 ] before modifyList:", aList[ 2:4 ]34 modifyList( aList[ 2:4 ] )35 print "aList[ 2:4 ] after modifyList:", aList[ 2:4 ]

Effects of passing entire list:The values of the original list are:1 2 3 4 5  The values of the modified list are:2 4 6 8 10  Effects of passing list element:aList[ 3 ] before modifyElement: 8aList[ 3 ] after modifyElement: 8 Effects of passing slices of list:aList[ 2:4 ] before modifyList: [6, 8]aList[ 2:4 ] after modifyList: [6, 8]

2002 Prentice Hall.All rights reserved.

33

Fig05_17.py

Program Output

1 # Fig. 5.17: fig05_17.py2 # Sorting a list.3 4 aList = [ 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 ]5 6 print "Data items in original order"7 8 for item in aList:9 print item,10 11 aList.sort()12 13 print "\n\nData items after sorting"14 15 for item in aList:16 print item,17 18 print

Data items in original order2 6 4 8 10 12 89 68 45 37  Data items after sorting2 4 6 8 10 12 37 45 68 89

The sort method is used to order the numbers in ascending order

Displays the sorted list

Displays the unorganized list

Sorting a list with the sort() method

2002 Prentice Hall.All rights reserved.

34

Fig05_18.py

Program Output

1 # Fig. 5.18: fig05_18.py2 # Searching a list for an integer.3 4 # Create a list of even integers 0 to 1985 aList = range( 0, 199, 2 )6 7 number = int( raw_input( "Enter integer number: " ) )8 9 if number in aList:10 print "Found at index:", aList.index( number )11 else:12 print "Value not found"

Enter integer number: 36Found at index: 18

Enter integer number: 37Value not found

The index method is used to find an item in the list and return the index of that item. If it is not there, you get an error

Creates a list containing the even numbers from 0 to 198

Searching a list with the index() method

Easy way to check if some element appears in a list

2002 Prentice Hall. All rights reserved.

41

Writing and testing a function

When writing a function myfunction, think thus:

1. What should myfunction do? – Think in terms of input/output: on this input it should give this output.

Don't include any interaction with the user in the actual function.

2. How do I know that myfunction works? – Choose a representative list of input and corresponding correct output: if

myfunction works on these, it works.

3. Automatic testing. – Write another function test_function that explicitly calls

myfunction on every input from the above list and checks the output.

The test_function should not change even if you change the implementation of myfunction . If you discover errors, leave the input for which the function failed in the list so that you can see that your function works after you fix the bug.

• In most cases, this strategy is applicable, wise, and encouraged!

2002 Prentice Hall. All rights reserved.

42

Deitel exercise 4.4c (see course homepage)

Write a function that determines whether a number

is a prime. Let's call it is_prime.

1. is_prime should take an integer n>0 as input and return 1 if n is a prime and 0 otherwise.

2. There are infinitely many primes so we can't check all of them. But it should return 1 for all this input: 2, 3, 5, 7, 19, 31, 137, 881, and it should return 0 for all this input: 9, 14, 77, 100, 169.

3. Put all these input/output checks in test_function

2002 Prentice Hall. All rights reserved.

43

First solution

import math

def is_prime(c): for i in range(2, int(math.sqrt(c))): # why is this enough? if c%i == 0: return 0 return 1

def test_function():

# list of input/output tuples: inout = [(2, 1), (5, 1), (7, 1), (19, 1), (31, 1), (137, 1), (881, 1), (9, 0), (14, 0), (77, 0), (100, 0), (169, 0)] for input, output in inout: if is_prime(input) != output: print "oops: input %d gave wrong output" %input

if __name__== "__main__": test_function() # this code not executed when file imported as a module

2002 Prentice Hall. All rights reserved.

44

Running the test

threonine:~% python ex4_4.py

oops: input 9 gave wrong output

oops: input 169 gave wrong output

Hmm.. Well, 9 and 169 are quadratic numbers, do we check

for their squareroots 3 and 13?

def is_prime(c):

for i in range(2, int(math.sqrt(c))): #oops, +1

if c%i == 0:

return 0

return 1

2002 Prentice Hall. All rights reserved.

45

Revised solutionimport math

def is_prime(c): for i in range(2, 1 + int(math.sqrt(c))): if c%i == 0: return 0 return 1

def test_function(): # KEEP the test function instead you change is_prime inout = [(2, 1), (5, 1), (7, 1), (19, 1), (31, 1), (137, 1), (881, 1), (9, 0), (14, 0), (77, 0), (100, 0), (169, 0)] for input, output in inout: if is_prime(input) != output: print "oops: input %d gave wrong output" %input

if __name__=="__main__": # test_function()

Either import this module from another program that handles the user interaction, or place any user interaction in the name/main wrapper