Started to learn programming 2 months ago, in one of my little projects i encountered the need to generate permutations of list of objects.
I knew that i’ll find how to do this if i’ll just searched for it, but i wanted to make one of my own, so i worked up and made my own permutation generator code:
def perm(lst, c = [], x = 0):
i = -1
g = len(lst) - 1
if x == g:
while i < g:
i += 1
if lst[i] in c:
continue
c.append(lst[i])
print(c)
del c[-1]
i = g
else:
while i < g:
if x == 0:
del c[:]
elif g == x:
del c[-1]
elif len(c) > x:
del c[-1]
continue
i += 1
if lst[i] in c:
continue
c.append(lst[i])
x + 1
perm(lst, c, x + 1)
This is what it gives if i run it:
perm(range(2))
[0, 1]
[1, 0]
perm([1, 4, 5])
[1, 4, 5]
[1, 5, 4]
[4, 1, 5]
[4, 5, 1]
[5, 1, 4]
[5, 4, 1]
It works as i expected, but when i use bigger lists it take some time for it to generate all the permutations of the list.
So all i want is hints on how to improve my code, only hints.
Or if you can tell me what should i learn to be able to make a better generator?
Thanks in advance for all the helpers.
The best way to understand what is making your code slow is to actually measure it. When you attempt to guess at what will make something fast, it’s often wrong. You’ve got the right idea in that you’re noticing that your code is slower and it’s time for some improvement.
Since this is a fairly small piece of code, the timeit module will probably be useful. Break the code up into sections, and time them. A good rule of thumb is that it’s better to look at an inner loop for improvements, since this will be executed the most times. In your example, this would be the loop inside the
permfunction.It is also worth noting that
whileloops are generally slower thanforloops in python, and that list comprehensions are faster than both of these.Once you start writing longer scripts, you’ll want to be aware of the ability to profile in python, which will help you identify where your code is slow. Hopefully this has given you a few places to look.