CSC111 Breaking-out-of-Loop Exercises
--D. Thiebaut 09:50, 17 November 2011 (EST)
Problem 1 (to get the idea)
- Given a list of lines L, shown below, write a program that generate the list of the line numbers for lines containing words starting with 'a' and ending with 'z'.
L = [ "------- --------- -------- --- - --------- ---------", # line 0 "------- ---------- a----z -------- -- --------- --------", # line 1 "------- ---------- ------ -------- -- --------- --------", # line 2 "------- ---------- ------ -------- -- --------- --------", # line 3 "------- ---------- ------ -------- az --------- --------", # line 4 "------- ---------- ------ -------- -- --------- --------" ] # line 5
- For the example above, the result would be a list newL = [ 1, 4 ].
The enumerate function
- Here's a way to go through the items of a list and get their index at the same time:
farm = [ "pig", "dog", "cat", "mouse", "horse" ] for i, animal in enumerate( farm ): print( "Animal #%d is a %s" % ( i, animal ) )
- Its output is the following:
Animal #0 is a pig Animal #1 is a dog Animal #2 is a cat Animal #3 is a mouse Animal #4 is a horse
Problem 2 (the real problem)
- Same idea, but we want to get the first line that contains such a word.