0

I got this function to looking for some specific characters in a string and if it is found it add a value at that position in the array, ex:

def skew_array(text):
    import numpy as np
    skew = np.zeros(len(text))
    for i in range(0, len(text)):
        if text[i] == 'G':
            skew[i] += 1
        elif text[i] == 'C':
            skew[i] -= 1
        else:
            skew[i] = 0
    return np.insert(skew, 0, 0)

>> skew_array('gacaattagcaa'.upper())
array([ 0.,  1.,  0., -1.,  0.,  0.,  0.,  0.,  0.,  1., -1.,  0.,  0.])

I am not sure if it is the right way to do it (inserting at the end) or if there are a way just to keep the first position as zero when creating the array.

I appreciate any tip! Thank you by your time.

PS - I was using a list, but it is very bad for memory in bigger strings!

0

1 Answer 1

1

i think that functions that change the flat size of arrays are pretty slow, so i'd create skew larger from the start. and you can use a dict to avoid an elif soup

import numpy as np
def skew_array(text, dict_):
    skew = np.zeros(len(text)+1)
    for i, char in enumerate(text, start=1):
        skew[i] = dict_.get(char, 0)
    return skew

skew_dict={"G":1, "C":-1}
code='gacaattagcaa'.upper()
print(skew_array(code, skew_dict))
Sign up to request clarification or add additional context in comments.

5 Comments

Since you need both the index and the value at said index, it would be better to loop with for i, char in enumerate(text, start=1). The dict could also contain only the keys for G and C and then fetch the value with dict.get(key, 0).
i always forgot about that start argument, thanks
Just to be clear, the dict suggestion is a preference. I just think leaving out any zero keys makes it less cumbersome to write and it's more apparent what has non-zero values. But for only 4 keys, initialising all 4 is also fine.
that's part of the things i always forget though they are very handy when we need them. so i'm really ok with that
That is very nice! Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.