Description
1. (5 points) Explain in words the output of the following program (copy from here:
https://math.scu.edu/~linnell/169resources/scopehw.py )
def scope_test():
def do_local():
spam = “local spam”
def do_nonlocal():
nonlocal spam
spam = “nonlocal spam”
def do_global():
global spam
spam = “global spam”
spam = “test spam”
do_local()
print(“After local assignment:”, spam)
do_nonlocal()
print(“After nonlocal assignment:”, spam)
do_global()
print(“After global assignment:”, spam)
scope_test()
print(“In global scope:”, spam)
2. (15 points) In this problem, you will write a Python program to solve the 8-Queens problem. In
chess, a queen can move any number of squares horizontally, vertically, or diagonally. The 8-
queens problem is the problem of trying to place eight queens on an empty chessboard in such
a way that no queen can attack any other queen. This problem is intriguing because there is no
efficient algorithm known for solving the general problem. Rather, the straightforward
algorithm of trying all possible placements is most often used in practice, with the only
optimization being that each queen must be placed in a separate row and column:
a. Starting with the first row, try to place a queen in the current column.
b. If you can safely place a queen in that column, move on to the next column
c. If you are unable to safely place a queen in that column, go back to the previous
column, and move that queen down to the next row where it can safely be placed.
Move on to the next column.
Write a program in python to solve the 8-queens problem. Your program should produce as
output an 8X8 diagram of the chessboard, with a 1 indicating the presence of a queen in a
square and a 0 indicating the absence of a queen.
Hints: You can represent the board as either an 8X8 list or as a one-dimensional list with
the ith item representing the row number of the queen in column i. You can solve this
problem recursively or iteratively, but the recursive solution is usually much easier.
Submission instructions: You will print out your code for each problem, stapling together multiple
sheets (there will be deductions for unstapled homework!). Turn in the hardcopy at the beginning of
class. You will ALSO submit all of your .py files as attachments, to
cs169@math.scu.edu (NOT Dr. Linnell’s email!!)
The subject line of the email should be “CS169 HW3 YourLastName YourIDNumber “

