Intellipaat Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (18.4k points)

I want to generate permutations of the list while considering the following constraint:

  • Every permutation starts with a number 0

Thus, I have a list li = [1,2,3,4], and I am interested in finding all unique permutations for those 4 numbers while adding a number 0 at index 0 to each permutation.

For example:

[0,1,2,3,4]

[0,1,3,2,4]

and so on.

1 Answer

0 votes
by (36.8k points)
edited by

Kindly use the below code:

def create_perm(actual_list, add_list):

    """

    Recursive function for the creation of the permutation

    """

    if len(add_list)==1:

        # If you reach the last item, print the found permutation

        # (add the 0 at the beginning)

        print([0] + actual_list + add_list)

    else:

        for i in add_list:

            # Go one step deeper by removing one item and add it to the found permutation

            new_add_list = add_list.copy()

            new_add_list.remove(i)

            # Make the recursion

            create_perm(actual_list + [i], new_add_list)

    

li = [1, 2, 3, 4]

create_perm([], li)

Want to gain skills in Data Science with Python? Sign up today for this Data Science with Python Course and be a master in it 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 26, 2020 in Python by Sudhir_1997 (55.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...