Question

Task 3:N ns Brute For In mathematics, the notion of permutation relates to the act of arranging all the members of a set into

python code,please!

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import itertools

def isValidPermutation(permutation): # checks whether the given permutation is valid N queens placement or not
canPlace = [] # keeps track of whether a queen can be placed on the board of not
N = len(permutation)
for i in range(N):
row = []
for j in range(N):
row.append(True)
canPlace.append(row)
for i in range(N): # iterate through all rows
if canPlace[i][permutation[i]] is False:
return False
for j in range(i + 1, N): # iterate through all rows below current row
canPlace[j][permutation[i]] = False # set the cell directly below the current column to be False
if permutation[i] - (j - i) >= 0: # set the cell on the left diagonal to be False
canPlace[j][permutation[i] - (j - i)] = False
if permutation[i] + (j - i) < N: # set the cell on the right diagonal to be False
canPlace[j][permutation[i] + (j-i)] = False
return True

def printBoard(permutation): # prints the board for the given permutation
N = len(permutation)
for i in range(N):
for j in range(N):
if j == permutation[i]:
print 'Q',
else:
print '0',
print ''

N = input("Enter the size of N: ")
permutations = itertools.permutations(range(N)) # get all the permutations
valid_permutations = []
valid_count = 0
for permutation in permutations:
if isValidPermutation(permutation):
valid_count += 1
valid_permutations.append(permutation)
print 'Number of solutions:', valid_count
print ''
for permutation in valid_permutations:
printBoard(permutation)
print ''

Enter the size of N: 4 Number of solutions: 2 0 Q 0 0 0 0 Q 0 0 0 Q 0 Q 0 0 0 0 0 0 Q 0 Q 0 0import itertools def isValidPermutation(permutation): # checks whether the given permutation is valid N queens placement or n

Add a comment
Know the answer?
Add Answer to:
python code,please! Task 3:N ns Brute For In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence or order, or if the set is already or...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT