Home > Mobile >  rearrange elements in a python list based on given array of indices, but not of the same size of the
rearrange elements in a python list based on given array of indices, but not of the same size of the

Time:04-14

I'm trying to build a function that takes an array of chars and an array of indices, then it rearranges the array elements with the given indices, only thing is the array of indices could be smaller than the given array, for example, array = [1,2,3,4,5] and the indices could be something like [1,0] which repeats until the end of the array. this is what I have so far, will appreciate any help on this!

for example here are some test cases:

cipher = ['t', 'h', 'i', 's', 'w', 'o', 'r', 'k', 'i', 'n', 'g']
index = [1, 2, 0]

         [1,    2,   0] [1,    2,   0]  [1,    2,   0]  [1,    2]
output = ['h', 'i', 't', 'w', 'o', 's', 'k',  'i', 'r', 'n', 'g']

cipher = ['r', 'e', 'a', 'f', 'g', 'c', 'v', 'f', 'q', 'j']

arr = []
index = [1, 0]

start = 0
end = len(index)-1

for i in range(start, end):
    for j,elem in enumerate(index):
        arr.append(cipher[elem])
    start  = len(index)
    end  = len(index)
    
print(arr)

CodePudding user response:

This should do the trick

cipher = ['t', 'h', 'i', 's', 'w', 'o', 'r', 'k', 'i', 'n', 'g']
index = [1, 2, 0]

splitCipher = [cipher[i:i len(index)] for i in range(0,len(cipher),len(index))]
newCipher = []
for group in splitCipher:
    for i in range(len(index)):
        try:
            newCipher.append(group[index[i]])
        except:
            pass

print(newCipher)
  • Related