How can I write a function to describe this fractal's Nth stage?
I know it should be equal to 1 for some x and 0 for the rest but can't figure the math. I don't know if my drawing is good enough. But I think what I mean is clear. I need to use it in a computer code. and thanks in advance!

Instead of a formula, a recursive specification is more natural, something like:
Start with the interval $[a, b]$ on the $x$-axis and recursively perform the operation:
The call
cantor(x, 0, 1, 6), for example, starts with $[0, 1]$ and returns the height at $x$ after six iterations of the preceding operation.