8 Queens' Problem (Solved by Python 3.6)

def conflict(state,nextX):

    nextY=len(state) #next row

    for i in range(nextY): #go through 0 to nextY-1 rows

        if abs(state[i]-nextX) in (0,nextY-i):

        return True

    return False



def queens(num,state): #output a sequence

    if len(state)==num-1: #last row

        for pos in range(num): #go throuth 0 to num-1 columns

            if not conflict(state,pos): #if not conflict

            yield (pos,) #generate a tuple(pos,)

    else:

        for pos in range(num): #go throuth 0 to num-1 columns

            if not conflict(state,pos): #if not conflict

                for result in queens(num,state+(pos,)): #go through next queens()'results

                    yield (pos,)+result #generate a (pos,)+a next queens()'result



def prettyprint(solution):

    def line(pos,length=len(solution)):

        return '. '*(pos)+'X '+'. '*(length-pos-1)

    for pos in solution:

        print(line(pos))



import random

prettyprint(random.choice(list(queens(8,()))))

Results ( A Example ):

Functions and Statements:
(1) def [function name] ( [parameters] ):
[return or no return]
[yield]
(2) len( [object] )
(3) print( [strings] )
(4) range( [num] )=[0,1,2,...,num-1]
(5) list( [sequence] )=[sequence]

Methods:
(1)Recursion
A Example:

def factorial(n):
    if n==1:
        return 1   # ending condition
    else:
        return n*factorial(n-1)  # recursive formula

Reference:
Beginning Python From Novice to Professional (2nd Edition)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,481评论 0 23
  • The Python Data Model If you learned another object-orien...
    plutoese阅读 5,790评论 0 51
  • 他们俩蹑手蹑脚的进了屋,怕惊醒了么么,都没敢洗漱,直接上了床。躺下后,孔利娜向郭玉安这边挪了挪,郭玉安熟练的伸出胳...
    直云霄阅读 2,286评论 0 0
  • 婚姻中,有正确婚恋观的人,生活必然是幸福美满的。 步入中年的我,觉得婚姻中女人要为自己努力争取、创造幸福快乐的生活...
    琳琳丽阅读 3,421评论 6 1