Python Forum
Permutations - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Permutations (/thread-23342.html)



Permutations - mikke3141 - Dec-23-2019

Hi,

I'm new to Python and trying to learn the basics. How can I only show unique lists as a result so that if the list values are just in a different order to an already found result, it would not show it as one of the possible alternatives. So for example if the code has already found (1,2,3,4) as a results if would not show (4,3,2,1) as another result.


numlist = [1, 2, 3, 4, 5]
target_sum = 10

for length in range(2, len(numlist) + 1):
    perms = list(permutations(numlist, length))
    print("checking {} permutations of length {}".format(len(perms), length))
    for p in perms:
        s = sum(p)
        if s == int(target_sum):
            print("sum({}) = {}".format(list(p), sum(p)))
I appreciate your help.


RE: Permutations - ichabod801 - Dec-23-2019

It's not clear where you are getting your permutations function from. If you are getting it from itertools, use itertools.combinations instead. Otherwise show use the code for your permutations function.


RE: Permutations - mikke3141 - Dec-23-2019

Yes I was using itertools. Thank you for your help.