Shriniwas
Shriniwas

Reputation: 754

List arithmetic operation in python

one problem statement on python list arithmetic that is I have one list say,

my_set = [24565,24621,32,598,899]

I want to take difference between first two elements and if difference is in range of -127 to 127 then add +128 to next index position and so on. First element of the list stays as-is

Like this the output

[24565, 56, +128, 24589, +128, −566, +128, -301].

this is what I tried to do

def inRange(val):
    return val in range(-127,127)

my_set = [24565,24621,32,598,899]
for i in range(len(my_set)-1):
    res = my_set[i] - my_set[i+1]
    if inRange(res) == True:
        my_set.insert(i+1,res)
        my_set.insert(i+2,128)

print(my_set)  

Please tell me how to do that.?? THankyou!

Upvotes: 0

Views: 262

Answers (1)

KBN
KBN

Reputation: 153

But in the desired output that you have written, you are adding 128 in spite of what the difference is. And you are also adding the difference value to the list. I got confused there. Anyways, this does adding the difference and 128 to the list. Also, can you make use of a new list to update the output or should you update the same list? The first case, its easy; the second case, you can try the below code

def inRange(val): # a simple if is enough and faster range
    if val < 127 and val >= -127:
        return True

my_set = [24565,24621,32,598,899]

#as you wanted the first element as is, moved this piece of code out of the loop
my_set.insert(1, my_set[0]-my_set[1])
my_set.insert(2,128)

i = 3
while i < len(my_set) - 1:
    res = my_set[i] - my_set[i+1]
    #if inRange(res) == True: # you can add this loop if required and do the inserts accordingly
    my_set[i] = res
    my_set.insert(i+1, 128)
    i = i + 2 # if you are gonna add the if check and insert only then, you might want to change the i increment as per that
print(my_set)  

Hope this helps. And expecting some one else to give a better answer :)

Upvotes: 2

Related Questions