I have found some algorithms online to generate derangements in Python but they’re all exponential in complexity and as a result I can’t get them to converge with a set of 26 elements (the alphabet)!
So I’m trying to find a way to improve the following code (source here):
def derangement(vs):
l = [None for x in vs]
sol = set()
sol.add(tuple(l))
for v in vs:
sol1 = set()
for s in sol:
for (i, v1) in enumerate(s):
if not v1 and v != vs[i]:
s1 = list(s)
s1[i] = v
sol1.add(tuple(s1))
sol = sol1
return list(sol)
If anyone is curious this is for a bruteforce substitution cipher solver. I’m trying to see how long it takes to bruteforce a cipher!
As permutation algorithms are Ω(n!) nothing will make your code converge. This may be faster, but that means nothing for things of that complexity:
It’s a lazy iterator. If you need all values (I doubt you need) just
list()it