0

I tried to make permutation algorithm. Do you think this is bad algorithm?

def permutation():
 data = ['a', 'b', 'c', 'd']
 for i in data:
    for j in data:
        for k in data:
            if (i == j) or (j == k) or (i == k):
                pass
            else:
                print(i+"-"+j+"-"+k)
permutation()

2 Answers2

0

No. It's not really a good one... May be something like

For i in data 
For j in data 
If i=j,  pass
Else for k in data 
If k=j or k=i,  pass
Else print

Only difference is that there won't be an unnecessary loop for k.

Som Shekhar
  • 138
  • 10
0

You can do the whole thing in a list comprehension:

result = [i + " " + j + " " + k for k in data for j in data for i in data if (i!=j and j!=k and i!=k)]
print result

One difference is that the print is done once, and doesn't need to each time it finds a permutation. Your results are also captured in the list.

To answer your question, your algorithm gives the correct answer according to your data list. However, it does not scale if your data list does not contain 4 elements. How would it work for 10 elements? The list is also not passed via the permutation() parameters, so you could also not reuse this function. You access the print services each time you loop, which you could postpone until later.

Therefore no, if you are making a general permutation algorithm, this would be considered bad on many accounts.

ergonaut
  • 6,929
  • 1
  • 17
  • 47