Special type of permutation


Joined
Dec 19, 2021
Messages
1
Reaction score
0
Hello everyone! :)
This is my first post on here. I am currently studying python, and I've been doing some very "mathematical exercises" from a book I found online. I am also working on recursion, because it's one of my weak points. I can do some permutations with my code recursively, but I'm sort of stumped on a problem that I can't really solve. I am supposed to find all permutations from a list. They have to be of k-size. The catch is that they have a pattern that I'm struggling to code for some reason :/
Basically, if I have an array like=[1,2,3,4] and n=4, a valid output would be [[1,2,1,2], [2,1,2,1], [1,4,1,4] ,etc...]
English is not my first language, but I believe you could call it a criss-cross pattern(?).
This is my code for the regular permutations:
Python:
def comb(k,array):
    if k<=0:
        return [[]]
    else:
        final=[]
        for part in comb(k-1,array):
            for e in array:
                final.append([e]+part)
            return final
Any help would be greatly appreciated!
 
Ad

Advertisements

Joined
Mar 3, 2021
Messages
243
Reaction score
29
This is the cleanest I could come up with. There's probably a better way to create the actual crisscross lists, but I got nothin'. Is this the correct output?

Python:
#!/usr/bin/env python3

def comb(k,array):
        if not array:
                return []
        else:
                final=[]
                e1 = array[0]
                for e2 in array[1:]:
                        n1 = []
                        n2 = []
                        for i in range(0,int((k+1)/2)):
                                n1.extend([e1, e2])
                                n2.extend([e2, e1])
                        final.append(n1[0:k])
                        final.append(n2[0:k])
                final.extend(comb(k,array[1:]))
                return final

print(comb(4, [1,2,3,4]))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top