Reputation: 148
From this post I understand that the log10() evaluates before the where is evaluated. Put simply I dont understand the answer provided in that question. Also why would the log10() be evaluated first, surely that just results in unnecessary computations?
merge_y = np.where(n <= 1, 1, n * np.log10(n))
import matplotlib.pyplot as plt
import numpy as np
n = np.arange(0, 10, 0.0001)
merge_y = np.where(n <= 1, 1, n * np.log10(n))
insertion_y = n*n
plt.plot(n, merge_y,'g')
plt.plot(n,insertion_y,'r')
plt.grid(True)
plt.xlabel('n')
plt.ylabel('T(n)')
plt.title('Time complexities of merge and insertion sort w/ input size n')
plt.show()
Upvotes: 1
Views: 5345
Reputation: 2323
You have to understand that np.where
is working based on logical indexing, you are thinking about it like a loop. What np.where
does is
np.where(return_this_logical_indexes, From_this_array_if_true, From_this_array_if_false)
But in order to to do this, those arrays must exist, if it's a function, then it will evaluate it in order to obtain an array and then index it with the logical array created by the condition.
You are thinking it more like a list comprenhension, like:
merge_y = [x*np.log10(x) if x>=1 else 1 for x in n]
Upvotes: 2
Reputation: 654
Why not do:
merge_y = np.ones_like(n)
mask = (n > 1)
n_m = n[mask]
merge_y[mask] = n_m * np.log10(n_m)
Upvotes: 0