Issue
I have a list of variable price
changes:
price = 1000
changes = [0, -0.5, +0.5, -1, 1]
# change means new_price = old_price * (1 + change)
I need a list that shows how price
will change as a result of several consecutive changes; for example, this is what it looks like for 2 consecutive changes:
[1000, 1000, 1000]
[1000, 1000, 500]
[1000, 1000, 1500]
[1000, 1000, 0]
[1000, 1000, 2000]
[1000, 500, 500]
[1000, 500, 250]
[1000, 500, 750]
[1000, 500, 0]
[1000, 500, 1000]
[1000, 1500, 1500]
[1000, 1500, 750]
[1000, 1500, 2250]
[1000, 1500, 0]
[1000, 1500, 3000]
[1000, 0, 0]
[1000, 0, 0]
[1000, 0, 0]
[1000, 0, 0]
[1000, 0, 0]
[1000, 2000, 2000]
[1000, 2000, 1000]
[1000, 2000, 3000]
[1000, 2000, 0]
[1000, 2000, 4000]
The numpy
library is allowed to be used.
Solution
Broadcast the calculation repeatedly, then broadcast the results to each other, and finally move the axis:
>>> changes = np.array([0, -0.5, +0.5, -1, 1])
>>> price = np.array(1000)
>>> prices = [price]
>>> times = 2
>>> for _ in range(times):
... prices.append(prices[-1][..., None] * (changes + 1))
...
>>> shape = prices[-1].shape
>>> ar = np.array([np.broadcast_to(a[(...,) + (None,) * (times - i)], shape) for i, a in enumerate(prices)])
>>> np.moveaxis(ar, 0, -1)
array([[[1000., 1000., 1000.],
[1000., 1000., 500.],
[1000., 1000., 1500.],
[1000., 1000., 0.],
[1000., 1000., 2000.]],
[[1000., 500., 500.],
[1000., 500., 250.],
[1000., 500., 750.],
[1000., 500., 0.],
[1000., 500., 1000.]],
[[1000., 1500., 1500.],
[1000., 1500., 750.],
[1000., 1500., 2250.],
[1000., 1500., 0.],
[1000., 1500., 3000.]],
[[1000., 0., 0.],
[1000., 0., 0.],
[1000., 0., 0.],
[1000., 0., 0.],
[1000., 0., 0.]],
[[1000., 2000., 2000.],
[1000., 2000., 1000.],
[1000., 2000., 3000.],
[1000., 2000., 0.],
[1000., 2000., 4000.]]])
Answered By - Mechanic Pig
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.