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!
-
1Not quite clear. And modifying the list while iterating over it is not a good idea. So if the difference between two consecutive numbers is in the range of -127 to 127 you would want to add that difference value. And for each check you want to add +128?KBN– KBN2018年04月13日 07:32:57 +00:00Commented Apr 13, 2018 at 7:32
-
can you explain how you get to the following output?shahaf– shahaf2018年04月13日 07:43:16 +00:00Commented Apr 13, 2018 at 7:43
-
@KeerthiBachu yes what you got is right ..this is exactly what I want..... Actually this problem statement was asked me in interview. and interviewer was so clear about problem statement.Shriniwas– Shriniwas2018年04月13日 18:38:52 +00:00Commented Apr 13, 2018 at 18:38
-
@shahaf which exactly??? the code which tried or the output which I shown above??Shriniwas– Shriniwas2018年04月13日 18:40:03 +00:00Commented Apr 13, 2018 at 18:40
1 Answer 1
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 :)