Computer Science 15-110, Spring 2011
Class Notes: 2d Lists Practice (Problem-Solving)
- More coming soon....
- Word Search
- Sample Solutions
Lists
Practice (Problem-Solving)
- More coming soon...
More examples are coming soon...
- Word Search
Write
the function wordSearch that takes two parameters, a puzzle (a 2d list
of characters) and a word, and if the word is in the puzzle, the
function returns a tuple (see comment below) of the starting location and the direction of
the word, otherwise the function returns None (meaning the word is not
in the puzzle). Here is a sample puzzle:
puzzle = [ [ 'a', 'q', 'r', 'z' ],
[ 'g', 'o', 'd', 'q' ],
[ 'w', 'm', 'z', 'c' ]
]
And here is a smple call to the wordSearch function:
print wordSearch(puzzle, "dog")
Notice
that the word "dog" occurs in row 1 (the second row), starting at
column 2 (the third column), heading to the left. To represent
directions (headings), we will use a tuple of two numbers -- (drow, dcol) --
representing the change in row and change in col necessary to take one
step in that direction. Thus, "left" is represented as (0, -1),
since to take one step left we do not change our row but we subtract
one from our column. Thus, the example above prints:
(1,2,(0,-1))
This means the word "dog" was found, starting at row 1 and col 2, and heading left (0, -1).
Note: What is a tuple?
A tuple is just like a list, only it is created using parentheses
instead of brackets. So [2,3] is a list, but (2,3) is a tuple.
Unlike lists, tuples are immutable (unchangeable). So, if a =
(2,3), then you cannot say a[0] = 4, because you cannot change values
in the tuple. Tuples are more efficient than lists, and so they
are often used when returning multiple values from a function.
- Sample Solutions
- Word Search
carpe
diem - carpe
diem - carpe
diem - carpe
diem - carpe
diem - carpe
diem - carpe
diem - carpe
diem - carpe diem