Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created November 28, 2019 10:20
Show Gist options
  • Save vlad-bezden/37ae9457c8d68efb52c05ecb459dd42b to your computer and use it in GitHub Desktop.
Save vlad-bezden/37ae9457c8d68efb52c05ecb459dd42b to your computer and use it in GitHub Desktop.
Here is a powerful example of numpy diff function. In this example, I chunk of memory and I need to find start, end, and length of the memory. 1 means allocated and 0 means free. using numpy.diff I was able to find start and the end of the allocated memory. Another example thing I use here is dynamic size of the column col_size = 7 and the power…
import numpy as np
# Memory allocation:
# '1' means allocated, '0' means free
memory = np.array([0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0])
# contiguous memory allocations
diff = np.diff(memory)
# starts indices
starts = np.nonzero(diff == 1)[0] + 1
# ends indices
ends = np.nonzero(diff == -1)[0]
sizes = ends - starts
indices = np.argsort(sizes)
# printing column width
col_size = 7
print(f"{'starts':>{col_size}}{'ends':>{col_size}}{'size':>{col_size}}")
for i in range(len(sizes)):
# example on how to break long print column by multiple lines
# also example on how to use variable column size in print format
print(
f"{starts[indices[i]]:>{col_size}}"
f"{ends[indices[i]]:>{col_size}}"
f"{sizes[indices[i]] + 1:>{col_size}}"
)
# output
# starts ends size
# 9 9 1
# 1 2 2
# 5 7 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment