Difference between revisions of "CSC111 Breaking-out-of-Loop Exercises"
(→Problem 1 (to get the idea)) |
(→Something useful: the enumerate function) |
||
(2 intermediate revisions by the same user not shown) | |||
Line 14: | Line 14: | ||
* For the example above, the result would be a list newL = [ 1, 4 ]. | * For the example above, the result would be a list newL = [ 1, 4 ]. | ||
+ | |||
+ | ===Something useful: 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)== | ==Problem 2 (the real problem)== |
Latest revision as of 10:07, 17 November 2011
--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 ].
Something useful: 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.