[英]Backtracking in Python [2]
I have just came up with this simple Python algorithm for generating all the possible permutations from 1 to n, but it does not seem to work. 我刚刚想出了这个简单的Python算法,用于生成从1到n的所有可能排列,但是它似乎不起作用。 Here is the code: 这是代码:
def main ():
n = 3
x = [0] * 4
k = 1
while k:
ok = True
while x[k] < n and ok:
for i in range (0,k-1):
if x[i] == x[k]:
ok = False
if ok:
x[k] += 1
if x[k] < n:
if k == n:
print x
else:
k+=1
x[k] = 0
else:
k-=1
main()
When I run it, nothing happens. 当我运行它时,什么也没发生。 Can you please help me? 你能帮我么? I am also new to Python 我也是Python的新手
I have no idea why this is supposed to output permutations (also it prints newline every time, so in any case it will just print out a column of numbers even if it works). 我不知道为什么要输出排列(它每次也会打印换行符,因此无论如何它都只会打印出一列数字,即使它可以工作)。 You really should take a debugger and investigate it yourself. 您确实应该使用调试器并自己进行调查。
Just put this line in the beginning of the function: 只需将此行放在函数的开头:
import pdb; pdb.set_trace()
and you will be able to go through you program step-by-step. 您将可以逐步完成程序。 Here is a question with some links and tips on how to use it - Getting started with the Python Debugger pdb 这是一个带有一些链接和使用技巧的问题-Python调试器pdb入门
If you know how to install packages, you can install ipdb
and do 如果您知道如何安装软件包,则可以安装ipdb
并执行
import ipdb; ipdb.set_trace()
to the same effect, but the debugger will have autocomplete and will generally be a little bit sexier. 达到相同的效果,但调试器将具有自动完成功能,并且通常会有点性感。
Good luck in your studies! 祝你学习顺利!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.