As we continue to learn about python, we have found more and more convenient python and some similarities and differences between python and C/C ++. Due to the lack of programming exercises in my books, I was wondering how to get familiar with python as soon as possible. Since I have been participating in algorithm competitions, I thought of using Python to implement some data structures and algorithms. This type of programming usually does not use too many libraries, but it is a good way to exercise basic skills. After the program is written, you can spend several minutes to summarize the knowledge points used, which is very effective for beginners. The following is an example of a program in the book. I am familiar with the eight queens issue and will use some more complex data structures during this time.
[Python]
Def conflict (state, nextX ):
NextY = len (state)
For I in range (nextY): # note that range is a half-open half-closed interval, left-closed and right-open
If abs (state [I]-nextX) in (0, nextY-I): # This is a feature that I like very much in python and is much simpler than the same C code.
Return True
Return False
Def queens (num = 8, state = (): # default parameter. Like the C ++ rule, the default parameter must exist from right to left, that is, if a parameter with no default value still exists on the right of a default parameter, an error occurs.
For pos in range (num ):
If not conflict (state, pos): # if not Statement
If len (state) = num-1:
Yield (pos,) # yield generator to generate tuple. Note the format (pos ,).
Else:
For result in queens (num, state + (pos,): # connections to data structures such as tuple are also a reason why I like python very much.
Yield (pos,) + result
Def pretty_print (solution ):
Def line (pos, length = len (solution): # define a function in the function definition. This is different from C/C ++.
Return '.' * pos + 'X' + '.' * (length-pos-1)
For pos in solution:
Print line (pos)
# Print list (queens (4 ))
# Print len (list (queens (8 )))
Import random
Pretty_print (random. choice (list (queens (8 ))))
Author: NeilHappy