Let's say we have an array as follows:
x = [4.0,0,0,2.0,0,0]
And we also have a bunch of positions (positions represent indexes 1 (basically indexes starting at 1):
unboundedVarsIndex = [3]
My objctive is basically to "merge" or "put togheter" the values of x such that in final we have the following:
x = [4.0 , 0, 0-2.0, 0, 0]
So basically,
for index in unboundedVarsIndex:
x[index-1] = x[index-1] - x[index]
But this gives me the following output:
x = [4.0 , 0, -2.0, 2.0, 0, 0]
Which makes sense, since I did nothing to delete two from the array. I would like find a way to clear 2 from the array and also I would like to make this code work for more than 1 position, i.e., to make it work for example when we have this:
len(unboundedVarsIndex) >= 1
Take this as example: Let
unboundedVarsIndex = [1,2,3]
Then, for the same vector x defined in the beggining, I would like to get the following output:
x = [4.0 = x[0] - 0 = x[1], x[2] = 0 - 2.0 = x[3], x[4] = 0 - 0 = x[5]]
Thanks for any help in advance.
UPDATE Answering the comment:
understand I can do that by doing unboundedVarsIndex.sort(reverse=True) but still this doesn't give me the output wanted. Let's say I do the following:
x = [4,0,0,2,0,0]
unboundedVarsIndex = [1,2,3]
unboundedVarsIndex.sort(reverse=True)
for index in unboundedVarsIndex:
x.insert(index-1,x[index-1]-x[index])
del x[index 1]
del x[index]
print(x)
I get the output: x = [2,0,0] and this is not what I wanted. Where am I doing a mistake?
CodePudding user response:
I was able to solve my own issue using the following code:
x = [4,0,0,2,0,0]
unboundedVarsIndex = [1,2,3]
unboundedVarsIndex.sort(reverse=True)
for index in unboundedVarsIndex:
if index-1 in unboundedVarsIndex:
x[index] = x[index] - x[index 1]
del x[index 1]
else:
x[index-1] = x[index-1] - x[index]
del x[index]
Thanks for all the help in the comments from @jasonharper and @KarlKnetchel. Their help made me realise my mistakes and help me with the syntaxe.
CodePudding user response:
So you're trying to iterate through some given positions in the array, and for each position perform the following:
- Update:
array[position - 1] = array[position - 1] - array[position] - Remove:
array.pop(position)
def redefine(arr, unbounded_var_positions):
for position in unbounded_var_positions:
if not arr:
return
redefine_index = position - 1
if (redefine_index >= 0) and (redefine_index < len(arr) - 1):
arr[redefine_index] = arr[redefine_index] - arr[redefine_index 1]
arr.pop(redefine_index 1)
Which does the following:
>>> arr = [4, 0, 0, 2, 0, 0]
>>> unbounded_var_positions = [1, 2, 3]
>>> redefine(arr, unbounded_var_positions)
>>> arr
[4, -2, 0]
