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. 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
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
If you know how to install packages, you can install ipdb
and do
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.