Home > front end >  How to Swap Chars like a byte-swap but with in a String with Python?
How to Swap Chars like a byte-swap but with in a String with Python?

Time:11-18

I'm looking for the fastest way (computationally speaking) to do :

CDAB to ABCD

Say I have this list of strings:

a = ['3412','7895','0042','1122','0001']

And I want my output to be a string b = 12349578420022110100 with something like a 16-bit byte-swap

My code goes (I used the entry as a string but it will be a list soon):

a = '34127895004211220001'
b = ''
i = 0

while (i < len(a)):
    b = b   a[i   2:i   4]   a[i:i   2]
    i = i   4

print(b)

b = 12349578420022110100

Do you think this approach is the best one ?

CodePudding user response:

Like @Ashwini mentioned it's depend on input size. But my approach is to add how many possible functions so my solution is this:

def swap(string):
    return string[-2:]   string[:-2]

a = ['3412','7895','0042','1122','0001']
s = ''.join(swap(a[i]) for i in range(len(a)))

print(s)

CodePudding user response:

It depends on the input size, if your input size is small your current approach is fine. For bigger input, it's recommended to not use to build large strings, as new memory needs to be allocated every time and lots of copying happens and results in quadratic runtime.

The recommended way is to build a list and join it using str.join:

>>> a = '34127895004211220001'
>>> "".join([a[i   2:i   4]   a[i:i   2] for i in range(0, len(a), 4)])
'12349578420022110100'

Docs:

CodePudding user response:

Just two possibilities (which are both based on your code):

a = ['3412', '7895', '0042', '1122', '0001']

def first():
    return ''.join([ i[-2:] i[:2] for i in a ])

def second():
    return ''.join(map(lambda i: i[-2:] i[:2], a))

print(first())
print(second())

import timeit

print(timeit.timeit('first()', globals=globals()))  # 1.14
print(timeit.timeit('second()', globals=globals()))  # 1.34

If you have several millions of swaps to do, maybe I also would first try to check if the bottleneck is really the swapping. It also quite likely depends on the length of a (if much longer other methods e.g. numpy may be faster).

  • Related